oxicuda-sparse 0.2.0

OxiCUDA Sparse - GPU-accelerated sparse matrix operations (cuSPARSE equivalent)
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
//! Sparse matrix reordering algorithms.
//!
//! Reordering reduces bandwidth (RCM) or fill-in (AMD) of sparse matrices,
//! improving the performance of direct and iterative solvers.
//!
//! ## Algorithms
//!
//! - **Reverse Cuthill-McKee (RCM)**: BFS from a peripheral node, reversed.
//!   Reduces matrix bandwidth, which improves cache locality for SpMV and
//!   reduces fill-in for banded preconditioners.
//!
//! - **Approximate Minimum Degree (AMD)**: Greedy elimination choosing the
//!   node with minimum degree. Reduces fill-in for Cholesky/LU factorization.
//!
//! ## Usage
//!
//! ```rust,no_run
//! # use oxicuda_sparse::format::reorder::{rcm_ordering, permute_csr};
//! # use oxicuda_sparse::format::CsrMatrix;
//! # fn example(matrix: &CsrMatrix<f64>) -> Result<(), oxicuda_sparse::error::SparseError> {
//! let perm = rcm_ordering(matrix)?;
//! let reordered = permute_csr(matrix, &perm)?;
//! # Ok(())
//! # }
//! ```
#![allow(dead_code)]

use std::collections::VecDeque;

use oxicuda_blas::GpuFloat;

use crate::error::{SparseError, SparseResult};
use crate::format::CsrMatrix;

// ---------------------------------------------------------------------------
// Reverse Cuthill-McKee (RCM)
// ---------------------------------------------------------------------------

/// Compute the Reverse Cuthill-McKee (RCM) ordering of a sparse matrix.
///
/// The RCM ordering is a BFS-based reordering that reduces the bandwidth of
/// the matrix. The algorithm:
/// 1. Find a pseudo-peripheral node (node with near-maximal eccentricity).
/// 2. Perform BFS from that node, visiting neighbors in order of increasing
///    degree.
/// 3. Reverse the resulting ordering.
///
/// # Arguments
///
/// * `matrix` -- A square CSR matrix.
///
/// # Returns
///
/// A permutation vector `perm` of length `n` where `perm[new_index] = old_index`.
///
/// # Errors
///
/// Returns [`SparseError::DimensionMismatch`] if the matrix is not square.
pub fn rcm_ordering<T: GpuFloat>(matrix: &CsrMatrix<T>) -> SparseResult<Vec<usize>> {
    if matrix.rows() != matrix.cols() {
        return Err(SparseError::DimensionMismatch(format!(
            "RCM requires square matrix, got {}x{}",
            matrix.rows(),
            matrix.cols()
        )));
    }

    let n = matrix.rows() as usize;
    if n == 0 {
        return Ok(Vec::new());
    }

    let (h_row_ptr, h_col_idx, _) = matrix.to_host()?;
    rcm_ordering_host(&h_row_ptr, &h_col_idx, n)
}

/// Host-side RCM ordering computation.
pub fn rcm_ordering_host(row_ptr: &[i32], col_idx: &[i32], n: usize) -> SparseResult<Vec<usize>> {
    if n == 0 {
        return Ok(Vec::new());
    }

    // Compute degree of each node (excluding self-loops)
    let degrees: Vec<usize> = (0..n)
        .map(|i| {
            let start = row_ptr[i] as usize;
            let end = row_ptr[i + 1] as usize;
            col_idx[start..end]
                .iter()
                .filter(|&&c| c as usize != i && (c as usize) < n)
                .count()
        })
        .collect();

    // Find a pseudo-peripheral starting node
    let start_node = find_pseudo_peripheral(row_ptr, col_idx, &degrees, n);

    // BFS with neighbors sorted by degree
    let mut visited = vec![false; n];
    let mut order = Vec::with_capacity(n);

    // Handle potentially disconnected graph
    let starts = [start_node];
    // We will add other starting nodes if components are disconnected

    let mut queue: VecDeque<usize> = VecDeque::new();
    let mut component_start = 0;
    while order.len() < n {
        let root = if component_start < starts.len() {
            starts[component_start]
        } else {
            // Find next unvisited node
            match visited.iter().position(|&v| !v) {
                Some(node) => node,
                None => break,
            }
        };
        component_start += 1;

        if visited[root] {
            continue;
        }

        visited[root] = true;
        queue.push_back(root);

        while let Some(node) = queue.pop_front() {
            order.push(node);

            // Collect unvisited neighbors and sort by degree
            let start = row_ptr[node] as usize;
            let end = row_ptr[node + 1] as usize;
            let mut neighbors: Vec<usize> = col_idx[start..end]
                .iter()
                .map(|&c| c as usize)
                .filter(|&c| c < n && c != node && !visited[c])
                .collect();

            // Deduplicate
            neighbors.sort_unstable();
            neighbors.dedup();

            // Sort by degree (ascending) for RCM
            neighbors.sort_by_key(|&nbr| degrees[nbr]);

            for nbr in neighbors {
                if !visited[nbr] {
                    visited[nbr] = true;
                    queue.push_back(nbr);
                }
            }
        }
    }

    // Reverse the ordering (Reverse Cuthill-McKee)
    order.reverse();

    Ok(order)
}

/// Find a pseudo-peripheral node using the Gibbs-Poole-Stockmeyer approach.
///
/// Starting from the node with minimum degree, performs two BFS passes to find
/// a node with near-maximal eccentricity.
fn find_pseudo_peripheral(row_ptr: &[i32], col_idx: &[i32], degrees: &[usize], n: usize) -> usize {
    // Start from a minimum-degree node
    let mut current = 0;
    let mut min_deg = degrees[0];
    for (i, &d) in degrees.iter().enumerate().skip(1) {
        if d < min_deg {
            min_deg = d;
            current = i;
        }
    }

    // Refine: do a few BFS iterations to move toward a peripheral node
    for _ in 0..5 {
        let (last_level, _) = bfs_levels(row_ptr, col_idx, n, current);
        if last_level.is_empty() {
            break;
        }
        // Pick the node with minimum degree from the last BFS level
        let mut best = last_level[0];
        let mut best_deg = degrees[best];
        for &node in &last_level[1..] {
            if degrees[node] < best_deg {
                best_deg = degrees[node];
                best = node;
            }
        }
        if best == current {
            break;
        }
        current = best;
    }

    current
}

/// Performs BFS from `root` and returns the last level's nodes and the number of levels.
fn bfs_levels(row_ptr: &[i32], col_idx: &[i32], n: usize, root: usize) -> (Vec<usize>, usize) {
    let mut visited = vec![false; n];
    let mut current_level = Vec::new();
    let mut next_level = Vec::new();

    visited[root] = true;
    current_level.push(root);
    let mut num_levels = 1;

    loop {
        for &node in &current_level {
            let start = row_ptr[node] as usize;
            let end = row_ptr[node + 1] as usize;
            for &c in &col_idx[start..end] {
                let nbr = c as usize;
                if nbr < n && !visited[nbr] {
                    visited[nbr] = true;
                    next_level.push(nbr);
                }
            }
        }

        if next_level.is_empty() {
            break;
        }

        num_levels += 1;
        current_level.clear();
        std::mem::swap(&mut current_level, &mut next_level);
    }

    (current_level, num_levels)
}

// ---------------------------------------------------------------------------
// Approximate Minimum Degree (AMD)
// ---------------------------------------------------------------------------

/// Compute the Approximate Minimum Degree (AMD) ordering of a sparse matrix.
///
/// AMD is a greedy fill-reducing ordering for Cholesky and LU factorization.
/// At each step, the node with minimum approximate degree is eliminated.
///
/// # Arguments
///
/// * `matrix` -- A square CSR matrix.
///
/// # Returns
///
/// A permutation vector `perm` of length `n` where `perm[i]` is the `i`-th
/// node to be eliminated.
///
/// # Errors
///
/// Returns [`SparseError::DimensionMismatch`] if the matrix is not square.
pub fn amd_ordering<T: GpuFloat>(matrix: &CsrMatrix<T>) -> SparseResult<Vec<usize>> {
    if matrix.rows() != matrix.cols() {
        return Err(SparseError::DimensionMismatch(format!(
            "AMD requires square matrix, got {}x{}",
            matrix.rows(),
            matrix.cols()
        )));
    }

    let n = matrix.rows() as usize;
    if n == 0 {
        return Ok(Vec::new());
    }

    let (h_row_ptr, h_col_idx, _) = matrix.to_host()?;
    amd_ordering_host(&h_row_ptr, &h_col_idx, n)
}

/// Host-side AMD ordering computation.
pub fn amd_ordering_host(row_ptr: &[i32], col_idx: &[i32], n: usize) -> SparseResult<Vec<usize>> {
    if n == 0 {
        return Ok(Vec::new());
    }

    // Build adjacency lists (excluding self-loops, symmetric)
    let mut adj: Vec<Vec<usize>> = Vec::with_capacity(n);
    for i in 0..n {
        let start = row_ptr[i] as usize;
        let end = row_ptr[i + 1] as usize;
        let mut neighbors: Vec<usize> = col_idx[start..end]
            .iter()
            .map(|&c| c as usize)
            .filter(|&c| c != i && c < n)
            .collect();
        neighbors.sort_unstable();
        neighbors.dedup();
        adj.push(neighbors);
    }

    let mut eliminated = vec![false; n];
    let mut degree: Vec<usize> = adj.iter().map(|a| a.len()).collect();
    let mut perm = Vec::with_capacity(n);

    for _ in 0..n {
        // Find node with minimum degree among non-eliminated nodes
        let mut min_node = None;
        let mut min_deg = usize::MAX;
        for (i, (&d, &elim)) in degree.iter().zip(eliminated.iter()).enumerate() {
            if !elim && d < min_deg {
                min_deg = d;
                min_node = Some(i);
            }
        }

        let node = match min_node {
            Some(v) => v,
            None => break,
        };

        perm.push(node);
        eliminated[node] = true;

        // Collect non-eliminated neighbors
        let neighbors: Vec<usize> = adj[node]
            .iter()
            .copied()
            .filter(|&nbr| !eliminated[nbr])
            .collect();

        // Mass elimination: connect all neighbors of `node` to each other
        // and update degrees
        for &nbr in &neighbors {
            // Remove `node` from nbr's adjacency
            adj[nbr].retain(|&x| x != node);

            // Add edges to all other neighbors of `node`
            for &other in &neighbors {
                if other != nbr && !adj[nbr].contains(&other) {
                    adj[nbr].push(other);
                }
            }

            // Update degree
            degree[nbr] = adj[nbr].iter().filter(|&&x| !eliminated[x]).count();
        }

        degree[node] = 0;
    }

    Ok(perm)
}

// ---------------------------------------------------------------------------
// Permutation utilities
// ---------------------------------------------------------------------------

/// Apply a permutation to a CSR matrix: `P * A * P^T`.
///
/// Given a permutation `perm` where `perm[new_index] = old_index`,
/// computes the reordered matrix.
///
/// # Arguments
///
/// * `matrix` -- CSR matrix to permute.
/// * `perm` -- Permutation vector of length `n`.
///
/// # Errors
///
/// Returns [`SparseError::InvalidArgument`] if `perm` length does not match
/// the matrix dimension or contains invalid indices.
pub fn permute_csr<T: GpuFloat>(
    matrix: &CsrMatrix<T>,
    perm: &[usize],
) -> SparseResult<CsrMatrix<T>> {
    let n = matrix.rows() as usize;
    if perm.len() != n {
        return Err(SparseError::InvalidArgument(format!(
            "permutation length ({}) must match matrix dimension ({})",
            perm.len(),
            n
        )));
    }

    // Validate permutation
    let inv_perm = inverse_permutation(perm);
    if inv_perm.len() != n {
        return Err(SparseError::InvalidArgument(
            "invalid permutation: not a valid bijection".to_string(),
        ));
    }

    let (h_row_ptr, h_col_idx, h_values) = matrix.to_host()?;

    // Build reordered matrix: new_row i corresponds to old_row perm[i]
    let mut new_row_ptr = vec![0i32; n + 1];
    let mut new_entries: Vec<Vec<(i32, T)>> = Vec::with_capacity(n);

    for new_row in 0..n {
        let old_row = perm[new_row];
        if old_row >= n {
            return Err(SparseError::InvalidArgument(format!(
                "permutation index {} out of bounds (n={})",
                old_row, n
            )));
        }

        let start = h_row_ptr[old_row] as usize;
        let end = h_row_ptr[old_row + 1] as usize;

        let mut entries: Vec<(i32, T)> = Vec::with_capacity(end - start);
        for k in start..end {
            let old_col = h_col_idx[k] as usize;
            if old_col >= n {
                return Err(SparseError::InvalidArgument(format!(
                    "column index {} out of bounds (n={})",
                    old_col, n
                )));
            }
            let new_col = inv_perm[old_col];
            entries.push((new_col as i32, h_values[k]));
        }

        // Sort by new column index
        entries.sort_by_key(|&(c, _)| c);

        new_row_ptr[new_row + 1] = new_row_ptr[new_row] + entries.len() as i32;
        new_entries.push(entries);
    }

    let nnz = new_row_ptr[n] as usize;
    if nnz == 0 {
        return Err(SparseError::ZeroNnz);
    }

    let mut new_col_idx = Vec::with_capacity(nnz);
    let mut new_values = Vec::with_capacity(nnz);
    for entries in &new_entries {
        for &(c, v) in entries {
            new_col_idx.push(c);
            new_values.push(v);
        }
    }

    CsrMatrix::from_host(
        matrix.rows(),
        matrix.cols(),
        &new_row_ptr,
        &new_col_idx,
        &new_values,
    )
}

/// Compute the inverse permutation.
///
/// Given `perm[new] = old`, returns `inv[old] = new`.
pub fn inverse_permutation(perm: &[usize]) -> Vec<usize> {
    let n = perm.len();
    let mut inv = vec![0usize; n];
    for (new_idx, &old_idx) in perm.iter().enumerate() {
        if old_idx < n {
            inv[old_idx] = new_idx;
        }
    }
    inv
}

/// Compute the bandwidth of a matrix given its CSR structure.
///
/// Bandwidth = max |i - j| over all nonzero entries (i, j).
pub fn bandwidth(row_ptr: &[i32], col_idx: &[i32], n: usize) -> usize {
    let mut bw = 0usize;
    for i in 0..n {
        let start = row_ptr[i] as usize;
        let end = row_ptr[i + 1] as usize;
        for &c in &col_idx[start..end] {
            let j = c as usize;
            let diff = i.abs_diff(j);
            if diff > bw {
                bw = diff;
            }
        }
    }
    bw
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn rcm_identity() {
        // Identity: any ordering is valid, bandwidth = 0
        let row_ptr = vec![0, 1, 2, 3];
        let col_idx = vec![0, 1, 2];
        let perm = rcm_ordering_host(&row_ptr, &col_idx, 3);
        assert!(perm.is_ok());
        let perm = perm.expect("test: should succeed");
        assert_eq!(perm.len(), 3);
        // Should be a valid permutation
        let mut sorted = perm.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![0, 1, 2]);
    }

    #[test]
    fn rcm_tridiagonal() {
        // Tridiagonal 5x5
        let row_ptr = vec![0, 2, 5, 8, 11, 13];
        let col_idx = vec![0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4];
        let perm = rcm_ordering_host(&row_ptr, &col_idx, 5);
        assert!(perm.is_ok());
        let perm = perm.expect("test: should succeed");
        assert_eq!(perm.len(), 5);
        // Valid permutation
        let mut sorted = perm.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn rcm_reduces_bandwidth() {
        // Arrow matrix: row 0 connects to all, others only to 0 and self
        // Original bandwidth is n-1.
        // [1 1 1 1 1]
        // [1 1 0 0 0]
        // [1 0 1 0 0]
        // [1 0 0 1 0]
        // [1 0 0 0 1]
        let row_ptr = vec![0, 5, 7, 9, 11, 13];
        let col_idx = vec![0, 1, 2, 3, 4, 0, 1, 0, 2, 0, 3, 0, 4];
        let n = 5;
        let orig_bw = bandwidth(&row_ptr, &col_idx, n);
        assert_eq!(orig_bw, 4);

        let perm = rcm_ordering_host(&row_ptr, &col_idx, n);
        assert!(perm.is_ok());
        let perm = perm.expect("test: should succeed");

        // Apply permutation to check new bandwidth
        let inv = inverse_permutation(&perm);
        let mut new_bw = 0;
        for (i, &old_row) in perm.iter().enumerate().take(n) {
            let start = row_ptr[old_row] as usize;
            let end = row_ptr[old_row + 1] as usize;
            for &c in &col_idx[start..end] {
                let new_col = inv[c as usize];
                let diff = i.abs_diff(new_col);
                if diff > new_bw {
                    new_bw = diff;
                }
            }
        }
        // RCM should not increase bandwidth
        assert!(new_bw <= orig_bw);
    }

    #[test]
    fn amd_identity() {
        let row_ptr = vec![0, 1, 2, 3];
        let col_idx = vec![0, 1, 2];
        let perm = amd_ordering_host(&row_ptr, &col_idx, 3);
        assert!(perm.is_ok());
        let perm = perm.expect("test: should succeed");
        assert_eq!(perm.len(), 3);
        let mut sorted = perm.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![0, 1, 2]);
    }

    #[test]
    fn amd_tridiagonal() {
        let row_ptr = vec![0, 2, 5, 8, 10];
        let col_idx = vec![0, 1, 0, 1, 2, 1, 2, 3, 2, 3];
        let perm = amd_ordering_host(&row_ptr, &col_idx, 4);
        assert!(perm.is_ok());
        let perm = perm.expect("test: should succeed");
        assert_eq!(perm.len(), 4);
        // Valid permutation: all nodes appear exactly once
        let mut sorted = perm.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![0, 1, 2, 3]);
    }

    #[test]
    fn inverse_permutation_roundtrip() {
        let perm = vec![3, 1, 0, 2];
        let inv = inverse_permutation(&perm);
        assert_eq!(inv, vec![2, 1, 3, 0]);

        // inv(inv(perm)) == perm
        let inv_inv = inverse_permutation(&inv);
        assert_eq!(inv_inv, perm);
    }

    #[test]
    fn bandwidth_calculation() {
        // Tridiagonal: bandwidth = 1
        let row_ptr = vec![0, 2, 5, 7];
        let col_idx = vec![0, 1, 0, 1, 2, 1, 2];
        assert_eq!(bandwidth(&row_ptr, &col_idx, 3), 1);

        // Diagonal: bandwidth = 0
        let row_ptr = vec![0, 1, 2, 3];
        let col_idx = vec![0, 1, 2];
        assert_eq!(bandwidth(&row_ptr, &col_idx, 3), 0);
    }

    #[test]
    fn rcm_empty() {
        let perm = rcm_ordering_host(&[0], &[], 0);
        assert!(perm.is_ok());
        assert!(perm.expect("test: should succeed").is_empty());
    }

    #[test]
    fn amd_empty() {
        let perm = amd_ordering_host(&[0], &[], 0);
        assert!(perm.is_ok());
        assert!(perm.expect("test: should succeed").is_empty());
    }
}