-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathsample.rs
1240 lines (1102 loc) · 43.9 KB
/
sample.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#"
Randomly samples CSV data.
It supports seven sampling methods:
- RESERVOIR: the default sampling method when NO INDEX is present.
Visits every CSV record exactly once, using MEMORY PROPORTIONAL to the
sample size (k) - O(k).
https://en.wikipedia.org/wiki/Reservoir_sampling
- INDEXED: the default sampling method when an INDEX is present.
Uses random I/O to sample efficiently, as it only visits records selected
by random indexing, using MEMORY PROPORTIONAL to the sample size (k) - O(k).
https://en.wikipedia.org/wiki/Random_access
- BERNOULLI: the sampling method when the --bernoulli option is specified.
Each record has an independent probability p of being selected, where p is
specified by the <sample-size> argument. For example, if p=0.1, then each record
has a 10% chance of being selected, regardless of the other records. The final
sample size is random and follows a binomial distribution. Uses CONSTANT MEMORY - O(1).
https://en.wikipedia.org/wiki/Bernoulli_sampling
- SYSTEMATIC: the sampling method when the --systematic option is specified.
Selects every nth record from the input, where n is the integer part of <sample-size>
and the fraction part is the percentage of the population to sample.
For example, if <sample-size> is 10.5, it will select every 10th record and 50% of the
population. If <sample-size> is a whole number (no fractional part), it will select
every nth record for the whole population. Uses CONSTANT memory - O(1). The starting
point can be specified as "random" or "first". Useful for time series data or when you
want evenly spaced samples.
https://en.wikipedia.org/wiki/Systematic_sampling
- STRATIFIED: the sampling method when the --stratified option is specified.
Stratifies the population by the specified column and then samples from each stratum.
Particularly useful when a population has distinct subgroups (strata) that are
heterogeneous within but homogeneous between in terms of the variable of interest.
For example, if you want to sample 1,000 records from a population of 100,000 across the US,
you can stratify the population by US state and then sample 20 records from each stratum.
This will ensure that you have a representative sample from each of the 50 states.
The sample size must be a whole number. Uses MEMORY PROPORTIONAL to the
number of strata (s) and samples per stratum (k) as specified by <sample-size> - O(s*k).
https://en.wikipedia.org/wiki/Stratified_sampling
- WEIGHTED: the sampling method when the --weighted option is specified.
Samples records with probabilities proportional to values in a specified weight column.
Records with higher weights are more likely to be selected. For example, if you have
sales data and want to sample transactions weighted by revenue, high-value transactions
will have a higher chance of being included. Non-numeric weights are treated as zero.
The weights are automatically normalized using the maximum weight in the dataset.
Specify the desired sample size with <sample-size>. Uses MEMORY PROPORTIONAL to the
sample size (k) - O(k).
"Weighted random sampling with a reservoir" https://doi.org/10.1016/j.ipl.2005.11.003
- CLUSTER: the sampling method when the --cluster option is specified.
Samples entire groups of records together based on a cluster identifier column.
The number of clusters is specified by the <sample-size> argument.
Useful when records are naturally grouped (e.g., by household, neighborhood, etc.).
For example, if you have records grouped by neighborhood and specify a sample size of 10,
it will randomly select 10 neighborhoods and include ALL records from those neighborhoods
in the output. This ensures that natural groupings in the data are preserved.
Uses MEMORY PROPORTIONAL to the number of clusters (c) - O(c).
https://en.wikipedia.org/wiki/Cluster_sampling
Supports sampling from CSVs on remote URLs.
This command is intended to provide a means to sample from a CSV data set that
is too big to fit into memory (for example, for use with commands like
'qsv stats' with the '--everything' option).
For examples, see https://github.com/dathere/qsv/blob/master/tests/test_sample.rs.
Usage:
qsv sample [options] <sample-size> [<input>]
qsv sample --help
sample arguments:
<input> The CSV file to sample. This can be a local file,
stdin, or a URL (http and https schemes supported).
<sample-size> When using INDEXED, RESERVOIR or WEIGHTED sampling, the sample size.
Can either be a whole number or a value between value between 0 and 1.
If a fraction, specifies the sample size as a percentage of the population.
(e.g. 0.15 - 15 percent of the CSV)
When using BERNOULLI sampling, the probability of selecting each record
(between 0 and 1).
When using SYSTEMATIC sampling, the integer part is the interval between
records to sample & the fractional part is the percentage of the
population to sample. When there is no fractional part, it will
select every nth record for the entire population.
When using STRATIFIED sampling, the stratum sample size.
When using CLUSTER sampling, the number of clusters.
sample options:
--seed <number> Random Number Generator (RNG) seed.
--rng <kind> The Random Number Generator (RNG) algorithm to use.
Three RNGs are supported:
- standard: Use the standard RNG.
1.5 GB/s throughput.
- faster: Use faster RNG using the Xoshiro256Plus algorithm.
8 GB/s throughput.
- cryptosecure: Use cryptographically secure HC128 algorithm.
Recommended by eSTREAM (https://www.ecrypt.eu.org/stream/).
2.1 GB/s throughput though slow initialization.
[default: standard]
SAMPLING METHODS:
--bernoulli Use Bernoulli sampling instead of indexed or reservoir sampling.
When this flag is set, <sample-size> must be between
0 and 1 and represents the probability of selecting each record.
--systematic <arg> Use systematic sampling (every nth record as specified by <sample-size>).
If <arg> is "random", the starting point is randomly chosen between 0 & n.
If <arg> is "first", the starting point is the first record.
The sample size must be a whole number. Uses CONSTANT memory - O(1).
--stratified <col> Use stratified sampling. The strata column is specified by <col>.
Can be either a column name or 0-based column index.
The sample size must be a whole number. Uses MEMORY PROPORTIONAL to the
number of strata (s) and samples per stratum (k) - O(s*k).
--weighted <col> Use weighted sampling. The weight column is specified by <col>.
Can be either a column name or 0-based column index.
The column will be parsed as a number. Records with non-number weights
will be skipped.
Uses MEMORY PROPORTIONAL to the sample size (k) - O(k).
--cluster <col> Use cluster sampling. The cluster column is specified by <col>.
Can be either a column name or 0-based column index.
Uses MEMORY PROPORTIONAL to the number of clusters (c) - O(c).
REMOTE FILE OPTIONS:
--user-agent <agent> Specify custom user agent to use when the input is a URL.
It supports the following variables -
$QSV_VERSION, $QSV_TARGET, $QSV_BIN_NAME, $QSV_KIND and $QSV_COMMAND.
Try to follow the syntax here -
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
--timeout <secs> Timeout for downloading URLs in seconds.
[default: 30]
--max-size <mb> Maximum size of the file to download in MB before sampling.
Will download the entire file if not specified.
If the CSV is partially downloaded, the sample will be taken
only from the downloaded portion.
--force Do not use stats cache, even if its available.
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 be considered as part of
the population to sample from. (When not set, the
first row is the header row and will always appear
in the output.)
-d, --delimiter <arg> The field delimiter for reading/writing CSV data.
Must be a single character. (default: ,)
"#;
use std::{
collections::{HashMap, HashSet},
io,
str::FromStr,
};
use rand::{
distr::{Bernoulli, Distribution},
prelude::IndexedRandom,
rngs::StdRng,
Rng, SeedableRng,
};
use rand_hc::Hc128Rng;
use rand_xoshiro::Xoshiro256Plus;
use rayon::prelude::ParallelSliceMut;
use serde::Deserialize;
use strum_macros::EnumString;
use tempfile::NamedTempFile;
use url::Url;
use crate::{
config::{Config, Delimiter},
select::SelectColumns,
util,
util::{get_stats_records, SchemaArgs, StatsMode},
CliResult,
};
#[derive(Deserialize)]
struct Args {
arg_input: Option<String>,
arg_sample_size: f64,
flag_output: Option<String>,
flag_no_headers: bool,
flag_delimiter: Option<Delimiter>,
flag_seed: Option<u64>,
flag_rng: String,
flag_user_agent: Option<String>,
flag_timeout: Option<u16>,
flag_max_size: Option<u64>,
flag_bernoulli: bool,
flag_systematic: Option<String>,
flag_stratified: Option<String>,
flag_weighted: Option<String>,
flag_cluster: Option<String>,
flag_force: bool,
}
impl Args {
fn get_column_index(
header: &csv::ByteRecord,
column_spec: &str,
purpose: &str,
) -> CliResult<usize> {
// Try parsing as number first
if let Ok(idx) = column_spec.parse::<usize>() {
if idx < header.len() {
return Ok(idx);
}
return fail_incorrectusage_clierror!(
"{} column index {} is out of bounds (max: {})",
purpose,
idx,
header.len() - 1
);
}
// If not a number, try to find column by name
for (i, field) in header.iter().enumerate() {
if column_spec == String::from_utf8_lossy(field) {
return Ok(i);
}
}
fail_incorrectusage_clierror!("Could not find {} column named '{}'", purpose, column_spec)
}
fn get_strata_column(&self, header: &csv::ByteRecord) -> CliResult<usize> {
match &self.flag_stratified {
Some(col) => Self::get_column_index(header, col, "strata"),
None => {
fail_incorrectusage_clierror!(
"--stratified <col> is required for stratified sampling"
)
},
}
}
fn get_weight_column(&self, header: &csv::ByteRecord) -> CliResult<usize> {
match &self.flag_weighted {
Some(col) => Self::get_column_index(header, col, "weight"),
None => {
fail_incorrectusage_clierror!("--weighted <col> is required for weighted sampling")
},
}
}
fn get_cluster_column(&self, header: &csv::ByteRecord) -> CliResult<usize> {
match &self.flag_cluster {
Some(col) => Self::get_column_index(header, col, "cluster"),
None => {
fail_incorrectusage_clierror!("--cluster <col> is required for cluster sampling")
},
}
}
}
#[derive(Debug, EnumString, PartialEq)]
#[strum(ascii_case_insensitive)]
enum RngKind {
Standard,
Faster,
Cryptosecure,
}
enum SamplingMethod {
Bernoulli,
Systematic,
Stratified,
Weighted,
Cluster,
Default,
}
// trait to handle different RNG types
trait RngProvider: Sized {
type RngType: Rng + SeedableRng;
fn get_name() -> &'static str;
fn create(seed: Option<u64>) -> Self::RngType {
if let Some(seed) = seed {
Self::RngType::seed_from_u64(seed) // DevSkim: ignore DS148264
} else {
Self::RngType::from_os_rng()
}
}
}
// Implement for each RNG type
struct StandardRng;
impl RngProvider for StandardRng {
type RngType = StdRng;
fn get_name() -> &'static str {
"standard"
}
}
struct FasterRng;
impl RngProvider for FasterRng {
type RngType = Xoshiro256Plus;
fn get_name() -> &'static str {
"faster"
}
}
struct CryptoRng;
impl RngProvider for CryptoRng {
type RngType = Hc128Rng;
fn get_name() -> &'static str {
"cryptosecure"
}
}
fn check_stats_cache(
args: &Args,
method: &SamplingMethod,
) -> CliResult<(Option<u64>, Option<f64>, Option<u64>)> {
if args.flag_force {
return Ok((None, None, None));
}
// Set stats config
let schema_args = SchemaArgs {
arg_input: args.arg_input.clone(),
flag_no_headers: args.flag_no_headers,
flag_delimiter: args.flag_delimiter,
flag_jobs: None,
flag_memcheck: false,
flag_force: args.flag_force,
flag_prefer_dmy: false,
flag_dates_whitelist: String::new(),
flag_enum_threshold: 0,
flag_ignore_case: false,
flag_strict_dates: false,
flag_pattern_columns: SelectColumns::parse("")?,
flag_stdout: false,
};
// Get stats records
if let Ok((csv_fields, stats, dataset_stats)) =
get_stats_records(&schema_args, StatsMode::Frequency)
{
// Get row count from stats cache
let rowcount = dataset_stats
.get("qsv__rowcount")
.and_then(|rc| rc.parse::<f64>().ok())
.map(|rc| rc as u64);
let mut max_weight = None;
let mut cardinality = None;
match method {
SamplingMethod::Weighted => {
// For weighted sampling, get max weight
max_weight = if let Some(weight_col) = &args.flag_weighted {
let idx = if weight_col.chars().all(char::is_numeric) {
weight_col.parse::<usize>().ok()
} else {
csv_fields
.iter()
.position(|field| field == weight_col.as_bytes())
};
if let Some(idx) = idx {
if let Some(col_stats) = stats.get(idx) {
let min_weight = col_stats
.min
.clone()
.unwrap()
.parse::<f64>()
.unwrap_or_default();
if min_weight < 0.0 {
return fail_incorrectusage_clierror!(
"Weights must be non-negative. Lowest weight: {min_weight}"
);
}
col_stats.max.clone().unwrap().parse::<f64>().ok()
} else {
None
}
} else {
None
}
} else {
None
};
},
SamplingMethod::Cluster => {
// For cluster sampling, get cardinality
cardinality = if let Some(cluster_col) = &args.flag_cluster {
let idx = if cluster_col.chars().all(char::is_numeric) {
cluster_col.parse::<usize>().ok()
} else {
csv_fields
.iter()
.position(|field| field == cluster_col.as_bytes())
};
if let Some(idx) = idx {
stats.get(idx).map(|col_stats| col_stats.cardinality)
} else {
None
}
} else {
None
};
},
_ => {},
}
Ok((rowcount, max_weight, cardinality))
} else {
Ok((None, None, None))
}
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let mut args: Args = util::get_args(USAGE, argv)?;
if args.arg_sample_size.is_sign_negative() {
return fail_incorrectusage_clierror!("Sample size cannot be negative.");
}
// Validate that only one sampling method is selected
let methods = [
args.flag_bernoulli,
args.flag_systematic.is_some(),
args.flag_stratified.is_some(),
args.flag_weighted.is_some(),
args.flag_cluster.is_some(),
];
if methods.iter().filter(|&&x| x).count() > 1 {
return fail_incorrectusage_clierror!("Only one sampling method can be specified");
}
let Ok(rng_kind) = RngKind::from_str(&args.flag_rng) else {
return fail_incorrectusage_clierror!(
"Invalid RNG algorithm `{}`. Supported RNGs are: standard, faster, cryptosecure.",
args.flag_rng
);
};
let sampling_method = match (
args.flag_bernoulli,
args.flag_systematic.is_some(),
args.flag_stratified.is_some(),
args.flag_weighted.is_some(),
args.flag_cluster.is_some(),
) {
(true, _, _, _, _) => SamplingMethod::Bernoulli,
(_, true, _, _, _) => SamplingMethod::Systematic,
(_, _, true, _, _) => SamplingMethod::Stratified,
(_, _, _, true, _) => SamplingMethod::Weighted,
(_, _, _, _, true) => SamplingMethod::Cluster,
(false, false, false, false, false) => SamplingMethod::Default,
};
let temp_download = NamedTempFile::new()?;
// Clone the user_agent before using it
let user_agent = args.flag_user_agent.clone();
args.arg_input = match args.arg_input {
Some(uri) if Url::parse(&uri).is_ok() && uri.starts_with("http") => {
let max_size_bytes = args.flag_max_size.map(|mb| mb * 1024 * 1024);
// its a remote file, download it first
let future = util::download_file(
&uri,
temp_download.path().to_path_buf(),
false,
user_agent,
args.flag_timeout,
max_size_bytes,
);
tokio::runtime::Runtime::new()?.block_on(future)?;
// safety: temp_download is a NamedTempFile, so we know can unwrap.to_string
Some(temp_download.path().to_str().unwrap().to_string())
},
Some(uri) => Some(uri), // local file
None => None,
};
let rconfig = Config::new(args.arg_input.as_ref())
.delimiter(args.flag_delimiter)
.no_headers(args.flag_no_headers)
.flexible(true)
.skip_format_check(true);
let mut rdr = rconfig.reader()?;
let mut wtr = Config::new(args.flag_output.as_ref())
.delimiter(args.flag_delimiter)
.writer()?;
// Write headers unless --no-headers is specified
rconfig.write_headers(&mut rdr, &mut wtr)?;
let mut sample_size = args.arg_sample_size;
match sampling_method {
SamplingMethod::Bernoulli => {
if args.arg_sample_size >= 1.0 || args.arg_sample_size <= 0.0 {
return fail_incorrectusage_clierror!(
"Bernoulli sampling requires a probability between 0 and 1"
);
}
sample_bernoulli(
&mut rdr,
&mut wtr,
args.arg_sample_size,
args.flag_seed,
&rng_kind,
)?;
},
SamplingMethod::Systematic => {
let starting_point = match args.flag_systematic.as_deref().map(str::to_lowercase) {
Some(arg) if arg == "random" || arg == "first" => arg,
Some(_) => {
return fail_incorrectusage_clierror!(
"Systematic sampling starting point must be either 'random' or 'first'"
)
},
None => String::from("random"),
};
let (rowcount_stats, _, _) = check_stats_cache(&args, &SamplingMethod::Systematic)?;
let row_count = if let Some(rc) = rowcount_stats {
rc
} else if let Ok(rc) = util::count_rows(&rconfig) {
rc
} else {
return fail!("Cannot get rowcount. Systematic sampling requires a rowcount.");
};
sample_systematic(
&mut rdr,
&mut wtr,
args.arg_sample_size,
row_count,
&starting_point,
args.flag_seed,
&rng_kind,
)?;
},
SamplingMethod::Stratified => {
let strata_column = args.get_strata_column(&rdr.byte_headers()?.clone())?;
sample_stratified(
&mut rdr,
&mut wtr,
strata_column,
args.arg_sample_size as usize,
args.flag_seed,
&rng_kind,
)?;
},
SamplingMethod::Weighted => {
let weight_column = args.get_weight_column(&rdr.byte_headers()?.clone())?;
// Get max_weight from cache if available
let (rowcount, max_weight, _) = check_stats_cache(&args, &SamplingMethod::Weighted)?;
// determine sample size
#[allow(clippy::cast_precision_loss)]
let sample_size = if let Some(rc) = rowcount {
if args.arg_sample_size < 1.0 {
(rc as f64 * args.arg_sample_size).round() as usize
} else {
args.arg_sample_size as usize
}
} else if args.arg_sample_size < 1.0 {
let rowcount = util::count_rows(&rconfig)?;
(rowcount as f64 * args.arg_sample_size).round() as usize
} else {
args.arg_sample_size as usize
};
sample_weighted(
&rconfig,
&mut rdr,
&mut wtr,
weight_column,
max_weight,
sample_size,
args.flag_seed,
&rng_kind,
)?;
},
SamplingMethod::Cluster => {
let cluster_column = args.get_cluster_column(&rdr.byte_headers()?.clone())?;
// Get cardinality from cache if available
let (_, _, cardinality) = check_stats_cache(&args, &SamplingMethod::Cluster)?;
sample_cluster(
&rconfig,
&mut rdr,
&mut wtr,
cluster_column,
cardinality,
args.arg_sample_size as usize,
args.flag_seed,
&rng_kind,
)?;
},
SamplingMethod::Default => {
// no sampling method is specified, so we do indexed sampling
// if an index is present
if let Some(mut idx) = rconfig.indexed()? {
#[allow(clippy::cast_precision_loss)]
if sample_size < 1.0 {
sample_size *= idx.count() as f64;
}
let sample_count = sample_size as usize;
let total_count = idx.count().try_into().unwrap();
match rng_kind {
RngKind::Standard => {
log::info!("doing standard INDEXED sampling...");
let mut rng = StandardRng::create(args.flag_seed);
sample_indices(&mut rng, total_count, sample_count, |i| {
idx.seek(i as u64)?;
Ok(wtr.write_byte_record(&idx.byte_records().next().unwrap()?)?)
})?;
},
RngKind::Faster => {
log::info!("doing --faster INDEXED sampling...");
let mut rng = FasterRng::create(args.flag_seed);
sample_indices(&mut rng, total_count, sample_count, |i| {
idx.seek(i as u64)?;
Ok(wtr.write_byte_record(&idx.byte_records().next().unwrap()?)?)
})?;
},
RngKind::Cryptosecure => {
log::info!("doing --cryptosecure INDEXED sampling...");
let mut rng = CryptoRng::create(args.flag_seed);
sample_indices(&mut rng, total_count, sample_count, |i| {
idx.seek(i as u64)?;
Ok(wtr.write_byte_record(&idx.byte_records().next().unwrap()?)?)
})?;
},
}
} else {
// No sampling method is specified and no index is present
// do reservoir sampling
#[allow(clippy::cast_precision_loss)]
let sample_size = if args.arg_sample_size < 1.0 {
// Get rowcount from stats cache if available
let (rowcount_stats, _, _) =
check_stats_cache(&args, &SamplingMethod::Default)?;
if let Some(rc) = rowcount_stats {
(rc as f64 * args.arg_sample_size).round() as u64
} else if let Ok(rc) = util::count_rows(&rconfig) {
// we don't have a stats cache, get the rowcount the "regular" way
(rc as f64 * args.arg_sample_size).round() as u64
} else {
return fail!(
"Cannot get rowcount. Percentage sampling requires a rowcount."
);
}
} else {
args.arg_sample_size as u64
};
sample_reservoir(&mut rdr, &mut wtr, sample_size, args.flag_seed, &rng_kind)?;
}
},
}
Ok(wtr.flush()?)
}
fn sample_reservoir<R: io::Read, W: io::Write>(
rdr: &mut csv::Reader<R>,
wtr: &mut csv::Writer<W>,
sample_size: u64,
seed: Option<u64>,
rng_kind: &RngKind,
) -> CliResult<()> {
let mut reservoir = Vec::with_capacity(sample_size as usize);
let mut records = rdr.byte_records().enumerate();
// Pre-fill reservoir
// Note that we use by_ref() to avoid consuming the iterator
// and we only take the first sample_size records
for (_, row) in records.by_ref().take(sample_size as usize) {
reservoir.push(row?);
}
match rng_kind {
RngKind::Standard => {
do_reservoir_sampling::<StandardRng>(&mut records, &mut reservoir, sample_size, seed)
},
RngKind::Faster => {
do_reservoir_sampling::<FasterRng>(&mut records, &mut reservoir, sample_size, seed)
},
RngKind::Cryptosecure => {
do_reservoir_sampling::<CryptoRng>(&mut records, &mut reservoir, sample_size, seed)
},
}?;
// Write the reservoir to output
for record in reservoir {
wtr.write_byte_record(&record)?;
}
Ok(())
}
// Generic reservoir sampling implementation using constant memory
fn do_reservoir_sampling<T: RngProvider>(
records: &mut impl Iterator<Item = (usize, Result<csv::ByteRecord, csv::Error>)>,
reservoir: &mut [csv::ByteRecord],
sample_size: u64,
seed: Option<u64>,
) -> CliResult<()> {
log::info!("doing {} RESERVOIR sampling...", T::get_name());
let mut rng = T::create(seed);
let mut random_idx: usize;
// Process remaining records using Algorithm R (Robert Floyd)
for (i, row) in records {
random_idx = rng.random_range(0..=i);
if random_idx < sample_size as usize {
unsafe {
*reservoir.get_unchecked_mut(random_idx) = row?;
}
}
}
Ok(())
}
fn sample_bernoulli<R: io::Read, W: io::Write>(
rdr: &mut csv::Reader<R>,
wtr: &mut csv::Writer<W>,
probability: f64,
seed: Option<u64>,
rng_kind: &RngKind,
) -> CliResult<()> {
let mut records = rdr.byte_records();
match rng_kind {
RngKind::Standard => {
do_bernoulli_sampling::<StandardRng>(&mut records, wtr, probability, seed)
},
RngKind::Faster => do_bernoulli_sampling::<FasterRng>(&mut records, wtr, probability, seed),
RngKind::Cryptosecure => {
do_bernoulli_sampling::<CryptoRng>(&mut records, wtr, probability, seed)
},
}
}
// Generic bernoulli sampling implementation using constant memory
fn do_bernoulli_sampling<T: RngProvider>(
records: &mut impl Iterator<Item = Result<csv::ByteRecord, csv::Error>>,
wtr: &mut csv::Writer<impl io::Write>,
probability: f64,
seed: Option<u64>,
) -> CliResult<()> {
log::info!("doing {} BERNOULLI sampling...", T::get_name());
let mut rng = T::create(seed);
let dist =
Bernoulli::new(probability).map_err(|_| "probability must be between 0.0 and 1.0")?;
for row in records {
if dist.sample(&mut rng) {
wtr.write_byte_record(&row?)?;
}
}
Ok(())
}
// Helper function to sample indices using constant memory
fn sample_indices<F>(
rng: &mut impl Rng,
total_count: usize,
sample_count: usize,
mut process_index: F,
) -> CliResult<()>
where
F: FnMut(usize) -> CliResult<()>,
{
if sample_count > total_count {
return fail!("Sample size cannot be larger than population size");
}
// Store selected indices in a sorted vec of size k
let mut selected = Vec::with_capacity(sample_count);
// Fill first k positions
for i in 0..sample_count {
selected.push(i);
}
// Process remaining positions using reservoir sampling
for i in sample_count..total_count {
let j = rng.random_range(0..=i);
if j < sample_count {
unsafe { *selected.get_unchecked_mut(j) = i };
}
}
// Process indices in order to avoid seeking back and forth
selected.par_sort_unstable();
for idx in selected {
process_index(idx)?;
}
Ok(())
}
// Systematic sampling implementation
fn sample_systematic<R: io::Read, W: io::Write>(
rdr: &mut csv::Reader<R>,
wtr: &mut csv::Writer<W>,
sample_size: f64,
row_count: u64,
starting_point: &str,
seed: Option<u64>,
rng_kind: &RngKind,
) -> CliResult<()> {
if sample_size <= 0.0 {
return fail_incorrectusage_clierror!("Sample size must be positive");
}
// Split sample_size into integer and fractional parts
let interval = sample_size.trunc() as usize;
let percentage = sample_size.fract();
if interval == 0 {
return fail_incorrectusage_clierror!("Interval must be at least 1");
}
// Calculate target sample size based on percentage
#[allow(clippy::cast_precision_loss)]
let target_count = if percentage > 0.0 {
((row_count as f64) * percentage).round() as u64
} else {
row_count
};
// Select starting point
let start = if starting_point == "random" {
match rng_kind {
RngKind::Standard => {
let mut rng = StandardRng::create(seed);
rng.random_range(0..interval)
},
RngKind::Faster => {
let mut rng = FasterRng::create(seed);
rng.random_range(0..interval)
},
RngKind::Cryptosecure => {
let mut rng = CryptoRng::create(seed);
rng.random_range(0..interval)
},
}
} else {
0 // starting point is the first record
};
// Select records at regular intervals
let mut selected_count = 0;
for (i, record) in rdr.byte_records().enumerate().skip(start) {
if i % interval == 0 && selected_count < target_count {
wtr.write_byte_record(&record?)?;
selected_count += 1;
}
}
Ok(())
}
// Stratified sampling implementation
fn sample_stratified<R: io::Read, W: io::Write>(
rdr: &mut csv::Reader<R>,
wtr: &mut csv::Writer<W>,
strata_column: usize,
samples_per_stratum: usize,
seed: Option<u64>,
rng_kind: &RngKind,
) -> CliResult<()> {
const ESTIMATED_STRATA_COUNT: usize = 100;
// Pre-allocate with capacity for better performance
let mut strata_counts: HashMap<Vec<u8>, usize> = HashMap::with_capacity(ESTIMATED_STRATA_COUNT);
let mut records = Vec::with_capacity(ESTIMATED_STRATA_COUNT * samples_per_stratum);
let mut curr_record;
// First pass: count strata and collect records
for record in rdr.byte_records() {
curr_record = record?;
let stratum = curr_record
.get(strata_column)
.ok_or_else(|| format!("Strata column index {strata_column} out of bounds"))?
.to_vec();
*strata_counts.entry(stratum.clone()).or_default() += 1;
records.push(curr_record);
}
let strata_count = strata_counts.len();
if strata_count == 0 {
return fail_incorrectusage_clierror!("No valid strata found in the data");
}
// Initialize reservoirs with capacity
let mut reservoirs: HashMap<Vec<u8>, Vec<csv::ByteRecord>> =
HashMap::with_capacity(strata_count);
for stratum in strata_counts.keys() {
reservoirs.insert(stratum.clone(), Vec::with_capacity(samples_per_stratum));
}
// Create RNG and perform sampling
match rng_kind {
RngKind::Standard => {
let mut rng = StandardRng::create(seed);
do_stratified_sampling(
records.into_iter(),
&mut reservoirs,
strata_column,
samples_per_stratum,
&mut rng,
)?;
},
RngKind::Faster => {
let mut rng = FasterRng::create(seed);
do_stratified_sampling(
records.into_iter(),
&mut reservoirs,
strata_column,
samples_per_stratum,
&mut rng,
)?;
},
RngKind::Cryptosecure => {
let mut rng = CryptoRng::create(seed);
do_stratified_sampling(
records.into_iter(),
&mut reservoirs,
strata_column,
samples_per_stratum,
&mut rng,
)?;
},
}
// Write results in deterministic order
let mut strata: Vec<_> = reservoirs.keys().collect();
strata.par_sort_unstable();
for stratum in strata {
if let Some(records) = reservoirs.get(stratum) {
for record in records {
wtr.write_byte_record(record)?;
}
}
}
Ok(())
}
fn do_stratified_sampling<T: Rng + ?Sized>(
records: impl Iterator<Item = csv::ByteRecord>,
reservoirs: &mut HashMap<Vec<u8>, Vec<csv::ByteRecord>>,
strata_column: usize,
samples_per_stratum: usize,
rng: &mut T,
) -> CliResult<()> {
let mut records_seen: HashMap<Vec<u8>, usize> = HashMap::with_capacity(reservoirs.len());
for record in records {
let stratum = record
.get(strata_column)
.ok_or_else(|| format!("Strata column index {strata_column} out of bounds"))?
.to_vec();
let seen = records_seen.entry(stratum.clone()).or_default();
if let Some(reservoir) = reservoirs.get_mut(&stratum) {
if reservoir.len() < samples_per_stratum {
reservoir.push(record);
} else {
let j = rng.random_range(0..=*seen);
if j < samples_per_stratum {
// safety: we know that j is within the bounds of the reservoir
unsafe { *reservoir.get_unchecked_mut(j) = record };
}
}
*seen += 1;
}
}
Ok(())
}