tenflowers-dataset 0.1.1

Data pipeline and dataset utilities for TenfloweRS
Documentation
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
//! Image Pattern Generation
//!
//! This module contains functionality for generating synthetic images with
//! various patterns for computer vision tasks and dataset creation.

use super::core::{SyntheticConfig, SyntheticDataset};
use scirs2_core::random::{Rng, RngExt, SeedableRng};
use tenflowers_core::{Result, Tensor};

/// Configuration for synthetic image pattern generation
#[derive(Debug, Clone)]
pub struct ImagePatternConfig {
    pub width: usize,
    pub height: usize,
    pub channels: usize,
    pub pattern_type: ImagePatternType,
    pub noise_level: f64,
    pub background_color: [f32; 3],
    pub foreground_color: [f32; 3],
}

#[derive(Debug, Clone)]
pub enum ImagePatternType {
    Checkerboard {
        size: usize,
    },
    Stripes {
        width: usize,
        orientation: StripeOrientation,
    },
    Circles {
        radius: f32,
        num_circles: usize,
    },
    Gradient {
        direction: GradientDirection,
    },
    Noise {
        distribution: NoiseDistribution,
    },
    Geometric {
        shape: GeometricShape,
        size: f32,
    },
}

#[derive(Debug, Clone, Copy)]
pub enum StripeOrientation {
    Horizontal,
    Vertical,
    Diagonal,
}

#[derive(Debug, Clone, Copy)]
pub enum GradientDirection {
    Horizontal,
    Vertical,
    Radial,
}

#[derive(Debug, Clone, Copy)]
pub enum NoiseDistribution {
    Uniform,
    Gaussian,
    Salt,
    Pepper,
    SaltAndPepper,
}

#[derive(Debug, Clone, Copy)]
pub enum GeometricShape {
    Rectangle,
    Circle,
    Triangle,
    Star,
}

impl Default for ImagePatternConfig {
    fn default() -> Self {
        Self {
            width: 64,
            height: 64,
            channels: 3,
            pattern_type: ImagePatternType::Checkerboard { size: 8 },
            noise_level: 0.0,
            background_color: [0.0, 0.0, 0.0], // Black
            foreground_color: [1.0, 1.0, 1.0], // White
        }
    }
}

impl ImagePatternConfig {
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            width,
            height,
            ..Default::default()
        }
    }

    pub fn with_pattern(mut self, pattern_type: ImagePatternType) -> Self {
        self.pattern_type = pattern_type;
        self
    }

    pub fn with_colors(mut self, background: [f32; 3], foreground: [f32; 3]) -> Self {
        self.background_color = background;
        self.foreground_color = foreground;
        self
    }

    pub fn with_noise(mut self, noise_level: f64) -> Self {
        self.noise_level = noise_level;
        self
    }

    pub fn with_channels(mut self, channels: usize) -> Self {
        self.channels = channels;
        self
    }
}

/// Image pattern generator for creating synthetic image datasets
pub struct ImagePatternGenerator;

impl ImagePatternGenerator {
    /// Generate a single image with the specified pattern
    pub fn generate_image(config: &ImagePatternConfig, rng: &mut impl Rng) -> Result<Tensor<f32>> {
        let total_pixels = config.width * config.height * config.channels;
        let mut image_data = vec![0.0f32; total_pixels];

        // Generate base pattern
        match &config.pattern_type {
            ImagePatternType::Checkerboard { size } => {
                Self::generate_checkerboard(&mut image_data, config, *size);
            }
            ImagePatternType::Stripes { width, orientation } => {
                Self::generate_stripes(&mut image_data, config, *width, *orientation);
            }
            ImagePatternType::Circles {
                radius,
                num_circles,
            } => {
                Self::generate_circles(&mut image_data, config, *radius, *num_circles, rng);
            }
            ImagePatternType::Gradient { direction } => {
                Self::generate_gradient(&mut image_data, config, *direction);
            }
            ImagePatternType::Noise { distribution } => {
                Self::generate_noise(&mut image_data, config, *distribution, rng);
            }
            ImagePatternType::Geometric { shape, size } => {
                Self::generate_geometric(&mut image_data, config, *shape, *size);
            }
        }

        // Add noise if specified
        if config.noise_level > 0.0 {
            for pixel in image_data.iter_mut() {
                let noise = rng.random_range(-config.noise_level..config.noise_level) as f32;
                *pixel = (*pixel + noise).clamp(0.0, 1.0);
            }
        }

        let shape = vec![config.channels, config.height, config.width];
        Tensor::from_vec(image_data, &shape)
    }

    fn generate_checkerboard(data: &mut [f32], config: &ImagePatternConfig, size: usize) {
        for y in 0..config.height {
            for x in 0..config.width {
                let checker_x = (x / size) % 2;
                let checker_y = (y / size) % 2;
                let is_foreground = (checker_x + checker_y) % 2 == 0;

                let color = if is_foreground {
                    config.foreground_color
                } else {
                    config.background_color
                };

                for c in 0..config.channels {
                    let idx = c * config.height * config.width + y * config.width + x;
                    data[idx] = color[c.min(2)];
                }
            }
        }
    }

    fn generate_stripes(
        data: &mut [f32],
        config: &ImagePatternConfig,
        width: usize,
        orientation: StripeOrientation,
    ) {
        for y in 0..config.height {
            for x in 0..config.width {
                let stripe_pos = match orientation {
                    StripeOrientation::Horizontal => y,
                    StripeOrientation::Vertical => x,
                    StripeOrientation::Diagonal => x + y,
                };

                let is_foreground = (stripe_pos / width) % 2 == 0;
                let color = if is_foreground {
                    config.foreground_color
                } else {
                    config.background_color
                };

                for c in 0..config.channels {
                    let idx = c * config.height * config.width + y * config.width + x;
                    data[idx] = color[c.min(2)];
                }
            }
        }
    }

    fn generate_circles(
        data: &mut [f32],
        config: &ImagePatternConfig,
        radius: f32,
        num_circles: usize,
        rng: &mut impl Rng,
    ) {
        // Initialize with background
        for pixel in data.iter_mut() {
            *pixel = config.background_color[0];
        }

        for _ in 0..num_circles {
            let center_x = rng.random_range(0.0..config.width as f32);
            let center_y = rng.random_range(0.0..config.height as f32);

            for y in 0..config.height {
                for x in 0..config.width {
                    let dx = x as f32 - center_x;
                    let dy = y as f32 - center_y;
                    let distance = (dx * dx + dy * dy).sqrt();

                    if distance <= radius {
                        for c in 0..config.channels {
                            let idx = c * config.height * config.width + y * config.width + x;
                            data[idx] = config.foreground_color[c.min(2)];
                        }
                    }
                }
            }
        }
    }

    fn generate_gradient(
        data: &mut [f32],
        config: &ImagePatternConfig,
        direction: GradientDirection,
    ) {
        for y in 0..config.height {
            for x in 0..config.width {
                let gradient_value = match direction {
                    GradientDirection::Horizontal => x as f32 / config.width as f32,
                    GradientDirection::Vertical => y as f32 / config.height as f32,
                    GradientDirection::Radial => {
                        let center_x = config.width as f32 / 2.0;
                        let center_y = config.height as f32 / 2.0;
                        let dx = x as f32 - center_x;
                        let dy = y as f32 - center_y;
                        let max_distance = (center_x * center_x + center_y * center_y).sqrt();
                        let distance = (dx * dx + dy * dy).sqrt();
                        distance / max_distance
                    }
                };

                for c in 0..config.channels {
                    let idx = c * config.height * config.width + y * config.width + x;
                    data[idx] = gradient_value.clamp(0.0, 1.0);
                }
            }
        }
    }

    fn generate_noise(
        data: &mut [f32],
        _config: &ImagePatternConfig,
        distribution: NoiseDistribution,
        rng: &mut impl Rng,
    ) {
        for pixel in data.iter_mut() {
            *pixel = match distribution {
                NoiseDistribution::Uniform => rng.random::<f32>(),
                NoiseDistribution::Gaussian => {
                    // Box-Muller transform for Gaussian noise
                    let u1 = rng.random::<f32>();
                    let u2 = rng.random::<f32>();
                    let z0 = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f32::consts::PI * u2).cos();
                    (z0 * 0.5 + 0.5).clamp(0.0, 1.0)
                }
                NoiseDistribution::Salt => {
                    if rng.random::<f32>() < 0.1 {
                        1.0
                    } else {
                        0.0
                    }
                }
                NoiseDistribution::Pepper => {
                    if rng.random::<f32>() < 0.1 {
                        0.0
                    } else {
                        1.0
                    }
                }
                NoiseDistribution::SaltAndPepper => {
                    let rand_val = rng.random::<f32>();
                    if rand_val < 0.05 {
                        0.0
                    } else if rand_val < 0.1 {
                        1.0
                    } else {
                        0.5
                    }
                }
            };
        }
    }

    fn generate_geometric(
        data: &mut [f32],
        config: &ImagePatternConfig,
        shape: GeometricShape,
        size: f32,
    ) {
        // Initialize with background
        for pixel in data.iter_mut() {
            *pixel = config.background_color[0];
        }

        let center_x = config.width as f32 / 2.0;
        let center_y = config.height as f32 / 2.0;

        for y in 0..config.height {
            for x in 0..config.width {
                let dx = x as f32 - center_x;
                let dy = y as f32 - center_y;

                let is_inside = match shape {
                    GeometricShape::Rectangle => dx.abs() <= size / 2.0 && dy.abs() <= size / 2.0,
                    GeometricShape::Circle => (dx * dx + dy * dy).sqrt() <= size / 2.0,
                    GeometricShape::Triangle => {
                        // Simple triangle approximation
                        dy >= -size / 2.0 && dy <= size / 2.0 && dx.abs() <= size / 2.0 - dy.abs()
                    }
                    GeometricShape::Star => {
                        // Simple star approximation
                        let angle = dy.atan2(dx);
                        let distance = (dx * dx + dy * dy).sqrt();
                        let star_radius = size / 2.0 * (1.0 + 0.3 * (5.0 * angle).sin());
                        distance <= star_radius
                    }
                };

                if is_inside {
                    for c in 0..config.channels {
                        let idx = c * config.height * config.width + y * config.width + x;
                        data[idx] = config.foreground_color[c.min(2)];
                    }
                }
            }
        }
    }

    /// Generate a dataset of synthetic images
    pub fn generate_dataset(
        config: &ImagePatternConfig,
        synthetic_config: SyntheticConfig,
    ) -> Result<SyntheticDataset<f32>> {
        let mut rng = if let Some(seed) = synthetic_config.random_seed {
            scirs2_core::random::Random::seed(seed)
        } else {
            scirs2_core::random::Random::seed(0)
        };

        let image_size = config.width * config.height * config.channels;
        let mut all_images = Vec::with_capacity(synthetic_config.n_samples * image_size);
        let mut labels = Vec::with_capacity(synthetic_config.n_samples);

        for i in 0..synthetic_config.n_samples {
            let image = Self::generate_image(config, &mut rng)?;
            let image_data = image.to_vec().map_err(|_| {
                tenflowers_core::TensorError::invalid_argument(
                    "Failed to convert image tensor to vector".to_string(),
                )
            })?;

            all_images.extend(image_data);
            labels.push(i as f32); // Simple label scheme
        }

        let features = Tensor::from_vec(
            all_images,
            &[
                synthetic_config.n_samples,
                config.channels,
                config.height,
                config.width,
            ],
        )?;
        let labels_tensor = Tensor::from_vec(labels, &[synthetic_config.n_samples])?;

        Ok(SyntheticDataset::new(features, labels_tensor))
    }
}