-
Notifications
You must be signed in to change notification settings - Fork 71
/
stats.rs
2174 lines (1997 loc) · 89.4 KB
/
stats.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
static USAGE: &str = r#"
Compute summary statistics & infers data types for each column in a CSV.
> NOTE: `stats` is heavily optimized for speed. It assumes the CSV is well-formed and
UTF-8 encoded. If you encounter problems generating stats, use `qsv validate` to confirm the
input CSV is valid.
Summary statistics includes sum, min/max/range, sort order, min/max/sum/avg length, mean,
standard error of the mean (SEM), stddev, variance, coefficient of variation (CV), nullcount,
max_precision, sparsity, quartiles, interquartile range (IQR), lower/upper fences, skewness, median,
cardinality, mode/s & "antimode/s", and median absolute deviation (MAD). Note that some statistics
require loading the entire file into memory, so they must be enabled explicitly.
By default, the following "streaming" statistics are reported for *every* column:
sum, min/max/range values, sort order, min/max/sum/avg length, mean, sem, stddev, variance, cv,
nullcount, max_precision & sparsity. The default set of statistics corresponds to ones that can be
computed efficiently on a stream of data (i.e., constant memory) and works with arbitrarily large CSVs.
The following additional "non-streaming" statistics require loading the entire file into memory:
cardinality, mode/antimode, median, MAD, quartiles and its related measures (IQR,
lower/upper fences & skewness).
When computing “non-streaming” statistics, an Out-Of-Memory (OOM) heuristic check is done.
If the file is larger than the available memory minus a headroom buffer of 20% (which can be
adjusted using the QSV_FREEMEMORY_HEADROOM_PCT environment variable), processing will be
preemptively prevented.
"Antimode" is the least frequently occurring non-zero value and is the opposite of mode.
It returns "*ALL" if all the values are unique, and only returns a preview of the first
10 antimodes.
If you need all the antimode values of a column, run the `frequency` command with --limit set
to zero. The resulting frequency table will have all the antimode values.
Summary statistics for dates are also computed when --infer-dates is enabled, with DateTime
results in rfc3339 format and Date results in "yyyy-mm-dd" format in the UTC timezone.
Date range, stddev, variance, MAD & IQR are returned in days, not timestamp milliseconds.
Each column's data type is also inferred (NULL, Integer, String, Float, Date, DateTime and
Boolean with --infer-boolean option).
For String data types, it also determines if the column is all ASCII characters.
Unlike the sniff command, stats' data type inferences are GUARANTEED, as the entire file
is scanned, and not just sampled.
Note that the Date and DateTime data types are only inferred with the --infer-dates option
as its an expensive operation to match a date candidate against 19 possible date formats,
with each format, having several variants.
The date formats recognized and its sub-variants along with examples can be found at
https://github.com/jqnatividad/qsv-dateparser?tab=readme-ov-file#accepted-date-formats.
Computing statistics on a large file can be made MUCH faster if you create an index for it
first with 'qsv index' to enable multithreading. With an index, the file is split into equal
chunks and each chunk is processed in parallel. The number of chunks is determined by the
number of logical CPUs detected. You can override this by setting the --jobs option.
As stats is a central command in qsv, and can be expensive to compute, `stats` caches results
in <FILESTEM>.stats.csv & if the --stats-json option is used, <FILESTEM>.stats.csv.data.jsonl
(e.g., qsv stats nyc311.csv will create nyc311.stats.csv & nyc311.stats.csv.data.jsonl).
The arguments used to generate the cached stats are saved in <FILESTEM>.stats.csv.jsonl.
If stats have already been computed for the input file with similar arguments and the file
hasn't changed, the stats will be loaded from the cache instead of recomputing it.
These cached stats are also used by other qsv commands (currently `schema` & `tojsonl`) to
load the stats into memory faster. If the cached stats are not current (i.e., the input file
is newer than the cached stats), the cached stats will be ignored and recomputed. For example,
see the "boston311" test files in
https://github.com/jqnatividad/qsv/blob/4529d51273218347fef6aca15ac24e22b85b2ec4/tests/test_stats.rs#L608.
Examples:
Compute "streaming" statistics for the "nyc311.csv" file:
$ qsv stats nyc311.csv
Compute all statistics for the "nyc311.csv" file:
$ qsv stats --everything nyc311.csv
$ qsv stats -E nyc311.csv
Compute all statistics for the "nyc311.csv", inferring dates using default date column name patterns:
$ qsv stats -E --infer-dates nyc311.csv
Compute all statistics for the "nyc311.csv", inferring dates only for columns with "_date" & "_dte":
$ qsv stats -E --infer-dates --dates-whitelist _date,_dte nyc311.csv
In addition, also infer boolean data types for the "nyc311.csv" file:
$ qsv stats -E --infer-dates --dates-whitelist _date --infer-boolean nyc311.csv
In addition to basis "streaming" stats, also compute the cardinality for the "nyc311.csv" file:
$ qsv stats --cardinality nyc311.csv
Prefer DMY format when inferring dates for the "nyc311.csv" file:
$ qsv stats -E --infer-dates --prefer-dmy nyc311.csv
Infer data types only for the "nyc311.csv" file:
$ qsv stats --typesonly nyc311.csv
Infer data types only, including boolean and date types for the "nyc311.csv" file:
$ qsv stats --typesonly --infer-boolean --infer-dates nyc311.csv
Automatically create an index for the "nyc311.csv" file if it's larger than 5MB
and there is no existing index file:
$ qsv stats -E --cache-threshold -5000000 nyc311.csv
Auto-create an index for the "nyc311.csv" file if it's larger than 5MB and delete the index
and the stats cache file after the stats run:
$ qsv stats -E --cache-threshold -5000005 nyc311.csv
Prompt for CSV/TSV/TAB file to compute stats for:
$ qsv prompt -F tsv,csv,tab | qsv stats -E | qsv table
Prompt for a file to save the stats to in the ~/Documents directory:
$ qsv stats -E nyc311.csv | qsv prompt -d ~/Documents --fd-output
Prompt for both INPUT and OUTPUT files in the ~/Documents dir with custom prompts:
$ qsv prompt -m 'Select a CSV file to summarize' -d ~/Documents -F csv | \
qsv stats -E --infer-dates | \
qsv prompt -m 'Save summary to...' -d ~/Documents --fd-output --save-fname summarystats.csv
For more examples, see https://github.com/jqnatividad/qsv/tree/master/resources/test
For more info, see https://github.com/jqnatividad/qsv/wiki/Supplemental#stats-command-output-explanation
Usage:
qsv stats [options] [<input>]
qsv stats --help
stats options:
-s, --select <arg> Select a subset of columns to compute stats for.
See 'qsv select --help' for the format details.
This is provided here because piping 'qsv select'
into 'qsv stats' will prevent the use of indexing.
-E, --everything Compute all statistics available.
--typesonly Infer data types only and do not compute statistics.
Note that if you want to infer dates, you'll still need to use
the --infer-dates and --dates-whitelist options.
--infer-boolean Infer boolean data type. This automatically enables
the --cardinality option. When a column's cardinality is 2,
and the 2 values' first characters are 0/1, t/f & y/n
case-insensitive, the data type is inferred as boolean.
--mode Compute the mode/s & antimode/s. Multimodal-aware.
This requires loading all CSV data in memory.
--cardinality Compute the cardinality.
This requires loading all CSV data in memory.
--median Compute the median.
This requires loading all CSV data in memory.
--mad Compute the median absolute deviation (MAD).
This requires loading all CSV data in memory.
--quartiles Compute the quartiles, the IQR, the lower/upper inner/outer
fences and skewness.
This requires loading all CSV data in memory.
--round <decimal_places> Round statistics to <decimal_places>. Rounding is done following
Midpoint Nearest Even (aka "Bankers Rounding") rule.
https://docs.rs/rust_decimal/latest/rust_decimal/enum.RoundingStrategy.html
If set to the sentinel value 9999, no rounding is done.
For dates - range, stddev & IQR are always at least 5 decimal places as
they are reported in days, and 5 places gives us millisecond precision.
[default: 4]
--nulls Include NULLs in the population size for computing
mean and standard deviation.
--infer-dates Infer date/datetime datatypes. This is an expensive
option and should only be used when you know there
are date/datetime fields.
Also, if timezone is not specified in the data, it'll
be set to UTC.
--dates-whitelist <list> The case-insensitive patterns to look for when
shortlisting fields for date inferencing.
i.e. if the field's name has any of these patterns,
it is shortlisted for date inferencing.
Set to "all" to inspect ALL fields for
date/datetime types. Ignored if --infer-dates is false.
Note that false positive date matches WILL most likely occur
when using "all" as unix epoch timestamps are just numbers.
Be sure to only use "all" if you know ALL the columns you're
inspecting are dates, boolean or string fields.
To avoid false positives, preprocess the file first
with the `datefmt` command to convert unix epoch timestamp
columns to RFC3339 format.
[default: date,time,due,open,close,created]
--prefer-dmy Parse dates in dmy format. Otherwise, use mdy format.
Ignored if --infer-dates is false.
--force Force recomputing stats even if valid precomputed stats
cache exists.
-j, --jobs <arg> The number of jobs to run in parallel.
This works only when the given CSV has an index.
Note that a file handle is opened for each job.
When not set, the number of jobs is set to the
number of CPUs detected.
--stats-jsonl Also write the stats in JSONL format.
If set, the stats will be written to <FILESTEM>.stats.csv.data.jsonl.
Note that this option used internally by other qsv commands
(currently `frequency`, `schema`. `tojsonl` & `sqlp`) to load cached stats.
You can preemptively create the stats-jsonl file by using
this option BEFORE running the `frequency`, `schema` & `tojsonl`
commands and they will automatically use it.
-c, --cache-threshold <arg> When greater than 1, the threshold in milliseconds before caching
stats results. If a stats run takes longer than this threshold,
the stats results will be cached.
Set to 0 to suppress caching.
Set to 1 to force caching.
Set to a negative number to automatically create an index
when the input file size is greater than abs(arg) in bytes.
If the negative number ends with 5, it will delete the index
file and the stats cache file after the stats run. Otherwise,
the index file and the cache files are kept.
[default: 5000]
Common options:
-h, --help Display this message
-o, --output <file> Write output to <file> instead of stdout.
-n, --no-headers When set, the first row will NOT be interpreted
as column names. i.e., They will be included
in statistics.
-d, --delimiter <arg> The field delimiter for READING CSV data.
Must be a single character. (default: ,)
--memcheck Check if there is enough memory to load the entire
CSV into memory using CONSERVATIVE heuristics.
This option is ignored when computing default, streaming
statistics, as it is not needed.
"#;
/*
DEVELOPER NOTE: stats is heavily optimized and is a central command in qsv.
It was the primary reason I created the qsv fork as I needed to do GUARANTEED data type
inferencing & to compile smart Data Dictionaries in the most performant way possible
for Datapusher+ (https://github.com/dathere/datapusher-plus).
It underpins the `schema` and `validate` commands - enabling the automatic creation of
a JSONschema based on a CSV's summary statistics; and use the generated JSONschema to
quickly validate complex CSVs (NYC's 311 data) at almost 930,000 records/sec.
It's type inferences are also used by the `tojsonl` command to generate properly typed
JSONL files; the `frequency` command to short-circuit frequency table generation for columns
with all unique values; and the `schema` command to set the data type of a column and identify
low-cardinality columns for enum generation in the JSONschema.
To safeguard against undefined behavior, `stats` is the most extensively tested command,
with ~500 tests.
*/
use std::{
default::Default,
fmt, fs, io,
io::Write,
iter::repeat,
path::{Path, PathBuf},
str,
sync::OnceLock,
};
use crossbeam_channel;
use itertools::Itertools;
use qsv_dateparser::parse_with_preference;
use serde::{Deserialize, Serialize};
use simd_json::{prelude::ValueAsScalar, OwnedValue};
use smallvec::SmallVec;
use stats::{merge_all, Commute, MinMax, OnlineStats, Unsorted};
use tempfile::NamedTempFile;
use threadpool::ThreadPool;
use self::FieldType::{TDate, TDateTime, TFloat, TInteger, TNull, TString};
use crate::{
config::{get_delim_by_extension, Config, Delimiter},
select::{SelectColumns, Selection},
util, CliResult,
};
#[allow(clippy::unsafe_derive_deserialize)]
#[derive(Clone, Deserialize)]
pub struct Args {
pub arg_input: Option<String>,
pub flag_select: SelectColumns,
pub flag_everything: bool,
pub flag_typesonly: bool,
pub flag_infer_boolean: bool,
pub flag_mode: bool,
pub flag_cardinality: bool,
pub flag_median: bool,
pub flag_mad: bool,
pub flag_quartiles: bool,
pub flag_round: u32,
pub flag_nulls: bool,
pub flag_infer_dates: bool,
pub flag_dates_whitelist: String,
pub flag_prefer_dmy: bool,
pub flag_force: bool,
pub flag_jobs: Option<usize>,
pub flag_stats_jsonl: bool,
pub flag_cache_threshold: isize,
pub flag_output: Option<String>,
pub flag_no_headers: bool,
pub flag_delimiter: Option<Delimiter>,
pub flag_memcheck: bool,
}
// this struct is used to serialize/deserialize the stats to
// the "".stats.csv.json" file which we check to see
// if we can skip recomputing stats.
#[derive(Clone, Serialize, Deserialize, PartialEq, Default)]
struct StatsArgs {
arg_input: String,
flag_select: String,
flag_everything: bool,
flag_typesonly: bool,
flag_infer_boolean: bool,
flag_mode: bool,
flag_cardinality: bool,
flag_median: bool,
flag_mad: bool,
flag_quartiles: bool,
flag_round: u32,
flag_nulls: bool,
flag_infer_dates: bool,
flag_dates_whitelist: String,
flag_prefer_dmy: bool,
flag_no_headers: bool,
flag_delimiter: String,
flag_output_snappy: bool,
canonical_input_path: String,
canonical_stats_path: String,
record_count: u64,
date_generated: String,
compute_duration_ms: u64,
qsv_version: String,
}
impl StatsArgs {
// this is for deserializing the stats.csv.jsonl file
fn from_owned_value(value: &OwnedValue) -> Result<Self, Box<dyn std::error::Error>> {
Ok(Self {
arg_input: value["arg_input"].as_str().unwrap_or_default().to_string(),
flag_select: value["flag_select"]
.as_str()
.unwrap_or_default()
.to_string(),
flag_everything: value["flag_everything"].as_bool().unwrap_or_default(),
flag_typesonly: value["flag_typesonly"].as_bool().unwrap_or_default(),
flag_infer_boolean: value["flag_infer_boolean"].as_bool().unwrap_or_default(),
flag_mode: value["flag_mode"].as_bool().unwrap_or_default(),
flag_cardinality: value["flag_cardinality"].as_bool().unwrap_or_default(),
flag_median: value["flag_median"].as_bool().unwrap_or_default(),
flag_mad: value["flag_mad"].as_bool().unwrap_or_default(),
flag_quartiles: value["flag_quartiles"].as_bool().unwrap_or_default(),
flag_round: value["flag_round"].as_u64().unwrap_or_default() as u32,
flag_nulls: value["flag_nulls"].as_bool().unwrap_or_default(),
flag_infer_dates: value["flag_infer_dates"].as_bool().unwrap_or_default(),
flag_dates_whitelist: value["flag_dates_whitelist"]
.as_str()
.unwrap_or_default()
.to_string(),
flag_prefer_dmy: value["flag_prefer_dmy"].as_bool().unwrap_or_default(),
flag_no_headers: value["flag_no_headers"].as_bool().unwrap_or_default(),
flag_delimiter: value["flag_delimiter"]
.as_str()
.unwrap_or_default()
.to_string(),
flag_output_snappy: value["flag_output_snappy"].as_bool().unwrap_or_default(),
canonical_input_path: value["canonical_input_path"]
.as_str()
.unwrap_or_default()
.to_string(),
canonical_stats_path: value["canonical_stats_path"]
.as_str()
.unwrap_or_default()
.to_string(),
record_count: value["record_count"].as_u64().unwrap_or_default(),
date_generated: value["date_generated"]
.as_str()
.unwrap_or_default()
.to_string(),
compute_duration_ms: value["compute_duration_ms"].as_u64().unwrap_or_default(),
qsv_version: value["qsv_version"]
.as_str()
.unwrap_or_default()
.to_string(),
})
}
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct StatsData {
pub field: String,
// type is a reserved keyword in Rust
// so we escape it as r#type
// we need to do this for serde to work
pub r#type: String,
pub is_ascii: bool,
pub sum: Option<f64>,
pub min: Option<String>,
pub max: Option<String>,
pub range: Option<f64>,
pub sort_order: Option<String>,
pub min_length: Option<usize>,
pub max_length: Option<usize>,
pub sum_length: Option<usize>,
pub avg_length: Option<f64>,
pub mean: Option<f64>,
pub sem: Option<f64>,
pub stddev: Option<f64>,
pub variance: Option<f64>,
pub cv: Option<f64>,
pub nullcount: u64,
pub max_precision: Option<u32>,
pub sparsity: Option<f64>,
pub mad: Option<f64>,
pub lower_outer_fence: Option<f64>,
pub lower_inner_fence: Option<f64>,
pub q1: Option<f64>,
pub q2_median: Option<f64>,
pub q3: Option<f64>,
pub iqr: Option<f64>,
pub upper_inner_fence: Option<f64>,
pub upper_outer_fence: Option<f64>,
pub skewness: Option<f64>,
pub cardinality: u64,
pub mode: Option<String>,
pub mode_count: Option<u64>,
pub mode_occurrences: Option<u64>,
pub antimode: Option<String>,
pub antimode_count: Option<u64>,
pub antimode_occurrences: Option<u64>,
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum JsonTypes {
Int,
Float,
Bool,
String,
}
// we use this to serialize the StatsData data structure
// to a JSONL file using serde_json
const STATSDATA_TYPES_ARRAY: [JsonTypes; MAX_STAT_COLUMNS] = [
JsonTypes::String, //field
JsonTypes::String, //type
JsonTypes::Bool, //is_ascii
JsonTypes::Float, //sum
JsonTypes::String, //min
JsonTypes::String, //max
JsonTypes::Float, //range
JsonTypes::String, //sort_order
JsonTypes::Int, //min_length
JsonTypes::Int, //max_length
JsonTypes::Int, //sum_length
JsonTypes::Float, //avg_length
JsonTypes::Float, //mean
JsonTypes::Float, //sem
JsonTypes::Float, //stddev
JsonTypes::Float, //variance
JsonTypes::Float, //cv
JsonTypes::Int, //nullcount
JsonTypes::Int, //max_precision
JsonTypes::Float, //sparsity
JsonTypes::Float, //mad
JsonTypes::Float, //lower_outer_fence
JsonTypes::Float, //lower_inner_fence
JsonTypes::Float, //q1
JsonTypes::Float, //q2_median
JsonTypes::Float, //q3
JsonTypes::Float, //iqr
JsonTypes::Float, //upper_inner_fence
JsonTypes::Float, //upper_outer_fence
JsonTypes::Float, //skewness
JsonTypes::Int, //cardinality
JsonTypes::String, //mode
JsonTypes::Int, //mode_count
JsonTypes::Int, //mode_occurrences
JsonTypes::String, //antimode
JsonTypes::Int, //antimode_count
JsonTypes::Int, //antimode_occurrences
];
static INFER_DATE_FLAGS: OnceLock<SmallVec<[bool; 8]>> = OnceLock::new();
static RECORD_COUNT: OnceLock<u64> = OnceLock::new();
// standard overflow and underflow strings
// for sum, sum_length and avg_length
const OVERFLOW_STRING: &str = "*OVERFLOW*";
const UNDERFLOW_STRING: &str = "*UNDERFLOW*";
// number of milliseconds per day
const MS_IN_DAY: f64 = 86_400_000.0;
const MS_IN_DAY_INT: i64 = 86_400_000;
// number of decimal places when rounding days
// 5 decimal places give us millisecond precision
const DAY_DECIMAL_PLACES: u32 = 5;
// maximum number of output columns
const MAX_STAT_COLUMNS: usize = 37;
// maximum number of antimodes to display
const MAX_ANTIMODES: usize = 10;
// maximum length of antimode string before truncating and appending "..."
const MAX_ANTIMODE_LEN: usize = 100;
// we do this so this is evaluated at compile-time
pub const fn get_stats_data_types() -> [JsonTypes; MAX_STAT_COLUMNS] {
STATSDATA_TYPES_ARRAY
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let mut args: Args = util::get_args(USAGE, argv)?;
if args.flag_typesonly {
args.flag_everything = false;
args.flag_mode = false;
args.flag_cardinality = false;
args.flag_median = false;
args.flag_quartiles = false;
args.flag_mad = false;
}
// inferring boolean requires inferring cardinality
if args.flag_infer_boolean && !args.flag_cardinality {
args.flag_cardinality = true;
}
// check prefer_dmy env var
args.flag_prefer_dmy = args.flag_prefer_dmy || util::get_envvar_flag("QSV_PREFER_DMY");
// set stdout output flag
let stdout_output_flag = args.flag_output.is_none();
// save the current args, we'll use it to generate
// the stats.csv.json file
let mut current_stats_args = StatsArgs {
arg_input: format!("{:?}", args.arg_input),
flag_select: format!("{:?}", args.flag_select),
flag_everything: args.flag_everything,
flag_typesonly: args.flag_typesonly,
flag_infer_boolean: args.flag_infer_boolean,
flag_mode: args.flag_mode,
flag_cardinality: args.flag_cardinality,
flag_median: args.flag_median,
flag_mad: args.flag_mad,
flag_quartiles: args.flag_quartiles,
flag_round: args.flag_round,
flag_nulls: args.flag_nulls,
flag_infer_dates: args.flag_infer_dates,
flag_dates_whitelist: args.flag_dates_whitelist.clone(),
flag_prefer_dmy: args.flag_prefer_dmy,
flag_no_headers: args.flag_no_headers,
flag_delimiter: format!("{:?}", args.flag_delimiter.clone()),
// when we write to stdout, we don't use snappy compression
// when we write to a file with the --output option, we use
// snappy compression if the file ends with ".sz"
flag_output_snappy: if stdout_output_flag {
false
} else {
let p = args.flag_output.clone().unwrap();
p.to_ascii_lowercase().ends_with(".sz")
},
canonical_input_path: String::new(),
canonical_stats_path: String::new(),
record_count: 0,
date_generated: String::new(),
compute_duration_ms: 0,
// save the qsv version in the stats.csv.json file
// so cached stats are automatically invalidated
// when the qsv version changes
qsv_version: env!("CARGO_PKG_VERSION").to_string(),
};
// create a temporary file to store the <FILESTEM>.stats.csv file
let stats_csv_tempfile = if current_stats_args.flag_output_snappy {
tempfile::Builder::new().suffix(".sz").tempfile()?
} else {
NamedTempFile::new()?
};
// find the delimiter to use based on the extension of the output file
// and if we need to snappy compress the output
let (output_extension, output_delim, snappy) = if let Some(ref output_path) = args.flag_output {
get_delim_by_extension(Path::new(&output_path), b',')
} else {
(String::new(), b',', false)
};
let stats_csv_tempfile_fname = format!(
"{stem}.{prime_ext}{snappy_ext}",
//safety: we know the tempfile is a valid NamedTempFile, so we can use unwrap
stem = stats_csv_tempfile.path().to_str().unwrap(),
prime_ext = output_extension,
snappy_ext = if snappy { ".sz" } else { "" }
);
// we will write the stats to a temp file
let wconfig = Config::new(Some(stats_csv_tempfile_fname.clone()).as_ref())
.delimiter(Some(Delimiter(output_delim)));
let mut wtr = wconfig.writer()?;
let mut rconfig = args.rconfig();
let mut stdin_tempfile_path = None;
if rconfig.is_stdin() {
// read from stdin and write to a temp file
log::info!("Reading from stdin");
let mut stdin_file = NamedTempFile::new()?;
let stdin = std::io::stdin();
let mut stdin_handle = stdin.lock();
std::io::copy(&mut stdin_handle, &mut stdin_file)?;
drop(stdin_handle);
let (_file, tempfile_path) = stdin_file
.keep()
.or(Err("Cannot keep temporary file".to_string()))?;
stdin_tempfile_path = Some(tempfile_path.clone());
args.arg_input = Some(tempfile_path.to_string_lossy().to_string());
rconfig.path = Some(tempfile_path);
} else {
// check if the input file exists
if let Some(path) = rconfig.path.clone() {
if !path.exists() {
return fail_clierror!("File {:?} does not exist", path.display());
}
}
}
let mut compute_stats = true;
let mut create_cache = args.flag_cache_threshold > 0 || args.flag_stats_jsonl;
let mut autoindex_set = false;
let write_stats_jsonl = args.flag_stats_jsonl;
if let Some(path) = rconfig.path.clone() {
//safety: we know the path is a valid PathBuf, so we can use unwrap
let path_file_stem = path.file_stem().unwrap().to_str().unwrap();
let stats_file = stats_path(&path, false)?;
// check if <FILESTEM>.stats.csv file already exists.
// If it does, check if it was compiled using the same args.
// However, if the --force flag is set,
// recompute the stats even if the args are the same.
if stats_file.exists() && !args.flag_force {
let stats_args_json_file = stats_file.with_extension("csv.json");
let existing_stats_args_json_str =
match fs::read_to_string(stats_args_json_file.clone()) {
Ok(s) => s,
Err(e) => {
log::warn!(
"Could not read {path_file_stem}.stats.csv.json: {e:?}, recomputing..."
);
fs::remove_file(&stats_file)?;
fs::remove_file(&stats_args_json_file)?;
String::new()
},
};
let time_saved: u64;
// deserialize the existing stats args json
let existing_stats_args_json: StatsArgs = {
let mut json_buffer = existing_stats_args_json_str.into_bytes();
match simd_json::to_owned_value(&mut json_buffer) {
Ok(value) => {
// Convert OwnedValue to StatsArgs
match StatsArgs::from_owned_value(&value) {
Ok(mut stat_args) => {
// we init these fields to empty values because we don't want to
// compare them when checking if the
// args are the same
stat_args.canonical_input_path = String::new();
stat_args.canonical_stats_path = String::new();
stat_args.record_count = 0;
stat_args.date_generated = String::new();
time_saved = stat_args.compute_duration_ms;
stat_args.compute_duration_ms = 0;
stat_args
},
Err(e) => {
time_saved = 0;
log::warn!(
"Could not deserialize {path_file_stem}.stats.csv.json: \
{e:?}, recomputing..."
);
fs::remove_file(&stats_file)?;
fs::remove_file(&stats_args_json_file)?;
StatsArgs::default()
},
}
},
Err(e) => {
time_saved = 0;
log::warn!(
"Could not parse {path_file_stem}.stats.csv.json: {e:?}, \
recomputing..."
);
fs::remove_file(&stats_file)?;
fs::remove_file(&stats_args_json_file)?;
StatsArgs::default()
},
}
};
// check if the cached stats are current (ie the stats file is newer than the input
// file), use the same args or if the --everything flag was set, and
// all the other non-stats args are equal. If so, we don't need to recompute the stats
let input_file_modified = fs::metadata(&path)?.modified()?;
let stats_file_modified = fs::metadata(&stats_file)?.modified()?;
#[allow(clippy::nonminimal_bool)]
if stats_file_modified > input_file_modified
&& (existing_stats_args_json == current_stats_args
|| existing_stats_args_json.flag_everything
&& existing_stats_args_json.flag_infer_dates
== current_stats_args.flag_infer_dates
&& existing_stats_args_json.flag_dates_whitelist
== current_stats_args.flag_dates_whitelist
&& existing_stats_args_json.flag_prefer_dmy
== current_stats_args.flag_prefer_dmy
&& existing_stats_args_json.flag_no_headers
== current_stats_args.flag_no_headers
&& existing_stats_args_json.flag_dates_whitelist
== current_stats_args.flag_dates_whitelist
&& existing_stats_args_json.flag_delimiter
== current_stats_args.flag_delimiter
&& existing_stats_args_json.flag_nulls == current_stats_args.flag_nulls
&& existing_stats_args_json.qsv_version == current_stats_args.qsv_version)
{
log::info!(
"{path_file_stem}.stats.csv already exists and is current. Skipping compute \
and using cached stats instead - {time_saved} secs saved...",
);
compute_stats = false;
} else {
log::info!(
"{path_file_stem}.stats.csv already exists, but is older than the input file \
or the args have changed, recomputing...",
);
fs::remove_file(&stats_file)?;
}
}
if compute_stats {
let start_time = std::time::Instant::now();
// we're loading the entire file into memory, we need to check avail mem
if args.flag_everything
|| args.flag_mode
|| args.flag_cardinality
|| args.flag_median
|| args.flag_quartiles
|| args.flag_mad
{
util::mem_file_check(&path, false, args.flag_memcheck)?;
}
// check if flag_cache_threshold is a negative number,
// if so, set the autoindex_size to absolute of the number
if args.flag_cache_threshold.is_negative() {
rconfig.autoindex_size = args.flag_cache_threshold.unsigned_abs() as u64;
autoindex_set = true;
}
// we need to count the number of records in the file to calculate sparsity
// safety: we know util::count_rows() will not return an Err, so we can use unwrap
let record_count = RECORD_COUNT.get_or_init(|| util::count_rows(&rconfig).unwrap());
// log::info!("scanning {record_count} records...");
let (headers, stats) = match rconfig.indexed()? {
None => args.sequential_stats(&args.flag_dates_whitelist),
Some(idx) => {
let idx_count = idx.count();
if let Some(num_jobs) = args.flag_jobs {
if num_jobs == 1 {
args.sequential_stats(&args.flag_dates_whitelist)
} else {
args.parallel_stats(&args.flag_dates_whitelist, idx_count)
}
} else {
args.parallel_stats(&args.flag_dates_whitelist, idx_count)
}
},
}?;
let stats_sr_vec = args.stats_to_records(stats);
let stats_headers_sr = args.stat_headers();
wtr.write_record(&stats_headers_sr)?;
let fields = headers.iter().zip(stats_sr_vec);
for (i, (header, stat)) in fields.enumerate() {
let header = if args.flag_no_headers {
i.to_string().into_bytes()
} else {
header.to_vec()
};
let stat = stat.iter().map(str::as_bytes);
wtr.write_record(vec![&*header].into_iter().chain(stat))?;
}
// update the stats args json metadata
current_stats_args.compute_duration_ms = start_time.elapsed().as_millis() as u64;
if create_cache
&& current_stats_args.compute_duration_ms > args.flag_cache_threshold as u64
{
// if the stats run took longer than the cache threshold and the threshold > 0,
// cache the stats so we don't have to recompute it next time
// safety: we know the path is a valid PathBuf, so we can use unwrap
current_stats_args.canonical_input_path =
path.canonicalize()?.to_str().unwrap().to_string();
current_stats_args.record_count = *record_count;
current_stats_args.date_generated = chrono::Utc::now().to_rfc3339();
}
}
}
// ensure create_cache is also true if the user specified --cache-threshold 1
create_cache =
create_cache || args.flag_cache_threshold == 1 || args.flag_cache_threshold.is_negative();
wtr.flush()?;
if let Some(pb) = stdin_tempfile_path {
// remove the temp file we created to store stdin
std::fs::remove_file(pb)?;
}
let currstats_filename = if compute_stats {
// we computed the stats, use the stats temp file
stats_csv_tempfile_fname
} else {
// we didn't compute the stats, re-use the existing stats file
// safety: we know the path is a valid PathBuf, so we can use unwrap
stats_path(rconfig.path.as_ref().unwrap(), false)?
.to_str()
.unwrap()
.to_owned()
};
if rconfig.is_stdin() {
// if we read from stdin, copy the temp stats file to "stdin.stats.csv"
// safety: we know the path is a valid PathBuf, so we can use unwrap
let mut stats_pathbuf = stats_path(rconfig.path.as_ref().unwrap(), true)?;
fs::copy(currstats_filename.clone(), stats_pathbuf.clone())?;
// save the stats args to "stdin.stats.csv.json"
stats_pathbuf.set_extension("csv.json");
std::fs::write(
stats_pathbuf,
serde_json::to_string_pretty(¤t_stats_args)?,
)?;
} else if let Some(path) = rconfig.path {
// if we read from a file, copy the temp stats file to "<FILESTEM>.stats.csv"
let mut stats_pathbuf = path.clone();
stats_pathbuf.set_extension("stats.csv");
// safety: we know the path is a valid PathBuf, so we can use unwrap
if currstats_filename != stats_pathbuf.to_str().unwrap() {
// if the stats file is not the same as the input file, copy it
fs::copy(currstats_filename.clone(), stats_pathbuf.clone())?;
}
if args.flag_cache_threshold.is_negative() && args.flag_cache_threshold % 10 == -5 {
// if the cache threshold is a negative number ending in 5,
// delete both the index file and the stats cache file
if autoindex_set {
let index_file = path.with_extension("csv.idx");
log::debug!("deleting index file: {}", index_file.display());
if std::fs::remove_file(index_file.clone()).is_err() {
// fails silently if it can't remove the index file
log::warn!("Could not remove index file: {}", index_file.display());
}
}
create_cache = false;
}
if !create_cache {
// remove the stats cache file
if fs::remove_file(stats_pathbuf.clone()).is_err() {
// fails silently if it can't remove the stats file
log::warn!(
"Could not remove stats cache file: {}",
stats_pathbuf.display()
);
}
}
if compute_stats && create_cache {
// save the stats args to "<FILESTEM>.stats.csv.json"
// if we computed the stats
stats_pathbuf.set_extension("csv.json");
// write empty file first so we can canonicalize it
std::fs::File::create(stats_pathbuf.clone())?;
// safety: we know the path is a valid PathBuf, so we can use unwrap
current_stats_args.canonical_stats_path = stats_pathbuf
.clone()
.canonicalize()?
.to_str()
.unwrap()
.to_string();
std::fs::write(
stats_pathbuf.clone(),
serde_json::to_string_pretty(¤t_stats_args)?,
)?;
// save the stats data to "<FILESTEM>.stats.csv.data.jsonl"
if write_stats_jsonl {
stats_pathbuf.set_extension("data.jsonl");
util::csv_to_jsonl(&currstats_filename, &get_stats_data_types(), stats_pathbuf)?;
}
}
}
if stdout_output_flag {
// if we're outputting to stdout, copy the stats file to stdout
let currstats = fs::read_to_string(currstats_filename)?;
io::stdout().write_all(currstats.as_bytes())?;
io::stdout().flush()?;
} else if let Some(output) = args.flag_output {
// if we're outputting to a file, copy the stats file to the output file
if currstats_filename != output {
// if the stats file is not the same as the output file, copy it
fs::copy(currstats_filename, output)?;
}
}
Ok(())
}
impl Args {
fn sequential_stats(&self, whitelist: &str) -> CliResult<(csv::ByteRecord, Vec<Stats>)> {
let mut rdr = self.rconfig().reader()?;
let (headers, sel) = self.sel_headers(&mut rdr)?;
init_date_inference(self.flag_infer_dates, &headers, whitelist)?;
let stats = self.compute(&sel, rdr.byte_records());
Ok((headers, stats))
}
fn parallel_stats(
&self,
whitelist: &str,
idx_count: u64,
) -> CliResult<(csv::ByteRecord, Vec<Stats>)> {
// N.B. This method doesn't handle the case when the number of records
// is zero correctly. So we use `sequential_stats` instead.
if idx_count == 0 {
return self.sequential_stats(whitelist);
}
let mut rdr = self.rconfig().reader()?;
let (headers, sel) = self.sel_headers(&mut rdr)?;
init_date_inference(self.flag_infer_dates, &headers, whitelist)?;
let njobs = util::njobs(self.flag_jobs);
let chunk_size = util::chunk_size(idx_count as usize, njobs);
let nchunks = util::num_of_chunks(idx_count as usize, chunk_size);
let pool = ThreadPool::new(njobs);
let (send, recv) = crossbeam_channel::bounded(0);
for i in 0..nchunks {
let (send, args, sel) = (send.clone(), self.clone(), sel.clone());
pool.execute(move || {
// safety: indexed() is safe as we know we have an index file
// if it does return an Err, you have a bigger problem as the index file was
// modified WHILE stats is running and you NEED to abort if that
// happens, however unlikely
let mut idx = unsafe {
args.rconfig()
.indexed()
.unwrap_unchecked()
.unwrap_unchecked()
};
idx.seek((i * chunk_size) as u64)
.expect("File seek failed.");
let it = idx.byte_records().take(chunk_size);
// safety: this will only return an Error if the channel has been disconnected
unsafe {
send.send(args.compute(&sel, it)).unwrap_unchecked();
}
});
}
drop(send);
Ok((headers, merge_all(recv.iter()).unwrap_or_default()))
}
fn stats_to_records(&self, stats: Vec<Stats>) -> Vec<csv::StringRecord> {
let round_places = self.flag_round;
let infer_boolean = self.flag_infer_boolean;
let mut records = Vec::with_capacity(stats.len());
records.extend(repeat(csv::StringRecord::new()).take(stats.len()));
let pool = ThreadPool::new(util::njobs(self.flag_jobs));
let mut results = Vec::with_capacity(stats.len());
for mut stat in stats {
let (send, recv) = crossbeam_channel::bounded(0);
results.push(recv);
pool.execute(move || {
// safety: this will only return an Error if the channel has been disconnected
// which will not happen in this case
send.send(stat.to_record(round_places, infer_boolean))
.unwrap();
});
}
for (i, recv) in results.into_iter().enumerate() {
// safety: results.len() == records.len() so we know the index is valid
// and doesn't require a bounds check.
// The unwrap on recv.recv() is safe as the channel is bounded
unsafe {
*records.get_unchecked_mut(i) = recv.recv().unwrap();
}
}
records
}