oxigdal-algorithms 0.1.4

High-performance SIMD-optimized raster and vector algorithms for OxiGDAL - Pure Rust geospatial processing
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
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
//! Parallel tile processing
//!
//! This module provides parallel implementations for tile processing,
//! COG pyramid generation, and overview computation.

use core::sync::atomic::{AtomicUsize, Ordering};
use rayon::prelude::*;

use crate::error::{AlgorithmError, Result};
use crate::resampling::{Resampler, ResamplingMethod};
use oxigdal_core::buffer::RasterBuffer;
use oxigdal_core::types::RasterDataType;

/// Configuration for tile processing
#[derive(Debug, Clone)]
pub struct TileConfig {
    /// Tile width in pixels
    pub tile_width: u32,
    /// Tile height in pixels
    pub tile_height: u32,
    /// Number of threads for parallel processing
    pub num_threads: Option<usize>,
    /// Enable progress tracking
    pub progress: bool,
}

impl Default for TileConfig {
    fn default() -> Self {
        Self {
            tile_width: 256,
            tile_height: 256,
            num_threads: None,
            progress: false,
        }
    }
}

impl TileConfig {
    /// Creates a new tile configuration
    #[must_use]
    pub const fn new() -> Self {
        Self {
            tile_width: 256,
            tile_height: 256,
            num_threads: None,
            progress: false,
        }
    }

    /// Sets the tile dimensions
    #[must_use]
    pub const fn with_tile_size(mut self, width: u32, height: u32) -> Self {
        self.tile_width = width;
        self.tile_height = height;
        self
    }

    /// Sets the number of threads
    #[must_use]
    pub const fn with_threads(mut self, num_threads: usize) -> Self {
        self.num_threads = Some(num_threads);
        self
    }

    /// Enables progress tracking
    #[must_use]
    pub const fn with_progress(mut self, progress: bool) -> Self {
        self.progress = progress;
        self
    }
}

/// A tile extracted from a raster
#[derive(Debug, Clone)]
pub struct Tile {
    /// Tile X index
    pub x: u32,
    /// Tile Y index
    pub y: u32,
    /// X offset in pixels in the source raster
    pub x_offset: u64,
    /// Y offset in pixels in the source raster
    pub y_offset: u64,
    /// Actual width of the tile (may be smaller at edges)
    pub width: u32,
    /// Actual height of the tile (may be smaller at edges)
    pub height: u32,
    /// Tile data
    pub data: RasterBuffer,
}

/// Trait for processing tiles
pub trait TileProcessor: Sync + Send {
    /// Process a single tile
    ///
    /// # Errors
    /// Returns an error if processing fails
    fn process_tile(&self, tile: &Tile) -> Result<RasterBuffer>;
}

/// Progress tracker for tile processing
pub struct ProgressTracker {
    total: usize,
    processed: AtomicUsize,
}

impl ProgressTracker {
    /// Creates a new progress tracker
    #[must_use]
    pub const fn new(total: usize) -> Self {
        Self {
            total,
            processed: AtomicUsize::new(0),
        }
    }

    /// Increments the progress counter
    pub fn increment(&self) {
        let current = self.processed.fetch_add(1, Ordering::Relaxed) + 1;
        if current % 10 == 0 || current == self.total {
            let percent = (current * 100) / self.total;
            tracing::debug!(
                "Processing tiles: {}/{} ({}%)",
                current,
                self.total,
                percent
            );
        }
    }

    /// Returns the current progress count
    #[must_use]
    pub fn current(&self) -> usize {
        self.processed.load(Ordering::Relaxed)
    }

    /// Returns the total count
    #[must_use]
    pub const fn total(&self) -> usize {
        self.total
    }
}

/// Extract tiles from a raster buffer
///
/// # Arguments
///
/// * `input` - Input raster buffer
/// * `config` - Tile configuration
///
/// # Returns
///
/// Vector of extracted tiles
///
/// # Errors
///
/// Returns an error if tile extraction fails
pub fn extract_tiles(input: &RasterBuffer, config: &TileConfig) -> Result<Vec<Tile>> {
    let width = input.width();
    let height = input.height();

    let tiles_across =
        ((width + u64::from(config.tile_width) - 1) / u64::from(config.tile_width)) as u32;
    let tiles_down =
        ((height + u64::from(config.tile_height) - 1) / u64::from(config.tile_height)) as u32;

    let mut tiles = Vec::new();

    for ty in 0..tiles_down {
        for tx in 0..tiles_across {
            let x_offset = u64::from(tx * config.tile_width);
            let y_offset = u64::from(ty * config.tile_height);

            let tile_width = config.tile_width.min((width - x_offset) as u32);
            let tile_height = config.tile_height.min((height - y_offset) as u32);

            // Extract tile data
            let mut tile_data = RasterBuffer::zeros(
                u64::from(tile_width),
                u64::from(tile_height),
                input.data_type(),
            );

            for y in 0..tile_height {
                for x in 0..tile_width {
                    let src_x = x_offset + u64::from(x);
                    let src_y = y_offset + u64::from(y);
                    let value = input.get_pixel(src_x, src_y)?;
                    tile_data.set_pixel(u64::from(x), u64::from(y), value)?;
                }
            }

            tiles.push(Tile {
                x: tx,
                y: ty,
                x_offset,
                y_offset,
                width: tile_width,
                height: tile_height,
                data: tile_data,
            });
        }
    }

    Ok(tiles)
}

/// Process tiles in parallel
///
/// # Arguments
///
/// * `tiles` - Input tiles to process
/// * `processor` - Tile processor implementation
/// * `config` - Tile configuration
///
/// # Returns
///
/// Vector of processed tiles
///
/// # Errors
///
/// Returns an error if processing fails
pub fn parallel_process_tiles<P>(
    tiles: &[Tile],
    processor: &P,
    config: &TileConfig,
) -> Result<Vec<(Tile, RasterBuffer)>>
where
    P: TileProcessor,
{
    let progress = if config.progress {
        Some(ProgressTracker::new(tiles.len()))
    } else {
        None
    };

    let results: Result<Vec<_>> = tiles
        .par_iter()
        .map(|tile| {
            let processed = processor.process_tile(tile)?;

            if let Some(ref tracker) = progress {
                tracker.increment();
            }

            Ok((tile.clone(), processed))
        })
        .collect();

    results
}

/// Overview level for pyramid generation
#[derive(Debug, Clone)]
pub struct OverviewLevel {
    /// Scale factor (2 = half size, 4 = quarter size, etc.)
    pub factor: u32,
    /// Overview raster data
    pub data: RasterBuffer,
}

/// Generate overviews (image pyramids) in parallel
///
/// This function generates multiple overview levels simultaneously,
/// which is much faster than sequential generation.
///
/// # Arguments
///
/// * `input` - Input raster buffer
/// * `levels` - Scale factors for each level (e.g., [2, 4, 8, 16])
/// * `method` - Resampling method to use
///
/// # Returns
///
/// Vector of overview levels
///
/// # Errors
///
/// Returns an error if overview generation fails
///
/// # Example
///
/// ```ignore
/// # #[cfg(feature = "parallel")]
/// # {
/// use oxigdal_algorithms::parallel::parallel_generate_overviews;
/// use oxigdal_algorithms::resampling::ResamplingMethod;
/// use oxigdal_core::buffer::RasterBuffer;
/// use oxigdal_core::types::RasterDataType;
/// # use oxigdal_algorithms::error::Result;
///
/// # fn main() -> Result<()> {
/// let input = RasterBuffer::zeros(4096, 4096, RasterDataType::UInt8);
/// let overviews = parallel_generate_overviews(
///     &input,
///     &[2, 4, 8, 16],
///     ResamplingMethod::Average
/// )?;
/// # Ok(())
/// # }
/// # }
/// ```
pub fn parallel_generate_overviews(
    input: &RasterBuffer,
    levels: &[u32],
    method: ResamplingMethod,
) -> Result<Vec<OverviewLevel>> {
    if levels.is_empty() {
        return Ok(Vec::new());
    }

    // Validate levels
    for &level in levels {
        if level < 2 {
            return Err(AlgorithmError::InvalidParameter {
                parameter: "level",
                message: "Overview level must be >= 2".to_string(),
            });
        }
    }

    let resampler = Resampler::new(method);

    // Generate overviews in parallel
    let overviews: Result<Vec<_>> = levels
        .par_iter()
        .map(|&factor| {
            let width = input.width() / u64::from(factor);
            let height = input.height() / u64::from(factor);

            if width == 0 || height == 0 {
                return Err(AlgorithmError::InvalidParameter {
                    parameter: "level",
                    message: format!("Overview factor {} too large for image size", factor),
                });
            }

            let data = resampler.resample(input, width, height)?;

            Ok(OverviewLevel { factor, data })
        })
        .collect();

    overviews
}

/// Generate COG (Cloud Optimized GeoTIFF) pyramid in parallel
///
/// This generates a complete pyramid with all levels up to a maximum size.
///
/// # Arguments
///
/// * `input` - Input raster buffer
/// * `min_size` - Minimum dimension size for the smallest overview
/// * `method` - Resampling method to use
///
/// # Returns
///
/// Vector of overview levels in order (2x, 4x, 8x, etc.)
///
/// # Errors
///
/// Returns an error if pyramid generation fails
pub fn parallel_generate_cog_pyramid(
    input: &RasterBuffer,
    min_size: u64,
    method: ResamplingMethod,
) -> Result<Vec<OverviewLevel>> {
    let max_dim = input.width().max(input.height());

    // Calculate required levels
    let mut levels = Vec::new();
    let mut factor = 2u32;

    while max_dim / u64::from(factor) >= min_size {
        levels.push(factor);
        factor *= 2;
    }

    if levels.is_empty() {
        return Ok(Vec::new());
    }

    parallel_generate_overviews(input, &levels, method)
}

/// Merge tiles back into a single raster
///
/// # Arguments
///
/// * `tiles` - Vector of tiles with their processed data
/// * `width` - Total width of the output raster
/// * `height` - Total height of the output raster
/// * `data_type` - Data type for the output
///
/// # Returns
///
/// Merged raster buffer
///
/// # Errors
///
/// Returns an error if merging fails
pub fn merge_tiles(
    tiles: &[(Tile, RasterBuffer)],
    width: u64,
    height: u64,
    data_type: RasterDataType,
) -> Result<RasterBuffer> {
    let mut output = RasterBuffer::zeros(width, height, data_type);

    for (tile, data) in tiles {
        for y in 0..tile.height {
            for x in 0..tile.width {
                let dst_x = tile.x_offset + u64::from(x);
                let dst_y = tile.y_offset + u64::from(y);

                if dst_x < width && dst_y < height {
                    let value = data.get_pixel(u64::from(x), u64::from(y))?;
                    output.set_pixel(dst_x, dst_y, value)?;
                }
            }
        }
    }

    Ok(output)
}

/// Simple tile processor that applies a function to each tile
pub struct FunctionTileProcessor<F>
where
    F: Fn(&RasterBuffer) -> Result<RasterBuffer> + Sync + Send,
{
    func: F,
}

impl<F> FunctionTileProcessor<F>
where
    F: Fn(&RasterBuffer) -> Result<RasterBuffer> + Sync + Send,
{
    /// Creates a new function tile processor
    #[must_use]
    pub const fn new(func: F) -> Self {
        Self { func }
    }
}

impl<F> TileProcessor for FunctionTileProcessor<F>
where
    F: Fn(&RasterBuffer) -> Result<RasterBuffer> + Sync + Send,
{
    fn process_tile(&self, tile: &Tile) -> Result<RasterBuffer> {
        (self.func)(&tile.data)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use super::*;
    use approx::assert_relative_eq;

    #[test]
    fn test_tile_config() {
        let config = TileConfig::default();
        assert_eq!(config.tile_width, 256);
        assert_eq!(config.tile_height, 256);
    }

    #[test]
    fn test_tile_config_builder() {
        let config = TileConfig::new()
            .with_tile_size(512, 512)
            .with_threads(4)
            .with_progress(true);

        assert_eq!(config.tile_width, 512);
        assert_eq!(config.tile_height, 512);
        assert_eq!(config.num_threads, Some(4));
        assert!(config.progress);
    }

    #[test]
    fn test_extract_tiles() {
        let input = RasterBuffer::zeros(1000, 1000, RasterDataType::UInt8);
        let config = TileConfig::new().with_tile_size(256, 256);

        let tiles = extract_tiles(&input, &config).expect("should work");

        // Should have 4x4 = 16 tiles
        assert_eq!(tiles.len(), 16);

        // Check first tile
        assert_eq!(tiles[0].x, 0);
        assert_eq!(tiles[0].y, 0);
        assert_eq!(tiles[0].width, 256);
        assert_eq!(tiles[0].height, 256);

        // Check edge tile (last column)
        let edge_tile = &tiles[3];
        assert_eq!(edge_tile.x, 3);
        assert_eq!(edge_tile.width, 1000 - 3 * 256); // 232 pixels
    }

    #[test]
    fn test_parallel_process_tiles() {
        let input = RasterBuffer::zeros(512, 512, RasterDataType::Float32);
        let config = TileConfig::new().with_tile_size(256, 256);

        let tiles = extract_tiles(&input, &config).expect("should work");

        // Process tiles: multiply all values by 2
        let processor = FunctionTileProcessor::new(|tile: &RasterBuffer| {
            let mut result = RasterBuffer::zeros(tile.width(), tile.height(), tile.data_type());
            for y in 0..tile.height() {
                for x in 0..tile.width() {
                    let value = tile.get_pixel(x, y)?;
                    result.set_pixel(x, y, value * 2.0)?;
                }
            }
            Ok(result)
        });

        let processed = parallel_process_tiles(&tiles, &processor, &config).expect("should work");

        assert_eq!(processed.len(), 4); // 2x2 tiles
    }

    #[test]
    fn test_parallel_generate_overviews() {
        let input = RasterBuffer::zeros(1024, 1024, RasterDataType::UInt8);

        let overviews = parallel_generate_overviews(&input, &[2, 4, 8], ResamplingMethod::Nearest)
            .expect("should work");

        assert_eq!(overviews.len(), 3);

        // Check sizes
        assert_eq!(overviews[0].factor, 2);
        assert_eq!(overviews[0].data.width(), 512);
        assert_eq!(overviews[0].data.height(), 512);

        assert_eq!(overviews[1].factor, 4);
        assert_eq!(overviews[1].data.width(), 256);
        assert_eq!(overviews[1].data.height(), 256);

        assert_eq!(overviews[2].factor, 8);
        assert_eq!(overviews[2].data.width(), 128);
        assert_eq!(overviews[2].data.height(), 128);
    }

    #[test]
    fn test_parallel_generate_cog_pyramid() {
        let input = RasterBuffer::zeros(2048, 2048, RasterDataType::UInt8);

        let pyramid = parallel_generate_cog_pyramid(&input, 256, ResamplingMethod::Nearest)
            .expect("should work");

        // Should generate levels: 2, 4, 8 (stopping at 256x256)
        assert_eq!(pyramid.len(), 3);
        assert_eq!(pyramid[0].factor, 2);
        assert_eq!(pyramid[1].factor, 4);
        assert_eq!(pyramid[2].factor, 8);
    }

    #[test]
    fn test_merge_tiles() {
        let mut input = RasterBuffer::zeros(512, 512, RasterDataType::Float32);

        // Fill with test pattern
        for y in 0..512 {
            for x in 0..512 {
                input.set_pixel(x, y, (x + y) as f64).expect("should work");
            }
        }

        let config = TileConfig::new().with_tile_size(256, 256);
        let tiles = extract_tiles(&input, &config).expect("should work");

        // Convert to (Tile, RasterBuffer) pairs
        let tile_pairs: Vec<_> = tiles.iter().map(|t| (t.clone(), t.data.clone())).collect();

        let merged =
            merge_tiles(&tile_pairs, 512, 512, RasterDataType::Float32).expect("should work");

        // Verify data matches
        for y in 0..512 {
            for x in 0..512 {
                let original = input.get_pixel(x, y).expect("should work");
                let merged_val = merged.get_pixel(x, y).expect("should work");
                assert_relative_eq!(original, merged_val, epsilon = 1e-6);
            }
        }
    }

    #[test]
    fn test_progress_tracker() {
        let tracker = ProgressTracker::new(100);
        assert_eq!(tracker.total(), 100);
        assert_eq!(tracker.current(), 0);

        tracker.increment();
        assert_eq!(tracker.current(), 1);

        for _ in 0..99 {
            tracker.increment();
        }
        assert_eq!(tracker.current(), 100);
    }

    #[test]
    fn test_invalid_overview_level() {
        let input = RasterBuffer::zeros(256, 256, RasterDataType::UInt8);

        // Level < 2 should fail
        let result = parallel_generate_overviews(&input, &[1], ResamplingMethod::Nearest);
        assert!(result.is_err());

        // Level too large should fail
        let result = parallel_generate_overviews(&input, &[1000], ResamplingMethod::Nearest);
        assert!(result.is_err());
    }
}