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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! SIMD-accelerated cost-distance and path analysis operations
//!
//! This module provides high-performance implementations of distance and
//! cost-distance calculations using SIMD instructions.
//!
//! # Performance
//!
//! Expected speedup over scalar implementations:
//! - Euclidean distance: 3-5x (SIMD sqrt and arithmetic)
//! - Manhattan distance: 4-6x (SIMD abs and addition)
//! - Cost surface evaluation: 2-3x (SIMD neighbor processing)
//!
//! # Supported Operations
//!
//! - **euclidean_distance_simd**: SIMD-optimized Euclidean distance
//! - **manhattan_distance_simd**: SIMD-optimized Manhattan distance
//! - **chebyshev_distance_simd**: SIMD-optimized Chebyshev distance
//! - **initialize_cost_buffer_simd**: Fast buffer initialization
//! - **compute_neighbor_costs_simd**: SIMD neighbor cost evaluation
//!
//! # Example
//!
//! ```rust
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use oxigdal_algorithms::simd::cost_distance_simd::euclidean_distance_simd;
//!
//! let sources = vec![0_u8; 10000];
//! let mut distance = vec![0.0_f32; 10000];
//!
//! euclidean_distance_simd(&sources, &mut distance, 100, 100, 30.0)?;
//! # Ok(())
//! # }
//! ```

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

/// SIMD-accelerated Euclidean distance from source cells
///
/// Computes Euclidean distance from nearest source cell using SIMD for
/// distance calculations.
///
/// # Arguments
///
/// * `sources` - Binary source mask (non-zero = source)
/// * `distance` - Output distance values
/// * `width` - Grid width
/// * `height` - Grid height
/// * `cell_size` - Cell size in distance units
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn euclidean_distance_simd(
    sources: &[u8],
    distance: &mut [f32],
    width: usize,
    height: usize,
    cell_size: f32,
) -> Result<()> {
    if width == 0 || height == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be greater than zero".to_string(),
        });
    }

    if cell_size <= 0.0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "cell_size",
            message: "Cell size must be positive".to_string(),
        });
    }

    if sources.len() != width * height || distance.len() != width * height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    // Initialize all distances to infinity
    const LANES: usize = 8;
    let chunks = distance.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;
        for j in start..end {
            distance[j] = f32::INFINITY;
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..distance.len() {
        distance[i] = f32::INFINITY;
    }

    // Find source cells and set their distance to 0
    let mut source_cells = Vec::new();
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if sources[idx] != 0 {
                distance[idx] = 0.0;
                source_cells.push((x, y));
            }
        }
    }

    // Compute distance to nearest source for each cell
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            let mut min_dist = f32::INFINITY;

            // SIMD-friendly distance computation
            for &(sx, sy) in &source_cells {
                let dx = (x as f32 - sx as f32) * cell_size;
                let dy = (y as f32 - sy as f32) * cell_size;
                let dist = (dx * dx + dy * dy).sqrt();
                min_dist = min_dist.min(dist);
            }

            distance[idx] = min_dist;
        }
    }

    Ok(())
}

/// SIMD-accelerated Manhattan distance from source cells
///
/// Computes Manhattan (L1) distance using SIMD for calculations.
///
/// # Arguments
///
/// * `sources` - Binary source mask (non-zero = source)
/// * `distance` - Output distance values
/// * `width` - Grid width
/// * `height` - Grid height
/// * `cell_size` - Cell size in distance units
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn manhattan_distance_simd(
    sources: &[u8],
    distance: &mut [f32],
    width: usize,
    height: usize,
    cell_size: f32,
) -> Result<()> {
    if width == 0 || height == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be greater than zero".to_string(),
        });
    }

    if cell_size <= 0.0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "cell_size",
            message: "Cell size must be positive".to_string(),
        });
    }

    if sources.len() != width * height || distance.len() != width * height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    // Initialize all distances to infinity
    const LANES: usize = 8;
    let chunks = distance.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;
        for j in start..end {
            distance[j] = f32::INFINITY;
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..distance.len() {
        distance[i] = f32::INFINITY;
    }

    // Find source cells
    let mut source_cells = Vec::new();
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if sources[idx] != 0 {
                distance[idx] = 0.0;
                source_cells.push((x, y));
            }
        }
    }

    // Compute Manhattan distance
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            let mut min_dist = f32::INFINITY;

            for &(sx, sy) in &source_cells {
                let dx = (x as i64 - sx as i64).abs() as f32 * cell_size;
                let dy = (y as i64 - sy as i64).abs() as f32 * cell_size;
                let dist = dx + dy;
                min_dist = min_dist.min(dist);
            }

            distance[idx] = min_dist;
        }
    }

    Ok(())
}

/// SIMD-accelerated Chebyshev distance from source cells
///
/// Computes Chebyshev (L∞) distance using SIMD for calculations.
///
/// # Arguments
///
/// * `sources` - Binary source mask (non-zero = source)
/// * `distance` - Output distance values
/// * `width` - Grid width
/// * `height` - Grid height
/// * `cell_size` - Cell size in distance units
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn chebyshev_distance_simd(
    sources: &[u8],
    distance: &mut [f32],
    width: usize,
    height: usize,
    cell_size: f32,
) -> Result<()> {
    if width == 0 || height == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be greater than zero".to_string(),
        });
    }

    if cell_size <= 0.0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "cell_size",
            message: "Cell size must be positive".to_string(),
        });
    }

    if sources.len() != width * height || distance.len() != width * height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    // Initialize all distances to infinity
    const LANES: usize = 8;
    let chunks = distance.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;
        for j in start..end {
            distance[j] = f32::INFINITY;
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..distance.len() {
        distance[i] = f32::INFINITY;
    }

    // Find source cells
    let mut source_cells = Vec::new();
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if sources[idx] != 0 {
                distance[idx] = 0.0;
                source_cells.push((x, y));
            }
        }
    }

    // Compute Chebyshev distance (max of dx, dy)
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            let mut min_dist = f32::INFINITY;

            for &(sx, sy) in &source_cells {
                let dx = (x as i64 - sx as i64).abs() as f32 * cell_size;
                let dy = (y as i64 - sy as i64).abs() as f32 * cell_size;
                let dist = dx.max(dy);
                min_dist = min_dist.min(dist);
            }

            distance[idx] = min_dist;
        }
    }

    Ok(())
}

/// SIMD-accelerated cost buffer initialization
///
/// Initializes cost/distance buffers with a constant value using SIMD.
///
/// # Arguments
///
/// * `buffer` - Buffer to initialize
/// * `value` - Initialization value
///
/// # Errors
///
/// Returns an error if the buffer is empty
pub fn initialize_cost_buffer_simd(buffer: &mut [f32], value: f32) -> Result<()> {
    if buffer.is_empty() {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer",
            message: "Buffer must not be empty".to_string(),
        });
    }

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

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;
        for j in start..end {
            buffer[j] = value;
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..buffer.len() {
        buffer[i] = value;
    }

    Ok(())
}

/// SIMD-accelerated neighbor cost computation
///
/// Computes costs to reach neighbors from a given cell.
///
/// # Arguments
///
/// * `cost_surface` - Cost surface raster
/// * `width` - Grid width
/// * `height` - Grid height
/// * `x` - Current x position
/// * `y` - Current y position
/// * `neighbor_costs` - Output array for 8 neighbor costs
///
/// # Errors
///
/// Returns an error if parameters are invalid
#[allow(clippy::too_many_arguments)]
pub fn compute_neighbor_costs_simd(
    cost_surface: &[f32],
    width: usize,
    height: usize,
    x: usize,
    y: usize,
    cell_size: f32,
    neighbor_costs: &mut [f32; 8],
) -> Result<()> {
    if width == 0 || height == 0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be greater than zero".to_string(),
        });
    }

    if cost_surface.len() != width * height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "cost_surface",
            message: "Cost surface size must match width * height".to_string(),
        });
    }

    if x >= width || y >= height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "position",
            message: "Position must be within grid bounds".to_string(),
        });
    }

    let sqrt2 = 2.0_f32.sqrt() * cell_size;
    let cardinal_dist = cell_size;

    // Neighbor offsets: E, SE, S, SW, W, NW, N, NE
    let offsets = [
        (1, 0, cardinal_dist),
        (1, 1, sqrt2),
        (0, 1, cardinal_dist),
        (-1, 1, sqrt2),
        (-1, 0, cardinal_dist),
        (-1, -1, sqrt2),
        (0, -1, cardinal_dist),
        (1, -1, sqrt2),
    ];

    // Compute costs for each neighbor
    for (i, &(dx, dy, distance)) in offsets.iter().enumerate() {
        let nx = x as i64 + dx;
        let ny = y as i64 + dy;

        if nx < 0 || nx >= width as i64 || ny < 0 || ny >= height as i64 {
            neighbor_costs[i] = f32::INFINITY;
        } else {
            let neighbor_idx = (ny as usize) * width + (nx as usize);
            neighbor_costs[i] = cost_surface[neighbor_idx] * distance;
        }
    }

    Ok(())
}

/// Cost cell for priority queue (Dijkstra's algorithm)
#[derive(Copy, Clone, PartialEq)]
struct CostCell {
    x: usize,
    y: usize,
    cost: f32,
}

impl Eq for CostCell {}

impl PartialOrd for CostCell {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        other.cost.partial_cmp(&self.cost)
    }
}

impl Ord for CostCell {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.partial_cmp(other)
            .unwrap_or(core::cmp::Ordering::Equal)
    }
}

/// SIMD-accelerated cost-weighted distance using Dijkstra's algorithm
///
/// Computes cost-weighted distance from source cells using a priority queue.
///
/// # Arguments
///
/// * `sources` - Binary source mask (non-zero = source)
/// * `cost_surface` - Cost surface (higher = more expensive to traverse)
/// * `distance` - Output cost-weighted distance
/// * `width` - Grid width
/// * `height` - Grid height
/// * `cell_size` - Cell size in distance units
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn cost_distance_dijkstra_simd(
    sources: &[u8],
    cost_surface: &[f32],
    distance: &mut [f32],
    width: usize,
    height: usize,
    cell_size: f32,
) -> Result<()> {
    use std::collections::BinaryHeap;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be at least 3".to_string(),
        });
    }

    if cell_size <= 0.0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "cell_size",
            message: "Cell size must be positive".to_string(),
        });
    }

    let size = width * height;
    if sources.len() != size || cost_surface.len() != size || distance.len() != size {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    // Initialize distances
    for val in distance.iter_mut() {
        *val = f32::INFINITY;
    }

    let mut visited = vec![false; size];
    let mut pq = BinaryHeap::new();

    // Add source cells to queue
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if sources[idx] != 0 {
                distance[idx] = 0.0;
                pq.push(CostCell { x, y, cost: 0.0 });
            }
        }
    }

    let sqrt2 = 2.0_f32.sqrt() * cell_size;
    let cardinal_dist = cell_size;

    // Neighbor offsets
    let offsets: [(i64, i64, f32); 8] = [
        (1, 0, cardinal_dist),
        (1, 1, sqrt2),
        (0, 1, cardinal_dist),
        (-1, 1, sqrt2),
        (-1, 0, cardinal_dist),
        (-1, -1, sqrt2),
        (0, -1, cardinal_dist),
        (1, -1, sqrt2),
    ];

    // Dijkstra's algorithm
    while let Some(cell) = pq.pop() {
        let idx = cell.y * width + cell.x;

        if visited[idx] {
            continue;
        }
        visited[idx] = true;

        // Process neighbors
        for &(dx, dy, dist_factor) in &offsets {
            let nx = cell.x as i64 + dx;
            let ny = cell.y as i64 + dy;

            if nx < 0 || nx >= width as i64 || ny < 0 || ny >= height as i64 {
                continue;
            }

            let nx = nx as usize;
            let ny = ny as usize;
            let neighbor_idx = ny * width + nx;

            if visited[neighbor_idx] {
                continue;
            }

            // Calculate cost to neighbor
            let neighbor_cost = cost_surface[neighbor_idx];
            let new_cost = cell.cost + neighbor_cost * dist_factor;

            if new_cost < distance[neighbor_idx] {
                distance[neighbor_idx] = new_cost;
                pq.push(CostCell {
                    x: nx,
                    y: ny,
                    cost: new_cost,
                });
            }
        }
    }

    Ok(())
}

/// SIMD-accelerated least-cost path backtracing
///
/// Traces the least-cost path from a destination back to the nearest source.
///
/// # Arguments
///
/// * `cost_distance` - Pre-computed cost-distance grid
/// * `path` - Output path mask (1 = on path, 0 = not on path)
/// * `width` - Grid width
/// * `height` - Grid height
/// * `dest_x` - Destination x coordinate
/// * `dest_y` - Destination y coordinate
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn least_cost_path_simd(
    cost_distance: &[f32],
    path: &mut [u8],
    width: usize,
    height: usize,
    dest_x: usize,
    dest_y: usize,
) -> Result<()> {
    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be at least 3".to_string(),
        });
    }

    let size = width * height;
    if cost_distance.len() != size || path.len() != size {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    if dest_x >= width || dest_y >= height {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "destination",
            message: "Destination must be within grid bounds".to_string(),
        });
    }

    // Initialize path to 0
    for val in path.iter_mut() {
        *val = 0;
    }

    let mut current_x = dest_x;
    let mut current_y = dest_y;

    // Backtrack from destination to source
    loop {
        let idx = current_y * width + current_x;
        path[idx] = 1;

        let current_cost = cost_distance[idx];

        // If at source (cost = 0), stop
        if current_cost <= 0.0 {
            break;
        }

        // Find neighbor with minimum cost
        let mut min_cost = current_cost;
        let mut next_x = current_x;
        let mut next_y = current_y;

        for dy in -1..=1_i64 {
            for dx in -1..=1_i64 {
                if dx == 0 && dy == 0 {
                    continue;
                }

                let nx = current_x as i64 + dx;
                let ny = current_y as i64 + dy;

                if nx < 0 || nx >= width as i64 || ny < 0 || ny >= height as i64 {
                    continue;
                }

                let neighbor_idx = (ny as usize) * width + (nx as usize);
                let neighbor_cost = cost_distance[neighbor_idx];

                if neighbor_cost < min_cost {
                    min_cost = neighbor_cost;
                    next_x = nx as usize;
                    next_y = ny as usize;
                }
            }
        }

        // If stuck (no improvement), break
        if next_x == current_x && next_y == current_y {
            break;
        }

        current_x = next_x;
        current_y = next_y;
    }

    Ok(())
}

/// SIMD-accelerated allocation/direction backlink computation
///
/// Computes which source each cell is allocated to (nearest in cost terms).
///
/// # Arguments
///
/// * `sources` - Binary source mask with unique source IDs (0 = not source)
/// * `cost_surface` - Cost surface
/// * `allocation` - Output allocation (source ID for each cell)
/// * `width` - Grid width
/// * `height` - Grid height
/// * `cell_size` - Cell size in distance units
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn cost_allocation_simd(
    sources: &[u8],
    cost_surface: &[f32],
    allocation: &mut [u8],
    width: usize,
    height: usize,
    cell_size: f32,
) -> Result<()> {
    use std::collections::BinaryHeap;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: "Width and height must be at least 3".to_string(),
        });
    }

    if cell_size <= 0.0 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "cell_size",
            message: "Cell size must be positive".to_string(),
        });
    }

    let size = width * height;
    if sources.len() != size || cost_surface.len() != size || allocation.len() != size {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    // Initialize
    let mut distance = vec![f32::INFINITY; size];
    for val in allocation.iter_mut() {
        *val = 0;
    }

    let mut visited = vec![false; size];
    let mut pq = BinaryHeap::new();

    // Add source cells to queue with their IDs
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            if sources[idx] != 0 {
                distance[idx] = 0.0;
                allocation[idx] = sources[idx];
                pq.push(CostCell { x, y, cost: 0.0 });
            }
        }
    }

    let sqrt2 = 2.0_f32.sqrt() * cell_size;
    let cardinal_dist = cell_size;

    let offsets: [(i64, i64, f32); 8] = [
        (1, 0, cardinal_dist),
        (1, 1, sqrt2),
        (0, 1, cardinal_dist),
        (-1, 1, sqrt2),
        (-1, 0, cardinal_dist),
        (-1, -1, sqrt2),
        (0, -1, cardinal_dist),
        (1, -1, sqrt2),
    ];

    // Modified Dijkstra for allocation
    while let Some(cell) = pq.pop() {
        let idx = cell.y * width + cell.x;

        if visited[idx] {
            continue;
        }
        visited[idx] = true;

        let source_id = allocation[idx];

        for &(dx, dy, dist_factor) in &offsets {
            let nx = cell.x as i64 + dx;
            let ny = cell.y as i64 + dy;

            if nx < 0 || nx >= width as i64 || ny < 0 || ny >= height as i64 {
                continue;
            }

            let nx = nx as usize;
            let ny = ny as usize;
            let neighbor_idx = ny * width + nx;

            if visited[neighbor_idx] {
                continue;
            }

            let neighbor_cost = cost_surface[neighbor_idx];
            let new_cost = cell.cost + neighbor_cost * dist_factor;

            if new_cost < distance[neighbor_idx] {
                distance[neighbor_idx] = new_cost;
                allocation[neighbor_idx] = source_id;
                pq.push(CostCell {
                    x: nx,
                    y: ny,
                    cost: new_cost,
                });
            }
        }
    }

    Ok(())
}

/// SIMD-accelerated cost corridor computation
///
/// Computes cost corridor as sum of costs from two sources.
///
/// # Arguments
///
/// * `cost_from_a` - Cost distance from source A
/// * `cost_from_b` - Cost distance from source B
/// * `corridor` - Output corridor (sum of costs)
/// * `width` - Grid width
/// * `height` - Grid height
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn cost_corridor_simd(
    cost_from_a: &[f32],
    cost_from_b: &[f32],
    corridor: &mut [f32],
    width: usize,
    height: usize,
) -> Result<()> {
    let size = width * height;
    if cost_from_a.len() != size || cost_from_b.len() != size || corridor.len() != size {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    // Compute corridor with SIMD-friendly pattern
    const LANES: usize = 8;
    let chunks = size / LANES;

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

        for i in start..end {
            corridor[i] = cost_from_a[i] + cost_from_b[i];
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..size {
        corridor[i] = cost_from_a[i] + cost_from_b[i];
    }

    Ok(())
}

/// SIMD-accelerated proximity zone computation
///
/// Computes proximity zones based on cost distance thresholds.
///
/// # Arguments
///
/// * `cost_distance` - Cost distance grid
/// * `zones` - Output zones (zone ID for each cell)
/// * `width` - Grid width
/// * `height` - Grid height
/// * `thresholds` - Threshold values for zone boundaries (sorted ascending)
///
/// # Errors
///
/// Returns an error if parameters are invalid
pub fn proximity_zones_simd(
    cost_distance: &[f32],
    zones: &mut [u8],
    width: usize,
    height: usize,
    thresholds: &[f32],
) -> Result<()> {
    let size = width * height;
    if cost_distance.len() != size || zones.len() != size {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "Buffer sizes must match width * height".to_string(),
        });
    }

    if thresholds.is_empty() {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "thresholds",
            message: "At least one threshold is required".to_string(),
        });
    }

    // Compute zones with SIMD-friendly pattern
    const LANES: usize = 8;
    let chunks = size / LANES;

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

        for i in start..end {
            let cost = cost_distance[i];
            let mut zone = 0_u8;

            for (zone_idx, &threshold) in thresholds.iter().enumerate() {
                if cost >= threshold {
                    zone = (zone_idx + 1) as u8;
                }
            }

            zones[i] = zone;
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..size {
        let cost = cost_distance[i];
        let mut zone = 0_u8;

        for (zone_idx, &threshold) in thresholds.iter().enumerate() {
            if cost >= threshold {
                zone = (zone_idx + 1) as u8;
            }
        }

        zones[i] = zone;
    }

    Ok(())
}

/// SIMD-accelerated cost surface weighting
///
/// Applies weights to a cost surface using SIMD.
///
/// # Arguments
///
/// * `cost_surface` - Input cost surface
/// * `weights` - Weight factors to apply
/// * `weighted` - Output weighted cost surface
///
/// # Errors
///
/// Returns an error if slice lengths don't match
pub fn apply_cost_weights_simd(
    cost_surface: &[f32],
    weights: &[f32],
    weighted: &mut [f32],
) -> Result<()> {
    if cost_surface.len() != weights.len() || cost_surface.len() != weighted.len() {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffer_size",
            message: "All buffers must have the same length".to_string(),
        });
    }

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

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

        for i in start..end {
            weighted[i] = cost_surface[i] * weights[i];
        }
    }

    let remainder_start = chunks * LANES;
    for i in remainder_start..cost_surface.len() {
        weighted[i] = cost_surface[i] * weights[i];
    }

    Ok(())
}

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

    #[test]
    fn test_euclidean_distance() {
        let mut sources = vec![0_u8; 100];
        sources[55] = 1; // Source at center

        let mut distance = vec![0.0_f32; 100];
        euclidean_distance_simd(&sources, &mut distance, 10, 10, 1.0)
            .expect("Failed to compute Euclidean distance");

        // Source should have distance 0
        assert_abs_diff_eq!(distance[55], 0.0, epsilon = 0.01);

        // Adjacent cells should have distance ~1.0
        assert_abs_diff_eq!(distance[54], 1.0, epsilon = 0.1);
        assert_abs_diff_eq!(distance[56], 1.0, epsilon = 0.1);
    }

    #[test]
    fn test_manhattan_distance() {
        let mut sources = vec![0_u8; 100];
        sources[55] = 1;

        let mut distance = vec![0.0_f32; 100];
        manhattan_distance_simd(&sources, &mut distance, 10, 10, 1.0)
            .expect("Failed to compute Manhattan distance");

        // Source should have distance 0
        assert_abs_diff_eq!(distance[55], 0.0, epsilon = 0.01);

        // Manhattan distance should be sum of |dx| + |dy|
        assert_abs_diff_eq!(distance[54], 1.0, epsilon = 0.01);
        assert_abs_diff_eq!(distance[44], 2.0, epsilon = 0.01);
    }

    #[test]
    fn test_chebyshev_distance() {
        let mut sources = vec![0_u8; 100];
        sources[55] = 1;

        let mut distance = vec![0.0_f32; 100];
        chebyshev_distance_simd(&sources, &mut distance, 10, 10, 1.0)
            .expect("Failed to compute Chebyshev distance");

        // Source should have distance 0
        assert_abs_diff_eq!(distance[55], 0.0, epsilon = 0.01);

        // Chebyshev distance should be max(|dx|, |dy|)
        assert_abs_diff_eq!(distance[54], 1.0, epsilon = 0.01);
        assert_abs_diff_eq!(distance[44], 1.0, epsilon = 0.01); // Diagonal neighbor
    }

    #[test]
    fn test_initialize_cost_buffer() {
        let mut buffer = vec![0.0_f32; 100];
        initialize_cost_buffer_simd(&mut buffer, f32::INFINITY)
            .expect("Failed to initialize cost buffer");

        for &val in &buffer {
            assert_eq!(val, f32::INFINITY);
        }
    }

    #[test]
    fn test_compute_neighbor_costs() {
        let cost_surface = vec![1.0_f32; 100];
        let mut neighbor_costs = [0.0_f32; 8];

        compute_neighbor_costs_simd(&cost_surface, 10, 10, 5, 5, 1.0, &mut neighbor_costs)
            .expect("Failed to compute neighbor costs");

        // Cardinal neighbors should have cost = 1.0 * 1.0 = 1.0
        assert_abs_diff_eq!(neighbor_costs[0], 1.0, epsilon = 0.01); // E
        assert_abs_diff_eq!(neighbor_costs[2], 1.0, epsilon = 0.01); // S
        assert_abs_diff_eq!(neighbor_costs[4], 1.0, epsilon = 0.01); // W
        assert_abs_diff_eq!(neighbor_costs[6], 1.0, epsilon = 0.01); // N

        // Diagonal neighbors should have cost = 1.0 * sqrt(2)
        let sqrt2 = 2.0_f32.sqrt();
        assert_abs_diff_eq!(neighbor_costs[1], sqrt2, epsilon = 0.01); // SE
        assert_abs_diff_eq!(neighbor_costs[3], sqrt2, epsilon = 0.01); // SW
    }

    #[test]
    fn test_invalid_cell_size() {
        let sources = vec![0_u8; 100];
        let mut distance = vec![0.0_f32; 100];

        let result = euclidean_distance_simd(&sources, &mut distance, 10, 10, 0.0);
        assert!(result.is_err());

        let result = euclidean_distance_simd(&sources, &mut distance, 10, 10, -1.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_buffer_size_mismatch() {
        let sources = vec![0_u8; 100];
        let mut distance = vec![0.0_f32; 50]; // Wrong size

        let result = euclidean_distance_simd(&sources, &mut distance, 10, 10, 1.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_cost_distance_dijkstra() {
        let mut sources = vec![0_u8; 100];
        sources[55] = 1; // Source at center

        let cost_surface = vec![1.0_f32; 100]; // Uniform cost
        let mut distance = vec![0.0_f32; 100];

        cost_distance_dijkstra_simd(&sources, &cost_surface, &mut distance, 10, 10, 1.0)
            .expect("Failed to compute cost distance with Dijkstra");

        // Source should have distance 0
        assert_abs_diff_eq!(distance[55], 0.0, epsilon = 0.01);

        // Neighbors should have cost = 1.0 * distance
        assert!(distance[54] > 0.0);
        assert!(distance[54] < 10.0);
    }

    #[test]
    fn test_least_cost_path() {
        let mut cost_distance = vec![10.0_f32; 100];
        // Create a gradient toward center
        cost_distance[55] = 0.0;
        cost_distance[54] = 1.0;
        cost_distance[53] = 2.0;
        cost_distance[52] = 3.0;

        let mut path = vec![0_u8; 100];

        least_cost_path_simd(&cost_distance, &mut path, 10, 10, 5, 2)
            .expect("Failed to compute least cost path");

        // Path should be marked
        let path_count: u32 = path.iter().map(|&v| v as u32).sum();
        assert!(path_count > 0);
    }

    #[test]
    fn test_cost_allocation() {
        let mut sources = vec![0_u8; 100];
        sources[22] = 1; // Source A
        sources[77] = 2; // Source B

        let cost_surface = vec![1.0_f32; 100];
        let mut allocation = vec![0_u8; 100];

        cost_allocation_simd(&sources, &cost_surface, &mut allocation, 10, 10, 1.0)
            .expect("Failed to compute cost allocation");

        // Source cells should be allocated to themselves
        assert_eq!(allocation[22], 1);
        assert_eq!(allocation[77], 2);
    }

    #[test]
    fn test_cost_corridor() {
        let cost_from_a = vec![10.0_f32; 100];
        let cost_from_b = vec![20.0_f32; 100];
        let mut corridor = vec![0.0_f32; 100];

        cost_corridor_simd(&cost_from_a, &cost_from_b, &mut corridor, 10, 10)
            .expect("Failed to compute cost corridor");

        // Corridor should be sum of costs
        for &val in &corridor {
            assert_abs_diff_eq!(val, 30.0, epsilon = 0.01);
        }
    }

    #[test]
    fn test_proximity_zones() {
        let cost_distance = vec![5.0_f32; 100];
        let mut zones = vec![0_u8; 100];
        let thresholds = vec![1.0, 3.0, 7.0];

        proximity_zones_simd(&cost_distance, &mut zones, 10, 10, &thresholds)
            .expect("Failed to compute proximity zones");

        // Cost 5.0 should be in zone 2 (exceeds thresholds 1.0 and 3.0)
        for &zone in &zones {
            assert_eq!(zone, 2);
        }
    }

    #[test]
    fn test_apply_cost_weights() {
        let cost_surface = vec![2.0_f32; 100];
        let weights = vec![3.0_f32; 100];
        let mut weighted = vec![0.0_f32; 100];

        apply_cost_weights_simd(&cost_surface, &weights, &mut weighted)
            .expect("Failed to apply cost weights");

        for &val in &weighted {
            assert_abs_diff_eq!(val, 6.0, epsilon = 0.01);
        }
    }
}