oxigdal-dev-tools 0.1.7

Development tools for OxiGDAL: profiling, debugging, validation, and testing utilities
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
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
//! Test data generation utilities
//!
//! This module provides tools for generating test data for OxiGDAL operations.

use crate::Result;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Test data generator
pub struct DataGenerator {
    /// Random seed
    seed: u64,
}

impl DataGenerator {
    /// Create a new data generator
    pub fn new() -> Self {
        Self { seed: 12345 }
    }

    /// Create a generator with a specific seed
    pub fn with_seed(seed: u64) -> Self {
        Self { seed }
    }

    /// Generate raster data
    pub fn generate_raster(&self, width: usize, height: usize, pattern: RasterPattern) -> Vec<f64> {
        let mut data = vec![0.0; width * height];

        match pattern {
            RasterPattern::Flat(value) => {
                data.fill(value);
            }
            RasterPattern::Gradient {
                from,
                to,
                direction,
            } => {
                for y in 0..height {
                    for x in 0..width {
                        let t = match direction {
                            GradientDirection::Horizontal => x as f64 / (width - 1) as f64,
                            GradientDirection::Vertical => y as f64 / (height - 1) as f64,
                            GradientDirection::Diagonal => {
                                ((x + y) as f64) / ((width + height - 2) as f64)
                            }
                        };
                        data[y * width + x] = from + (to - from) * t;
                    }
                }
            }
            RasterPattern::Checkerboard {
                size,
                color1,
                color2,
            } => {
                for y in 0..height {
                    for x in 0..width {
                        let is_odd = ((x / size) + (y / size)) % 2 == 1;
                        data[y * width + x] = if is_odd { color1 } else { color2 };
                    }
                }
            }
            RasterPattern::Noise { min, max } => {
                for (i, item) in data.iter_mut().enumerate() {
                    *item = min + (max - min) * self.pseudo_random(i);
                }
            }
            RasterPattern::Sine {
                amplitude,
                frequency,
            } => {
                use std::f64::consts::PI;
                for y in 0..height {
                    for x in 0..width {
                        let phase = 2.0 * PI * frequency * (x as f64 / width as f64);
                        data[y * width + x] = amplitude * phase.sin();
                    }
                }
            }
        }

        data
    }

    /// Simple pseudo-random number generator (LCG)
    fn pseudo_random(&self, index: usize) -> f64 {
        let a = 1103515245u64;
        let c = 12345u64;
        let m = 2u64.pow(31);

        let x = ((a
            .wrapping_mul(self.seed.wrapping_add(index as u64))
            .wrapping_add(c))
            % m) as f64;
        x / m as f64
    }

    /// Generate vector features (points)
    pub fn generate_points(&self, count: usize, bounds: Bounds) -> Vec<Point> {
        let mut points = Vec::with_capacity(count);

        for i in 0..count {
            let x = bounds.min_x + (bounds.max_x - bounds.min_x) * self.pseudo_random(i * 2);
            let y = bounds.min_y + (bounds.max_y - bounds.min_y) * self.pseudo_random(i * 2 + 1);

            points.push(Point { x, y });
        }

        points
    }

    /// Generate regular grid of points
    pub fn generate_grid(&self, rows: usize, cols: usize, bounds: Bounds) -> Vec<Point> {
        let mut points = Vec::with_capacity(rows * cols);

        let dx = (bounds.max_x - bounds.min_x) / (cols - 1) as f64;
        let dy = (bounds.max_y - bounds.min_y) / (rows - 1) as f64;

        for row in 0..rows {
            for col in 0..cols {
                let x = bounds.min_x + col as f64 * dx;
                let y = bounds.min_y + row as f64 * dy;
                points.push(Point { x, y });
            }
        }

        points
    }
}

impl Default for DataGenerator {
    fn default() -> Self {
        Self::new()
    }
}

/// Raster pattern
#[derive(Debug, Clone)]
pub enum RasterPattern {
    /// Flat value
    Flat(f64),
    /// Gradient
    Gradient {
        /// Start value
        from: f64,
        /// End value
        to: f64,
        /// Direction
        direction: GradientDirection,
    },
    /// Checkerboard pattern
    Checkerboard {
        /// Cell size
        size: usize,
        /// Color 1
        color1: f64,
        /// Color 2
        color2: f64,
    },
    /// Random noise
    Noise {
        /// Minimum value
        min: f64,
        /// Maximum value
        max: f64,
    },
    /// Sine wave
    Sine {
        /// Amplitude
        amplitude: f64,
        /// Frequency
        frequency: f64,
    },
}

/// Gradient direction
#[derive(Debug, Clone, Copy)]
pub enum GradientDirection {
    /// Horizontal (left to right)
    Horizontal,
    /// Vertical (top to bottom)
    Vertical,
    /// Diagonal (top-left to bottom-right)
    Diagonal,
}

/// 2D point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Point {
    /// X coordinate
    pub x: f64,
    /// Y coordinate
    pub y: f64,
}

/// Bounding box
#[derive(Debug, Clone, Copy)]
pub struct Bounds {
    /// Minimum X
    pub min_x: f64,
    /// Minimum Y
    pub min_y: f64,
    /// Maximum X
    pub max_x: f64,
    /// Maximum Y
    pub max_y: f64,
}

impl Bounds {
    /// Create new bounds
    pub fn new(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Self {
        Self {
            min_x,
            min_y,
            max_x,
            max_y,
        }
    }
}

/// File generator for creating test files
pub struct FileGenerator;

impl FileGenerator {
    /// Generate a minimal valid single-band Float32 GeoTIFF with WGS84 georeferencing.
    ///
    /// The file is written using the `oxigdal-geotiff` driver so it is a fully
    /// conformant TIFF/GeoTIFF that can be re-opened by any compliant reader.
    ///
    /// # Arguments
    /// * `path`   – Destination file path.
    /// * `width`  – Image width in pixels (must be ≥ 1).
    /// * `height` – Image height in pixels (must be ≥ 1).
    ///
    /// The georeferencing covers a small WGS84 bounding box centred on the
    /// prime meridian / equator (lon 0..1°, lat 1..0° — north-up).
    pub fn generate_geotiff(path: &Path, width: usize, height: usize) -> Result<()> {
        use oxigdal_core::types::{GeoTransform, RasterDataType};
        use oxigdal_geotiff::tiff::Compression;
        use oxigdal_geotiff::writer::{GeoTiffWriter, GeoTiffWriterOptions, WriterConfig};

        if width == 0 || height == 0 {
            return Err(crate::DevToolsError::Generator(
                "width and height must be >= 1".to_string(),
            ));
        }

        // Build a simple gradient raster (Float32, 1 band).
        // Values increase linearly from 0.0 at top-left to 1.0 at bottom-right.
        let pixel_count = width * height;
        let max_idx = (pixel_count - 1) as f32;
        let float_data: Vec<f32> = (0..pixel_count)
            .map(|i| i as f32 / max_idx.max(1.0))
            .collect();

        // Re-interpret as raw bytes for the writer (little-endian f32).
        let raw: Vec<u8> = float_data.iter().flat_map(|v| v.to_le_bytes()).collect();

        // WGS84 bounding box: upper-left (0°E, 1°N), lower-right (1°E, 0°N).
        // pixel_width  =  1.0 / width  degrees per pixel  (west→east)
        // pixel_height = -1.0 / height degrees per pixel  (north→south, negative)
        let pixel_width = 1.0_f64 / width as f64;
        let pixel_height = -1.0_f64 / height as f64;
        let geo_transform = GeoTransform::new(
            0.0,          // origin_x  (upper-left longitude)
            pixel_width,  // pixel_width
            0.0,          // row_rotation (north-up → 0)
            1.0,          // origin_y  (upper-left latitude)
            0.0,          // col_rotation (north-up → 0)
            pixel_height, // pixel_height (negative = north-up)
        );

        let config = WriterConfig::new(
            width as u64,
            height as u64,
            1, // single band
            RasterDataType::Float32,
        )
        .with_compression(Compression::Lzw)
        .with_geo_transform(geo_transform)
        .with_epsg_code(4326); // WGS84 geographic CRS

        let mut writer = GeoTiffWriter::create(path, config, GeoTiffWriterOptions::default())?;
        writer.write(&raw)?;

        Ok(())
    }

    /// Generate a simple GeoJSON file
    pub fn generate_geojson(path: &Path, points: &[Point]) -> Result<()> {
        use std::io::Write;

        let mut geojson =
            String::from("{\n  \"type\": \"FeatureCollection\",\n  \"features\": [\n");

        for (i, point) in points.iter().enumerate() {
            geojson.push_str(&format!(
                "    {{\n      \"type\": \"Feature\",\n      \"geometry\": {{\n        \"type\": \"Point\",\n        \"coordinates\": [{}, {}]\n      }},\n      \"properties\": {{\n        \"id\": {}\n      }}\n    }}",
                point.x, point.y, i
            ));

            if i < points.len() - 1 {
                geojson.push_str(",\n");
            } else {
                geojson.push('\n');
            }
        }

        geojson.push_str("  ]\n}");

        let mut file = std::fs::File::create(path)?;
        file.write_all(geojson.as_bytes())?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generator_creation() {
        let generator = DataGenerator::new();
        assert_eq!(generator.seed, 12345);
    }

    #[test]
    fn test_generate_flat_raster() {
        let generator = DataGenerator::new();
        let data = generator.generate_raster(10, 10, RasterPattern::Flat(42.0));
        assert_eq!(data.len(), 100);
        assert!(data.iter().all(|&v| v == 42.0));
    }

    #[test]
    fn test_generate_gradient_raster() {
        let generator = DataGenerator::new();
        let data = generator.generate_raster(
            10,
            10,
            RasterPattern::Gradient {
                from: 0.0,
                to: 100.0,
                direction: GradientDirection::Horizontal,
            },
        );
        assert_eq!(data.len(), 100);
        assert_eq!(data[0], 0.0); // First column
        assert!((data[9] - 100.0).abs() < 0.01); // Last column
    }

    #[test]
    fn test_generate_checkerboard() {
        let generator = DataGenerator::new();
        let data = generator.generate_raster(
            10,
            10,
            RasterPattern::Checkerboard {
                size: 5,
                color1: 0.0,
                color2: 100.0,
            },
        );
        assert_eq!(data.len(), 100);
    }

    #[test]
    fn test_generate_noise() {
        let generator = DataGenerator::new();
        let data = generator.generate_raster(
            10,
            10,
            RasterPattern::Noise {
                min: 0.0,
                max: 100.0,
            },
        );
        assert_eq!(data.len(), 100);
        assert!(data.iter().all(|&v| (0.0..=100.0).contains(&v)));
    }

    #[test]
    fn test_generate_points() {
        let generator = DataGenerator::new();
        let bounds = Bounds::new(0.0, 0.0, 100.0, 100.0);
        let points = generator.generate_points(10, bounds);
        assert_eq!(points.len(), 10);
        assert!(points.iter().all(|p| p.x >= 0.0 && p.x <= 100.0));
        assert!(points.iter().all(|p| p.y >= 0.0 && p.y <= 100.0));
    }

    #[test]
    fn test_generate_grid() {
        let generator = DataGenerator::new();
        let bounds = Bounds::new(0.0, 0.0, 100.0, 100.0);
        let points = generator.generate_grid(5, 5, bounds);
        assert_eq!(points.len(), 25);
    }

    #[test]
    fn test_generate_geojson() -> Result<()> {
        use tempfile::NamedTempFile;

        let temp_file = NamedTempFile::new()?;
        let points = vec![Point { x: 0.0, y: 0.0 }, Point { x: 1.0, y: 1.0 }];

        FileGenerator::generate_geojson(temp_file.path(), &points)?;

        let content = std::fs::read_to_string(temp_file.path())?;
        assert!(content.contains("FeatureCollection"));
        assert!(content.contains("Point"));

        Ok(())
    }

    #[test]
    fn test_generate_geotiff_creates_nonempty_file() -> Result<()> {
        let mut path = std::env::temp_dir();
        path.push(format!(
            "oxigdal_devtools_test_{}.tif",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));

        FileGenerator::generate_geotiff(&path, 32, 32)?;

        let metadata = std::fs::metadata(&path)?;
        assert!(metadata.is_file(), "output must be a regular file");
        assert!(metadata.len() > 0, "generated GeoTIFF must be non-empty");

        // Verify TIFF magic bytes (little-endian: II + 42 or II + 43 for BigTIFF).
        let bytes = std::fs::read(&path)?;
        assert!(bytes.len() >= 4, "file too short to contain a TIFF header");
        let is_tiff_le = bytes[0] == b'I'
            && bytes[1] == b'I'
            && bytes[3] == 0
            && (bytes[2] == 42 || bytes[2] == 43); // 42 = classic TIFF, 43 = BigTIFF
        let is_tiff_be = bytes[0] == b'M' && bytes[1] == b'M' && (bytes[3] == 42 || bytes[3] == 43);
        assert!(
            is_tiff_le || is_tiff_be,
            "file does not start with a valid TIFF magic sequence"
        );

        let _ = std::fs::remove_file(&path);
        Ok(())
    }

    #[test]
    fn test_generate_geotiff_rejects_zero_dimensions() {
        let path = std::env::temp_dir().join("oxigdal_devtools_zero.tif");
        assert!(
            FileGenerator::generate_geotiff(&path, 0, 16).is_err(),
            "zero width should return an error"
        );
        assert!(
            FileGenerator::generate_geotiff(&path, 16, 0).is_err(),
            "zero height should return an error"
        );
    }
}