scirs2-sparse 0.4.2

Sparse matrix module for SciRS2 (scirs2-sparse)
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
//! Shortest path algorithms for sparse graphs
//!
//! This module provides efficient implementations of shortest path algorithms
//! for sparse matrices representing graphs.

use super::{num_vertices, to_adjacency_list, validate_graph, PriorityQueueNode};
use crate::error::{SparseError, SparseResult};
use crate::sparray::SparseArray;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::{Float, SparseElement};
use std::collections::BinaryHeap;
use std::fmt::Debug;

/// Shortest path algorithm types
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ShortestPathMethod {
    /// Dijkstra's algorithm (non-negative weights only)
    Dijkstra,
    /// Bellman-Ford algorithm (handles negative weights)
    BellmanFord,
    /// Floyd-Warshall algorithm (all pairs shortest paths)
    FloydWarshall,
    /// Automatic selection based on graph properties
    Auto,
}

impl ShortestPathMethod {
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> SparseResult<Self> {
        match s.to_lowercase().as_str() {
            "dijkstra" | "dij" => Ok(Self::Dijkstra),
            "bellman-ford" | "bellman_ford" | "bf" => Ok(Self::BellmanFord),
            "floyd-warshall" | "floyd_warshall" | "fw" => Ok(Self::FloydWarshall),
            "auto" => Ok(Self::Auto),
            _ => Err(SparseError::ValueError(format!(
                "Unknown shortest path method: {s}"
            ))),
        }
    }
}

/// Compute shortest paths in a graph
///
/// # Arguments
///
/// * `graph` - The graph as a sparse matrix
/// * `from_vertex` - Source vertex (None for all pairs)
/// * `to_vertex` - Target vertex (None for all destinations)
/// * `method` - Algorithm to use
/// * `directed` - Whether the graph is directed
/// * `returnpredecessors` - Whether to return predecessor information
///
/// # Returns
///
/// A tuple containing:
/// - Distance matrix/array
/// - Optional predecessor matrix/array
///
/// # Examples
///
/// ```
/// use scirs2_sparse::csgraph::shortest_path;
/// use scirs2_sparse::csr_array::CsrArray;
///
/// // Create a simple graph
/// let rows = vec![0, 0, 1, 2];
/// let cols = vec![1, 2, 2, 0];
/// let data = vec![1.0, 4.0, 2.0, 3.0];
/// let graph = CsrArray::from_triplets(&rows, &cols, &data, (3, 3), false).expect("Operation failed");
///
/// // Find shortest paths from vertex 0
/// let (distances_) = shortest_path(
///     &graph, Some(0), None, "dijkstra", true, false
/// ).expect("Operation failed");
/// ```
#[allow(dead_code)]
#[allow(clippy::too_many_arguments)]
pub fn shortest_path<T, S>(
    graph: &S,
    from_vertex: Option<usize>,
    to_vertex: Option<usize>,
    method: &str,
    directed: bool,
    returnpredecessors: bool,
) -> SparseResult<(Array2<T>, Option<Array2<isize>>)>
where
    T: Float + SparseElement + Debug + Copy + 'static,
    S: SparseArray<T>,
{
    validate_graph(graph, directed)?;
    let method = ShortestPathMethod::from_str(method)?;
    let n = num_vertices(graph);

    match (from_vertex, to_vertex) {
        (None, None) => {
            // All pairs shortest paths
            all_pairs_shortest_path(graph, method, directed, returnpredecessors)
        }
        (Some(source), None) => {
            // Single source shortest paths
            let (distances_, predecessors) =
                single_source_shortest_path(graph, source, method, directed, returnpredecessors)?;

            // Convert to matrix format
            let mut dist_matrix = Array2::from_elem((n, n), T::infinity());
            let mut pred_matrix = if returnpredecessors {
                Some(Array2::from_elem((n, n), -1isize))
            } else {
                None
            };

            for i in 0..n {
                dist_matrix[[source, i]] = distances_[i];
                if let Some(ref preds) = predecessors {
                    if let Some(ref mut pred_mat) = pred_matrix {
                        pred_mat[[source, i]] = preds[i];
                    }
                }
            }

            Ok((dist_matrix, pred_matrix))
        }
        (Some(source), Some(target)) => {
            // Single pair shortest path
            let (distances_, predecessors) =
                single_source_shortest_path(graph, source, method, directed, returnpredecessors)?;

            let dist_matrix = Array2::from_elem((1, 1), distances_[target]);
            let pred_matrix = if returnpredecessors {
                let mut pred_mat = Array2::from_elem((1, 1), -1isize);
                if let Some(ref preds) = predecessors {
                    pred_mat[[0, 0]] = preds[target];
                }
                Some(pred_mat)
            } else {
                None
            };

            Ok((dist_matrix, pred_matrix))
        }
        (None, Some(_)) => Err(SparseError::ValueError(
            "Cannot specify target _vertex without source _vertex".to_string(),
        )),
    }
}

/// Single source shortest paths
#[allow(dead_code)]
pub fn single_source_shortest_path<T, S>(
    graph: &S,
    source: usize,
    method: ShortestPathMethod,
    directed: bool,
    returnpredecessors: bool,
) -> SparseResult<(Array1<T>, Option<Array1<isize>>)>
where
    T: Float + SparseElement + Debug + Copy + 'static,
    S: SparseArray<T>,
{
    let n = num_vertices(graph);

    if source >= n {
        return Err(SparseError::ValueError(format!(
            "Source vertex {source} out of bounds for graph with {n} vertices"
        )));
    }

    let actual_method = match method {
        ShortestPathMethod::Auto => {
            // Check if graph has negative weights
            let (_, _, values) = graph.find();
            if values.iter().any(|&w| w < T::sparse_zero()) {
                ShortestPathMethod::BellmanFord
            } else {
                ShortestPathMethod::Dijkstra
            }
        }
        m => m,
    };

    match actual_method {
        ShortestPathMethod::Dijkstra => {
            dijkstra_single_source(graph, source, directed, returnpredecessors)
        }
        ShortestPathMethod::BellmanFord => {
            bellman_ford_single_source(graph, source, directed, returnpredecessors)
        }
        _ => Err(SparseError::ValueError(
            "Method not supported for single source shortest paths".to_string(),
        )),
    }
}

/// All pairs shortest paths
#[allow(dead_code)]
pub fn all_pairs_shortest_path<T, S>(
    graph: &S,
    method: ShortestPathMethod,
    directed: bool,
    returnpredecessors: bool,
) -> SparseResult<(Array2<T>, Option<Array2<isize>>)>
where
    T: Float + SparseElement + Debug + Copy + 'static,
    S: SparseArray<T>,
{
    let n = num_vertices(graph);

    let actual_method = match method {
        ShortestPathMethod::Auto => {
            if n <= 100 {
                ShortestPathMethod::FloydWarshall
            } else {
                ShortestPathMethod::Dijkstra
            }
        }
        m => m,
    };

    match actual_method {
        ShortestPathMethod::FloydWarshall => floyd_warshall(graph, directed, returnpredecessors),
        ShortestPathMethod::Dijkstra => {
            // Run Dijkstra from each vertex
            let mut distances = Array2::from_elem((n, n), T::infinity());
            let mut predecessors = if returnpredecessors {
                Some(Array2::from_elem((n, n), -1isize))
            } else {
                None
            };

            for source in 0..n {
                let (dist, pred) =
                    dijkstra_single_source(graph, source, directed, returnpredecessors)?;

                for target in 0..n {
                    distances[[source, target]] = dist[target];
                    if let Some(ref pred_vec) = pred {
                        if let Some(ref mut pred_matrix) = predecessors {
                            pred_matrix[[source, target]] = pred_vec[target];
                        }
                    }
                }
            }

            Ok((distances, predecessors))
        }
        _ => Err(SparseError::ValueError(
            "Method not supported for all pairs shortest paths".to_string(),
        )),
    }
}

/// Dijkstra's algorithm for single source shortest paths
#[allow(dead_code)]
pub fn dijkstra_single_source<T, S>(
    graph: &S,
    source: usize,
    directed: bool,
    returnpredecessors: bool,
) -> SparseResult<(Array1<T>, Option<Array1<isize>>)>
where
    T: Float + SparseElement + Debug + Copy + 'static,
    S: SparseArray<T>,
{
    let n = num_vertices(graph);
    let adj_list = to_adjacency_list(graph, directed)?;

    let mut distances = Array1::from_elem(n, T::infinity());
    let mut predecessors = if returnpredecessors {
        Some(Array1::from_elem(n, -1isize))
    } else {
        None
    };

    distances[source] = T::sparse_zero();

    let mut heap = BinaryHeap::new();
    heap.push(PriorityQueueNode {
        distance: T::sparse_zero(),
        node: source,
    });

    let mut visited = vec![false; n];

    while let Some(PriorityQueueNode { distance, node }) = heap.pop() {
        if visited[node] {
            continue;
        }

        visited[node] = true;

        // Early termination if we've processed all reachable nodes
        if distance == T::infinity() {
            break;
        }

        for &(neighbor, weight) in &adj_list[node] {
            if visited[neighbor] {
                continue;
            }

            let new_distance = distance + weight;

            if new_distance < distances[neighbor] {
                distances[neighbor] = new_distance;

                if let Some(ref mut preds) = predecessors {
                    preds[neighbor] = node as isize;
                }

                heap.push(PriorityQueueNode {
                    distance: new_distance,
                    node: neighbor,
                });
            }
        }
    }

    Ok((distances, predecessors))
}

/// Bellman-Ford algorithm for single source shortest paths
#[allow(dead_code)]
pub fn bellman_ford_single_source<T, S>(
    graph: &S,
    source: usize,
    directed: bool,
    returnpredecessors: bool,
) -> SparseResult<(Array1<T>, Option<Array1<isize>>)>
where
    T: Float + SparseElement + Debug + Copy + 'static,
    S: SparseArray<T>,
{
    let n = num_vertices(graph);
    let (row_indices, col_indices, values) = graph.find();

    let mut distances = Array1::from_elem(n, T::infinity());
    let mut predecessors = if returnpredecessors {
        Some(Array1::from_elem(n, -1isize))
    } else {
        None
    };

    distances[source] = T::sparse_zero();

    // Build edge list
    let mut edges = Vec::new();
    for (i, (&row, &col)) in row_indices.iter().zip(col_indices.iter()).enumerate() {
        let weight = values[i];
        if !SparseElement::is_zero(&weight) {
            edges.push((row, col, weight));

            // For undirected graphs, add reverse edge
            if !directed && row != col {
                edges.push((col, row, weight));
            }
        }
    }

    // Relax edges n-1 times
    for _ in 0..(n - 1) {
        let mut updated = false;

        for &(u, v, weight) in &edges {
            if distances[u] != T::infinity() {
                let new_distance = distances[u] + weight;

                if new_distance < distances[v] {
                    distances[v] = new_distance;

                    if let Some(ref mut preds) = predecessors {
                        preds[v] = u as isize;
                    }

                    updated = true;
                }
            }
        }

        // Early termination if no updates
        if !updated {
            break;
        }
    }

    // Check for negative cycles
    for &(u, v, weight) in &edges {
        if distances[u] != T::infinity() && distances[u] + weight < distances[v] {
            return Err(SparseError::ValueError(
                "Graph contains negative cycles".to_string(),
            ));
        }
    }

    Ok((distances, predecessors))
}

/// Floyd-Warshall algorithm for all pairs shortest paths
#[allow(dead_code)]
pub fn floyd_warshall<T, S>(
    graph: &S,
    directed: bool,
    returnpredecessors: bool,
) -> SparseResult<(Array2<T>, Option<Array2<isize>>)>
where
    T: Float + SparseElement + Debug + Copy + 'static,
    S: SparseArray<T>,
{
    let n = num_vertices(graph);

    // Initialize distance matrix
    let mut distances = Array2::from_elem((n, n), T::infinity());
    let mut predecessors = if returnpredecessors {
        Some(Array2::from_elem((n, n), -1isize))
    } else {
        None
    };

    // Set diagonal to zero
    for i in 0..n {
        distances[[i, i]] = T::sparse_zero();
    }

    // Fill in the initial distances from the graph
    let (row_indices, col_indices, values) = graph.find();
    for (i, (&row, &col)) in row_indices.iter().zip(col_indices.iter()).enumerate() {
        let weight = values[i];
        if !SparseElement::is_zero(&weight) {
            distances[[row, col]] = weight;

            if let Some(ref mut preds) = predecessors {
                if row != col {
                    preds[[row, col]] = row as isize;
                }
            }

            // For undirected graphs, set symmetric entries
            if !directed && row != col {
                distances[[col, row]] = weight;

                if let Some(ref mut preds) = predecessors {
                    preds[[col, row]] = col as isize;
                }
            }
        }
    }

    // Floyd-Warshall main loop
    for k in 0..n {
        for i in 0..n {
            for j in 0..n {
                let through_k = distances[[i, k]] + distances[[k, j]];

                if through_k < distances[[i, j]] {
                    distances[[i, j]] = through_k;

                    if let Some(ref mut preds) = predecessors {
                        preds[[i, j]] = preds[[k, j]];
                    }
                }
            }
        }
    }

    Ok((distances, predecessors))
}

/// Reconstruct shortest path from predecessor information
#[allow(dead_code)]
pub fn reconstruct_path(
    predecessors: &Array1<isize>,
    source: usize,
    target: usize,
) -> SparseResult<Vec<usize>> {
    let mut path = Vec::new();
    let mut current = target;

    // Check if target is reachable
    if predecessors[target] == -1 && source != target {
        return Ok(path); // Empty path means no path exists
    }

    while current != source {
        path.push(current);

        let pred = predecessors[current];
        if pred == -1 {
            return Err(SparseError::ValueError(
                "Invalid predecessor information".to_string(),
            ));
        }

        current = pred as usize;
    }

    path.push(source);
    path.reverse();

    Ok(path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::csr_array::CsrArray;
    use approx::assert_relative_eq;

    fn create_test_graph() -> CsrArray<f64> {
        // Create a simple graph:
        //   0 --(1)-- 1
        //   |         |
        //  (2)       (3)
        //   |         |
        //   2 --(1)-- 3
        let rows = vec![0, 0, 1, 1, 2, 2, 3, 3];
        let cols = vec![1, 2, 0, 3, 0, 3, 1, 2];
        let data = vec![1.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 1.0];

        CsrArray::from_triplets(&rows, &cols, &data, (4, 4), false).expect("Operation failed")
    }

    #[test]
    fn test_dijkstra_single_source() {
        let graph = create_test_graph();
        let (distances_, _) =
            dijkstra_single_source(&graph, 0, false, false).expect("Operation failed");

        assert_relative_eq!(distances_[0], 0.0);
        assert_relative_eq!(distances_[1], 1.0);
        assert_relative_eq!(distances_[2], 2.0);
        assert_relative_eq!(distances_[3], 3.0); // 0->2->3
    }

    #[test]
    fn test_dijkstra_withpredecessors() {
        let graph = create_test_graph();
        let (_distances, predecessors) =
            dijkstra_single_source(&graph, 0, false, true).expect("Operation failed");
        let preds = predecessors.expect("Operation failed");

        assert_eq!(preds[0], -1); // Source has no predecessor
        assert_eq!(preds[1], 0); // 1's predecessor is 0
        assert_eq!(preds[2], 0); // 2's predecessor is 0
        assert_eq!(preds[3], 2); // 3's predecessor is 2 (via shortest path 0->2->3)
    }

    #[test]
    fn test_bellman_ford() {
        let graph = create_test_graph();
        let (distances_, _) =
            bellman_ford_single_source(&graph, 0, false, false).expect("Operation failed");

        assert_relative_eq!(distances_[0], 0.0);
        assert_relative_eq!(distances_[1], 1.0);
        assert_relative_eq!(distances_[2], 2.0);
        assert_relative_eq!(distances_[3], 3.0);
    }

    #[test]
    fn test_floyd_warshall() {
        let graph = create_test_graph();
        let (distances_, _) = floyd_warshall(&graph, false, false).expect("Operation failed");

        // Check distances from vertex 0
        assert_relative_eq!(distances_[[0, 0]], 0.0);
        assert_relative_eq!(distances_[[0, 1]], 1.0);
        assert_relative_eq!(distances_[[0, 2]], 2.0);
        assert_relative_eq!(distances_[[0, 3]], 3.0);

        // Check distances from vertex 1
        assert_relative_eq!(distances_[[1, 0]], 1.0);
        assert_relative_eq!(distances_[[1, 1]], 0.0);
        assert_relative_eq!(distances_[[1, 2]], 3.0); // 1->0->2
        assert_relative_eq!(distances_[[1, 3]], 3.0); // 1->3
    }

    #[test]
    fn test_shortest_path_api() {
        let graph = create_test_graph();

        // Single source
        let (distances_, _) = shortest_path(&graph, Some(0), None, "dijkstra", false, false)
            .expect("Operation failed");
        assert_relative_eq!(distances_[[0, 1]], 1.0);
        assert_relative_eq!(distances_[[0, 3]], 3.0);

        // Single pair
        let (distance, _) = shortest_path(&graph, Some(0), Some(3), "auto", false, false)
            .expect("Operation failed");
        assert_relative_eq!(distance[[0, 0]], 3.0);
    }

    #[test]
    fn test_reconstruct_path() {
        let graph = create_test_graph();
        let (_, predecessors) =
            dijkstra_single_source(&graph, 0, false, true).expect("Operation failed");
        let preds = predecessors.expect("Operation failed");

        let path = reconstruct_path(&preds, 0, 3).expect("Operation failed");
        assert_eq!(path, vec![0, 2, 3]); // Shortest path 0->2->3
    }

    #[test]
    fn test_negative_cycle_detection() {
        // Create a graph with a negative cycle
        let rows = vec![0, 1, 2];
        let cols = vec![1, 2, 0];
        let data = vec![1.0, 1.0, -3.0]; // Cycle 0->1->2->0 with total weight -1

        let graph =
            CsrArray::from_triplets(&rows, &cols, &data, (3, 3), false).expect("Operation failed");

        // Bellman-Ford should detect the negative cycle
        let result = bellman_ford_single_source(&graph, 0, true, false);
        assert!(result.is_err());
    }
}