Skip to main content

incin_data/transforms/
mod.rs

1//! Data transformation and augmentation pipeline.
2//!
3//! Provides traits and implementations for data preprocessing, batch normalization,
4//! image transformations, and pipeline composition.
5
6use alloc::boxed::Box;
7use alloc::vec;
8use alloc::vec::Vec;
9use anyhow::{Result, bail};
10use rand::Rng;
11
12/// Core trait for a data transformation step.
13pub trait Transform: Send + Sync {
14    /// Input data type.
15    type Input;
16    /// Output data type.
17    type Output;
18
19    /// Applies the transformation to `input`.
20    fn transform(&self, input: Self::Input) -> Result<Self::Output>;
21}
22
23/// Pipeline composing multiple sequential transformations on the same data type.
24pub struct Compose<T> {
25    transforms: Vec<Box<dyn Transform<Input = T, Output = T>>>,
26}
27
28impl<T> Compose<T> {
29    /// Creates a new empty transform pipeline.
30    pub fn new() -> Self {
31        Self {
32            transforms: Vec::new(),
33        }
34    }
35
36    /// Appends a transform step to the pipeline.
37    pub fn push<TR>(mut self, transform: TR) -> Self
38    where
39        TR: Transform<Input = T, Output = T> + 'static,
40    {
41        self.transforms.push(Box::new(transform));
42        self
43    }
44}
45
46impl<T> Default for Compose<T> {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52impl<T> Transform for Compose<T> {
53    type Input = T;
54    type Output = T;
55
56    fn transform(&self, mut input: Self::Input) -> Result<Self::Output> {
57        for t in &self.transforms {
58            input = t.transform(input)?;
59        }
60        Ok(input)
61    }
62}
63
64/// Normalizes floating point slice values across channels: `out[c] = (in[c] - mean[c]) / std[c]`.
65#[derive(Debug, Clone)]
66pub struct Normalize {
67    /// Mean value per channel.
68    pub mean: Vec<f32>,
69    /// Standard deviation value per channel.
70    pub std: Vec<f32>,
71}
72
73impl Normalize {
74    /// Creates a new `Normalize` transform for 1 or more channels.
75    pub fn new(mean: Vec<f32>, std: Vec<f32>) -> Self {
76        Self { mean, std }
77    }
78
79    /// Standard ImageNet normalization (3 channels).
80    pub fn imagenet() -> Self {
81        Self {
82            mean: vec![0.485, 0.456, 0.406],
83            std: vec![0.229, 0.224, 0.225],
84        }
85    }
86}
87
88impl Transform for Normalize {
89    type Input = (Vec<f32>, Vec<usize>); // (data, shape [C, H, W] or [C, L])
90    type Output = (Vec<f32>, Vec<usize>);
91
92    fn transform(&self, (mut data, shape): Self::Input) -> Result<Self::Output> {
93        if shape.is_empty() {
94            bail!("Normalize transform requires a non-empty shape");
95        }
96        let channels = shape[0];
97        if channels != self.mean.len() || channels != self.std.len() {
98            bail!(
99                "Normalize channel count mismatch: input has {} channels, mean has {}, std has {}",
100                channels,
101                self.mean.len(),
102                self.std.len()
103            );
104        }
105
106        let channel_stride = data.len() / channels;
107        for c in 0..channels {
108            let mean_c = self.mean[c];
109            let std_c = self.std[c];
110            if std_c == 0.0 {
111                bail!("Normalize std dev cannot be zero for channel {}", c);
112            }
113            let start = c * channel_stride;
114            let end = start + channel_stride;
115            for val in &mut data[start..end] {
116                *val = (*val - mean_c) / std_c;
117            }
118        }
119        Ok((data, shape))
120    }
121}
122
123/// Multiplies all elements in a flat float buffer by a scaling factor (e.g. `1.0 / 255.0`).
124#[derive(Debug, Clone, Copy)]
125pub struct Scale {
126    /// Scaling factor.
127    pub factor: f32,
128}
129
130impl Scale {
131    /// Creates a new `Scale` transform with the given factor.
132    pub fn new(factor: f32) -> Self {
133        Self { factor }
134    }
135}
136
137impl Transform for Scale {
138    type Input = Vec<f32>;
139    type Output = Vec<f32>;
140
141    fn transform(&self, mut input: Self::Input) -> Result<Self::Output> {
142        for x in &mut input {
143            *x *= self.factor;
144        }
145        Ok(input)
146    }
147}
148
149/// Randomly flips 2D or 3D image data ([C, H, W]) horizontally along the width axis with probability `p`.
150#[derive(Debug, Clone, Copy)]
151pub struct RandomHorizontalFlip {
152    /// Probability of flipping (default 0.5).
153    pub p: f64,
154}
155
156impl RandomHorizontalFlip {
157    /// Creates a new `RandomHorizontalFlip` with probability `p`.
158    pub fn new(p: f64) -> Self {
159        Self { p }
160    }
161}
162
163impl Default for RandomHorizontalFlip {
164    fn default() -> Self {
165        Self { p: 0.5 }
166    }
167}
168
169impl Transform for RandomHorizontalFlip {
170    type Input = (Vec<f32>, Vec<usize>); // (data, shape [C, H, W])
171    type Output = (Vec<f32>, Vec<usize>);
172
173    fn transform(&self, (data, shape): Self::Input) -> Result<Self::Output> {
174        if shape.len() != 3 {
175            bail!("RandomHorizontalFlip requires 3D shape [C, H, W]");
176        }
177        let mut rng = rand::thread_rng();
178        if rng.gen_bool(self.p) {
179            let channels = shape[0];
180            let height = shape[1];
181            let width = shape[2];
182
183            let mut flipped = vec![0.0f32; data.len()];
184            for c in 0..channels {
185                for h in 0..height {
186                    for w in 0..width {
187                        let src_idx = c * height * width + h * width + w;
188                        let dst_idx = c * height * width + h * width + (width - 1 - w);
189                        flipped[dst_idx] = data[src_idx];
190                    }
191                }
192            }
193            Ok((flipped, shape))
194        } else {
195            Ok((data, shape))
196        }
197    }
198}
199
200/// Center-crops a 3D tensor ([C, H, W]) to target height `crop_h` and width `crop_w`.
201#[derive(Debug, Clone, Copy)]
202pub struct CenterCrop {
203    /// Target height.
204    pub crop_h: usize,
205    /// Target width.
206    pub crop_w: usize,
207}
208
209impl CenterCrop {
210    /// Creates a new `CenterCrop` with target dimensions.
211    pub fn new(crop_h: usize, crop_w: usize) -> Self {
212        Self { crop_h, crop_w }
213    }
214}
215
216impl Transform for CenterCrop {
217    type Input = (Vec<f32>, Vec<usize>); // (data, shape [C, H, W])
218    type Output = (Vec<f32>, Vec<usize>);
219
220    fn transform(&self, (data, shape): Self::Input) -> Result<Self::Output> {
221        if shape.len() != 3 {
222            bail!("CenterCrop requires 3D shape [C, H, W]");
223        }
224        let c = shape[0];
225        let h = shape[1];
226        let w = shape[2];
227
228        if self.crop_h > h || self.crop_w > w {
229            bail!(
230                "Crop dimensions [{}, {}] exceed image dimensions [{}, {}]",
231                self.crop_h,
232                self.crop_w,
233                h,
234                w
235            );
236        }
237
238        let start_h = (h - self.crop_h) / 2;
239        let start_w = (w - self.crop_w) / 2;
240
241        let mut cropped = Vec::with_capacity(c * self.crop_h * self.crop_w);
242        for ch in 0..c {
243            for row in start_h..(start_h + self.crop_h) {
244                let row_start = ch * h * w + row * w + start_w;
245                let row_end = row_start + self.crop_w;
246                cropped.extend_from_slice(&data[row_start..row_end]);
247            }
248        }
249        Ok((cropped, vec![c, self.crop_h, self.crop_w]))
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn test_scale_transform() {
259        let scale = Scale::new(0.5);
260        let data = vec![1.0, 2.0, 4.0, 8.0];
261        let out = scale.transform(data).unwrap();
262        assert_eq!(out, vec![0.5, 1.0, 2.0, 4.0]);
263    }
264
265    #[test]
266    fn test_normalize_transform() {
267        let norm = Normalize::new(vec![0.5, 1.0], vec![0.5, 2.0]);
268        let data = vec![1.0, 0.5, 5.0, 1.0]; // 2 channels, 2 elements each
269        let (out, shape) = norm.transform((data, vec![2, 2])).unwrap();
270        assert_eq!(shape, vec![2, 2]);
271        // ch0: (1.0-0.5)/0.5 = 1.0, (0.5-0.5)/0.5 = 0.0
272        // ch1: (5.0-1.0)/2.0 = 2.0, (1.0-1.0)/2.0 = 0.0
273        assert_eq!(out, vec![1.0, 0.0, 2.0, 0.0]);
274    }
275
276    #[test]
277    fn test_center_crop_transform() {
278        let crop = CenterCrop::new(2, 2);
279        // 1 channel, 4x4 image
280        let data: Vec<f32> = (0..16).map(|x| x as f32).collect();
281        let (out, shape) = crop.transform((data, vec![1, 4, 4])).unwrap();
282        assert_eq!(shape, vec![1, 2, 2]);
283        // Center 2x2 of 4x4: rows 1..3, cols 1..3 -> [5, 6, 9, 10]
284        assert_eq!(out, vec![5.0, 6.0, 9.0, 10.0]);
285    }
286}