-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathstats.rs
More file actions
4744 lines (4374 loc) · 200 KB
/
stats.rs
File metadata and controls
4744 lines (4374 loc) · 200 KB
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.
> IMPORTANT: `stats` is heavily optimized for speed. It ASSUMES the CSV is well-formed & UTF-8 encoded.
> This allows it to employ numerous performance optimizations (skip repetitive UTF-8 validation, skip
> bounds checks, cache results, etc.) that may result in undefined behavior if the CSV is not well-formed.
> All these optimizations are GUARANTEED to work with well-formed CSVs.
> If you encounter problems generating stats, use `qsv validate` FIRST to confirm the CSV is valid.
> For MAXIMUM PERFORMANCE, create an index for the CSV first with 'qsv index' to enable multithreading,
> or set --cache-threshold option or set the QSV_AUTOINDEX_SIZE environment variable to automatically
> create an index when the file size is greater than the specified size (in bytes).
Summary stats include sum, min/max/range, sort order/sortiness, min/max/sum/avg/stddev/variance/cv length,
mean, standard error of the mean (SEM), geometric mean, harmonic mean, stddev, variance, coefficient of
variation (CV), nullcount, n_negative, n_zero, n_positive, max_precision, sparsity,
Median Absolute Deviation (MAD), quartiles, lower/upper inner/outer fences, skewness, median,
cardinality/uniqueness ratio, mode/s & "antimode/s" & percentiles.
Note that some stats 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/"sortiness", min/max/sum/avg/stddev/variance/cv length, mean, sem,
geometric_mean, harmonic_mean,stddev, variance, cv, nullcount, n_negative, n_zero, n_positive,
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, advanced" statistics require loading the entire file into memory:
cardinality/uniqueness ratio, modes/antimodes, median, MAD, quartiles and its related measures
(q1, q2, q3, IQR, lower/upper fences & skewness) and percentiles.
When computing "non-streaming" statistics, a memory-aware chunking algorithm is used to dynamically
calculate chunk size based on available memory & record sampling. This SHOULD help process arbitrarily
large "real-world" files by creating smaller chunks that fit in available memory.
However, there is still a chance that the command will run out of memory if the cardinality of
several columns is very high.
Chunk size is dynamically calculated based on the number of logical CPUs detected.
You can override this behavior by setting the QSV_STATS_CHUNK_MEMORY_MB environment variable
(set to 0 for dynamic sizing, or a positive number for a fixed memory limit per chunk,
or -1 for CPU-based chunking (1 chunk = records/number of CPUs)).
"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, truncating after 100 characters (configurable with QSV_ANTIMODES_LEN).
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/dathere/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 chunks
and each chunk is processed in parallel.
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 `describegpt`, `frequency`,
`joinp`, `pivotp`, `schema`, `sqlp` & `tojsonl`) to work smarter & 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.
Examples:
# Compute "streaming" statistics for "nyc311.csv"
qsv stats nyc311.csv
# Compute all statistics for "nyc311.csv"
qsv stats --everything nyc311.csv
# Compute all statistics for "nyc311.tsv" (Tab-separated)
qsv stats -E nyc311.tsv
# Compute all stats for "nyc311.tsv", inferring dates using sniff to auto-detect date columns
qsv stats -E --infer-dates nyc311.tsv
# Compute all stats for "nyc311.tab", inferring dates only for columns
# with "_date" & "_dte" in the column names
qsv stats -E --infer-dates --dates-whitelist _date,_dte nyc311.tab
# Compute all stats, infer dates and boolean data types for "nyc311.ssv" file
qsv stats -E --infer-dates --infer-boolean nyc311.ssv
# In addition to basic "streaming" stats, also compute cardinality for "nyc311.csv"
qsv stats --cardinality nyc311.csv
# Prefer DMY format when inferring dates for the "nyc311.csv"
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 "nyc311.csv"
$ qsv stats --typesonly --infer-boolean --infer-dates nyc311.csv
# Automatically create an index for the "nyc311.csv" file to enable multithreading
# if it's larger than 5MB and there is no existing index file:
qsv stats -E --cache-threshold -5000000 nyc311.csv
# Auto-create a TEMPORARY index for the "nyc311.csv" file to enable multithreading
# 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
For more examples, see https://github.com/dathere/qsv/tree/master/resources/test
If the polars feature is enabled, support additional tabular file formats and
compression formats:
$ qsv stats data.parquet // Parquet
$ qsv stats data.avro // Avro
$ qsv stats data.jsonl // JSON Lines
$ qsv stats data.json (will only work with a JSON Array)
$ qsv stats data.csv.gz // Gzipped CSV
$ qsv stats data.tab.zlib // Zlib-compressed Tab-separated
$ qsv stats data.ssv.zst // Zstd-compressed Semicolon-separated
For more info, see https://github.com/dathere/qsv/blob/master/docs/STATS_DEFINITIONS.md
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 and boolean types, you'll
still need to use the --infer-dates & --infer-boolean options.
BOOLEAN INFERENCING:
--infer-boolean Infer boolean data type. This automatically enables
the --cardinality option. When a column's cardinality is 2,
and the 2 values' are in the true/false patterns specified
by --boolean-patterns, the data type is inferred as boolean.
--boolean-patterns <arg> Comma-separated list of boolean pattern pairs in the format
"true_pattern:false_pattern". Each pattern can be a string
of any length. The patterns are case-insensitive. If a pattern
ends with a "*", it is treated as a prefix. For example,
"t*:f*,y*:n*" will match "true", "truthy", "Truth" as boolean true
values so long as the corresponding false pattern (e.g. False, f, etc.)
is also matched & cardinality is 2. Ignored if --infer-boolean is false.
[default: 1:0,t*:f*,y*:n*]
--mode Compute the mode/s & antimode/s. Multimodal-aware.
If there are multiple modes/antimodes, they are separated by the
QSV_STATS_SEPARATOR environment variable. If not set, the default
separator is "|".
Uses memory proportional to the cardinality of each column.
--cardinality Compute the cardinality and the uniqueness ratio.
This is automatically enabled if --infer-boolean is enabled.
https://en.wikipedia.org/wiki/Cardinality_(SQL_statements)
Uses memory proportional to the number of unique values in each column.
NUMERIC & DATE/DATETIME STATS THAT REQUIRE IN-MEMORY SORTING:
The following statistics are only computed for numeric & date/datetime
columns & require loading & sorting ALL the selected columns' data
in memory FIRST before computing the statistics.
--median Compute the median.
Loads & sorts all the selected columns' data in memory.
https://en.wikipedia.org/wiki/Median
--mad Compute the median absolute deviation (MAD).
https://en.wikipedia.org/wiki/Median_absolute_deviation
--quartiles Compute the quartiles (using method 3), the IQR, the lower/upper,
inner/outer fences and skewness.
https://en.wikipedia.org/wiki/Quartile#Method_3
--percentiles Compute custom percentiles using the nearest rank method.
https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method
--percentile-list <arg> Comma-separated list of percentiles to compute.
For example, "5,10,40,60,90,95" will compute percentiles
5th, 10th, 40th, 60th, 90th, and 95th.
Multiple percentiles are separated by the QSV_STATS_SEPARATOR
environment variable. If not set, the default separator is "|".
It is ignored if --percentiles is not set.
Special values "deciles" and "quintiles" are automatically expanded
to "10,20,30,40,50,60,70,80,90" and "20,40,60,80" respectively.
[default: 5,10,40,60,90,95]
--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.
--weight <column> Compute weighted statistics using the specified column as weights.
The weight column must be numeric. When specified, all statistics
(mean, stddev, variance, median, quartiles, mode, etc.) will be
computed using weighted algorithms. The weight column is automatically
excluded from statistics computation. Missing or non-numeric weights
default to 1.0. Zero and negative weights are ignored and do not
contribute to the statistics. The output filename will be
<FILESTEM>.stats.weighted.csv to distinguish from unweighted statistics.
DATE INFERENCING:
--infer-dates Infer date/datetime data types. 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 comma-separated, 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.
Special values:
* "all" - inspect ALL fields for date/datetime types
* "sniff" - use `qsv sniff` to auto-detect date/datetime columns
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.
When set to "sniff", we do two-stage date inferencing.
First running sniff on the input file and then second,
only inferring dates for the columns that sniff identifies
as date/datetime candidates.
This is much faster than "all", and more convenient than
manually specifying patterns in the whitelist.
[default: sniff]
--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 "smart" commands (see
https://github.com/dathere/qsv/blob/master/docs/PERFORMANCE.md#stats-cache)
to load cached stats to make them work smarter & faster.
You can preemptively create the stats-jsonl file by using this option
BEFORE running "smart" commands and they will automatically use it.
-c, --cache-threshold <arg> Controls the creation of stats cache files.
* 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.
* 0 to suppress caching.
* 1 to force caching.
* 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]
--vis-whitespace Visualize whitespace characters in the output.
See https://github.com/dathere/qsv/wiki/Supplemental#whitespace-markers
for the list of whitespace markers.
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 JSON Schema based on a CSV's summary statistics; and use the generated JSON Schema
to quickly validate complex CSVs hundreds of thousands of records/sec.
It's type inferences are also used by the "smart" commands (see
https://github.com/dathere/qsv/blob/master/docs/PERFORMANCE.md#stats-cache)
to make them work smarter & faster.
To safeguard against undefined behavior, `stats` is the most extensively tested command,
with ~625 tests. It also employs numerous performance optimizations (skip repetitive UTF-8
validation, skip bounds checks, cache results, etc.) that may result in undefined behavior
if the CSV is not well-formed. See "safety:" comments in the code for more details.
*/
use std::{
fmt, fs,
io::{self, BufRead, Seek, Write},
iter::repeat_n,
path::{Path, PathBuf},
str,
sync::{Arc, OnceLock},
};
use blake3;
use crossbeam_channel;
use foldhash::{HashMap, HashMapExt};
use itertools::Itertools;
use phf::phf_map;
use qsv_dateparser::parse_with_preference;
use rayon::slice::ParallelSliceMut;
use serde::{Deserialize, Serialize};
// Use serde_json on big-endian platforms (e.g. s390x) due to simd_json endianness issues
#[cfg(target_endian = "little")]
use simd_json::{OwnedValue, prelude::ValueAsScalar, prelude::ValueObjectAccess};
use smallvec::SmallVec;
use stats::{Commute, MinMax, OnlineStats, Unsorted, merge_all};
use tempfile::Builder as TempFileBuilder;
use threadpool::ThreadPool;
use self::FieldType::{TDate, TDateTime, TFloat, TInteger, TNull, TString};
use crate::{
CliError, CliResult,
config::{Config, Delimiter, get_delim_by_extension},
select::{SelectColumns, Selection},
util,
};
#[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_boolean_patterns: String,
pub flag_mode: bool,
pub flag_cardinality: bool,
pub flag_median: bool,
pub flag_mad: bool,
pub flag_quartiles: bool,
pub flag_percentiles: bool,
pub flag_percentile_list: String,
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,
pub flag_vis_whitespace: bool,
pub flag_weight: Option<String>,
}
// 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_percentiles: bool,
flag_percentile_list: String,
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,
flag_weight: String,
field_count: u64,
filesize_bytes: u64,
hash: FileHash,
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Default)]
struct FileHash {
#[serde(rename = "BLAKE3", skip_serializing_if = "String::is_empty")]
blake3: String,
}
#[cfg(target_endian = "little")]
impl StatsArgs {
// this is for deserializing the stats.csv.jsonl file
// we use .get() instead of [] indexing to avoid panics on missing keys
// (e.g. when reading older cache files that don't have newer fields like flag_weight)
fn from_owned_value(value: &OwnedValue) -> Result<Self, Box<dyn std::error::Error>> {
// helper closures for safe access - returns default if key is missing
let get_str = |key: &str| -> String {
value
.get(key)
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string()
};
let get_str_or = |key: &str, default: &str| -> String {
value
.get(key)
.and_then(|v| v.as_str())
.unwrap_or(default)
.to_string()
};
let get_bool = |key: &str| -> bool {
value
.get(key)
.and_then(simd_json::prelude::ValueAsScalar::as_bool)
.unwrap_or_default()
};
let get_u64 = |key: &str| -> u64 {
value
.get(key)
.and_then(simd_json::prelude::ValueAsScalar::as_u64)
.unwrap_or_default()
};
let get_hash = || -> FileHash {
value
.get("hash")
.map(|h| FileHash {
blake3: h
.get("BLAKE3")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
})
.unwrap_or_default()
};
Ok(Self {
arg_input: get_str("arg_input"),
flag_select: get_str("flag_select"),
flag_everything: get_bool("flag_everything"),
flag_typesonly: get_bool("flag_typesonly"),
flag_infer_boolean: get_bool("flag_infer_boolean"),
flag_mode: get_bool("flag_mode"),
flag_cardinality: get_bool("flag_cardinality"),
flag_median: get_bool("flag_median"),
flag_mad: get_bool("flag_mad"),
flag_quartiles: get_bool("flag_quartiles"),
flag_percentiles: get_bool("flag_percentiles"),
flag_percentile_list: get_str_or("flag_percentile_list", "5,10,40,60,90,95"),
flag_round: get_u64("flag_round") as u32,
flag_nulls: get_bool("flag_nulls"),
flag_infer_dates: get_bool("flag_infer_dates"),
flag_dates_whitelist: get_str("flag_dates_whitelist"),
flag_prefer_dmy: get_bool("flag_prefer_dmy"),
flag_no_headers: get_bool("flag_no_headers"),
flag_delimiter: get_str("flag_delimiter"),
flag_output_snappy: get_bool("flag_output_snappy"),
canonical_input_path: get_str("canonical_input_path"),
canonical_stats_path: get_str("canonical_stats_path"),
record_count: get_u64("record_count"),
date_generated: get_str("date_generated"),
compute_duration_ms: get_u64("compute_duration_ms"),
qsv_version: get_str("qsv_version"),
flag_weight: get_str("flag_weight"),
field_count: get_u64("field_count"),
filesize_bytes: get_u64("filesize_bytes"),
hash: get_hash(),
})
}
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Default, Debug)]
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,
#[serde(default)]
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 stddev_length: Option<f64>,
pub variance_length: Option<f64>,
pub cv_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 n_negative: Option<u64>,
pub n_zero: Option<u64>,
pub n_positive: Option<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 uniqueness_ratio: Option<f64>,
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
pub static STATSDATA_TYPES_MAP: phf::Map<&'static str, JsonTypes> = phf_map! {
"field" => JsonTypes::String,
"type" => JsonTypes::String,
"is_ascii" => JsonTypes::Bool,
"sum" => JsonTypes::Float,
"min" => JsonTypes::String,
"max" => JsonTypes::String,
"range" => JsonTypes::Float,
"sort_order" => JsonTypes::String,
"sortiness" => JsonTypes::Float,
"min_length" => JsonTypes::Int,
"max_length" => JsonTypes::Int,
"sum_length" => JsonTypes::Int,
"avg_length" => JsonTypes::Float,
"stddev_length" => JsonTypes::Float,
"variance_length" => JsonTypes::Float,
"cv_length" => JsonTypes::Float,
"mean" => JsonTypes::Float,
"sem" => JsonTypes::Float,
"geometric_mean" => JsonTypes::Float,
"harmonic_mean" => JsonTypes::Float,
"stddev" => JsonTypes::Float,
"variance" => JsonTypes::Float,
"cv" => JsonTypes::Float,
"nullcount" => JsonTypes::Int,
"n_negative" => JsonTypes::Int,
"n_zero" => JsonTypes::Int,
"n_positive" => JsonTypes::Int,
"max_precision" => JsonTypes::Int,
"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::Float,
"cardinality" => JsonTypes::Int,
"uniqueness_ratio" => JsonTypes::Float,
"mode" => JsonTypes::String,
"mode_count" => JsonTypes::Int,
"mode_occurrences" => JsonTypes::Int,
"antimode" => JsonTypes::String,
"antimode_count" => JsonTypes::Int,
"antimode_occurrences" => JsonTypes::Int,
};
static INFER_DATE_FLAGS: OnceLock<SmallVec<[bool; 50]>> = OnceLock::new();
static RECORD_COUNT: OnceLock<u64> = OnceLock::new();
static ANTIMODES_LEN: OnceLock<usize> = OnceLock::new();
static STATS_SEPARATOR: OnceLock<String> = OnceLock::new();
static STATS_STRING_MAX_LENGTH: OnceLock<Option<usize>> = 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 = 47;
// the first N columns are fingerprint hash columns
const FINGERPRINT_HASH_COLUMNS: usize = 26;
// maximum number of antimodes to display
const MAX_ANTIMODES: usize = 10;
// default length of antimode string before truncating and appending "..."
const DEFAULT_ANTIMODES_LEN: usize = 100;
// the default separator we use for stats that have multiple values
// in one column, i.e. antimodes/modes & percentiles
pub const DEFAULT_STATS_SEPARATOR: &str = "|";
// the threshold for when to use parallel sorting for modes/antimodes etc.
const PAR_SORT_THRESHOLD: usize = 10_000;
static BOOLEAN_PATTERNS: OnceLock<Vec<BooleanPattern>> = OnceLock::new();
#[derive(Clone, Debug)]
/// Represents a pattern for boolean value inference in CSV data.
///
/// This struct defines patterns that can be used to identify boolean values in CSV columns.
/// It supports both exact matches and prefix matching with wildcards for flexible boolean
/// detection during CSV statistics computation.
///
/// # Fields
///
/// * `true_pattern` - The pattern that identifies `true` values (case-insensitive)
/// * `false_pattern` - The pattern that identifies `false` values (case-insensitive)
///
/// # Pattern Matching
///
/// Patterns support two types of matching:
/// * **Exact match**: The value must exactly match the pattern (case-insensitive)
/// * **Prefix match**: If the pattern ends with `*`, it matches any value that starts with the
/// prefix (e.g., `"yes*"` matches `"yes"`, `"yes please"`, `"YES"`, etc.)
struct BooleanPattern {
true_pattern: String,
false_pattern: String,
}
impl BooleanPattern {
/// Checks if a value matches the boolean pattern.
///
/// This method determines whether a given string value matches either the true or false
/// pattern defined in this `BooleanPattern`. The matching is case-insensitive and supports
/// both exact matches and prefix matching with wildcards.
///
/// # Arguments
///
/// * `value` - The string value to check against the boolean patterns
///
/// # Returns
///
/// * `Some(true)` - If the value matches the true pattern
/// * `Some(false)` - If the value matches the false pattern
/// * `None` - If the value doesn't match either pattern
///
/// # Matching Logic
///
/// 1. **Exact match**: The value is compared directly to both patterns (case-insensitive)
/// 2. **Prefix match**: If a pattern ends with `*`, the value is checked if it starts with the
/// prefix (excluding the `*` character)
/// 3. **Priority**: Exact matches are checked before prefix matches for better performance
fn matches(&self, value: &str) -> Option<bool> {
let value_lower = value.to_lowercase();
// Check for exact match first
if value_lower == self.true_pattern {
return Some(true);
} else if value_lower == self.false_pattern {
return Some(false);
}
// Check for prefix match if pattern ends with "*"
if self.true_pattern.ends_with('*') {
let prefix = &self.true_pattern[..self.true_pattern.len() - 1];
if value_lower.starts_with(prefix) {
return Some(true);
}
}
if self.false_pattern.ends_with('*') {
let prefix = &self.false_pattern[..self.false_pattern.len() - 1];
if value_lower.starts_with(prefix) {
return Some(false);
}
}
None
}
}
/// Parses a comma-separated string of boolean patterns into a vector of `BooleanPattern` structs.
///
/// This function takes a string containing boolean pattern pairs and converts them into
/// `BooleanPattern` objects that can be used for boolean value inference in CSV data.
///
/// # Arguments
///
/// * `boolean_patterns` - A comma-separated string of pattern pairs in the format `"true:false"`
///
/// # Format
///
/// The input string should contain pattern pairs separated by commas, where each pair
/// consists of a true pattern and false pattern separated by a colon:
/// `"true_pattern1:false_pattern1,true_pattern2:false_pattern2"`
///
/// # Returns
///
/// * `Ok(Vec<BooleanPattern>)` - Vector of parsed boolean patterns
/// * `Err(CliError)` - If the format is invalid or patterns are empty
///
/// # Errors
///
/// * Returns an error if any pattern pair is missing the colon separator
/// * Returns an error if either the true or false pattern is empty
/// * Returns an error if no patterns are provided
fn parse_boolean_patterns(boolean_patterns: &str) -> CliResult<Vec<BooleanPattern>> {
let mut patterns = Vec::new();
for pair in boolean_patterns.split(',') {
let mut parts = pair.split(':');
let true_pattern = parts.next().unwrap_or("").trim().to_lowercase();
let false_pattern = parts.next().unwrap_or("").trim().to_lowercase();
if true_pattern.is_empty() || false_pattern.is_empty() {
return fail_incorrectusage_clierror!("Invalid boolean pattern: {pair}");
}
patterns.push(BooleanPattern {
true_pattern,
false_pattern,
});
}
if patterns.is_empty() {
return fail_incorrectusage_clierror!("Boolean patterns must have at least one pattern");
}
Ok(patterns)
}
/// Main entry point for the stats command.
///
/// This function orchestrates the entire CSV statistics computation process, including
/// argument parsing, configuration setup, data processing, and output generation.
/// It handles both sequential and parallel processing approaches based on the dataset size
/// and available system resources.
///
/// # Arguments
///
/// * `argv` - Command line arguments as string slices
///
/// # Returns
///
/// * `Ok(())` - Successfully completed statistics computation
/// * `Err(CliError)` - If there's an error during processing
///
/// # Process Overview
///
/// 1. **Argument Parsing**: Parses command line arguments and validates configuration
/// 2. **Boolean Inference Setup**: Configures boolean pattern matching if enabled
/// 3. **Environment Variables**: Checks for QSV_PREFER_DMY environment variable
/// 4. **Output Configuration**: Determines output format and compression settings
/// 5. **Statistics Computation**: Processes CSV data using sequential or parallel approach
/// 6. **Cache Management**: Handles statistics caching and cache invalidation
/// 7. **Output Generation**: Writes results to stdout or specified output file
/// 8. **Cleanup**: Removes temporary files and handles cleanup operations
///
/// # Features
///
/// * **Type Inference**: Automatically detects data types (numeric, string, date, boolean)
/// * **Date Inference**: Configurable date pattern recognition
/// * **Boolean Inference**: Pattern-based boolean value detection
/// * **Parallel Processing**: Multi-threaded computation for large datasets
/// * **Caching**: Intelligent caching of computed statistics
/// * **Multiple Output Formats**: CSV, JSON, and compressed formats
/// * **Comprehensive Statistics**: Mean, median, quartiles, mode, cardinality, etc.
///
/// # Error Handling
///
/// * Validates input file existence and format
/// * Handles CSV parsing errors gracefully
/// * Manages temporary file creation and cleanup
/// * Provides detailed error messages for configuration issues
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;
}
// percentile_list special values
// deciles and quintiles are automatically expanded to their corresponding percentile lists
// case-insensitive comparison is used to check for these special values
if args.flag_percentile_list.to_lowercase() == "deciles" {
args.flag_percentile_list = "10,20,30,40,50,60,70,80,90".to_string();
} else if args.flag_percentile_list.to_lowercase() == "quintiles" {
args.flag_percentile_list = "20,40,60,80".to_string();
}
// validate percentile list
let percentile_list = args.flag_percentile_list.split(',').collect::<Vec<&str>>();
for p in percentile_list {
if fast_float2::parse::<f64, &[u8]>(p.trim().as_bytes()).is_err() {
return fail_incorrectusage_clierror!(
"Invalid percentile list: {}: {}",
args.flag_percentile_list,
p
);
}
}
// inferring boolean requires inferring cardinality
if args.flag_infer_boolean {
if !args.flag_cardinality {
args.flag_cardinality = true;
}
// validate boolean patterns
let patterns = parse_boolean_patterns(&args.flag_boolean_patterns)?;
let _ = BOOLEAN_PATTERNS.set(patterns);
}
// 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: args.arg_input.clone().unwrap_or_default(),
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_percentiles: args.flag_percentiles,
flag_percentile_list: args.flag_percentile_list.clone(),
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: args
.flag_delimiter
.as_ref()
.map(|d| (d.as_byte() as char).to_string())
.unwrap_or_default(),
// 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(),
flag_weight: args.flag_weight.clone().unwrap_or_default(),
field_count: 0,
filesize_bytes: 0,
hash: FileHash::default(),
};
// create a temporary file to store the <FILESTEM>.stats.csv file
// The cache is always plain CSV (comma-delimited, uncompressed) regardless of
// the --output format, since it's an internal format consumed by moarstats,
// schema, frequency, etc. Use .csv suffix so NamedTempFile RAII cleanup
// deletes the correct file.
let stats_csv_tempfile = TempFileBuilder::new().suffix(".csv").tempfile()?;
// safety: we know the tempfile is a valid NamedTempFile, so we can use unwrap
let stats_csv_tempfile_fname = stats_csv_tempfile.path().to_str().unwrap().to_string();
// 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) = match args.flag_output {
Some(ref output_path) => get_delim_by_extension(Path::new(&output_path), b','),
_ => (String::new(), b',', false),
};
// we will write the stats to a temp file - always as plain CSV
let wconfig = Config::new(Some(&stats_csv_tempfile_fname)).delimiter(Some(Delimiter(b',')));
let mut wtr = wconfig.writer()?;
let mut rconfig = args.rconfig();
if let Some(format_error) = rconfig.format_error {
return fail_incorrectusage_clierror!("{format_error}");
}
// infer delimiter when we're getting input from stdin
// as the stats engine needs to know the delimiter or it will panic
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 temp_dir =
crate::config::TEMP_FILE_DIR.get_or_init(|| tempfile::TempDir::new().unwrap().keep());
let mut stdin_file = TempFileBuilder::new().tempfile_in(temp_dir)?;
let stdin = std::io::stdin();
let mut stdin_handle = stdin.lock();
std::io::copy(&mut stdin_handle, &mut stdin_file)?;
drop(stdin_handle);
let (mut preview_file, tempfile_path) = stdin_file
.keep()
.or(Err("Cannot keep temporary file".to_string()))?;
// Only infer delimiter if QSV_DEFAULT_DELIMITER is not set
if std::env::var("QSV_DEFAULT_DELIMITER").is_err() {
// Seek to start of file before reading
preview_file.seek(std::io::SeekFrom::Start(0))?;
// Read first line to infer delimiter
let mut first_line = String::new();
let mut reader = io::BufReader::new(&preview_file);
reader.read_line(&mut first_line)?;
// Count occurrences of each potential delimiter
let tab_count = first_line.matches('\t').count();
let semicolon_count = first_line.matches(';').count();
let comma_count = first_line.matches(',').count();
// Special case: if we see multiple consecutive spaces but no tabs,
// those spaces might actually be tabs in the original file
let space_groups = first_line
.split(|c: char| !c.is_whitespace())
.filter(|s| !s.is_empty())
.count();
// Infer delimiter by finding the most frequent one
let inferred = if tab_count > 0
|| (space_groups > 2 && comma_count == 0 && semicolon_count == 0)
{
"\t"
} else if semicolon_count > 0 && semicolon_count >= comma_count {
";"
} else {
","
};