Skip to main content

torsh_data/
augmentation_pipeline.rs

1//! Data augmentation pipeline for machine learning training
2//!
3//! This module provides a comprehensive augmentation system for training data preprocessing.
4//! Augmentation is a critical technique for improving model generalization by applying
5//! random transformations to training data.
6//!
7//! # Features
8//!
9//! - **Pipeline composition**: AugmentationPipeline for chaining multiple transforms
10//! - **Probabilistic transforms**: ConditionalTransform for random application
11//! - **Image augmentations**: Color, brightness, contrast, and geometric transforms
12//! - **Noise augmentation**: GaussianNoise for regularization
13//! - **Cutout/Erasing**: RandomErasing for occlusion robustness
14//! - **Preset pipelines**: Common augmentation configurations for different use cases
15
16use crate::transforms::Transform;
17use torsh_core::dtype::{FloatElement, TensorElement};
18use torsh_core::error::Result;
19use torsh_tensor::Tensor;
20
21#[cfg(not(feature = "std"))]
22use alloc::{boxed::Box, vec::Vec};
23
24#[cfg(feature = "std")]
25use scirs2_core::random::thread_rng;
26
27#[cfg(not(feature = "std"))]
28use scirs2_core::random::thread_rng;
29
30/// Augmentation pipeline builder for easy composition of transforms
31pub struct AugmentationPipeline<T> {
32    transforms: Vec<Box<dyn Transform<T, Output = T> + Send + Sync>>,
33    probability: f32,
34}
35
36impl<T: 'static + Send + Sync> AugmentationPipeline<T> {
37    /// Create a new augmentation pipeline
38    pub fn new() -> Self {
39        Self {
40            transforms: Vec::new(),
41            probability: 1.0,
42        }
43    }
44
45    /// Set the probability of applying the entire pipeline
46    ///
47    /// # Panics
48    ///
49    /// Panics if `prob` is outside `[0.0, 1.0]`. See [`Self::try_with_probability`]
50    /// for a non-panicking variant.
51    pub fn with_probability(mut self, prob: f32) -> Self {
52        assert!(
53            (0.0..=1.0).contains(&prob),
54            "Probability must be between 0 and 1"
55        );
56        self.probability = prob;
57        self
58    }
59
60    /// Fallible variant of [`Self::with_probability`] that returns an error
61    /// instead of panicking when `prob` is outside `[0.0, 1.0]`.
62    pub fn try_with_probability(mut self, prob: f32) -> Result<Self> {
63        crate::utils::validate_probability(prob, "prob")?;
64        self.probability = prob;
65        Ok(self)
66    }
67
68    /// Add a transform to the pipeline
69    pub fn add_transform<F>(mut self, transform: F) -> Self
70    where
71        F: Transform<T, Output = T> + 'static,
72    {
73        self.transforms.push(Box::new(transform));
74        self
75    }
76
77    /// Add a conditional transform that only applies with given probability
78    pub fn add_conditional<F>(self, transform: F, prob: f32) -> Self
79    where
80        F: Transform<T, Output = T> + 'static,
81    {
82        self.add_transform(ConditionalTransform::new(transform, prob))
83    }
84}
85
86impl<T: 'static + Send + Sync> Default for AugmentationPipeline<T> {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92impl<T> Transform<T> for AugmentationPipeline<T> {
93    type Output = T;
94
95    fn transform(&self, mut input: T) -> Result<Self::Output> {
96        let mut rng = thread_rng();
97
98        // Check if we should apply the pipeline at all
99        if rng.random::<f32>() > self.probability {
100            return Ok(input);
101        }
102
103        // Apply all transforms in sequence
104        for transform in &self.transforms {
105            input = transform.transform(input)?;
106        }
107
108        Ok(input)
109    }
110}
111
112/// Conditional transform that applies with a given probability
113pub struct ConditionalTransform<T, F> {
114    transform: F,
115    probability: f32,
116    _phantom: core::marker::PhantomData<T>,
117}
118
119impl<T, F> ConditionalTransform<T, F> {
120    /// # Panics
121    ///
122    /// Panics if `probability` is outside `[0.0, 1.0]`. See
123    /// [`Self::try_new`] for a non-panicking variant.
124    pub fn new(transform: F, probability: f32) -> Self {
125        assert!(
126            (0.0..=1.0).contains(&probability),
127            "Probability must be between 0 and 1"
128        );
129        Self {
130            transform,
131            probability,
132            _phantom: core::marker::PhantomData,
133        }
134    }
135
136    /// Fallible variant of [`Self::new`] that returns an error instead of
137    /// panicking when `probability` is outside `[0.0, 1.0]`.
138    pub fn try_new(transform: F, probability: f32) -> Result<Self> {
139        crate::utils::validate_probability(probability, "probability")?;
140        Ok(Self {
141            transform,
142            probability,
143            _phantom: core::marker::PhantomData,
144        })
145    }
146}
147
148impl<T, F> Transform<T> for ConditionalTransform<T, F>
149where
150    F: Transform<T, Output = T>,
151    T: Send + Sync,
152{
153    type Output = T;
154
155    fn transform(&self, input: T) -> Result<Self::Output> {
156        let mut rng = thread_rng();
157
158        if rng.random::<f32>() < self.probability {
159            self.transform.transform(input)
160        } else {
161            Ok(input)
162        }
163    }
164}
165
166/// Random brightness adjustment
167pub struct RandomBrightness {
168    factor_range: (f32, f32),
169}
170
171impl RandomBrightness {
172    /// # Panics
173    ///
174    /// Panics if `factor_range.0 > factor_range.1`. See [`Self::try_new`] for
175    /// a non-panicking variant.
176    pub fn new(factor_range: (f32, f32)) -> Self {
177        assert!(factor_range.0 <= factor_range.1, "Invalid factor range");
178        Self { factor_range }
179    }
180
181    /// Fallible variant of [`Self::new`] that returns an error instead of
182    /// panicking when `factor_range.0 > factor_range.1`.
183    pub fn try_new(factor_range: (f32, f32)) -> Result<Self> {
184        crate::utils::validate_range(factor_range, "factor_range")?;
185        Ok(Self { factor_range })
186    }
187
188    /// Create with symmetric range around 1.0
189    pub fn symmetric(factor: f32) -> Self {
190        Self::new((1.0 - factor, 1.0 + factor))
191    }
192}
193
194impl<T: FloatElement> Transform<Tensor<T>> for RandomBrightness {
195    type Output = Tensor<T>;
196
197    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
198        let mut rng = thread_rng();
199        let (lo, hi) = self.factor_range;
200        let factor = lo + rng.random::<f32>() * (hi - lo);
201        let shape = input.shape().dims().to_vec();
202        let device = input.device();
203        let data = input
204            .to_vec()
205            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
206        let out: Vec<T> = data
207            .iter()
208            .map(|&x| {
209                let v = <T as TensorElement>::to_f64(&x).unwrap_or(0.0) * factor as f64;
210                let clamped = v.max(0.0).min(1.0);
211                <T as TensorElement>::from_f64(clamped).unwrap_or(x)
212            })
213            .collect();
214        Tensor::from_data(out, shape, device).map_err(|e| e.into())
215    }
216}
217
218/// Random contrast adjustment
219pub struct RandomContrast {
220    factor_range: (f32, f32),
221}
222
223impl RandomContrast {
224    /// # Panics
225    ///
226    /// Panics if `factor_range.0 > factor_range.1`. See [`Self::try_new`] for
227    /// a non-panicking variant.
228    pub fn new(factor_range: (f32, f32)) -> Self {
229        assert!(factor_range.0 <= factor_range.1, "Invalid factor range");
230        Self { factor_range }
231    }
232
233    /// Fallible variant of [`Self::new`] that returns an error instead of
234    /// panicking when `factor_range.0 > factor_range.1`.
235    pub fn try_new(factor_range: (f32, f32)) -> Result<Self> {
236        crate::utils::validate_range(factor_range, "factor_range")?;
237        Ok(Self { factor_range })
238    }
239
240    /// Create with symmetric range around 1.0
241    pub fn symmetric(factor: f32) -> Self {
242        Self::new((1.0 - factor, 1.0 + factor))
243    }
244}
245
246impl<T: FloatElement> Transform<Tensor<T>> for RandomContrast {
247    type Output = Tensor<T>;
248
249    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
250        let mut rng = thread_rng();
251        let (lo, hi) = self.factor_range;
252        let factor = lo + rng.random::<f32>() * (hi - lo);
253        let shape = input.shape().dims().to_vec();
254        let device = input.device();
255        let data = input
256            .to_vec()
257            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
258        let n = data.len();
259        let mean: f64 = data
260            .iter()
261            .map(|x| <T as TensorElement>::to_f64(x).unwrap_or(0.0))
262            .sum::<f64>()
263            / n.max(1) as f64;
264        let out: Vec<T> = data
265            .iter()
266            .map(|&x| {
267                let v =
268                    mean + (<T as TensorElement>::to_f64(&x).unwrap_or(0.0) - mean) * factor as f64;
269                let clamped = v.max(0.0).min(1.0);
270                <T as TensorElement>::from_f64(clamped).unwrap_or(x)
271            })
272            .collect();
273        Tensor::from_data(out, shape, device).map_err(|e| e.into())
274    }
275}
276
277/// Random saturation adjustment (for color images)
278pub struct RandomSaturation {
279    factor_range: (f32, f32),
280}
281
282impl RandomSaturation {
283    /// # Panics
284    ///
285    /// Panics if `factor_range.0 > factor_range.1`. See [`Self::try_new`] for
286    /// a non-panicking variant.
287    pub fn new(factor_range: (f32, f32)) -> Self {
288        assert!(factor_range.0 <= factor_range.1, "Invalid factor range");
289        Self { factor_range }
290    }
291
292    /// Fallible variant of [`Self::new`] that returns an error instead of
293    /// panicking when `factor_range.0 > factor_range.1`.
294    pub fn try_new(factor_range: (f32, f32)) -> Result<Self> {
295        crate::utils::validate_range(factor_range, "factor_range")?;
296        Ok(Self { factor_range })
297    }
298
299    /// Create with symmetric range around 1.0
300    pub fn symmetric(factor: f32) -> Self {
301        Self::new((1.0 - factor, 1.0 + factor))
302    }
303}
304
305impl<T: FloatElement> Transform<Tensor<T>> for RandomSaturation {
306    type Output = Tensor<T>;
307
308    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
309        let mut rng = thread_rng();
310        let (lo, hi) = self.factor_range;
311        let factor = lo + rng.random::<f32>() * (hi - lo);
312        let binding = input.shape();
313        let dims = binding.dims();
314        // Only apply saturation for 3-channel CHW images
315        if dims.len() != 3 || dims[0] != 3 {
316            return Ok(input);
317        }
318        let (_, height, width) = (dims[0], dims[1], dims[2]);
319        let hw = height * width;
320        let device = input.device();
321        let data = input
322            .to_vec()
323            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
324        // ITU-R BT.601 luminance coefficients
325        const LUM_R: f64 = 0.299;
326        const LUM_G: f64 = 0.587;
327        const LUM_B: f64 = 0.114;
328        let mut out = data.clone();
329        for px in 0..hw {
330            let r = <T as TensorElement>::to_f64(&data[px]).unwrap_or(0.0);
331            let g = <T as TensorElement>::to_f64(&data[hw + px]).unwrap_or(0.0);
332            let b = <T as TensorElement>::to_f64(&data[2 * hw + px]).unwrap_or(0.0);
333            let lum = LUM_R * r + LUM_G * g + LUM_B * b;
334            let sat = factor as f64;
335            let new_r = (lum + sat * (r - lum)).max(0.0).min(1.0);
336            let new_g = (lum + sat * (g - lum)).max(0.0).min(1.0);
337            let new_b = (lum + sat * (b - lum)).max(0.0).min(1.0);
338            out[px] = <T as TensorElement>::from_f64(new_r).unwrap_or(data[px]);
339            out[hw + px] = <T as TensorElement>::from_f64(new_g).unwrap_or(data[hw + px]);
340            out[2 * hw + px] = <T as TensorElement>::from_f64(new_b).unwrap_or(data[2 * hw + px]);
341        }
342        Tensor::from_data(out, dims.to_vec(), device).map_err(|e| e.into())
343    }
344}
345
346/// Random hue adjustment (for color images)
347pub struct RandomHue {
348    delta_range: (f32, f32),
349}
350
351impl RandomHue {
352    /// # Panics
353    ///
354    /// Panics if `delta_range.0 > delta_range.1`, or if either bound falls
355    /// outside `[-1.0, 1.0]`. See [`Self::try_new`] for a non-panicking
356    /// variant.
357    pub fn new(delta_range: (f32, f32)) -> Self {
358        assert!(delta_range.0 <= delta_range.1, "Invalid delta range");
359        assert!(
360            delta_range.0 >= -1.0 && delta_range.1 <= 1.0,
361            "Hue delta must be in [-1, 1]"
362        );
363        Self { delta_range }
364    }
365
366    /// Fallible variant of [`Self::new`] that returns an error instead of
367    /// panicking on an invalid `delta_range`.
368    pub fn try_new(delta_range: (f32, f32)) -> Result<Self> {
369        crate::utils::validate_range(delta_range, "delta_range")?;
370        if !(delta_range.0 >= -1.0 && delta_range.1 <= 1.0) {
371            return Err(torsh_core::error::TorshError::InvalidArgument(format!(
372                "Hue delta must be in [-1, 1], got {delta_range:?}"
373            )));
374        }
375        Ok(Self { delta_range })
376    }
377
378    /// Create with symmetric range
379    pub fn symmetric(delta: f32) -> Self {
380        Self::new((-delta, delta))
381    }
382}
383
384impl<T: FloatElement> Transform<Tensor<T>> for RandomHue {
385    type Output = Tensor<T>;
386
387    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
388        // Note: True hue rotation requires RGB→HSV→RGB conversion.
389        // This is a per-channel scale approximation: each channel is
390        // scaled by a slightly different random factor derived from the
391        // hue delta, which shifts the apparent color balance.
392        let mut rng = thread_rng();
393        let (lo, hi) = self.delta_range;
394        let delta = lo + rng.random::<f32>() * (hi - lo);
395        let binding = input.shape();
396        let dims = binding.dims();
397        // Only apply to 3-channel CHW images
398        if dims.len() != 3 || dims[0] != 3 {
399            return Ok(input);
400        }
401        let (_, height, width) = (dims[0], dims[1], dims[2]);
402        let hw = height * width;
403        let device = input.device();
404        let data = input
405            .to_vec()
406            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
407        // Hue shift: rotate color weights using delta as rotation angle proxy
408        // R channel boosted by sin(delta*pi), G unchanged, B reduced by sin(delta*pi)
409        let angle = delta as f64 * std::f64::consts::PI;
410        let r_scale = 1.0 + angle.sin() * 0.5;
411        let g_scale = 1.0 - angle.abs().sin() * 0.1;
412        let b_scale = 1.0 - angle.sin() * 0.5;
413        let mut out = data.clone();
414        for px in 0..hw {
415            let r = <T as TensorElement>::to_f64(&data[px]).unwrap_or(0.0);
416            let g = <T as TensorElement>::to_f64(&data[hw + px]).unwrap_or(0.0);
417            let b = <T as TensorElement>::to_f64(&data[2 * hw + px]).unwrap_or(0.0);
418            out[px] =
419                <T as TensorElement>::from_f64((r * r_scale).max(0.0).min(1.0)).unwrap_or(data[px]);
420            out[hw + px] = <T as TensorElement>::from_f64((g * g_scale).max(0.0).min(1.0))
421                .unwrap_or(data[hw + px]);
422            out[2 * hw + px] = <T as TensorElement>::from_f64((b * b_scale).max(0.0).min(1.0))
423                .unwrap_or(data[2 * hw + px]);
424        }
425        Tensor::from_data(out, dims.to_vec(), device).map_err(|e| e.into())
426    }
427}
428
429/// Random vertical flip
430pub struct RandomVerticalFlip {
431    prob: f32,
432}
433
434impl RandomVerticalFlip {
435    /// # Panics
436    ///
437    /// Panics if `prob` is outside `[0.0, 1.0]`. See [`Self::try_new`] for a
438    /// non-panicking variant.
439    pub fn new(prob: f32) -> Self {
440        assert!(
441            (0.0..=1.0).contains(&prob),
442            "Probability must be between 0 and 1"
443        );
444        Self { prob }
445    }
446
447    /// Fallible variant of [`Self::new`] that returns an error instead of
448    /// panicking when `prob` is outside `[0.0, 1.0]`.
449    pub fn try_new(prob: f32) -> Result<Self> {
450        crate::utils::validate_probability(prob, "prob")?;
451        Ok(Self { prob })
452    }
453}
454
455impl<T: FloatElement> Transform<Tensor<T>> for RandomVerticalFlip {
456    type Output = Tensor<T>;
457
458    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
459        let mut rng = thread_rng();
460        if rng.random::<f32>() >= self.prob {
461            return Ok(input);
462        }
463        let binding = input.shape();
464        let dims = binding.dims();
465        if dims.len() < 2 {
466            return Err(torsh_core::error::TorshError::InvalidArgument(
467                "Input tensor must have at least 2 dimensions for vertical flip".to_string(),
468            ));
469        }
470        let device = input.device();
471        let data = input
472            .to_vec()
473            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
474        // For CHW (3D+), flip dim[-2] (height); for HW (2D), flip dim 0 (height)
475        let (height, width, channels) = if dims.len() == 2 {
476            (dims[0], dims[1], 1usize)
477        } else {
478            (
479                dims[dims.len() - 2],
480                dims[dims.len() - 1],
481                dims[..dims.len() - 2].iter().product(),
482            )
483        };
484        let mut out = data.clone();
485        for c in 0..channels {
486            for row in 0..height / 2 {
487                let mirror_row = height - 1 - row;
488                for col in 0..width {
489                    let idx1 = c * height * width + row * width + col;
490                    let idx2 = c * height * width + mirror_row * width + col;
491                    out.swap(idx1, idx2);
492                }
493            }
494        }
495        Tensor::from_data(out, dims.to_vec(), device).map_err(|e| e.into())
496    }
497}
498
499/// Gaussian noise addition
500pub struct GaussianNoise {
501    mean: f32,
502    std: f32,
503}
504
505impl GaussianNoise {
506    /// # Panics
507    ///
508    /// Panics if `std` is negative. See [`Self::try_new`] for a non-panicking
509    /// variant.
510    pub fn new(mean: f32, std: f32) -> Self {
511        assert!(std >= 0.0, "Standard deviation must be non-negative");
512        Self { mean, std }
513    }
514
515    /// Fallible variant of [`Self::new`] that returns an error instead of
516    /// panicking when `std` is negative.
517    pub fn try_new(mean: f32, std: f32) -> Result<Self> {
518        if std < 0.0 {
519            return Err(torsh_core::error::TorshError::InvalidArgument(format!(
520                "Standard deviation must be non-negative, got {std}"
521            )));
522        }
523        Ok(Self { mean, std })
524    }
525
526    /// Create with zero mean
527    pub fn with_std(std: f32) -> Self {
528        Self::new(0.0, std)
529    }
530}
531
532impl<T: FloatElement> Transform<Tensor<T>> for GaussianNoise {
533    type Output = Tensor<T>;
534
535    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
536        if self.std <= 0.0 {
537            return Ok(input);
538        }
539        let mut rng = thread_rng();
540        let shape = input.shape().dims().to_vec();
541        let device = input.device();
542        let data = input
543            .to_vec()
544            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
545        let mean_f64 = self.mean as f64;
546        let std_f64 = self.std as f64;
547        let out: Vec<T> = data
548            .iter()
549            .map(|&x| {
550                // Box-Muller transform for Gaussian noise
551                let u1: f32 = rng.random::<f32>().max(f32::EPSILON);
552                let u2: f32 = rng.random::<f32>();
553                let noise = ((-2.0 * u1.ln()) as f64).sqrt()
554                    * (2.0 * std::f64::consts::PI * u2 as f64).cos();
555                let noisy =
556                    <T as TensorElement>::to_f64(&x).unwrap_or(0.0) + mean_f64 + std_f64 * noise;
557                <T as TensorElement>::from_f64(noisy).unwrap_or(x)
558            })
559            .collect();
560        Tensor::from_data(out, shape, device).map_err(|e| e.into())
561    }
562}
563
564/// Random erasing (cutout) augmentation
565pub struct RandomErasing {
566    prob: f32,
567    scale_range: (f32, f32),
568    ratio_range: (f32, f32),
569    fill_value: f32,
570}
571
572impl RandomErasing {
573    /// # Panics
574    ///
575    /// Panics if `prob` is outside `[0.0, 1.0]`, or if either range is
576    /// inverted. See [`Self::try_new`] for a non-panicking variant.
577    pub fn new(prob: f32, scale_range: (f32, f32), ratio_range: (f32, f32)) -> Self {
578        assert!(
579            (0.0..=1.0).contains(&prob),
580            "Probability must be between 0 and 1"
581        );
582        assert!(scale_range.0 <= scale_range.1, "Invalid scale range");
583        assert!(ratio_range.0 <= ratio_range.1, "Invalid ratio range");
584
585        Self {
586            prob,
587            scale_range,
588            ratio_range,
589            fill_value: 0.0,
590        }
591    }
592
593    /// Fallible variant of [`Self::new`] that returns an error instead of
594    /// panicking on an invalid `prob`, `scale_range`, or `ratio_range`.
595    pub fn try_new(prob: f32, scale_range: (f32, f32), ratio_range: (f32, f32)) -> Result<Self> {
596        crate::utils::validate_probability(prob, "prob")?;
597        crate::utils::validate_range(scale_range, "scale_range")?;
598        crate::utils::validate_range(ratio_range, "ratio_range")?;
599
600        Ok(Self {
601            prob,
602            scale_range,
603            ratio_range,
604            fill_value: 0.0,
605        })
606    }
607
608    pub fn with_fill_value(mut self, fill_value: f32) -> Self {
609        self.fill_value = fill_value;
610        self
611    }
612}
613
614impl<T: FloatElement> Transform<Tensor<T>> for RandomErasing {
615    type Output = Tensor<T>;
616
617    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
618        let mut rng = thread_rng();
619        if rng.random::<f32>() >= self.prob {
620            return Ok(input);
621        }
622        let binding = input.shape();
623        let dims = binding.dims();
624        if dims.len() < 2 {
625            return Err(torsh_core::error::TorshError::InvalidArgument(
626                "Input tensor must have at least 2 dimensions for random erasing".to_string(),
627            ));
628        }
629        let device = input.device();
630        let (height, width, channels) = if dims.len() == 2 {
631            (dims[0], dims[1], 1usize)
632        } else {
633            (
634                dims[dims.len() - 2],
635                dims[dims.len() - 1],
636                dims[..dims.len() - 2].iter().product(),
637            )
638        };
639        let total_area = (height * width) as f32;
640        // Sample erasing area as fraction of total
641        let (scale_lo, scale_hi) = self.scale_range;
642        let area_frac = scale_lo + rng.random::<f32>() * (scale_hi - scale_lo);
643        let erase_area = (total_area * area_frac) as usize;
644        // Sample aspect ratio
645        let (ratio_lo, ratio_hi) = self.ratio_range;
646        let ratio = ratio_lo + rng.random::<f32>() * (ratio_hi - ratio_lo);
647        let erase_h = ((erase_area as f32 / ratio).sqrt() as usize).clamp(1, height);
648        let erase_w = ((erase_area as f32 * ratio).sqrt() as usize).clamp(1, width);
649        if erase_h >= height || erase_w >= width {
650            return Ok(input);
651        }
652        let top = rng.gen_range(0..=(height - erase_h));
653        let left = rng.gen_range(0..=(width - erase_w));
654        let fill = <T as TensorElement>::from_f64(self.fill_value as f64)
655            .unwrap_or_else(<T as TensorElement>::zero);
656        let mut data = input
657            .to_vec()
658            .map_err(|e| torsh_core::error::TorshError::Other(format!("to_vec failed: {}", e)))?;
659        for c in 0..channels {
660            for row in top..(top + erase_h) {
661                for col in left..(left + erase_w) {
662                    let idx = c * height * width + row * width + col;
663                    data[idx] = fill;
664                }
665            }
666        }
667        Tensor::from_data(data, dims.to_vec(), device).map_err(|e| e.into())
668    }
669}
670
671/// Common augmentation presets
672impl AugmentationPipeline<Tensor<f32>> {
673    /// Create a light augmentation pipeline for training
674    pub fn light_augmentation() -> Self {
675        Self::new()
676            .add_conditional(
677                crate::tensor_transforms::RandomHorizontalFlip::new(0.5),
678                1.0,
679            )
680            .add_conditional(RandomBrightness::symmetric(0.1), 0.3)
681            .add_conditional(RandomContrast::symmetric(0.1), 0.3)
682    }
683
684    /// Create a medium augmentation pipeline
685    pub fn medium_augmentation() -> Self {
686        Self::new()
687            .add_conditional(
688                crate::tensor_transforms::RandomHorizontalFlip::new(0.5),
689                1.0,
690            )
691            .add_conditional(RandomVerticalFlip::new(0.1), 1.0)
692            .add_conditional(RandomBrightness::symmetric(0.2), 0.5)
693            .add_conditional(RandomContrast::symmetric(0.2), 0.5)
694            .add_conditional(RandomSaturation::symmetric(0.2), 0.3)
695            .add_conditional(GaussianNoise::with_std(0.01), 0.2)
696    }
697
698    /// Create a heavy augmentation pipeline
699    pub fn heavy_augmentation() -> Self {
700        Self::new()
701            .add_conditional(
702                crate::tensor_transforms::RandomHorizontalFlip::new(0.5),
703                1.0,
704            )
705            .add_conditional(RandomVerticalFlip::new(0.2), 1.0)
706            .add_conditional(RandomBrightness::symmetric(0.3), 0.7)
707            .add_conditional(RandomContrast::symmetric(0.3), 0.7)
708            .add_conditional(RandomSaturation::symmetric(0.3), 0.5)
709            .add_conditional(RandomHue::symmetric(0.1), 0.3)
710            .add_conditional(GaussianNoise::with_std(0.02), 0.3)
711            .add_conditional(RandomErasing::new(0.5, (0.02, 0.33), (0.3, 3.3)), 1.0)
712    }
713
714    /// Create an augmentation pipeline for ImageNet-style training
715    pub fn imagenet_augmentation() -> Self {
716        Self::new()
717            .add_conditional(
718                crate::tensor_transforms::RandomHorizontalFlip::new(0.5),
719                1.0,
720            )
721            .add_conditional(RandomBrightness::symmetric(0.2), 0.4)
722            .add_conditional(RandomContrast::symmetric(0.2), 0.4)
723            .add_conditional(RandomSaturation::symmetric(0.2), 0.4)
724            .add_conditional(RandomHue::symmetric(0.1), 0.1)
725    }
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731    use torsh_core::device::DeviceType;
732    use torsh_tensor::Tensor;
733
734    // Mock tensor for testing
735    fn mock_tensor() -> Tensor<f32> {
736        Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0], vec![2, 2], DeviceType::Cpu).unwrap()
737    }
738
739    #[test]
740    fn test_augmentation_pipeline_creation() {
741        let pipeline = AugmentationPipeline::<i32>::new();
742        assert_eq!(pipeline.probability, 1.0);
743        assert_eq!(pipeline.transforms.len(), 0);
744    }
745
746    #[test]
747    fn test_augmentation_pipeline_with_probability() {
748        let pipeline = AugmentationPipeline::<i32>::new().with_probability(0.5);
749        assert_eq!(pipeline.probability, 0.5);
750    }
751
752    #[test]
753    #[should_panic(expected = "Probability must be between 0 and 1")]
754    fn test_invalid_probability() {
755        AugmentationPipeline::<i32>::new().with_probability(1.5);
756    }
757
758    #[test]
759    fn test_conditional_transform_creation() {
760        let transform: ConditionalTransform<i32, _> =
761            ConditionalTransform::new(crate::transforms::lambda(|x: i32| Ok(x * 2)), 0.5);
762        assert_eq!(transform.probability, 0.5);
763    }
764
765    #[test]
766    fn test_random_brightness_creation() {
767        let brightness = RandomBrightness::new((0.8, 1.2));
768        assert_eq!(brightness.factor_range, (0.8, 1.2));
769    }
770
771    #[test]
772    fn test_random_brightness_symmetric() {
773        let brightness = RandomBrightness::symmetric(0.2);
774        assert_eq!(brightness.factor_range, (0.8, 1.2));
775    }
776
777    #[test]
778    fn test_gaussian_noise_creation() {
779        let noise = GaussianNoise::new(0.0, 0.1);
780        assert_eq!(noise.mean, 0.0);
781        assert_eq!(noise.std, 0.1);
782    }
783
784    #[test]
785    fn test_gaussian_noise_with_std() {
786        let noise = GaussianNoise::with_std(0.05);
787        assert_eq!(noise.mean, 0.0);
788        assert_eq!(noise.std, 0.05);
789    }
790
791    #[test]
792    fn test_random_erasing_creation() {
793        let erasing = RandomErasing::new(0.5, (0.02, 0.33), (0.3, 3.3));
794        assert_eq!(erasing.prob, 0.5);
795        assert_eq!(erasing.scale_range, (0.02, 0.33));
796        assert_eq!(erasing.ratio_range, (0.3, 3.3));
797        assert_eq!(erasing.fill_value, 0.0);
798    }
799
800    #[test]
801    fn test_light_augmentation_preset() {
802        let pipeline = AugmentationPipeline::light_augmentation();
803        assert_eq!(pipeline.transforms.len(), 3);
804    }
805
806    #[test]
807    fn test_medium_augmentation_preset() {
808        let pipeline = AugmentationPipeline::medium_augmentation();
809        assert_eq!(pipeline.transforms.len(), 6);
810    }
811
812    #[test]
813    fn test_heavy_augmentation_preset() {
814        let pipeline = AugmentationPipeline::heavy_augmentation();
815        assert_eq!(pipeline.transforms.len(), 8);
816    }
817
818    #[test]
819    fn test_augmentation_transform_shape_preserved() {
820        let tensor = mock_tensor();
821        let brightness = RandomBrightness::symmetric(0.1);
822        let result = brightness.transform(tensor.clone()).unwrap();
823
824        // Transforms operate on shape-preserving tensors
825        assert_eq!(result.shape(), tensor.shape());
826    }
827
828    #[test]
829    fn test_random_brightness_changes_tensor() {
830        // factor range that never includes 1.0, so output always differs from input (all-1.0 tensor)
831        let brightness = RandomBrightness::new((0.5, 0.7));
832        let tensor = Tensor::from_data(vec![1.0f32; 4], vec![2, 2], DeviceType::Cpu).unwrap();
833        let result = brightness.transform(tensor).unwrap();
834        let result_data = result.to_vec().unwrap();
835        // Should be between 0.5 and 0.7 (darkened from 1.0)
836        assert!(
837            result_data.iter().all(|&x| x < 1.0),
838            "Brightness transform must darken the tensor (factor in [0.5, 0.7])"
839        );
840    }
841
842    #[test]
843    fn test_gaussian_noise_changes_tensor() {
844        let noise = GaussianNoise::with_std(0.5);
845        // Run multiple times to be nearly certain noise is non-zero
846        let mut changed = false;
847        for _ in 0..10 {
848            let tensor = Tensor::from_data(vec![0.5f32; 16], vec![4, 4], DeviceType::Cpu).unwrap();
849            let result = noise.transform(tensor).unwrap();
850            let data = result.to_vec().unwrap();
851            if data.iter().any(|&x| (x - 0.5f32).abs() > 1e-6) {
852                changed = true;
853                break;
854            }
855        }
856        assert!(changed, "GaussianNoise must change tensor values");
857    }
858
859    #[test]
860    fn test_random_vertical_flip_changes_tensor() {
861        // Always flip (prob=1.0)
862        let flip = RandomVerticalFlip::new(1.0);
863        // HW tensor: [[1,2],[3,4]] -> after vertical flip -> [[3,4],[1,2]]
864        let tensor =
865            Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0], vec![2, 2], DeviceType::Cpu).unwrap();
866        let result = flip.transform(tensor).unwrap();
867        let data = result.to_vec().unwrap();
868        // After vertical flip: row 0 becomes [3,4], row 1 becomes [1,2]
869        assert!(
870            (data[0] - 3.0).abs() < 1e-6 && (data[1] - 4.0).abs() < 1e-6,
871            "Vertical flip must reverse rows: got {:?}",
872            data
873        );
874    }
875
876    #[test]
877    fn test_random_erasing_changes_tensor() {
878        // Always erase (prob=1.0), large erase area
879        let erasing = RandomErasing::new(1.0, (0.5, 0.9), (1.0, 1.0));
880        // Large tensor of all 1.0s; after erasing, some should be 0.0 (fill_value)
881        let tensor = Tensor::from_data(vec![1.0f32; 100], vec![10, 10], DeviceType::Cpu).unwrap();
882        let result = erasing.transform(tensor).unwrap();
883        let data = result.to_vec().unwrap();
884        assert!(
885            data.iter().any(|&x| x == 0.0f32),
886            "RandomErasing must fill some values with fill_value (0.0)"
887        );
888    }
889}