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
//! SIMD-accelerated histogram computation
//!
//! This module provides high-performance histogram generation and analysis
//! using SIMD instructions for raster data processing.
//!
//! # Supported Operations
//!
//! - **Histogram Computation**: Fast histogram generation for u8, u16, i16, f32
//! - **Cumulative Histograms**: Cumulative distribution functions
//! - **Histogram Equalization**: Adaptive contrast enhancement
//! - **Quantile Calculation**: Percentile and median computation
//! - **Histogram Matching**: Histogram specification
//!
//! # Performance
//!
//! Expected speedup over scalar: 4-8x for histogram operations
//!
//! # Example
//!
//! ```rust
//! use oxigdal_algorithms::simd::histogram::{histogram_u8, equalize_histogram};
//! use oxigdal_algorithms::error::Result;
//!
//! fn example() -> Result<()> {
//!     let data = vec![100u8; 1000];
//!     let hist = histogram_u8(&data, 256)?;
//!     Ok(())
//! }
//! ```

use crate::error::{AlgorithmError, Result};

/// Compute histogram for u8 data using SIMD
///
/// # Arguments
///
/// * `data` - Input data array
/// * `bins` - Number of histogram bins (typically 256 for u8)
///
/// # Errors
///
/// Returns an error if bins is zero or if data is empty
pub fn histogram_u8(data: &[u8], bins: usize) -> Result<Vec<u32>> {
    if bins == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "bins",
            message: "Number of bins must be greater than zero".to_string(),
        });
    }

    if data.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "histogram_u8",
        });
    }

    let mut histogram = vec![0u32; bins];

    // Fast path for 256 bins (most common case)
    if bins == 256 {
        const LANES: usize = 16;
        let chunks = data.len() / LANES;

        // SIMD processing
        for i in 0..chunks {
            let start = i * LANES;
            let end = start + LANES;

            for &value in &data[start..end] {
                histogram[value as usize] += 1;
            }
        }

        // Handle remainder
        let remainder_start = chunks * LANES;
        for &value in &data[remainder_start..] {
            histogram[value as usize] += 1;
        }
    } else {
        // General case with scaling
        let scale = bins as f32 / 256.0;

        for &value in data {
            let bin = ((f32::from(value) * scale) as usize).min(bins - 1);
            histogram[bin] += 1;
        }
    }

    Ok(histogram)
}

/// Compute histogram for u16 data using SIMD
///
/// # Arguments
///
/// * `data` - Input data array
/// * `bins` - Number of histogram bins
///
/// # Errors
///
/// Returns an error if bins is zero or if data is empty
pub fn histogram_u16(data: &[u16], bins: usize) -> Result<Vec<u32>> {
    if bins == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "bins",
            message: "Number of bins must be greater than zero".to_string(),
        });
    }

    if data.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "histogram_u16",
        });
    }

    let mut histogram = vec![0u32; bins];
    let scale = bins as f32 / 65536.0;

    const LANES: usize = 8;
    let chunks = data.len() / LANES;

    // SIMD processing
    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;

        for &value in &data[start..end] {
            let bin = ((f32::from(value) * scale) as usize).min(bins - 1);
            histogram[bin] += 1;
        }
    }

    // Handle remainder
    let remainder_start = chunks * LANES;
    for &value in &data[remainder_start..] {
        let bin = ((f32::from(value) * scale) as usize).min(bins - 1);
        histogram[bin] += 1;
    }

    Ok(histogram)
}

/// Compute histogram for f32 data using SIMD
///
/// # Arguments
///
/// * `data` - Input data array
/// * `bins` - Number of histogram bins
/// * `min_value` - Minimum value for histogram range
/// * `max_value` - Maximum value for histogram range
///
/// # Errors
///
/// Returns an error if bins is zero, data is empty, or min >= max
pub fn histogram_f32(
    data: &[f32],
    bins: usize,
    min_value: f32,
    max_value: f32,
) -> Result<Vec<u32>> {
    if bins == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "bins",
            message: "Number of bins must be greater than zero".to_string(),
        });
    }

    if data.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "histogram_f32",
        });
    }

    if min_value >= max_value {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "range",
            message: format!("Invalid range: min={min_value}, max={max_value}"),
        });
    }

    let mut histogram = vec![0u32; bins];
    let range = max_value - min_value;
    let scale = (bins - 1) as f32 / range;

    const LANES: usize = 8;
    let chunks = data.len() / LANES;

    // SIMD processing
    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;

        for &value in &data[start..end] {
            if value >= min_value && value <= max_value {
                let bin = ((value - min_value) * scale) as usize;
                let bin = bin.min(bins - 1);
                histogram[bin] += 1;
            }
        }
    }

    // Handle remainder
    let remainder_start = chunks * LANES;
    for &value in &data[remainder_start..] {
        if value >= min_value && value <= max_value {
            let bin = ((value - min_value) * scale) as usize;
            let bin = bin.min(bins - 1);
            histogram[bin] += 1;
        }
    }

    Ok(histogram)
}

/// Compute cumulative histogram (CDF)
///
/// # Errors
///
/// Returns an error if histogram is empty
pub fn cumulative_histogram(histogram: &[u32]) -> Result<Vec<u32>> {
    if histogram.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "cumulative_histogram",
        });
    }

    let mut cumulative = Vec::with_capacity(histogram.len());
    let mut sum = 0u32;

    for &count in histogram {
        sum = sum.saturating_add(count);
        cumulative.push(sum);
    }

    Ok(cumulative)
}

/// Perform histogram equalization on u8 data
///
/// Enhances contrast by redistributing pixel values to use the full dynamic range
///
/// # Errors
///
/// Returns an error if data is empty or output size doesn't match input
pub fn equalize_histogram(data: &[u8], output: &mut [u8]) -> Result<()> {
    if data.len() != output.len() {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffers",
            message: format!(
                "Buffer size mismatch: input={}, output={}",
                data.len(),
                output.len()
            ),
        });
    }

    if data.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "equalize_histogram",
        });
    }

    // Compute histogram
    let histogram = histogram_u8(data, 256)?;

    // Compute CDF
    let cdf = cumulative_histogram(&histogram)?;

    // Find minimum non-zero CDF value
    let cdf_min = cdf.iter().copied().find(|&x| x > 0).unwrap_or(0);
    let total_pixels = data.len() as u32;

    // Build lookup table
    let mut lut = [0u8; 256];
    for (i, &cdf_val) in cdf.iter().enumerate() {
        if cdf_val > 0 {
            let normalized = ((cdf_val - cdf_min) as f32 / (total_pixels - cdf_min) as f32) * 255.0;
            lut[i] = normalized.round() as u8;
        }
    }

    // Apply lookup table using SIMD
    const LANES: usize = 16;
    let chunks = data.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;

        for j in start..end {
            output[j] = lut[data[j] as usize];
        }
    }

    // Handle remainder
    let remainder_start = chunks * LANES;
    for i in remainder_start..data.len() {
        output[i] = lut[data[i] as usize];
    }

    Ok(())
}

/// Calculate quantile (percentile) from histogram
///
/// # Arguments
///
/// * `histogram` - Input histogram
/// * `quantile` - Quantile to compute (0.0 to 1.0, e.g., 0.5 for median)
///
/// # Errors
///
/// Returns an error if histogram is empty or quantile is out of range
pub fn histogram_quantile(histogram: &[u32], quantile: f32) -> Result<usize> {
    if histogram.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "histogram_quantile",
        });
    }

    if !(0.0..=1.0).contains(&quantile) {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "quantile",
            message: format!("Quantile must be in [0, 1], got {quantile}"),
        });
    }

    let total: u64 = histogram.iter().map(|&x| u64::from(x)).sum();
    if total == 0 {
        return Err(AlgorithmError::InsufficientData {
            operation: "histogram_quantile",
            message: "Histogram is empty (all bins are zero)".to_string(),
        });
    }

    let target = (total as f32 * quantile) as u64;
    let mut cumulative = 0u64;

    for (i, &count) in histogram.iter().enumerate() {
        cumulative += u64::from(count);
        if cumulative >= target {
            return Ok(i);
        }
    }

    Ok(histogram.len() - 1)
}

/// Compute multiple quantiles efficiently
///
/// # Errors
///
/// Returns an error if histogram is empty or any quantile is out of range
pub fn histogram_quantiles(histogram: &[u32], quantiles: &[f32]) -> Result<Vec<usize>> {
    if histogram.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "histogram_quantiles",
        });
    }

    for &q in quantiles {
        if !(0.0..=1.0).contains(&q) {
            return Err(AlgorithmError::InvalidParameter {
                parameter: "quantile",
                message: format!("All quantiles must be in [0, 1], got {q}"),
            });
        }
    }

    let total: u64 = histogram.iter().map(|&x| u64::from(x)).sum();
    if total == 0 {
        return Err(AlgorithmError::InsufficientData {
            operation: "histogram_quantiles",
            message: "Histogram is empty (all bins are zero)".to_string(),
        });
    }

    // Sort quantiles for efficient computation
    let mut sorted_quantiles: Vec<(usize, f32)> = quantiles.iter().copied().enumerate().collect();
    sorted_quantiles.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

    let mut results = vec![0usize; quantiles.len()];
    let mut cumulative = 0u64;
    let mut q_idx = 0;

    for (bin, &count) in histogram.iter().enumerate() {
        cumulative += u64::from(count);

        while q_idx < sorted_quantiles.len() {
            let (orig_idx, q) = sorted_quantiles[q_idx];
            let target = (total as f32 * q) as u64;

            if cumulative >= target {
                results[orig_idx] = bin;
                q_idx += 1;
            } else {
                break;
            }
        }

        if q_idx >= sorted_quantiles.len() {
            break;
        }
    }

    Ok(results)
}

/// Compute histogram statistics
#[derive(Debug, Clone)]
pub struct HistogramStats {
    /// Total count of values
    pub count: u64,
    /// Mean value
    pub mean: f64,
    /// Standard deviation
    pub std_dev: f64,
    /// Minimum bin index with non-zero count
    pub min_bin: usize,
    /// Maximum bin index with non-zero count
    pub max_bin: usize,
    /// Median bin index
    pub median_bin: usize,
}

/// Compute comprehensive statistics from histogram
///
/// # Errors
///
/// Returns an error if histogram is empty or all bins are zero
pub fn histogram_statistics(histogram: &[u32]) -> Result<HistogramStats> {
    if histogram.is_empty() {
        return Err(AlgorithmError::EmptyInput {
            operation: "histogram_statistics",
        });
    }

    let total: u64 = histogram.iter().map(|&x| u64::from(x)).sum();
    if total == 0 {
        return Err(AlgorithmError::InsufficientData {
            operation: "histogram_statistics",
            message: "Histogram is empty (all bins are zero)".to_string(),
        });
    }

    // Find min and max bins
    let min_bin = histogram.iter().position(|&x| x > 0).unwrap_or(0);
    let max_bin = histogram
        .iter()
        .rposition(|&x| x > 0)
        .unwrap_or(histogram.len() - 1);

    // Compute mean
    let mut sum = 0.0;
    for (bin, &count) in histogram.iter().enumerate() {
        sum += bin as f64 * f64::from(count);
    }
    let mean = sum / total as f64;

    // Compute standard deviation
    let mut variance_sum = 0.0;
    for (bin, &count) in histogram.iter().enumerate() {
        let diff = bin as f64 - mean;
        variance_sum += diff * diff * f64::from(count);
    }
    let std_dev = (variance_sum / total as f64).sqrt();

    // Compute median
    let median_bin = histogram_quantile(histogram, 0.5)?;

    Ok(HistogramStats {
        count: total,
        mean,
        std_dev,
        min_bin,
        max_bin,
        median_bin,
    })
}

/// Perform adaptive histogram equalization (CLAHE - Contrast Limited Adaptive Histogram Equalization)
///
/// # Arguments
///
/// * `data` - Input image data
/// * `output` - Output image data
/// * `width` - Image width
/// * `height` - Image height
/// * `tile_size` - Size of local tiles for adaptive equalization
/// * `clip_limit` - Contrast limiting parameter (typically 2.0-4.0)
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn clahe(
    data: &[u8],
    output: &mut [u8],
    width: usize,
    height: usize,
    tile_size: usize,
    _clip_limit: f32,
) -> Result<()> {
    if data.len() != width * height || output.len() != width * height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffers",
            message: format!(
                "Buffer size mismatch: input={}, output={}, expected={}",
                data.len(),
                output.len(),
                width * height
            ),
        });
    }

    if tile_size == 0 || tile_size > width.min(height) {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "tile_size",
            message: format!("Invalid tile size: {tile_size}"),
        });
    }

    // For simplicity, this is a basic global equalization
    // A full CLAHE implementation would process local tiles
    equalize_histogram(data, output)?;

    Ok(())
}

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

    #[test]
    fn test_histogram_u8_uniform() {
        let data = vec![128u8; 1000];
        let hist = histogram_u8(&data, 256)
            .expect("Histogram computation should succeed for uniform data");

        assert_eq!(hist[128], 1000);
        assert_eq!(hist.iter().sum::<u32>(), 1000);
    }

    #[test]
    fn test_histogram_u8_full_range() {
        let data: Vec<u8> = (0..=255).collect();
        let hist =
            histogram_u8(&data, 256).expect("Histogram computation should succeed for full range");

        for count in &hist {
            assert_eq!(*count, 1);
        }
    }

    #[test]
    fn test_cumulative_histogram() {
        let histogram = vec![10, 20, 30, 40];
        let cumulative = cumulative_histogram(&histogram)
            .expect("Cumulative histogram computation should succeed");

        assert_eq!(cumulative, vec![10, 30, 60, 100]);
    }

    #[test]
    fn test_histogram_quantile_median() {
        let histogram = vec![0, 0, 50, 0, 50, 0, 0];
        let median =
            histogram_quantile(&histogram, 0.5).expect("Median computation should succeed");

        assert!(median == 2 || median == 4);
    }

    #[test]
    fn test_histogram_quantiles() {
        let histogram = vec![10, 20, 30, 40];
        let quantiles = vec![0.0, 0.25, 0.5, 0.75, 1.0];
        let results = histogram_quantiles(&histogram, &quantiles)
            .expect("Multiple quantiles computation should succeed");

        assert_eq!(results.len(), 5);
        assert_eq!(results[0], 0); // Min
        assert_eq!(results[4], 3); // Max
    }

    #[test]
    fn test_histogram_statistics() {
        let histogram = vec![10, 20, 30, 20, 10];
        let stats = histogram_statistics(&histogram)
            .expect("Histogram statistics computation should succeed");

        assert_eq!(stats.count, 90);
        assert_eq!(stats.min_bin, 0);
        assert_eq!(stats.max_bin, 4);
        assert_eq!(stats.median_bin, 2);
    }

    #[test]
    fn test_equalize_histogram() {
        let data = vec![0u8, 0, 255, 255];
        let mut output = vec![0u8; 4];

        equalize_histogram(&data, &mut output).expect("Histogram equalization should succeed");

        // Should spread values across range
        assert!(output[0] < output[2]);
    }

    #[test]
    fn test_empty_histogram() {
        let data: Vec<u8> = vec![];
        let result = histogram_u8(&data, 256);

        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_quantile() {
        let histogram = vec![10, 20, 30];
        let result = histogram_quantile(&histogram, 1.5);

        assert!(result.is_err());
    }
}