-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathmoarstats.rs
More file actions
5661 lines (5108 loc) · 231 KB
/
moarstats.rs
File metadata and controls
5661 lines (5108 loc) · 231 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#"
Add dozens of additional statistics, including extended outlier, robust & bivariate
statistics to an existing stats CSV file. It also maps the field type to the most specific
W3C XML Schema Definition (XSD) datatype (https://www.w3.org/TR/xmlschema-2/).
The `moarstats` command extends an existing stats CSV file (created by the `stats` command)
by computing "moar" (https://www.dictionary.com/culture/slang/moar) statistics that can be
derived from existing stats columns and by scanning the original CSV file.
It looks for the `<FILESTEM>.stats.csv` file for a given CSV input. If the stats CSV file
does not exist, it will first run the `stats` command with configurable options to establish
the baseline stats, to which it will add more stats columns.
If the `.stats.csv` file is found, it will skip running stats and just append the additional
stats columns.
Currently computes the following 25 additional univariate statistics:
1. Pearson's Second Skewness Coefficient: 3 * (mean - median) / stddev
Measures asymmetry of the distribution.
Positive values indicate right skew, negative values indicate left skew.
https://en.wikipedia.org/wiki/Skewness
2. Range to Standard Deviation Ratio: range / stddev
Normalizes the spread of data.
Higher values indicate more extreme outliers relative to the variability.
3. Quartile Coefficient of Dispersion: (Q3 - Q1) / (Q3 + Q1)
Measures relative variability using quartiles.
Useful for comparing dispersion across different scales.
https://en.wikipedia.org/wiki/Quartile_coefficient_of_dispersion
4. Z-Score of Mode: (mode - mean) / stddev
Indicates how typical the mode is relative to the distribution.
Values near 0 suggest the mode is near the mean.
5. Relative Standard Error: sem / mean
Measures precision of the mean estimate relative to its magnitude.
Lower values indicate more reliable estimates.
6. Z-Score of Min: (min - mean) / stddev
Shows how extreme the minimum value is.
Large negative values indicate outliers or heavy left tail.
7. Z-Score of Max: (max - mean) / stddev
Shows how extreme the maximum value is.
Large positive values indicate outliers or heavy right tail.
8. Median-to-Mean Ratio: median / mean
Indicates skewness direction.
Ratio < 1 suggests right skew, > 1 suggests left skew, = 1 suggests symmetry.
9. IQR-to-Range Ratio: iqr / range
Measures concentration of data.
Higher values (closer to 1) indicate more data concentrated in the middle 50%.
10. MAD-to-StdDev Ratio: mad / stddev
Compares robust vs non-robust spread measures.
Higher values suggest presence of outliers affecting stddev.
11. Trimean: (Q1 + 2*median + Q3) / 4
Tukey's trimean - a robust estimator of central tendency combining the median
with the midhinge. More robust than mean, more efficient than median alone.
https://en.wikipedia.org/wiki/Trimean
12. Midhinge: (Q1 + Q3) / 2
Midpoint of the middle 50% of data. A robust central tendency measure
that complements the mean and median.
https://en.wikipedia.org/wiki/Midhinge
13. Robust CV: MAD / |median|
Robust Coefficient of Variation using MAD and the magnitude of the median.
Always non-negative. Resistant to outliers, useful for comparing variability.
https://en.wikipedia.org/wiki/Robust_measures_of_scale
14. Kurtosis: Measures the "tailedness" of the distribution (excess kurtosis).
Positive values indicate heavy tails, negative values indicate light tails.
Values near 0 indicate a normal distribution.
Requires --advanced flag.
https://en.wikipedia.org/wiki/Kurtosis
15. Bimodality Coefficient: Measures whether a distribution has two modes (peaks) or is unimodal.
BC < 0.555 indicates unimodal, BC >= 0.555 indicates bimodal/multimodal.
Computed as (skewness² + 1) / (kurtosis + 3).
Requires --advanced flag (needs skewness from base stats and kurtosis from --advanced flag).
https://en.wikipedia.org/wiki/Bimodality
16. Jarque-Bera Test: (n/6) * (S² + K²/4)
Standard test for normality using skewness and kurtosis.
Also computes jarque_bera_pvalue (from chi-squared distribution with 2 df).
Low p-values (< 0.05) indicate the data is NOT normally distributed.
Requires --advanced flag (needs kurtosis).
https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
17. Gini Coefficient: Measures inequality/dispersion in the distribution.
Values range from 0 (perfect equality) to 1 (maximum inequality).
Requires --advanced flag.
https://en.wikipedia.org/wiki/Gini_coefficient
18. Atkinson Index: Measures inequality in the distribution with a sensitivity parameter.
Values range from 0 (perfect equality) to 1 (maximum inequality).
The Atkinson Index is a more general form of the Gini coefficient that allows for
different sensitivity to inequality. Sensitivity is configurable via --epsilon.
Requires --advanced flag.
https://en.wikipedia.org/wiki/Atkinson_index
19. Theil Index: (1/n) * Σ((x_i / mean) * ln(x_i / mean))
Measures inequality/concentration. Unlike Gini, it is decomposable into
within-group and between-group components. Only computed for positive values.
Requires --advanced flag.
https://en.wikipedia.org/wiki/Theil_index
20. Mean Absolute Deviation (from mean): (1/n) * Σ|x_i - mean|
Average absolute distance from the mean. Different from MAD (which uses median).
Less robust but more statistically efficient than MAD.
Requires --advanced flag.
21. Shannon Entropy: Measures the information content/uncertainty in the distribution.
Higher values indicate more diversity, lower values indicate more concentration.
Values range from 0 (all values identical) to log2(n) where n is the number of unique values.
Requires --advanced flag.
https://en.wikipedia.org/wiki/Entropy_(information_theory)
22. Normalized Entropy: Normalized version of Shannon Entropy scaled to [0, 1].
Values range from 0 (all values identical) to 1 (all values equally distributed).
Computed as shannon_entropy / log2(cardinality).
Requires shannon_entropy (from --advanced flag) and cardinality (from base stats).
23. Simpson's Diversity Index: 1 - Σ(p_i²)
Probability that two randomly chosen values are different.
Ranges from 0 (all identical) to 1 (all unique). More intuitive than entropy.
Requires --advanced flag (computed alongside entropy from frequency data).
https://en.wikipedia.org/wiki/Diversity_index#Simpson_index
24. Winsorized Mean: Replaces values below/above thresholds with threshold values, then computes mean.
All values are included in the calculation, but extreme values are capped at thresholds.
https://en.wikipedia.org/wiki/Winsorized_mean
Also computes: winsorized_stddev, winsorized_variance, winsorized_cv, winsorized_range,
and winsorized_stddev_ratio (winsorized_stddev / overall_stddev).
25. Trimmed Mean: Excludes values outside thresholds, then computes mean.
Only values within thresholds are included in the calculation.
https://en.wikipedia.org/wiki/Truncated_mean
Also computes: trimmed_stddev, trimmed_variance, trimmed_cv, trimmed_range,
and trimmed_stddev_ratio (trimmed_stddev / overall_stddev).
By default, uses Q1 and Q3 as thresholds (25% winsorization/trimming).
With --use-percentiles, uses configurable percentiles (e.g., 5th/95th) as thresholds
with --pct-thresholds.
In addition, it computes the following univariate outlier statistics (24 outlier statistics total).
https://en.wikipedia.org/wiki/Outlier
(requires --quartiles or --everything in stats):
Outlier Counts (7 statistics):
- outliers_extreme_lower_cnt: Count of values below the lower outer fence
- outliers_mild_lower_cnt: Count of values between lower outer and inner fences
- outliers_normal_cnt: Count of values between inner fences (non-outliers)
- outliers_mild_upper_cnt: Count of values between upper inner and outer fences
- outliers_extreme_upper_cnt: Count of values above the upper outer fence
- outliers_total_cnt: Total count of all outliers (sum of extreme and mild outliers)
- outliers_percentage: Percentage of values that are outliers
Outlier Descriptive Statistics (6 statistics):
- outliers_mean: Mean value of outliers
- non_outliers_mean: Mean value of non-outliers
- outliers_to_normal_mean_ratio: Ratio of outlier mean to non-outlier mean
- outliers_min: Minimum value among outliers
- outliers_max: Maximum value among outliers
- outliers_range: Range of outlier values (max - min)
Outlier Variance/Spread Statistics (7 statistics):
- outliers_stddev: Standard deviation of outlier values
- outliers_variance: Variance of outlier values
- non_outliers_stddev: Standard deviation of non-outlier values
- non_outliers_variance: Variance of non-outlier values
- outliers_cv: Coefficient of variation for outliers (stddev / mean)
- non_outliers_cv: Coefficient of variation for non-outliers (stddev / mean)
- outliers_normal_stddev_ratio: Ratio of outlier stddev to non-outlier stddev
Outlier Impact Statistics (2 statistics):
- outlier_impact: Difference between overall mean and non-outlier mean
- outlier_impact_ratio: Relative impact (outlier_impact / non_outlier_mean)
Outlier Boundary Statistics (2 statistics):
- lower_outer_fence_zscore: Z-score of the lower outer fence boundary
- upper_outer_fence_zscore: Z-score of the upper outer fence boundary
These outlier statistics require reading the original CSV file and comparing each
value against the fence thresholds.
Fences are computed using the IQR method:
inner fences at Q1/Q3 ± 1.5*IQR, outer fences at Q1/Q3 ± 3.0*IQR.
These univariate statistics are only computed for numeric and date/datetime columns
where the required base univariate statistics (mean, median, stddev, etc.) are available.
Univariate outlier statistics additionally require that quartiles (and thus fences) were
computed when generating the stats CSV.
Winsorized/trimmed means require either Q1/Q3 or percentiles to be available.
Kurtosis, Gini & Atkinson Index require reading the original CSV file to collect
all values for computation.
BIVARIATE STATISTICS:
The `moarstats` command also computes the following 6 bivariate statistics:
1. Pearson's correlation
Measures linear correlation between two numeric/date fields.
Values range from -1 (perfect negative correlation) to +1 (perfect positive correlation).
0 indicates no linear correlation.
https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
2. Spearman's rank correlation
Measures monotonic correlation between two numeric/date fields.
Values range from -1 (perfect negative correlation) to +1 (perfect positive correlation).
0 indicates no monotonic correlation.
https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient
3. Kendall's tau
Measures monotonic correlation between two numeric/date fields.
Values range from -1 (perfect negative correlation) to +1 (perfect positive correlation).
0 indicates no monotonic correlation.
https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient
4. Covariance
Measures the linear relationship between two numeric/date fields.
Values range from negative infinity to positive infinity.
0 indicates no linear relationship.
https://en.wikipedia.org/wiki/Covariance
5. Mutual Information
Measures the amount of information obtained about one field by observing another.
Values range from 0 (independent) to positive infinity.
https://en.wikipedia.org/wiki/Mutual_information
6. Normalized Mutual Information
Normalized version of mutual information, scaled by the geometric mean of individual entropies.
Values range from 0 (independent) to 1 (perfectly dependent).
https://en.wikipedia.org/wiki/Mutual_information#Normalized_variants
These bivariate statistics are computed when the `--bivariate` flag is used
and require an indexed CSV file (index will be auto-created if missing).
Bivariate statistics are output to a separate file: `<FILESTEM>.stats.bivariate.csv`.
Bivariate statistics require reading the entire CSV file and are computationally VERY expensive.
For large files (>= 10k records), parallel chunked processing is used when an index is available.
For smaller files or when no index exists, sequential processing is used.
MULTI-DATASET BIVARIATE STATISTICS:
When using the `--join-inputs` flag, multiple datasets can be joined internally before
computing bivariate statistics. This allows analyzing bivariate statistics across datasets
that share common join keys. The joined dataset is saved as a temporary file that is
automatically deleted after computing the bivariate statistics.
The bivariate statistics are saved to `<FILESTEM>.stats.bivariate.joined.csv`.
Non-finite numeric tokens ("NaN", "Infinity", "-Infinity", and their case variants) are
excluded from moarstats computations — the parser in moarstats filters them out before they
reach correlation, variance and mean calculations, preventing a single bad cell from silently
poisoning the results. Note that the baseline `stats` command may still count these tokens
as Float observations, so the `type`/`null_count` columns in `<FILESTEM>.stats.csv` are not
affected by this filter.
Examples:
# Add moar stats to existing stats file
qsv moarstats data.csv
# Generate baseline stats first with custom options, then add moar stats
qsv moarstats data.csv --stats-options "--everything --infer-dates"
# Compute bivariate statistics between fields
qsv moarstats data.csv --bivariate
# Compute even more bivariate statistics
qsv moarstats data.csv --bivariate --bivariate-stats pearson,spearman,kendall,mi,nmi,covariance
# Join multiple datasets and compute bivariate statistics
qsv moarstats data.csv --bivariate --join-inputs customers.csv,products.csv --join-keys cust_id,prod_id
# Join multiple datasets and compute bivariate statistics with different join type
qsv moarstats data.csv --bivariate --join-inputs customers.csv,products.csv --join-keys cust_id,prod_id --join-type left
For more examples, see https://github.com/dathere/qsv/blob/master/tests/test_moarstats.rs.
Usage:
qsv moarstats [options] [<input>]
qsv moarstats --help
moarstats options:
--advanced Compute Kurtosis, Shannon Entropy, Bimodality Coefficient,
Jarque-Bera, Gini Coefficient, Atkinson Index, Theil Index,
Mean Absolute Deviation, and Simpson's Diversity Index.
These advanced statistics computations require reading the
original CSV file to collect all values
for computation and are computationally expensive.
Further, Entropy computation requires the frequency command
to be run with --limit 0 to collect all frequencies.
An index will be auto-created for the original CSV file
if it doesn't already exist to enable parallel processing.
-e, --epsilon <n> The Atkinson Index Inequality Aversion parameter.
Epsilon controls the sensitivity of the Atkinson Index to inequality.
The higher the epsilon, the more sensitive the index is to inequality.
Typical values are 0.5 (standard in economic research),
1.0 (natural boundary), or 2.0 (useful for poverty analysis).
[default: 1.0]
--stats-options <arg> Options to pass to the stats command if baseline stats need
to be generated. The options are passed as a single string
that will be split by whitespace.
[default: --infer-dates --infer-boolean --mad --quartiles --percentiles --force --stats-jsonl]
--round <n> Round statistics to <n> decimal places. Rounding follows
Midpoint Nearest Even (Bankers Rounding) rule.
[default: 4]
--use-percentiles Use percentiles instead of Q1/Q3 for winsorization/trimming.
Requires percentiles to be computed in the stats CSV.
--pct-thresholds <arg> Comma-separated percentile pair (e.g., "10,90") to use
for winsorization/trimming when --use-percentiles is set.
Both values must be between 0 and 100, and lower < upper.
[default: 5,95]
--xsd-gdate-scan <mode> Gregorian XSD date type detection mode.
"quick": Fast detection using min/max values.
Produces types with ?? suffix (less confident).
"thorough": Comprehensive detection checking all percentile values.
Slower but ensures all values match the pattern.
Produces types with ? suffix (more confident).
[default: quick]
BIVARIATE STATISTICS OPTIONS:
-B, --bivariate Enable bivariate statistics computation.
Requires indexed CSV file (index will be auto-created if missing).
Computes pairwise correlations, covariances, mutual information, and
normalized mutual information between columns. The bivariate statistics
are saved to a separate file in the same directory as the input:
<FILESTEM>.stats.bivariate.csv.
-S, --bivariate-stats <stats>
Comma-separated list of bivariate statistics to compute.
Options: pearson, spearman, kendall, covariance, mi (mutual information),
nmi (normalized mutual information)
Use "all" to compute all statistics or "fast" to compute only
pearson & covariance, which is much faster as it doesn't require storing
all values and uses streaming algorithms.
[default: fast]
-C, --cardinality-threshold <n>
Skip mutual information computation for field pairs where either
field has cardinality exceeding this threshold. Helps avoid
expensive computations for high-cardinality fields.
[default: 1000000]
-J, --join-inputs <files>
Additional datasets to join. Comma-separated list of CSV files to join
with the primary input.
e.g.: --join-inputs customers.csv,products.csv
-K, --join-keys <keys>
Join keys for each dataset. Comma-separated list of join key column names,
one per dataset. Must specify same number of keys as datasets (primary + addl).
e.g.: --join-keys customer_id,customer_id,product_id
-T, --join-type <type>
Join type when using --join-inputs.
Valid values: inner, left, right, full
[default: inner]
-p, --progressbar Show progress bars when computing bivariate statistics.
Common options:
--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.
-h, --help Display this message
-o, --output <file> Write output to <file> instead of overwriting the stats CSV file.
"#;
use std::{
env, fs,
path::{Path, PathBuf},
process::Command,
sync::Arc,
time::Instant,
};
use crossbeam_channel;
use csv::{ReaderBuilder, StringRecord, WriterBuilder};
use foldhash::{HashMap, HashMapExt, HashSet, HashSetExt};
use indexmap::IndexMap;
use indicatif::{HumanCount, ProgressBar, ProgressDrawTarget, ProgressStyle};
use qsv_dateparser::parse_with_preference;
use rayon::prelude::*;
use serde::Deserialize;
use simdutf8::basic::from_utf8;
use stats::{atkinson, gini, kurtosis};
use threadpool::ThreadPool;
use crate::{CliError, CliResult, config::Config, regex_oncelock, util};
/// Minimum record count before parallel processing is worthwhile for outliers and
/// bivariate stats. Below this, the scheduling overhead outweighs the speedup, so
/// fall back to the sequential path.
const PARALLEL_THRESHOLD: usize = 10_000;
#[derive(Debug, Deserialize)]
struct Args {
arg_input: Option<String>,
flag_stats_options: String,
flag_round: u32,
flag_output: Option<String>,
flag_use_percentiles: bool,
flag_pct_thresholds: Option<String>,
flag_xsd_gdate_scan: Option<String>,
flag_advanced: bool,
flag_epsilon: f64,
flag_bivariate: bool,
flag_bivariate_stats: String,
flag_cardinality_threshold: Option<u64>,
flag_join_inputs: Option<String>,
flag_join_keys: Option<String>,
flag_join_type: Option<String>,
flag_progressbar: bool,
flag_jobs: Option<usize>,
flag_force: bool,
}
/// Configuration for which bivariate statistics to compute
#[derive(Clone, Copy, Debug, Default)]
struct BivariateStatsConfig {
pearson: bool,
spearman: bool,
kendall: bool,
covariance: bool,
mi: bool, // mutual information
nmi: bool, // normalized mutual information
}
impl BivariateStatsConfig {
/// Parse the --bivariate-stats flag value
fn from_flag(flag_value: &str) -> CliResult<Self> {
let mut config = Self::default();
let mut invalid_stats = Vec::new();
let flag_lower = flag_value.to_lowercase();
for stat in flag_lower.split(',') {
let stat_trimmed = stat.trim();
if stat_trimmed.is_empty() {
continue; // Skip empty entries from trailing commas
}
match stat_trimmed {
"pearson" => config.pearson = true,
"spearman" => config.spearman = true,
"kendall" => config.kendall = true,
"covariance" | "cov" => config.covariance = true,
"mi" | "mutual_information" | "mutual-information" => config.mi = true,
"nmi" | "normalized_mutual_information" | "normalized-mutual-information" => {
config.nmi = true;
},
"all" => return Ok(Self::all()),
"fast" => {
config.pearson = true;
config.covariance = true;
},
_ => {
invalid_stats.push(stat_trimmed.to_string());
},
}
}
if !invalid_stats.is_empty() {
return fail_clierror!(
"Invalid bivariate statistics: {}. Valid options are: pearson, spearman, kendall, \
covariance (or cov), mi (or mutual_information or mutual-information), nmi (or \
normalized_mutual_information or normalized-mutual-information), fast, all",
invalid_stats.join(", ")
);
}
// Check if at least one stat was requested
if !config.pearson
&& !config.spearman
&& !config.kendall
&& !config.covariance
&& !config.mi
&& !config.nmi
{
return fail_clierror!(
"No valid bivariate statistics specified. Valid options are: pearson, spearman, \
kendall, covariance (or cov), mi (or mutual_information or mutual-information), \
nmi (or normalized_mutual_information or normalized-mutual-information), fast, \
all"
);
}
Ok(config)
}
/// Enable all bivariate statistics
const fn all() -> Self {
Self {
pearson: true,
spearman: true,
kendall: true,
covariance: true,
mi: true,
nmi: true,
}
}
/// Check if we need to store all values (required for Spearman/Kendall)
#[inline]
const fn needs_all_values(self) -> bool {
self.spearman || self.kendall
}
/// Check if we need frequency counts (required for mutual information and normalized mutual
/// information)
#[inline]
const fn needs_frequency_counts(self) -> bool {
self.mi || self.nmi
}
}
/// Get the absolute stats CSV file path for a given input CSV path.
/// Delegates to the shared implementation in `util::get_stats_csv_path`.
fn get_stats_csv_path(input_path: &Path) -> CliResult<PathBuf> {
util::get_stats_csv_path(input_path)
}
/// Get the absolute bivariate CSV file path for a given input CSV path
/// If `is_joined` is true, appends `.joined` to the filename before `.csv`
fn get_bivariate_csv_path(input_path: &Path, is_joined: bool) -> CliResult<PathBuf> {
let parent = input_path.parent().unwrap_or_else(|| Path::new("."));
let fstem = input_path
.file_stem()
.ok_or_else(|| CliError::Other("Invalid input path: no file name".to_string()))?;
let bivariate_filename = if is_joined {
format!("{}.stats.bivariate.joined.csv", fstem.to_string_lossy())
} else {
format!("{}.stats.bivariate.csv", fstem.to_string_lossy())
};
let result = parent.join(bivariate_filename);
if result.is_absolute() {
Ok(result)
} else {
Ok(std::env::current_dir()?.join(result))
}
}
/// Join multiple datasets internally using join
fn join_datasets_internal(
primary_input: &Path,
additional_inputs: &[String],
join_keys: &[String],
join_type: &str,
) -> CliResult<PathBuf> {
use tempfile::NamedTempFile;
if additional_inputs.is_empty() {
return fail_clierror!("No additional datasets provided for joining");
}
if join_keys.len() != additional_inputs.len() + 1 {
return fail_clierror!(
"Number of join keys ({}) must match number of datasets ({})",
join_keys.len(),
additional_inputs.len() + 1
);
}
// Create temporary file for joined output with .csv extension
let temp_dir =
crate::config::TEMP_FILE_DIR.get_or_init(|| tempfile::TempDir::new().unwrap().keep());
let temp_file = tempfile::Builder::new()
.suffix(".csv")
.tempfile_in(temp_dir)?;
let temp_path = temp_file.path().to_path_buf();
drop(temp_file); // Close the file so join can write to it
let temp_path_str = temp_path
.to_str()
.ok_or_else(|| CliError::Other("Invalid temp path".to_string()))?
.to_string();
let primary_input_str = primary_input
.to_str()
.ok_or_else(|| CliError::Other("Invalid input path".to_string()))?
.to_string();
// Build join command arguments
let join_type_flag: Option<&str> = match join_type {
"left" => Some("--left"),
"right" => Some("--right"),
"full" => Some("--full"),
_ => None, // inner is default
};
// Join datasets sequentially (join first additional to primary, then next to result, etc.)
// This is simpler than handling multiple joins at once
let mut current_input = primary_input_str;
let mut current_key = join_keys[0].clone();
// Resolve the executable path once before the loop
let qsv_path = env::current_exe()
.map_err(|e| CliError::Other(format!("Failed to get current executable path: {e:?}")))?
.to_string_lossy()
.to_string();
// These are never read, but we need to declare them to avoid compiler errors
#[allow(clippy::collection_is_never_read)]
let mut intermediate_temps: Vec<NamedTempFile> = Vec::new();
#[allow(clippy::collection_is_never_read)]
let mut intermediate_path_strs: Vec<String> = Vec::new();
for (i, (additional_input, next_key)) in additional_inputs
.iter()
.zip(join_keys[1..].iter())
.enumerate()
{
let mut args: Vec<&str> = Vec::new();
// Add join type flag if specified
if let Some(flag) = join_type_flag {
args.push(flag);
}
args.push(¤t_key);
args.push(¤t_input);
args.push(next_key);
args.push(additional_input);
let output_path_str = if i == additional_inputs.len() - 1 {
// Last join - use final temp path
temp_path_str.clone()
} else {
// Intermediate join - create another temp file with .csv extension
let intermediate_temp = tempfile::Builder::new()
.suffix(".csv")
.tempfile_in(temp_dir)?;
let intermediate_path = intermediate_temp.path().to_path_buf();
intermediate_temps.push(intermediate_temp); // Keep temp file alive
let intermediate_path_str = intermediate_path
.to_str()
.ok_or_else(|| CliError::Other("Invalid intermediate temp path".to_string()))?
.to_string();
intermediate_path_strs.push(intermediate_path_str.clone());
intermediate_path_str
};
args.push("--output");
args.push(&output_path_str);
// Construct join command directly since it doesn't fit run_qsv_cmd pattern
// (join takes two input files, not one)
let mut cmd = Command::new(&qsv_path);
cmd.arg("join").args(&args);
let output = cmd
.output()
.map_err(|e| CliError::Other(format!("Error while executing join command: {e:?}")))?;
if !output.status.success() {
return fail_clierror!(
"Command join failed: Output {{ status: {:?}, stdout: {:?}, stderr: {:?} }}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
log::info!("Joining datasets...");
// Update for next iteration
current_input = output_path_str;
current_key.clone_from(next_key);
}
Ok(temp_path)
}
/// Compute Pearson's Second Skewness Coefficient: 3 * (mean - median) / stddev
#[inline]
fn compute_pearson_skewness(
mean: Option<f64>,
median: Option<f64>,
stddev: Option<f64>,
) -> Option<f64> {
if let (Some(mean_val), Some(median_val), Some(stddev_val)) = (mean, median, stddev) {
if stddev_val.abs() > f64::EPSILON {
Some(3.0 * (mean_val - median_val) / stddev_val)
} else {
None
}
} else {
None
}
}
/// Compute Range to Standard Deviation Ratio: range / stddev
#[inline]
fn compute_range_stddev_ratio(range: Option<f64>, stddev: Option<f64>) -> Option<f64> {
if let (Some(range_val), Some(stddev_val)) = (range, stddev) {
if stddev_val.abs() > f64::EPSILON {
Some(range_val / stddev_val)
} else {
None
}
} else {
None
}
}
/// Compute Quartile Coefficient of Dispersion: (Q3 - Q1) / (Q3 + Q1)
///
/// Note: If Q1 or Q3 are negative, especially if both are negative and equal in magnitude,
/// the denominator (Q3 + Q1) may be zero or near zero, causing the result to be `None`.
/// Also, the standard formula may not yield meaningful results if Q1 is negative and
/// Q1 >= Q3 (i.e., quartiles are not in the expected order).
/// Return None if quartiles are not in a valid order (Q1 < Q3), or denominator is 0.
#[inline]
fn compute_quartile_coefficient_dispersion(q1: Option<f64>, q3: Option<f64>) -> Option<f64> {
if let (Some(q1_val), Some(q3_val)) = (q1, q3) {
// Check that quartile order is valid (Q1 < Q3)
if q1_val >= q3_val {
return None;
}
let sum = q3_val + q1_val;
// Only compute if the denominator is effectively non-zero to avoid division by zero and
// instability.
if sum.abs() <= f64::EPSILON {
None
} else {
Some((q3_val - q1_val) / sum)
}
} else {
None
}
}
/// Compute Z-Score of Mode: (mode - mean) / stddev
#[inline]
fn compute_mode_zscore(mode: Option<f64>, mean: Option<f64>, stddev: Option<f64>) -> Option<f64> {
if let (Some(mode_val), Some(mean_val), Some(stddev_val)) = (mode, mean, stddev) {
if stddev_val.abs() > f64::EPSILON {
Some((mode_val - mean_val) / stddev_val)
} else {
None
}
} else {
None
}
}
/// Compute Relative Standard Error: sem / mean
#[inline]
fn compute_relative_standard_error(sem: Option<f64>, mean: Option<f64>) -> Option<f64> {
if let (Some(sem_val), Some(mean_val)) = (sem, mean) {
if mean_val.abs() > f64::EPSILON {
Some(sem_val / mean_val)
} else {
None
}
} else {
None
}
}
/// Compute Z-Score: (value - mean) / stddev
#[inline]
fn compute_zscore(value: Option<f64>, mean: Option<f64>, stddev: Option<f64>) -> Option<f64> {
if let (Some(val), Some(mean_val), Some(stddev_val)) = (value, mean, stddev) {
if stddev_val.abs() > f64::EPSILON {
Some((val - mean_val) / stddev_val)
} else {
None
}
} else {
None
}
}
/// Compute Median-to-Mean Ratio: median / mean
#[inline]
fn compute_median_mean_ratio(median: Option<f64>, mean: Option<f64>) -> Option<f64> {
if let (Some(median_val), Some(mean_val)) = (median, mean) {
if mean_val.abs() > f64::EPSILON {
Some(median_val / mean_val)
} else {
None
}
} else {
None
}
}
/// Compute IQR-to-Range Ratio: iqr / range
#[inline]
fn compute_iqr_range_ratio(iqr: Option<f64>, range: Option<f64>) -> Option<f64> {
if let (Some(iqr_val), Some(range_val)) = (iqr, range) {
if range_val.abs() > f64::EPSILON {
Some(iqr_val / range_val)
} else {
None
}
} else {
None
}
}
/// Compute MAD-to-StdDev Ratio: mad / stddev
#[inline]
fn compute_mad_stddev_ratio(mad: Option<f64>, stddev: Option<f64>) -> Option<f64> {
if let (Some(mad_val), Some(stddev_val)) = (mad, stddev) {
if stddev_val.abs() > f64::EPSILON {
Some(mad_val / stddev_val)
} else {
None
}
} else {
None
}
}
/// Compute Trimean: (Q1 + 2*median + Q3) / 4
/// Tukey's trimean - a robust estimator of central tendency that
/// combines the median with the midhinge.
#[inline]
fn compute_trimean(q1: Option<f64>, median: Option<f64>, q3: Option<f64>) -> Option<f64> {
if let (Some(q1_val), Some(median_val), Some(q3_val)) = (q1, median, q3) {
Some((2.0f64.mul_add(median_val, q1_val) + q3_val) / 4.0)
} else {
None
}
}
/// Compute Midhinge: (Q1 + Q3) / 2
/// Midpoint of the middle 50% of data, a robust central tendency measure.
#[inline]
const fn compute_midhinge(q1: Option<f64>, q3: Option<f64>) -> Option<f64> {
if let (Some(q1_val), Some(q3_val)) = (q1, q3) {
Some(f64::midpoint(q1_val, q3_val))
} else {
None
}
}
/// Compute Robust Coefficient of Variation: MAD / |median|
/// Uses robust measures (MAD and median magnitude) instead of stddev and mean.
#[inline]
fn compute_robust_cv(mad: Option<f64>, median: Option<f64>) -> Option<f64> {
if let (Some(mad_val), Some(median_val)) = (mad, median) {
if median_val.abs() > f64::EPSILON {
Some(mad_val / median_val.abs())
} else {
None
}
} else {
None
}
}
/// Compute Jarque-Bera test statistic: (n/6) * (S^2 + K^2/4)
/// Tests whether data follows a normal distribution.
/// Returns (jb_statistic, p_value) where p_value is from chi-squared(2) distribution.
#[inline]
fn compute_jarque_bera(skewness: Option<f64>, kurtosis: Option<f64>, n: u64) -> Option<(f64, f64)> {
if n < 3 {
return None;
}
if let (Some(skew_val), Some(kurt_val)) = (skewness, kurtosis) {
#[allow(clippy::cast_precision_loss)]
let n_f64 = n as f64;
let jb = (n_f64 / 6.0) * skew_val.mul_add(skew_val, kurt_val * kurt_val / 4.0);
// Upper-tail p-value from chi-squared distribution with 2 degrees of freedom
// For chi-squared(2), the survival function (1 - CDF) is e^(-x/2)
let p_value = (-jb / 2.0_f64).exp();
Some((jb, p_value))
} else {
None
}
}
/// Compute Bimodality Coefficient: (skewness² + 1) / (kurtosis + 3)
/// BC < 0.555 indicates unimodal, BC >= 0.555 indicates bimodal/multimodal
fn compute_bimodality_coefficient(skewness: Option<f64>, kurtosis: Option<f64>) -> Option<f64> {
if let (Some(skew_val), Some(kurt_val)) = (skewness, kurtosis) {
let denominator = kurt_val + 3.0;
if denominator.abs() > f64::EPSILON {
Some(skew_val.mul_add(skew_val, 1.0) / denominator)
} else {
None
}
} else {
None
}
}
/// Compute Normalized Entropy: shannon_entropy / log2(cardinality)
/// Values range from 0 (all values identical) to 1 (all values equally distributed)
fn compute_normalized_entropy(
shannon_entropy: Option<f64>,
cardinality: Option<u64>,
) -> Option<f64> {
if let (Some(entropy_val), Some(card_val)) = (shannon_entropy, cardinality) {
if card_val > 1 {
#[allow(clippy::cast_precision_loss)]
let max_entropy = (card_val as f64).log2();
if max_entropy.abs() > f64::EPSILON {
Some(entropy_val / max_entropy)
} else {
None
}
} else {
// If cardinality is 0 or 1, normalized entropy is 0
Some(0.0)
}
} else {
None
}
}
/// Parse a numeric value from a string, handling empty strings and invalid values
#[inline]
fn parse_float_opt(s: &str) -> Option<f64> {
if s.is_empty() {
return None;
}
// Filter NaN/±Infinity: a single non-finite cell would poison Welford
// correlation state and propagate silently through all downstream statistics.
fast_float2::parse::<f64, &[u8]>(s.as_bytes())
.ok()
.filter(|v| v.is_finite())
}
/// Parse a numeric value from bytes, handling empty bytes and invalid values
#[inline]
fn parse_float_opt_from_bytes(bytes: &[u8]) -> Option<f64> {
if bytes.is_empty() {
return None;
}
fast_float2::parse::<f64, &[u8]>(bytes)
.ok()
.filter(|v| v.is_finite())
}
/// Format a percentile value compactly: integral percentiles render without a
/// fractional part (e.g. `5.0` -> `"5"`, `5.5` -> `"5.5"`). Used for both
/// constructing column names and for looking up keys in the percentiles string;
/// keeping a single formatter avoids drift between the two sites.
#[inline]
fn fmt_pct(p: f64) -> String {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
if p.fract() == 0.0 && p >= 0.0 {
format!("{}", p as u32)
} else {
format!("{p}")
}
}
/// Parse a percentile value from the percentiles column string
/// Format: "5: value1|10: value2|..." (separator from QSV_STATS_SEPARATOR env var, default "|")
/// For Date/DateTime types, values are RFC3339 date strings; for numeric types, they're numbers
/// Returns the numeric value (in days since epoch for dates) for the specified percentile label, or
/// None if not found
fn parse_percentile_value(
percentile_str: &str,
percentile_label: &str,
field_type: FieldType,
separator: &str,
prefer_dmy: bool,
) -> Option<f64> {
if percentile_str.is_empty() {
return None;
}
// Split by separator and find matching percentile
for entry in percentile_str.split(separator) {
let entry = entry.trim();
if let Some(colon_pos) = entry.find(':') {
let label = entry[..colon_pos].trim();
let value_str = entry[colon_pos + 1..].trim();
if label == percentile_label {
// For Date/DateTime types, parse as date string; for numeric types, parse as float
return if field_type.is_date_or_datetime() {
parse_date_to_days(value_str, prefer_dmy)
} else {
parse_float_opt(value_str)
};
}
}
}
None
}
/// Parse all percentile string values from the percentiles column string
/// Format: "5: value1|10: value2|25: value3|..." (separator from QSV_STATS_SEPARATOR env var,
/// default "|") Returns a vector of all percentile value strings (the values after colons)
/// Used for pattern matching all percentile values in fast mode
fn parse_all_percentile_string_values<'a>(
percentile_str: &'a str,
separator: &str,
) -> Vec<&'a str> {
if percentile_str.is_empty() {
return Vec::new();
}
// Split by separator and extract all values after colons
percentile_str
.split(separator)
.filter_map(|entry| {
let entry = entry.trim();
if let Some(colon_pos) = entry.find(':') {
let value_str = entry[colon_pos + 1..].trim();
if !value_str.is_empty() {
return Some(value_str);
}
}
None
})
.collect()
}
/// Field type enum for efficient comparisons
/// Matches the FieldType enum from stats.rs but kept local for performance
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, PartialEq)]
enum FieldType {
TNull,
TString,
TFloat,
TInteger,
TDate,
TDateTime,
TBoolean,
}