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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! Polars-first event dropping augmentations for event camera data
//!
//! This module provides event dropping functionality using Polars DataFrames
//! and LazyFrames for maximum performance and memory efficiency. All operations
//! work directly with Polars expressions and avoid unnecessary conversions.
//!
//! # Philosophy
//!
//! This implementation follows a strict Polars-first approach:
//! - Input: LazyFrame (from events_to_dataframe)
//! - Processing: Polars expressions and transformations
//! - Output: LazyFrame (convertible to Vec<Event>/numpy only when needed)
//!
//! # Performance Benefits
//!
//! - Lazy evaluation: Operations are optimized and executed only when needed
//! - Vectorized operations: All dropping uses SIMD-optimized Polars operations
//! - Memory efficiency: No intermediate Vec<Event> allocations
//! - Query optimization: Polars optimizes the entire augmentation pipeline
//!
//! # Strategies
//!
//! - drop_by_probability: Use ev_filtering::downsampling with uniform strategy
//! - drop_by_time: Drop events within a time interval
//! - drop_by_area: Drop events within a spatial region
//!
//! # Example
//!
//! ```rust
//! use polars::prelude::*;
//! use evlib::ev_augmentation::drop_event::*;
//!
//! // Convert events to LazyFrame once
//! let events_df = events_to_dataframe(&events)?.lazy();
//!
//! // Apply event dropping with Polars expressions
//! let filtered = apply_drop_event(events_df, &DropEventAugmentation::new(0.2))?;
//! ```
use crate;
// Removed: use crate::Events; - legacy type no longer exists
use crateDownsamplingFilter;
// Tracing imports removed due to unused warnings
use *;
// Polars column names for event data consistency
pub const COL_X: &str = "x";
pub const COL_Y: &str = "y";
pub const COL_T: &str = "t";
pub const COL_POLARITY: &str = "polarity";
/// Drop event by probability augmentation
///
/// This is a wrapper around the existing downsampling functionality
/// for API consistency with tonic.
/// Apply drop event using DataFrame - this is the main implementation function
/* Commented out - legacy SingleAugmentation trait no longer exists
impl SingleAugmentation for DropEventAugmentation {
fn apply(&self, events: &Events) -> AugmentationResult<Events> {
// Legacy Vec<Event> interface - convert to DataFrame and back
// This is for backward compatibility only
#[cfg(unix)]
tracing::warn!("Using legacy Vec<Event> interface - consider using LazyFrame directly for better performance");
#[cfg(not(unix))]
eprintln!("[WARN] Using legacy Vec<Event> interface - consider using LazyFrame directly for better performance");
{
let df = crate::events_to_dataframe(events)
.map_err(|e| {
AugmentationError::ProcessingError(format!(
"DataFrame conversion failed: {}",
e
))
})?
.lazy();
let filtered_df = self.apply_to_dataframe(df).map_err(|e| {
AugmentationError::ProcessingError(format!("Polars dropping failed: {}", e))
})?;
// Convert back to Vec<Event> - this is inefficient but maintains compatibility
let result_df = filtered_df.collect().map_err(|e| {
AugmentationError::ProcessingError(format!("LazyFrame collection failed: {}", e))
})?;
// Convert DataFrame back to Events
dataframe_to_events(&result_df)
}
crate::ev_filtering::downsampling::apply_downsampling_filter(events, &filter)
.map_err(|e| AugmentationError::ProcessingError(e.to_string()))
}
}
fn description(&self) -> String {
format!("Drop event: {}", self.description())
}
}
*/
/// Drop events by time interval augmentation
///
/// Drops events within a randomly selected time interval.
/// Apply drop time using DataFrame - this is the main implementation function
/* Commented out - legacy SingleAugmentation trait no longer exists
impl SingleAugmentation for DropTimeAugmentation {
fn apply(&self, events: &Events) -> AugmentationResult<Events> {
// Legacy Vec<Event> interface - convert to DataFrame and back
// This is for backward compatibility only
#[cfg(unix)]
tracing::warn!("Using legacy Vec<Event> interface - consider using LazyFrame directly for better performance");
#[cfg(not(unix))]
eprintln!("[WARN] Using legacy Vec<Event> interface - consider using LazyFrame directly for better performance");
{
let df = crate::events_to_dataframe(events)
.map_err(|e| {
AugmentationError::ProcessingError(format!(
"DataFrame conversion failed: {}",
e
))
})?
.lazy();
let filtered_df = self.apply_to_dataframe(df).map_err(|e| {
AugmentationError::ProcessingError(format!("Polars dropping failed: {}", e))
})?;
// Convert back to Vec<Event> - this is inefficient but maintains compatibility
let result_df = filtered_df.collect().map_err(|e| {
AugmentationError::ProcessingError(format!("LazyFrame collection failed: {}", e))
})?;
// Convert DataFrame back to Events
dataframe_to_events(&result_df)
}
}
fn description(&self) -> String {
format!("Drop time: {}", self.description())
}
}
*/
/// Drop events by area augmentation
///
/// Drops events within a randomly selected rectangular area.
/// Apply drop area using DataFrame - this is the main implementation function
/* Commented out - legacy SingleAugmentation trait no longer exists
impl SingleAugmentation for DropAreaAugmentation {
fn apply(&self, events: &Events) -> AugmentationResult<Events> {
// Legacy Vec<Event> interface - convert to DataFrame and back
// This is for backward compatibility only
#[cfg(unix)]
tracing::warn!("Using legacy Vec<Event> interface - consider using LazyFrame directly for better performance");
#[cfg(not(unix))]
eprintln!("[WARN] Using legacy Vec<Event> interface - consider using LazyFrame directly for better performance");
{
let df = crate::events_to_dataframe(events)
.map_err(|e| {
AugmentationError::ProcessingError(format!(
"DataFrame conversion failed: {}",
e
))
})?
.lazy();
let filtered_df = self.apply_to_dataframe(df).map_err(|e| {
AugmentationError::ProcessingError(format!("Polars dropping failed: {}", e))
})?;
// Convert back to Vec<Event> - this is inefficient but maintains compatibility
let result_df = filtered_df.collect().map_err(|e| {
AugmentationError::ProcessingError(format!("LazyFrame collection failed: {}", e))
})?;
// Convert DataFrame back to Events
dataframe_to_events(&result_df)
}
}
fn description(&self) -> String {
format!("Drop area: {}", self.description())
}
}
*/
/* Commented out - legacy Events type no longer exists
/// Legacy function for backward compatibility - delegates to Polars implementation
pub fn drop_by_probability(events: &Events, probability: f64) -> AugmentationResult<Events> {
let aug = DropEventAugmentation::new(probability);
aug.apply(events)
}
/// Helper function to convert DataFrame back to Events (for legacy compatibility)
fn dataframe_to_events(df: &DataFrame) -> AugmentationResult<Events> {
let height = df.height();
let mut events = Vec::with_capacity(height);
let x_series = df
.column(COL_X)
.map_err(|e| AugmentationError::ProcessingError(format!("Missing x column: {}", e)))?;
let y_series = df
.column(COL_Y)
.map_err(|e| AugmentationError::ProcessingError(format!("Missing y column: {}", e)))?;
let t_series = df
.column(COL_T)
.map_err(|e| AugmentationError::ProcessingError(format!("Missing t column: {}", e)))?;
let p_series = df
.column(COL_POLARITY)
.map_err(|e| AugmentationError::ProcessingError(format!("Missing polarity column: {}", e)))?;
let x_values = x_series
.i64()
.map_err(|e| AugmentationError::ProcessingError(format!("X column type error: {}", e)))?;
let y_values = y_series
.i64()
.map_err(|e| AugmentationError::ProcessingError(format!("Y column type error: {}", e)))?;
let t_values = t_series
.f64()
.map_err(|e| AugmentationError::ProcessingError(format!("T column type error: {}", e)))?;
let p_values = p_series
.i64()
.map_err(|e| AugmentationError::ProcessingError(format!("Polarity column type error: {}", e)))?;
for i in 0..height {
let x = x_values
.get(i)
.ok_or_else(|| AugmentationError::ProcessingError("Missing x value".to_string()))?
as u16;
let y = y_values
.get(i)
.ok_or_else(|| AugmentationError::ProcessingError("Missing y value".to_string()))?
as u16;
let t = t_values
.get(i)
.ok_or_else(|| AugmentationError::ProcessingError("Missing t value".to_string()))?;
let p = p_values
.get(i)
.ok_or_else(|| AugmentationError::ProcessingError("Missing polarity value".to_string()))?
> 0;
events.push(crate::Event {
x,
y,
t,
polarity: p,
});
}
Ok(events)
}
/// Drop events within a time interval
#[cfg_attr(unix, instrument(skip(events), fields(n_events = events.len())))]
pub fn drop_by_time(events: &Events, config: &DropTimeAugmentation) -> AugmentationResult<Events> {
let start_time = std::time::Instant::now();
if events.is_empty() {
debug!("No events to drop");
return Ok(Vec::new());
}
// Validate configuration
config.validate()?;
// Find time range
let t_start = events
.iter()
.map(|e| e.t)
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(0.0);
let t_end = events
.iter()
.map(|e| e.t)
.max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(1.0);
let total_duration = t_end - t_start;
if total_duration <= 0.0 {
return Ok(events.clone());
}
// Initialize RNG
let mut rng = if let Some(seed) = config.seed {
rand::rngs::StdRng::seed_from_u64(seed)
} else {
rand::rngs::StdRng::from_entropy()
};
// Get actual ratio to use
let ratio = if let Some((min, max)) = config.ratio_range {
Uniform::new(min, max).sample(&mut rng)
} else {
config.duration_ratio
};
// Calculate drop interval
let drop_duration = total_duration * ratio;
let max_start = total_duration - drop_duration;
let drop_start = if max_start > 0.0 {
t_start + Uniform::new(0.0, max_start).sample(&mut rng)
} else {
t_start
};
let drop_end = drop_start + drop_duration;
// Filter events
let mut filtered_events = Vec::with_capacity(events.len());
let mut dropped_count = 0;
for event in events {
if event.t >= drop_start && event.t <= drop_end {
dropped_count += 1;
} else {
filtered_events.push(*event);
}
}
let processing_time = start_time.elapsed().as_secs_f64();
info!(
"Drop by time applied (interval {:.3}s-{:.3}s): {} -> {} events ({} dropped) in {:.3}s",
drop_start,
drop_end,
events.len(),
filtered_events.len(),
dropped_count,
processing_time
);
Ok(filtered_events)
}
/// Drop events within a spatial area
#[cfg_attr(unix, instrument(skip(events), fields(n_events = events.len())))]
pub fn drop_by_area(events: &Events, config: &DropAreaAugmentation) -> AugmentationResult<Events> {
let start_time = std::time::Instant::now();
if events.is_empty() {
debug!("No events to drop");
return Ok(Vec::new());
}
// Validate configuration
config.validate()?;
// Initialize RNG
let mut rng = if let Some(seed) = config.seed {
rand::rngs::StdRng::seed_from_u64(seed)
} else {
rand::rngs::StdRng::from_entropy()
};
// Get actual ratio to use
let ratio = if let Some((min, max)) = config.ratio_range {
Uniform::new(min, max).sample(&mut rng)
} else {
config.area_ratio
};
// Calculate box dimensions
let box_width = ((config.sensor_width as f64) * ratio.sqrt()) as u16;
let box_height = ((config.sensor_height as f64) * ratio.sqrt()) as u16;
// Random box position
let max_x = config.sensor_width.saturating_sub(box_width);
let max_y = config.sensor_height.saturating_sub(box_height);
let box_x = if max_x > 0 {
Uniform::new(0, max_x).sample(&mut rng)
} else {
0
};
let box_y = if max_y > 0 {
Uniform::new(0, max_y).sample(&mut rng)
} else {
0
};
let box_x_end = box_x + box_width;
let box_y_end = box_y + box_height;
// Filter events
let mut filtered_events = Vec::with_capacity(events.len());
let mut dropped_count = 0;
for event in events {
if event.x >= box_x && event.x < box_x_end && event.y >= box_y && event.y < box_y_end {
dropped_count += 1;
} else {
filtered_events.push(*event);
}
}
let processing_time = start_time.elapsed().as_secs_f64();
info!(
"Drop by area applied (box [{},{})x[{},{})): {} -> {} events ({} dropped) in {:.3}s",
box_x,
box_x_end,
box_y,
box_y_end,
events.len(),
filtered_events.len(),
dropped_count,
processing_time
);
Ok(filtered_events)
}
/// Apply drop by time using Polars expressions
///
/// This is the main time-based dropping function that works entirely with Polars
/// operations for maximum performance. For random parameters, it collects data
/// to compute ranges but uses vectorized filtering.
///
/// # Arguments
///
/// * `df` - Input LazyFrame containing event data
/// * `config` - Time dropping configuration
///
/// # Returns
///
/// Filtered LazyFrame with events in time interval dropped
///
/// # Example
///
/// ```rust
/// use polars::prelude::*;
/// use evlib::ev_augmentation::drop_event::*;
///
/// let events_df = events_to_dataframe(&events)?.lazy();
/// let config = DropTimeAugmentation::new(0.2);
/// let filtered = apply_drop_time(events_df, &config)?;
/// ```
#[cfg_attr(unix, instrument(skip(df), fields(config = ?config)))]
pub fn apply_drop_time(
df: LazyFrame,
config: &DropTimeAugmentation,
) -> PolarsResult<LazyFrame> {
debug!("Applying drop by time with Polars: {:?}", config);
if config.duration_ratio <= 0.0 {
debug!("No time dropping needed (ratio <= 0)");
return Ok(df);
}
// Get time bounds
let time_bounds = df.clone()
.select([
col(COL_T).min().alias("t_min"),
col(COL_T).max().alias("t_max"),
])
.collect()?;
let t_min = time_bounds.column("t_min")?.get(0)?.try_extract::<f64>()?;
let t_max = time_bounds.column("t_max")?.get(0)?.try_extract::<f64>()?;
let total_duration = t_max - t_min;
if total_duration <= 0.0 {
debug!("No temporal range to drop from");
return Ok(df);
}
// For random parameters, we need to generate random values
// This requires some computation but we can still use Polars for filtering
let ratio = if let Some((min, max)) = config.ratio_range {
use rand::Rng;
let mut rng = if let Some(seed) = config.seed {
rand::rngs::StdRng::seed_from_u64(seed)
} else {
rand::rngs::StdRng::from_entropy()
};
rand_distr::Uniform::new(min, max).sample(&mut rng)
} else {
config.duration_ratio
};
// Calculate drop interval
let drop_duration = total_duration * ratio;
let max_start = total_duration - drop_duration;
let drop_start = if max_start > 0.0 {
use rand::Rng;
let mut rng = if let Some(seed) = config.seed {
rand::rngs::StdRng::seed_from_u64(seed.wrapping_add(1))
} else {
rand::rngs::StdRng::from_entropy()
};
t_min + rand_distr::Uniform::new(0.0, max_start).sample(&mut rng)
} else {
t_min
};
let drop_end = drop_start + drop_duration;
info!(
"Drop by time interval [{:.6}, {:.6}] (ratio={:.3})",
drop_start, drop_end, ratio
);
// Apply vectorized filtering
Ok(df.filter(
col(COL_T).lt(lit(drop_start))
.or(col(COL_T).gt(lit(drop_end)))
))
}
/// Legacy Polars function for backward compatibility
pub fn apply_drop_time_polars(
df: LazyFrame,
config: &DropTimeAugmentation,
) -> PolarsResult<LazyFrame> {
apply_drop_time(df, config)
}
/// Apply drop by area using Polars expressions
///
/// This is the main spatial area-based dropping function that works entirely with Polars
/// operations for maximum performance. It uses vectorized filtering with spatial bounds.
///
/// # Arguments
///
/// * `df` - Input LazyFrame containing event data
/// * `config` - Area dropping configuration
///
/// # Returns
///
/// Filtered LazyFrame with events in spatial area dropped
///
/// # Example
///
/// ```rust
/// use polars::prelude::*;
/// use evlib::ev_augmentation::drop_event::*;
///
/// let events_df = events_to_dataframe(&events)?.lazy();
/// let config = DropAreaAugmentation::new(0.25, 640, 480);
/// let filtered = apply_drop_area(events_df, &config)?;
/// ```
#[cfg_attr(unix, instrument(skip(df), fields(config = ?config)))]
pub fn apply_drop_area(
df: LazyFrame,
config: &DropAreaAugmentation,
) -> PolarsResult<LazyFrame> {
debug!("Applying drop by area with Polars: {:?}", config);
if config.area_ratio <= 0.0 {
debug!("No area dropping needed (ratio <= 0)");
return Ok(df);
}
// Generate random parameters for drop area
let ratio = if let Some((min, max)) = config.ratio_range {
use rand::Rng;
let mut rng = if let Some(seed) = config.seed {
rand::rngs::StdRng::seed_from_u64(seed)
} else {
rand::rngs::StdRng::from_entropy()
};
rand_distr::Uniform::new(min, max).sample(&mut rng)
} else {
config.area_ratio
};
// Calculate box dimensions
let box_width = ((config.sensor_width as f64) * ratio.sqrt()) as u16;
let box_height = ((config.sensor_height as f64) * ratio.sqrt()) as u16;
// Random box position
let max_x = config.sensor_width.saturating_sub(box_width);
let max_y = config.sensor_height.saturating_sub(box_height);
let (box_x, box_y) = {
use rand::Rng;
let mut rng = if let Some(seed) = config.seed {
rand::rngs::StdRng::seed_from_u64(seed.wrapping_add(1))
} else {
rand::rngs::StdRng::from_entropy()
};
let x = if max_x > 0 {
rand_distr::Uniform::new(0, max_x).sample(&mut rng)
} else {
0
};
let y = if max_y > 0 {
rand_distr::Uniform::new(0, max_y).sample(&mut rng)
} else {
0
};
(x, y)
};
let box_x_end = box_x + box_width;
let box_y_end = box_y + box_height;
info!(
"Drop by area box [{},{})x[{},{}) (ratio={:.3})",
box_x, box_x_end, box_y, box_y_end, ratio
);
// Apply vectorized filtering - keep events OUTSIDE the box
Ok(df.filter(
col(COL_X).lt(lit(box_x as i64))
.or(col(COL_X).gt_eq(lit(box_x_end as i64)))
.or(col(COL_Y).lt(lit(box_y as i64)))
.or(col(COL_Y).gt_eq(lit(box_y_end as i64)))
))
}
/// Legacy Polars function for backward compatibility
pub fn apply_drop_area_polars(
df: LazyFrame,
config: &DropAreaAugmentation,
) -> PolarsResult<LazyFrame> {
apply_drop_area(df, config)
}
/// Apply drop event using Polars expressions
///
/// This is the main probabilistic dropping function that works entirely with Polars
/// operations for maximum performance. It leverages the existing downsampling
/// functionality for consistent behavior.
///
/// # Arguments
///
/// * `df` - Input LazyFrame containing event data
/// * `config` - Event dropping configuration
///
/// # Returns
///
/// Filtered LazyFrame with events randomly dropped
///
/// # Example
///
/// ```rust
/// use polars::prelude::*;
/// use evlib::ev_augmentation::drop_event::*;
///
/// let events_df = events_to_dataframe(&events)?.lazy();
/// let config = DropEventAugmentation::new(0.3);
/// let filtered = apply_drop_event(events_df, &config)?;
/// ```
#[cfg_attr(unix, instrument(skip(df), fields(config = ?config)))]
pub fn apply_drop_event(
df: LazyFrame,
config: &DropEventAugmentation,
) -> PolarsResult<LazyFrame> {
debug!("Applying drop event with Polars: {:?}", config);
if config.drop_probability <= 0.0 {
debug!("No event dropping needed (probability <= 0)");
return Ok(df);
}
if config.drop_probability >= 1.0 {
debug!("Dropping all events (probability >= 1)");
return Ok(df.limit(0)); // Return empty DataFrame with same schema
}
// Use downsampling functionality for consistent behavior
let keep_rate = 1.0 - config.drop_probability;
let mut filter = DownsamplingFilter::uniform(keep_rate);
if let Some(seed) = config.seed {
filter.random_seed = Some(seed);
}
crate::ev_filtering::downsampling::apply_downsampling_filter_polars(df, &filter)
}
/// Legacy Polars function for backward compatibility
pub fn apply_drop_event_polars(
df: LazyFrame,
config: &DropEventAugmentation,
) -> PolarsResult<LazyFrame> {
apply_drop_event(df, config)
}
/// Apply event dropping directly to LazyFrame - DataFrame-native version (recommended)
///
/// This function applies probabilistic event dropping directly to a LazyFrame for optimal performance.
/// Use this instead of the legacy Vec<Event> version when possible.
///
/// # Arguments
///
/// * `df` - Input LazyFrame containing event data
/// * `drop_probability` - Probability of dropping each event (0.0 to 1.0)
///
/// # Returns
///
/// Filtered LazyFrame
pub fn drop_by_probability_df(
df: LazyFrame,
drop_probability: f64
) -> PolarsResult<LazyFrame> {
let config = DropEventAugmentation::new(drop_probability);
apply_drop_event(df, &config)
}
/// Apply time dropping directly to LazyFrame - DataFrame-native version (recommended)
///
/// This function applies time-based event dropping directly to a LazyFrame for optimal performance.
/// Use this instead of the legacy Vec<Event> version when possible.
///
/// # Arguments
///
/// * `df` - Input LazyFrame containing event data
/// * `duration_ratio` - Ratio of total duration to drop (0.0 to 1.0)
///
/// # Returns
///
/// Filtered LazyFrame
pub fn drop_by_time_df(
df: LazyFrame,
duration_ratio: f64
) -> PolarsResult<LazyFrame> {
let config = DropTimeAugmentation::new(duration_ratio);
apply_drop_time(df, &config)
}
/// Apply area dropping directly to LazyFrame - DataFrame-native version (recommended)
///
/// This function applies area-based event dropping directly to a LazyFrame for optimal performance.
/// Use this instead of the legacy Vec<Event> version when possible.
///
/// # Arguments
///
/// * `df` - Input LazyFrame containing event data
/// * `area_ratio` - Ratio of sensor area to drop (0.0 to 1.0)
/// * `sensor_width` - Sensor width in pixels
/// * `sensor_height` - Sensor height in pixels
///
/// # Returns
///
/// Filtered LazyFrame
pub fn drop_by_area_df(
df: LazyFrame,
area_ratio: f64,
sensor_width: u16,
sensor_height: u16
) -> PolarsResult<LazyFrame> {
let config = DropAreaAugmentation::new(area_ratio, sensor_width, sensor_height);
apply_drop_area(df, &config)
}
#[cfg(test)]
mod tests {
use super::*;
fn create_test_events() -> Events {
let mut events = Vec::new();
for i in 0..100 {
events.push(Event {
t: i as f64 * 0.01, // 0 to 0.99 seconds
x: (i % 40) as u16 * 10, // 0 to 390
y: (i / 40) as u16 * 10, // 0 to 20
polarity: i % 2 == 0,
});
}
events
}
#[test]
fn test_drop_event_augmentation() {
let events = create_test_events();
let aug = DropEventAugmentation::new(0.3).with_seed(42);
let filtered = aug.apply(&events).unwrap();
// Should drop approximately 30% of events
assert!(filtered.len() < events.len());
assert!(filtered.len() > events.len() / 2); // But not too many
}
#[test]
fn test_drop_by_time() {
let events = create_test_events();
let config = DropTimeAugmentation::new(0.2).with_seed(42);
let filtered = drop_by_time(&events, &config).unwrap();
// Should drop approximately 20% of events
assert!(filtered.len() < events.len());
assert!(filtered.len() > events.len() * 0.7);
// Remaining events should not be in a contiguous interval
let times: Vec<f64> = filtered.iter().map(|e| e.t).collect();
let mut has_gap = false;
for i in 1..times.len() {
if times[i] - times[i - 1] > 0.011 {
// Larger than normal spacing
has_gap = true;
break;
}
}
assert!(has_gap);
}
#[test]
fn test_drop_by_area() {
let events = create_test_events();
let config = DropAreaAugmentation::new(0.25, 400, 400).with_seed(42);
let filtered = drop_by_area(&events, &config).unwrap();
// Should drop approximately 25% of events
assert!(filtered.len() < events.len());
assert!(filtered.len() > events.len() / 2);
}
#[test]
fn test_drop_by_time_random_range() {
let events = create_test_events();
let config = DropTimeAugmentation::random(0.1, 0.3).with_seed(42);
let filtered = drop_by_time(&events, &config).unwrap();
// Should drop between 10% and 30% of events
assert!(filtered.len() <= events.len() * 0.9);
assert!(filtered.len() >= events.len() * 0.7);
}
#[test]
fn test_drop_by_area_random_range() {
let events = create_test_events();
let config = DropAreaAugmentation::random(0.1, 0.3, 400, 400).with_seed(42);
let filtered = drop_by_area(&events, &config).unwrap();
// Should drop between 10% and 30% of events (approximately)
assert!(filtered.len() < events.len());
}
#[test]
fn test_validation() {
// Valid configs
assert!(DropEventAugmentation::new(0.5).validate().is_ok());
assert!(DropTimeAugmentation::new(0.5).validate().is_ok());
assert!(DropAreaAugmentation::new(0.5, 640, 480).validate().is_ok());
// Invalid configs
assert!(DropEventAugmentation::new(-0.1).validate().is_err());
assert!(DropEventAugmentation::new(1.1).validate().is_err());
assert!(DropTimeAugmentation::new(1.0).validate().is_err());
assert!(DropAreaAugmentation::new(0.5, 0, 480).validate().is_err());
}
#[test]
fn test_empty_events() {
let events = Vec::new();
let filtered = drop_by_time(&events, &DropTimeAugmentation::new(0.5)).unwrap();
assert!(filtered.is_empty());
let filtered = drop_by_area(&events, &DropAreaAugmentation::new(0.5, 640, 480)).unwrap();
assert!(filtered.is_empty());
}
#[test]
fn test_drop_event_dataframe_native() -> PolarsResult<()> {
use crate::{events_to_dataframe, Event};
let events = create_test_events();
let df = events_to_dataframe(&events)?.lazy();
let config = DropEventAugmentation::new(0.3);
let dropped_df = config.apply_to_dataframe(df)?;
let result = dropped_df.collect()?;
// Should have fewer events
assert!(result.height() < events.len());
Ok(())
}
#[test]
fn test_drop_by_time_dataframe_native() -> PolarsResult<()> {
use crate::events_to_dataframe;
let events = create_test_events();
let df = events_to_dataframe(&events)?.lazy();
let config = DropTimeAugmentation::new(0.2);
let dropped_df = config.apply_to_dataframe(df)?;
let result = dropped_df.collect()?;
// Should have fewer events
assert!(result.height() < events.len());
Ok(())
}
#[test]
fn test_drop_by_area_dataframe_native() -> PolarsResult<()> {
use crate::events_to_dataframe;
let events = create_test_events();
let df = events_to_dataframe(&events)?.lazy();
let config = DropAreaAugmentation::new(0.25, 400, 400);
let dropped_df = config.apply_to_dataframe(df)?;
let result = dropped_df.collect()?;
// Should have fewer events
assert!(result.height() < events.len());
Ok(())
}
#[test]
fn test_drop_convenience_functions() -> PolarsResult<()> {
use crate::events_to_dataframe;
let events = create_test_events();
let df = events_to_dataframe(&events)?.lazy();
// Test probability dropping
let dropped1 = drop_by_probability_df(df.clone(), 0.2)?;
let result1 = dropped1.collect()?;
assert!(result1.height() <= events.len());
// Test time dropping
let dropped2 = drop_by_time_df(df.clone(), 0.1)?;
let result2 = dropped2.collect()?;
assert!(result2.height() <= events.len());
// Test area dropping
let dropped3 = drop_by_area_df(df, 0.1, 400, 400)?;
let result3 = dropped3.collect()?;
assert!(result3.height() <= events.len());
Ok(())
}
#[test]
fn test_drop_legacy_compatibility() {
let events = create_test_events();
let config1 = DropEventAugmentation::new(0.2);
let dropped1 = config1.apply(&events).unwrap();
assert!(dropped1.len() <= events.len());
let config2 = DropTimeAugmentation::new(0.1);
let dropped2 = config2.apply(&events).unwrap();
assert!(dropped2.len() <= events.len());
let config3 = DropAreaAugmentation::new(0.1, 400, 400);
let dropped3 = config3.apply(&events).unwrap();
assert!(dropped3.len() <= events.len());
}
}
*/