Skip to main content

aocl_sparse/
lib.rs

1//! Safe wrappers for AOCL-Sparse.
2
3#![allow(
4    clippy::too_many_arguments,
5    reason = "wrappers mirror the C API's argument lists"
6)]
7#![warn(missing_debug_implementations)]
8#![cfg_attr(docsrs, feature(doc_cfg))]
9// The Scalar / ComplexScalar traits in this crate are sealed (require
10// `aocl_types::sealed::Sealed`), so they cannot be implemented from
11// outside this crate. The raw-pointer arguments on a few trait methods
12// are FFI plumbing called only by the safe wrappers in this same
13// crate; clippy's lint targets the case where a downstream
14// implementer might deref a hostile pointer, which can't happen here.
15#![allow(
16    clippy::not_unsafe_ptr_arg_deref,
17    reason = "sealed traits; the raw-pointer arguments are FFI plumbing called only by this crate's wrappers"
18)]
19// Some `(IndexBase, Vec, Vec, Vec)` return tuples are intentional —
20// they mirror what the C API hands back. Aliasing them would obscure
21// rather than clarify the underlying data layout.
22#![allow(
23    clippy::type_complexity,
24    reason = "return tuples intentionally mirror what the C API hands back"
25)]
26
27use std::ffi::CString;
28use std::marker::PhantomData;
29
30pub use aocl_error::{Error, Result};
31use aocl_sparse_sys as sys;
32use aocl_types::sealed::Sealed;
33pub use aocl_types::{Complex32, Complex64, Trans};
34
35pub mod complex;
36
37fn trans_raw(t: Trans) -> sys::aoclsparse_operation {
38    match t {
39        Trans::No => sys::aoclsparse_operation__aoclsparse_operation_none,
40        Trans::T => sys::aoclsparse_operation__aoclsparse_operation_transpose,
41        Trans::C => sys::aoclsparse_operation__aoclsparse_operation_conjugate_transpose,
42    }
43}
44
45fn check_status(component: &'static str, status: sys::aoclsparse_status) -> Result<()> {
46    if status == sys::aoclsparse_status__aoclsparse_status_success {
47        return Ok(());
48    }
49    let message = match status {
50        s if s == sys::aoclsparse_status__aoclsparse_status_not_implemented => "not implemented",
51        s if s == sys::aoclsparse_status__aoclsparse_status_invalid_pointer => "invalid pointer",
52        s if s == sys::aoclsparse_status__aoclsparse_status_invalid_size => "invalid size",
53        s if s == sys::aoclsparse_status__aoclsparse_status_internal_error => "internal error",
54        s if s == sys::aoclsparse_status__aoclsparse_status_invalid_value => "invalid value",
55        s if s == sys::aoclsparse_status__aoclsparse_status_invalid_index_value => {
56            "invalid index value"
57        }
58        s if s == sys::aoclsparse_status__aoclsparse_status_maxit => "max iterations reached",
59        s if s == sys::aoclsparse_status__aoclsparse_status_user_stop => "user stop",
60        s if s == sys::aoclsparse_status__aoclsparse_status_wrong_type => "wrong type",
61        s if s == sys::aoclsparse_status__aoclsparse_status_memory_error => "memory error",
62        _ => "unknown sparse status",
63    }
64    .to_string();
65    Err(Error::Status {
66        component,
67        code: status as i64,
68        message,
69    })
70}
71
72/// RAII wrapper for `aoclsparse_mat_descr`.
73pub struct MatDescr {
74    raw: sys::aoclsparse_mat_descr,
75}
76
77impl MatDescr {
78    /// Create a fresh descriptor with library defaults.
79    pub fn new() -> Result<Self> {
80        let mut raw: sys::aoclsparse_mat_descr = std::ptr::null_mut();
81        let status = unsafe { sys::aoclsparse_create_mat_descr(&mut raw) };
82        check_status("sparse", status)?;
83        if raw.is_null() {
84            return Err(Error::AllocationFailed("sparse"));
85        }
86        Ok(MatDescr { raw })
87    }
88
89    /// Borrow the underlying handle for raw FFI calls.
90    ///
91    /// # Safety
92    /// The returned pointer is valid only for the lifetime of `self`.
93    /// Do not call `aoclsparse_destroy_mat_descr` on it.
94    pub fn as_raw(&self) -> sys::aoclsparse_mat_descr {
95        self.raw
96    }
97
98    /// Set the matrix-type hint (general / symmetric / hermitian /
99    /// triangular). Affects which fast paths the library can take.
100    pub fn set_type(&mut self, ty: MatType) -> Result<()> {
101        let status = unsafe { sys::aoclsparse_set_mat_type(self.raw, ty.raw()) };
102        check_status("sparse", status)
103    }
104
105    /// Set the index base (zero- or one-based) for column / row arrays.
106    pub fn set_index_base(&mut self, base: IndexBase) -> Result<()> {
107        let status = unsafe { sys::aoclsparse_set_mat_index_base(self.raw, base.raw()) };
108        check_status("sparse", status)
109    }
110
111    /// For triangular / symmetric matrices, declare which triangle is
112    /// stored (upper or lower).
113    pub fn set_fill_mode(&mut self, fill: FillMode) -> Result<()> {
114        let status = unsafe { sys::aoclsparse_set_mat_fill_mode(self.raw, fill.raw()) };
115        check_status("sparse", status)
116    }
117
118    /// For triangular matrices, declare whether the diagonal is unit
119    /// (implicit) or non-unit (explicitly stored).
120    pub fn set_diag_type(&mut self, diag: DiagType) -> Result<()> {
121        let status = unsafe { sys::aoclsparse_set_mat_diag_type(self.raw, diag.raw()) };
122        check_status("sparse", status)
123    }
124
125    /// Read back the matrix-type hint.
126    pub fn ty(&self) -> MatType {
127        let raw = unsafe { sys::aoclsparse_get_mat_type(self.raw) };
128        MatType::from_raw(raw).unwrap_or(MatType::General)
129    }
130
131    /// Read back the index base.
132    pub fn index_base(&self) -> IndexBase {
133        let raw = unsafe { sys::aoclsparse_get_mat_index_base(self.raw) };
134        if raw == sys::aoclsparse_index_base__aoclsparse_index_base_one {
135            IndexBase::One
136        } else {
137            IndexBase::Zero
138        }
139    }
140
141    /// Read back the fill mode.
142    pub fn fill_mode(&self) -> FillMode {
143        let raw = unsafe { sys::aoclsparse_get_mat_fill_mode(self.raw) };
144        FillMode::from_raw(raw).unwrap_or(FillMode::Lower)
145    }
146
147    /// Read back the diagonal-type hint.
148    pub fn diag_type(&self) -> DiagType {
149        let raw = unsafe { sys::aoclsparse_get_mat_diag_type(self.raw) };
150        DiagType::from_raw(raw).unwrap_or(DiagType::NonUnit)
151    }
152}
153
154/// Storage type of a sparse matrix's nonzero pattern.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156pub enum MatType {
157    General,
158    Symmetric,
159    Hermitian,
160    Triangular,
161}
162
163impl MatType {
164    fn raw(self) -> sys::aoclsparse_matrix_type {
165        match self {
166            MatType::General => sys::aoclsparse_matrix_type__aoclsparse_matrix_type_general,
167            MatType::Symmetric => sys::aoclsparse_matrix_type__aoclsparse_matrix_type_symmetric,
168            MatType::Hermitian => sys::aoclsparse_matrix_type__aoclsparse_matrix_type_hermitian,
169            MatType::Triangular => sys::aoclsparse_matrix_type__aoclsparse_matrix_type_triangular,
170        }
171    }
172
173    fn from_raw(raw: sys::aoclsparse_matrix_type) -> Option<Self> {
174        Some(match raw {
175            r if r == sys::aoclsparse_matrix_type__aoclsparse_matrix_type_general => {
176                MatType::General
177            }
178            r if r == sys::aoclsparse_matrix_type__aoclsparse_matrix_type_symmetric => {
179                MatType::Symmetric
180            }
181            r if r == sys::aoclsparse_matrix_type__aoclsparse_matrix_type_hermitian => {
182                MatType::Hermitian
183            }
184            r if r == sys::aoclsparse_matrix_type__aoclsparse_matrix_type_triangular => {
185                MatType::Triangular
186            }
187            _ => return None,
188        })
189    }
190}
191
192/// Which triangle of a symmetric / triangular matrix is stored.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
194pub enum FillMode {
195    Lower,
196    Upper,
197}
198
199impl FillMode {
200    fn raw(self) -> sys::aoclsparse_fill_mode {
201        match self {
202            FillMode::Lower => sys::aoclsparse_fill_mode__aoclsparse_fill_mode_lower,
203            FillMode::Upper => sys::aoclsparse_fill_mode__aoclsparse_fill_mode_upper,
204        }
205    }
206    fn from_raw(raw: sys::aoclsparse_fill_mode) -> Option<Self> {
207        Some(match raw {
208            r if r == sys::aoclsparse_fill_mode__aoclsparse_fill_mode_lower => FillMode::Lower,
209            r if r == sys::aoclsparse_fill_mode__aoclsparse_fill_mode_upper => FillMode::Upper,
210            _ => return None,
211        })
212    }
213}
214
215/// Whether the diagonal of a triangular matrix is implicitly unit
216/// (`Unit`) or explicitly stored (`NonUnit`).
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
218pub enum DiagType {
219    Unit,
220    NonUnit,
221}
222
223impl DiagType {
224    fn raw(self) -> sys::aoclsparse_diag_type {
225        match self {
226            DiagType::Unit => sys::aoclsparse_diag_type__aoclsparse_diag_type_unit,
227            DiagType::NonUnit => sys::aoclsparse_diag_type__aoclsparse_diag_type_non_unit,
228        }
229    }
230    fn from_raw(raw: sys::aoclsparse_diag_type) -> Option<Self> {
231        Some(match raw {
232            r if r == sys::aoclsparse_diag_type__aoclsparse_diag_type_unit => DiagType::Unit,
233            r if r == sys::aoclsparse_diag_type__aoclsparse_diag_type_non_unit => DiagType::NonUnit,
234            _ => return None,
235        })
236    }
237}
238
239/// Make a deep copy of a `MatDescr` with the same options.
240pub fn copy_mat_descr(src: &MatDescr) -> Result<MatDescr> {
241    let dest = MatDescr::new()?;
242    let status = unsafe { sys::aoclsparse_copy_mat_descr(dest.raw, src.raw) };
243    check_status("sparse", status)?;
244    Ok(dest)
245}
246
247/// Run AOCL-Sparse's analysis / optimization step on a matrix handle.
248/// Use this after declaring hints (e.g. `set_mv_hint`) to let the
249/// library choose specialised kernels for repeated operations.
250pub fn optimize<T: Scalar>(mat: &mut SparseMatrix<T>) -> Result<()> {
251    let status = unsafe { sys::aoclsparse_optimize(mat.as_raw()) };
252    check_status("sparse", status)
253}
254
255/// AOCL-Sparse library version string (e.g. `"AOCL-Sparse 5.1.0"`).
256pub fn version() -> &'static str {
257    unsafe {
258        let p = sys::aoclsparse_get_version();
259        if p.is_null() {
260            return "";
261        }
262        std::ffi::CStr::from_ptr(p).to_str().unwrap_or("")
263    }
264}
265
266impl Drop for MatDescr {
267    fn drop(&mut self) {
268        if !self.raw.is_null() {
269            unsafe {
270                let _ = sys::aoclsparse_destroy_mat_descr(self.raw);
271            }
272            self.raw = std::ptr::null_mut();
273        }
274    }
275}
276
277impl std::fmt::Debug for MatDescr {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.debug_struct("MatDescr").finish_non_exhaustive()
280    }
281}
282
283/// Scalar element type usable with the wrapped sparse routines.
284pub trait Scalar: Copy + Sized + Sealed {
285    /// `y := α · op(A) · x + β · y` where `A` is in CSR format.
286    fn csrmv(
287        op: Trans,
288        alpha: Self,
289        m: usize,
290        n: usize,
291        csr_val: &[Self],
292        csr_col_ind: &[sys::aoclsparse_int],
293        csr_row_ptr: &[sys::aoclsparse_int],
294        descr: &MatDescr,
295        x: &[Self],
296        beta: Self,
297        y: &mut [Self],
298    ) -> Result<()>;
299
300    /// Sparse `y[indx] := α·x + y[indx]`.
301    fn axpyi(alpha: Self, x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()>;
302
303    /// Sparse gather: `x[i] := y[indx[i]]`.
304    fn gthr(y: &[Self], indx: &[sys::aoclsparse_int], x: &mut [Self]) -> Result<()>;
305
306    /// Sparse scatter: `y[indx[i]] := x[i]`.
307    fn sctr(x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()>;
308
309    /// Solve `op(A) · y = α · x` where `A` is sparse triangular (CSR).
310    fn csrsv(
311        op: Trans,
312        alpha: Self,
313        m: usize,
314        csr_val: &[Self],
315        csr_col_ind: &[sys::aoclsparse_int],
316        csr_row_ptr: &[sys::aoclsparse_int],
317        descr: &MatDescr,
318        x: &[Self],
319        y: &mut [Self],
320    ) -> Result<()>;
321
322    /// Convert a CSR matrix to a dense `m × n` matrix.
323    fn csr_to_dense(
324        m: usize,
325        n: usize,
326        descr: &MatDescr,
327        csr_val: &[Self],
328        csr_row_ptr: &[sys::aoclsparse_int],
329        csr_col_ind: &[sys::aoclsparse_int],
330        a: &mut [Self],
331        ld: usize,
332        order: Order,
333    ) -> Result<()>;
334
335    /// Convert CSR → CSC.
336    fn csr_to_csc(
337        m: usize,
338        n: usize,
339        descr: &MatDescr,
340        base_csc: IndexBase,
341        csr_row_ptr: &[sys::aoclsparse_int],
342        csr_col_ind: &[sys::aoclsparse_int],
343        csr_val: &[Self],
344        csc_row_ind: &mut [sys::aoclsparse_int],
345        csc_col_ptr: &mut [sys::aoclsparse_int],
346        csc_val: &mut [Self],
347    ) -> Result<()>;
348
349    /// `y := α · op(A) · x + β · y` where `A` is in ELLPACK format.
350    /// Library only supports `op = aoclsparse_operation_none`.
351    fn ellmv(
352        op: Trans,
353        alpha: Self,
354        m: usize,
355        n: usize,
356        ell_val: &[Self],
357        ell_col_ind: &[sys::aoclsparse_int],
358        ell_width: usize,
359        descr: &MatDescr,
360        x: &[Self],
361        beta: Self,
362        y: &mut [Self],
363    ) -> Result<()>;
364
365    /// `y := α · op(A) · x + β · y` where `A` is in BSR format.
366    /// `mb`/`nb` are block-row / block-column counts and `bsr_dim` is the
367    /// block edge length. Library only supports `op = aoclsparse_operation_none`.
368    fn bsrmv(
369        op: Trans,
370        alpha: Self,
371        mb: usize,
372        nb: usize,
373        bsr_dim: usize,
374        bsr_val: &[Self],
375        bsr_col_ind: &[sys::aoclsparse_int],
376        bsr_row_ptr: &[sys::aoclsparse_int],
377        descr: &MatDescr,
378        x: &[Self],
379        beta: Self,
380        y: &mut [Self],
381    ) -> Result<()>;
382
383    /// Wrap raw CSR pointers in a fresh `aoclsparse_matrix` handle. The
384    /// library does not copy the underlying arrays — keep them alive for as
385    /// long as the returned handle is in use.
386    fn create_csr(
387        base: IndexBase,
388        m: usize,
389        n: usize,
390        nnz: usize,
391        row_ptr: *mut sys::aoclsparse_int,
392        col_idx: *mut sys::aoclsparse_int,
393        val: *mut Self,
394    ) -> Result<sys::aoclsparse_matrix>;
395
396    /// Read out a library-owned CSR matrix's metadata and array pointers.
397    /// Pointers reference internal storage; do not modify or free them.
398    fn export_csr(
399        mat: sys::aoclsparse_matrix,
400    ) -> Result<(
401        IndexBase,
402        usize,
403        usize,
404        usize,
405        *mut sys::aoclsparse_int,
406        *mut sys::aoclsparse_int,
407        *mut Self,
408    )>;
409
410    /// ILU(0) smoother: applies one ILU step in place to `x`.
411    fn ilu_smoother(
412        op: Trans,
413        a: sys::aoclsparse_matrix,
414        descr: &MatDescr,
415        x: &mut [Self],
416        b: &[Self],
417    ) -> Result<()>;
418
419    /// Initialise an iterative-solver handle for this scalar type.
420    fn itsol_init(handle: &mut sys::aoclsparse_itsol_handle) -> Result<()>;
421
422    /// Run the iterative solver's forward (direct) interface.
423    fn itsol_solve(
424        handle: sys::aoclsparse_itsol_handle,
425        n: usize,
426        mat: sys::aoclsparse_matrix,
427        descr: &MatDescr,
428        b: &[Self],
429        x: &mut [Self],
430        rinfo: &mut [Self; 100],
431    ) -> Result<()>;
432
433    /// Sparse-sparse matrix product producing a new CSR matrix. The output
434    /// pointer is written through `*out`.
435    ///
436    /// # Safety
437    /// Caller is responsible for the validity of all `aoclsparse_*` handle
438    /// arguments and for adopting `*out` (e.g. via
439    /// [`SparseMatrix::from_library_owned`]) on success.
440    unsafe fn csr2m_ffi(
441        op_a: sys::aoclsparse_operation,
442        descr_a: sys::aoclsparse_mat_descr,
443        a: sys::aoclsparse_matrix,
444        op_b: sys::aoclsparse_operation,
445        descr_b: sys::aoclsparse_mat_descr,
446        b: sys::aoclsparse_matrix,
447        request: sys::aoclsparse_request,
448        out: *mut sys::aoclsparse_matrix,
449    ) -> sys::aoclsparse_status;
450
451    /// `C := α · op(A) · B + β · C` where `A` is sparse (CSR via the
452    /// matrix handle) and `B`, `C` are dense.
453    fn csrmm(
454        op: Trans,
455        alpha: Self,
456        a: sys::aoclsparse_matrix,
457        descr: &MatDescr,
458        order: Order,
459        b: &[Self],
460        n: usize,
461        ldb: usize,
462        beta: Self,
463        c: &mut [Self],
464        ldc: usize,
465    ) -> Result<()>;
466
467    /// `C := op(A) · B` where both `A` and `B` are sparse and `C` is
468    /// dense.
469    fn spmmd(
470        op: Trans,
471        a: sys::aoclsparse_matrix,
472        b: sys::aoclsparse_matrix,
473        layout: Order,
474        c: &mut [Self],
475        ldc: usize,
476    ) -> Result<()>;
477
478    /// `C := α · op_A(A) · op_B(B) + β · C` where both `A` and `B` are
479    /// sparse and `C` is dense.
480    fn sp2md(
481        op_a: Trans,
482        descr_a: &MatDescr,
483        a: sys::aoclsparse_matrix,
484        op_b: Trans,
485        descr_b: &MatDescr,
486        b: sys::aoclsparse_matrix,
487        alpha: Self,
488        beta: Self,
489        c: &mut [Self],
490        layout: Order,
491        ldc: usize,
492    ) -> Result<()>;
493
494    /// Sparse-sparse `C := α · op(A) + B` returning a fresh CSR handle.
495    ///
496    /// # Safety
497    /// Caller must adopt the resulting `*out` (e.g. via
498    /// [`SparseMatrix::from_library_owned`]).
499    unsafe fn add_ffi(
500        op: sys::aoclsparse_operation,
501        a: sys::aoclsparse_matrix,
502        alpha: Self,
503        b: sys::aoclsparse_matrix,
504        out: *mut sys::aoclsparse_matrix,
505    ) -> sys::aoclsparse_status;
506
507    /// One step of the (S)SOR / forward / backward Gauss-Seidel
508    /// relaxation: `x_new := (1 − ω) x + ω · A⁻¹ (α · b)`.
509    fn sorv(
510        sor_type: SorType,
511        descr: &MatDescr,
512        a: sys::aoclsparse_matrix,
513        omega: Self,
514        alpha: Self,
515        x: &mut [Self],
516        b: &[Self],
517    ) -> Result<()>;
518}
519
520/// Sweep direction for [`sorv`].
521#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
522pub enum SorType {
523    /// Forward Gauss-Seidel sweep.
524    Forward,
525    /// Backward Gauss-Seidel sweep.
526    Backward,
527    /// Symmetric (forward + backward) sweep.
528    Symmetric,
529}
530
531impl SorType {
532    pub(crate) fn raw(self) -> sys::aoclsparse_sor_type {
533        match self {
534            SorType::Forward => sys::aoclsparse_sor_type__aoclsparse_sor_forward,
535            SorType::Backward => sys::aoclsparse_sor_type__aoclsparse_sor_backward,
536            SorType::Symmetric => sys::aoclsparse_sor_type__aoclsparse_sor_symmetric,
537        }
538    }
539}
540
541macro_rules! impl_scalar {
542    (
543        $t:ty,
544        csrmv = $csrmv:ident,
545        axpyi = $axpyi:ident,
546        gthr = $gthr:ident,
547        sctr = $sctr:ident,
548        csrsv = $csrsv:ident,
549        csr2dense = $csr2dense:ident,
550        csr2csc = $csr2csc:ident,
551        ellmv = $ellmv:ident,
552        bsrmv = $bsrmv:ident,
553        create_csr = $create_csr:ident,
554        export_csr = $export_csr:ident,
555        ilu_smoother = $ilu_smoother:ident,
556        itsol_init = $itsol_init:ident,
557        itsol_solve = $itsol_solve:ident,
558        csr2m = $csr2m:ident,
559        csrmm = $csrmm:ident,
560        spmmd = $spmmd:ident,
561        sp2md = $sp2md:ident,
562        add = $add:ident,
563        sorv = $sorv:ident
564    ) => {
565        impl Scalar for $t {
566            fn csrmv(
567                op: Trans,
568                alpha: Self,
569                m: usize,
570                n: usize,
571                csr_val: &[Self],
572                csr_col_ind: &[sys::aoclsparse_int],
573                csr_row_ptr: &[sys::aoclsparse_int],
574                descr: &MatDescr,
575                x: &[Self],
576                beta: Self,
577                y: &mut [Self],
578            ) -> Result<()> {
579                if csr_row_ptr.len() != m + 1 {
580                    return Err(Error::InvalidArgument(format!(
581                        "csrmv: csr_row_ptr length {} != m+1 = {}",
582                        csr_row_ptr.len(),
583                        m + 1
584                    )));
585                }
586                let nnz = csr_val.len();
587                if csr_col_ind.len() != nnz {
588                    return Err(Error::InvalidArgument(format!(
589                        "csrmv: csr_col_ind length {} != csr_val length {}",
590                        csr_col_ind.len(),
591                        nnz
592                    )));
593                }
594                let (x_len, y_len) = match op {
595                    Trans::No => (n, m),
596                    Trans::T | Trans::C => (m, n),
597                };
598                if x.len() < x_len {
599                    return Err(Error::InvalidArgument(format!(
600                        "csrmv: x length {} < expected {x_len}",
601                        x.len()
602                    )));
603                }
604                if y.len() < y_len {
605                    return Err(Error::InvalidArgument(format!(
606                        "csrmv: y length {} < expected {y_len}",
607                        y.len()
608                    )));
609                }
610
611                let status = unsafe {
612                    sys::$csrmv(
613                        trans_raw(op),
614                        &alpha,
615                        m as sys::aoclsparse_int,
616                        n as sys::aoclsparse_int,
617                        nnz as sys::aoclsparse_int,
618                        csr_val.as_ptr(),
619                        csr_col_ind.as_ptr(),
620                        csr_row_ptr.as_ptr(),
621                        descr.as_raw(),
622                        x.as_ptr(),
623                        &beta,
624                        y.as_mut_ptr(),
625                    )
626                };
627                check_status("sparse", status)
628            }
629
630            fn axpyi(
631                alpha: Self,
632                x: &[Self],
633                indx: &[sys::aoclsparse_int],
634                y: &mut [Self],
635            ) -> Result<()> {
636                let status = unsafe {
637                    sys::$axpyi(
638                        x.len() as sys::aoclsparse_int,
639                        alpha,
640                        x.as_ptr(),
641                        indx.as_ptr(),
642                        y.as_mut_ptr(),
643                    )
644                };
645                check_status("sparse", status)
646            }
647
648            fn gthr(y: &[Self], indx: &[sys::aoclsparse_int], x: &mut [Self]) -> Result<()> {
649                let status = unsafe {
650                    sys::$gthr(
651                        x.len() as sys::aoclsparse_int,
652                        y.as_ptr(),
653                        x.as_mut_ptr(),
654                        indx.as_ptr(),
655                    )
656                };
657                check_status("sparse", status)
658            }
659
660            fn sctr(x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()> {
661                let status = unsafe {
662                    sys::$sctr(
663                        x.len() as sys::aoclsparse_int,
664                        x.as_ptr(),
665                        indx.as_ptr(),
666                        y.as_mut_ptr(),
667                    )
668                };
669                check_status("sparse", status)
670            }
671
672            fn csrsv(
673                op: Trans,
674                alpha: Self,
675                m: usize,
676                csr_val: &[Self],
677                csr_col_ind: &[sys::aoclsparse_int],
678                csr_row_ptr: &[sys::aoclsparse_int],
679                descr: &MatDescr,
680                x: &[Self],
681                y: &mut [Self],
682            ) -> Result<()> {
683                if csr_row_ptr.len() != m + 1 {
684                    return Err(Error::InvalidArgument(format!(
685                        "csrsv: csr_row_ptr length {} != m+1 = {}",
686                        csr_row_ptr.len(),
687                        m + 1
688                    )));
689                }
690                if x.len() < m || y.len() < m {
691                    return Err(Error::InvalidArgument(format!(
692                        "csrsv: x.len()={}, y.len()={}, m={m}",
693                        x.len(),
694                        y.len()
695                    )));
696                }
697                let status = unsafe {
698                    sys::$csrsv(
699                        trans_raw(op),
700                        &alpha,
701                        m as sys::aoclsparse_int,
702                        csr_val.as_ptr(),
703                        csr_col_ind.as_ptr(),
704                        csr_row_ptr.as_ptr(),
705                        descr.as_raw(),
706                        x.as_ptr(),
707                        y.as_mut_ptr(),
708                    )
709                };
710                check_status("sparse", status)
711            }
712
713            fn csr_to_dense(
714                m: usize,
715                n: usize,
716                descr: &MatDescr,
717                csr_val: &[Self],
718                csr_row_ptr: &[sys::aoclsparse_int],
719                csr_col_ind: &[sys::aoclsparse_int],
720                a: &mut [Self],
721                ld: usize,
722                order: Order,
723            ) -> Result<()> {
724                let status = unsafe {
725                    sys::$csr2dense(
726                        m as sys::aoclsparse_int,
727                        n as sys::aoclsparse_int,
728                        descr.as_raw(),
729                        csr_val.as_ptr(),
730                        csr_row_ptr.as_ptr(),
731                        csr_col_ind.as_ptr(),
732                        a.as_mut_ptr(),
733                        ld as sys::aoclsparse_int,
734                        order.raw(),
735                    )
736                };
737                check_status("sparse", status)
738            }
739
740            fn csr_to_csc(
741                m: usize,
742                n: usize,
743                descr: &MatDescr,
744                base_csc: IndexBase,
745                csr_row_ptr: &[sys::aoclsparse_int],
746                csr_col_ind: &[sys::aoclsparse_int],
747                csr_val: &[Self],
748                csc_row_ind: &mut [sys::aoclsparse_int],
749                csc_col_ptr: &mut [sys::aoclsparse_int],
750                csc_val: &mut [Self],
751            ) -> Result<()> {
752                let nnz = csr_val.len();
753                let status = unsafe {
754                    sys::$csr2csc(
755                        m as sys::aoclsparse_int,
756                        n as sys::aoclsparse_int,
757                        nnz as sys::aoclsparse_int,
758                        descr.as_raw(),
759                        base_csc.raw(),
760                        csr_row_ptr.as_ptr(),
761                        csr_col_ind.as_ptr(),
762                        csr_val.as_ptr(),
763                        csc_row_ind.as_mut_ptr(),
764                        csc_col_ptr.as_mut_ptr(),
765                        csc_val.as_mut_ptr(),
766                    )
767                };
768                check_status("sparse", status)
769            }
770
771            fn ellmv(
772                op: Trans,
773                alpha: Self,
774                m: usize,
775                n: usize,
776                ell_val: &[Self],
777                ell_col_ind: &[sys::aoclsparse_int],
778                ell_width: usize,
779                descr: &MatDescr,
780                x: &[Self],
781                beta: Self,
782                y: &mut [Self],
783            ) -> Result<()> {
784                let nnz = ell_val.len();
785                if ell_col_ind.len() != nnz {
786                    return Err(Error::InvalidArgument(format!(
787                        "ellmv: ell_col_ind length {} != ell_val length {nnz}",
788                        ell_col_ind.len()
789                    )));
790                }
791                let needed = m.checked_mul(ell_width).ok_or_else(|| {
792                    Error::InvalidArgument("ellmv: m * ell_width overflows".into())
793                })?;
794                if nnz < needed {
795                    return Err(Error::InvalidArgument(format!(
796                        "ellmv: ell_val length {nnz} < m*ell_width = {needed}"
797                    )));
798                }
799                let (x_len, y_len) = match op {
800                    Trans::No => (n, m),
801                    Trans::T | Trans::C => (m, n),
802                };
803                if x.len() < x_len || y.len() < y_len {
804                    return Err(Error::InvalidArgument(format!(
805                        "ellmv: x.len()={}, y.len()={}, expected ({x_len}, {y_len})",
806                        x.len(),
807                        y.len()
808                    )));
809                }
810                let status = unsafe {
811                    sys::$ellmv(
812                        trans_raw(op),
813                        &alpha,
814                        m as sys::aoclsparse_int,
815                        n as sys::aoclsparse_int,
816                        nnz as sys::aoclsparse_int,
817                        ell_val.as_ptr(),
818                        ell_col_ind.as_ptr(),
819                        ell_width as sys::aoclsparse_int,
820                        descr.as_raw(),
821                        x.as_ptr(),
822                        &beta,
823                        y.as_mut_ptr(),
824                    )
825                };
826                check_status("sparse", status)
827            }
828
829            fn bsrmv(
830                op: Trans,
831                alpha: Self,
832                mb: usize,
833                nb: usize,
834                bsr_dim: usize,
835                bsr_val: &[Self],
836                bsr_col_ind: &[sys::aoclsparse_int],
837                bsr_row_ptr: &[sys::aoclsparse_int],
838                descr: &MatDescr,
839                x: &[Self],
840                beta: Self,
841                y: &mut [Self],
842            ) -> Result<()> {
843                if bsr_row_ptr.len() != mb + 1 {
844                    return Err(Error::InvalidArgument(format!(
845                        "bsrmv: bsr_row_ptr length {} != mb+1 = {}",
846                        bsr_row_ptr.len(),
847                        mb + 1
848                    )));
849                }
850                let block_area = bsr_dim.checked_mul(bsr_dim).ok_or_else(|| {
851                    Error::InvalidArgument("bsrmv: bsr_dim*bsr_dim overflows".into())
852                })?;
853                let nnzb = bsr_col_ind.len();
854                if bsr_val.len() < nnzb * block_area {
855                    return Err(Error::InvalidArgument(format!(
856                        "bsrmv: bsr_val length {} < nnzb*bsr_dim^2 = {}",
857                        bsr_val.len(),
858                        nnzb * block_area
859                    )));
860                }
861                let (x_len, y_len) = match op {
862                    Trans::No => (nb * bsr_dim, mb * bsr_dim),
863                    Trans::T | Trans::C => (mb * bsr_dim, nb * bsr_dim),
864                };
865                if x.len() < x_len || y.len() < y_len {
866                    return Err(Error::InvalidArgument(format!(
867                        "bsrmv: x.len()={}, y.len()={}, expected ({x_len}, {y_len})",
868                        x.len(),
869                        y.len()
870                    )));
871                }
872                let status = unsafe {
873                    sys::$bsrmv(
874                        trans_raw(op),
875                        &alpha,
876                        mb as sys::aoclsparse_int,
877                        nb as sys::aoclsparse_int,
878                        bsr_dim as sys::aoclsparse_int,
879                        bsr_val.as_ptr(),
880                        bsr_col_ind.as_ptr(),
881                        bsr_row_ptr.as_ptr(),
882                        descr.as_raw(),
883                        x.as_ptr(),
884                        &beta,
885                        y.as_mut_ptr(),
886                    )
887                };
888                check_status("sparse", status)
889            }
890
891            fn create_csr(
892                base: IndexBase,
893                m: usize,
894                n: usize,
895                nnz: usize,
896                row_ptr: *mut sys::aoclsparse_int,
897                col_idx: *mut sys::aoclsparse_int,
898                val: *mut Self,
899            ) -> Result<sys::aoclsparse_matrix> {
900                let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
901                let status = unsafe {
902                    sys::$create_csr(
903                        &mut raw,
904                        base.raw(),
905                        m as sys::aoclsparse_int,
906                        n as sys::aoclsparse_int,
907                        nnz as sys::aoclsparse_int,
908                        row_ptr,
909                        col_idx,
910                        val,
911                    )
912                };
913                check_status("sparse", status)?;
914                if raw.is_null() {
915                    return Err(Error::AllocationFailed("sparse"));
916                }
917                Ok(raw)
918            }
919
920            fn export_csr(
921                mat: sys::aoclsparse_matrix,
922            ) -> Result<(
923                IndexBase,
924                usize,
925                usize,
926                usize,
927                *mut sys::aoclsparse_int,
928                *mut sys::aoclsparse_int,
929                *mut Self,
930            )> {
931                let mut base: sys::aoclsparse_index_base = 0;
932                let mut m: sys::aoclsparse_int = 0;
933                let mut n: sys::aoclsparse_int = 0;
934                let mut nnz: sys::aoclsparse_int = 0;
935                let mut row_ptr: *mut sys::aoclsparse_int = std::ptr::null_mut();
936                let mut col_ind: *mut sys::aoclsparse_int = std::ptr::null_mut();
937                let mut val: *mut Self = std::ptr::null_mut();
938                let status = unsafe {
939                    sys::$export_csr(
940                        mat,
941                        &mut base,
942                        &mut m,
943                        &mut n,
944                        &mut nnz,
945                        &mut row_ptr,
946                        &mut col_ind,
947                        &mut val,
948                    )
949                };
950                check_status("sparse", status)?;
951                let base_e = if base == sys::aoclsparse_index_base__aoclsparse_index_base_one {
952                    IndexBase::One
953                } else {
954                    IndexBase::Zero
955                };
956                Ok((
957                    base_e,
958                    m as usize,
959                    n as usize,
960                    nnz as usize,
961                    row_ptr,
962                    col_ind,
963                    val,
964                ))
965            }
966
967            fn ilu_smoother(
968                op: Trans,
969                a: sys::aoclsparse_matrix,
970                descr: &MatDescr,
971                x: &mut [Self],
972                b: &[Self],
973            ) -> Result<()> {
974                let mut precond_csr_val: *mut Self = std::ptr::null_mut();
975                let status = unsafe {
976                    sys::$ilu_smoother(
977                        trans_raw(op),
978                        a,
979                        descr.as_raw(),
980                        &mut precond_csr_val,
981                        std::ptr::null(),
982                        x.as_mut_ptr(),
983                        b.as_ptr(),
984                    )
985                };
986                check_status("sparse", status)
987            }
988
989            fn itsol_init(handle: &mut sys::aoclsparse_itsol_handle) -> Result<()> {
990                let status = unsafe { sys::$itsol_init(handle) };
991                check_status("sparse", status)
992            }
993
994            fn itsol_solve(
995                handle: sys::aoclsparse_itsol_handle,
996                n: usize,
997                mat: sys::aoclsparse_matrix,
998                descr: &MatDescr,
999                b: &[Self],
1000                x: &mut [Self],
1001                rinfo: &mut [Self; 100],
1002            ) -> Result<()> {
1003                if b.len() < n || x.len() < n {
1004                    return Err(Error::InvalidArgument(format!(
1005                        "itsol_solve: b.len()={}, x.len()={}, n={n}",
1006                        b.len(),
1007                        x.len()
1008                    )));
1009                }
1010                let status = unsafe {
1011                    sys::$itsol_solve(
1012                        handle,
1013                        n as sys::aoclsparse_int,
1014                        mat,
1015                        descr.as_raw(),
1016                        b.as_ptr(),
1017                        x.as_mut_ptr(),
1018                        rinfo.as_mut_ptr(),
1019                        None,
1020                        None,
1021                        std::ptr::null_mut(),
1022                    )
1023                };
1024                check_status("sparse", status)
1025            }
1026
1027            unsafe fn csr2m_ffi(
1028                op_a: sys::aoclsparse_operation,
1029                descr_a: sys::aoclsparse_mat_descr,
1030                a: sys::aoclsparse_matrix,
1031                op_b: sys::aoclsparse_operation,
1032                descr_b: sys::aoclsparse_mat_descr,
1033                b: sys::aoclsparse_matrix,
1034                request: sys::aoclsparse_request,
1035                out: *mut sys::aoclsparse_matrix,
1036            ) -> sys::aoclsparse_status {
1037                sys::$csr2m(op_a, descr_a, a, op_b, descr_b, b, request, out)
1038            }
1039
1040            fn csrmm(
1041                op: Trans,
1042                alpha: Self,
1043                a: sys::aoclsparse_matrix,
1044                descr: &MatDescr,
1045                order: Order,
1046                b: &[Self],
1047                n: usize,
1048                ldb: usize,
1049                beta: Self,
1050                c: &mut [Self],
1051                ldc: usize,
1052            ) -> Result<()> {
1053                let status = unsafe {
1054                    sys::$csrmm(
1055                        trans_raw(op),
1056                        alpha,
1057                        a,
1058                        descr.as_raw(),
1059                        order.raw(),
1060                        b.as_ptr(),
1061                        n as sys::aoclsparse_int,
1062                        ldb as sys::aoclsparse_int,
1063                        beta,
1064                        c.as_mut_ptr(),
1065                        ldc as sys::aoclsparse_int,
1066                    )
1067                };
1068                check_status("sparse", status)
1069            }
1070
1071            fn spmmd(
1072                op: Trans,
1073                a: sys::aoclsparse_matrix,
1074                b: sys::aoclsparse_matrix,
1075                layout: Order,
1076                c: &mut [Self],
1077                ldc: usize,
1078            ) -> Result<()> {
1079                let status = unsafe {
1080                    sys::$spmmd(
1081                        trans_raw(op),
1082                        a,
1083                        b,
1084                        layout.raw(),
1085                        c.as_mut_ptr(),
1086                        ldc as sys::aoclsparse_int,
1087                    )
1088                };
1089                check_status("sparse", status)
1090            }
1091
1092            fn sp2md(
1093                op_a: Trans,
1094                descr_a: &MatDescr,
1095                a: sys::aoclsparse_matrix,
1096                op_b: Trans,
1097                descr_b: &MatDescr,
1098                b: sys::aoclsparse_matrix,
1099                alpha: Self,
1100                beta: Self,
1101                c: &mut [Self],
1102                layout: Order,
1103                ldc: usize,
1104            ) -> Result<()> {
1105                let status = unsafe {
1106                    sys::$sp2md(
1107                        trans_raw(op_a),
1108                        descr_a.as_raw(),
1109                        a,
1110                        trans_raw(op_b),
1111                        descr_b.as_raw(),
1112                        b,
1113                        alpha,
1114                        beta,
1115                        c.as_mut_ptr(),
1116                        layout.raw(),
1117                        ldc as sys::aoclsparse_int,
1118                    )
1119                };
1120                check_status("sparse", status)
1121            }
1122
1123            unsafe fn add_ffi(
1124                op: sys::aoclsparse_operation,
1125                a: sys::aoclsparse_matrix,
1126                alpha: Self,
1127                b: sys::aoclsparse_matrix,
1128                out: *mut sys::aoclsparse_matrix,
1129            ) -> sys::aoclsparse_status {
1130                sys::$add(op, a, alpha, b, out)
1131            }
1132
1133            fn sorv(
1134                sor_type: SorType,
1135                descr: &MatDescr,
1136                a: sys::aoclsparse_matrix,
1137                omega: Self,
1138                alpha: Self,
1139                x: &mut [Self],
1140                b: &[Self],
1141            ) -> Result<()> {
1142                let status = unsafe {
1143                    sys::$sorv(
1144                        sor_type.raw(),
1145                        descr.as_raw(),
1146                        a,
1147                        omega,
1148                        alpha,
1149                        x.as_mut_ptr(),
1150                        b.as_ptr(),
1151                    )
1152                };
1153                check_status("sparse", status)
1154            }
1155        }
1156    };
1157}
1158
1159impl_scalar!(
1160    f32,
1161    csrmv = aoclsparse_scsrmv,
1162    axpyi = aoclsparse_saxpyi,
1163    gthr = aoclsparse_sgthr,
1164    sctr = aoclsparse_ssctr,
1165    csrsv = aoclsparse_scsrsv,
1166    csr2dense = aoclsparse_scsr2dense,
1167    csr2csc = aoclsparse_scsr2csc,
1168    ellmv = aoclsparse_sellmv,
1169    bsrmv = aoclsparse_sbsrmv,
1170    create_csr = aoclsparse_create_scsr,
1171    export_csr = aoclsparse_export_scsr,
1172    ilu_smoother = aoclsparse_silu_smoother,
1173    itsol_init = aoclsparse_itsol_s_init,
1174    itsol_solve = aoclsparse_itsol_s_solve,
1175    csr2m = aoclsparse_scsr2m,
1176    csrmm = aoclsparse_scsrmm,
1177    spmmd = aoclsparse_sspmmd,
1178    sp2md = aoclsparse_ssp2md,
1179    add = aoclsparse_sadd,
1180    sorv = aoclsparse_ssorv
1181);
1182impl_scalar!(
1183    f64,
1184    csrmv = aoclsparse_dcsrmv,
1185    axpyi = aoclsparse_daxpyi,
1186    gthr = aoclsparse_dgthr,
1187    sctr = aoclsparse_dsctr,
1188    csrsv = aoclsparse_dcsrsv,
1189    csr2dense = aoclsparse_dcsr2dense,
1190    csr2csc = aoclsparse_dcsr2csc,
1191    ellmv = aoclsparse_dellmv,
1192    bsrmv = aoclsparse_dbsrmv,
1193    create_csr = aoclsparse_create_dcsr,
1194    export_csr = aoclsparse_export_dcsr,
1195    ilu_smoother = aoclsparse_dilu_smoother,
1196    itsol_init = aoclsparse_itsol_d_init,
1197    itsol_solve = aoclsparse_itsol_d_solve,
1198    csr2m = aoclsparse_dcsr2m,
1199    csrmm = aoclsparse_dcsrmm,
1200    spmmd = aoclsparse_dspmmd,
1201    sp2md = aoclsparse_dsp2md,
1202    add = aoclsparse_dadd,
1203    sorv = aoclsparse_dsorv
1204);
1205
1206/// Compute `y := α · A · x + β · y` for a CSR matrix `A`.
1207pub fn csrmv<T: Scalar>(
1208    alpha: T,
1209    m: usize,
1210    n: usize,
1211    csr_val: &[T],
1212    csr_col_ind: &[sys::aoclsparse_int],
1213    csr_row_ptr: &[sys::aoclsparse_int],
1214    descr: &MatDescr,
1215    x: &[T],
1216    beta: T,
1217    y: &mut [T],
1218) -> Result<()> {
1219    check_csr_arrays(
1220        "csrmv",
1221        m,
1222        Some(n),
1223        descr.index_base(),
1224        csr_row_ptr,
1225        csr_col_ind,
1226        csr_val.len(),
1227    )?;
1228    T::csrmv(
1229        Trans::No,
1230        alpha,
1231        m,
1232        n,
1233        csr_val,
1234        csr_col_ind,
1235        csr_row_ptr,
1236        descr,
1237        x,
1238        beta,
1239        y,
1240    )
1241}
1242
1243// =========================================================================
1244//   Sparse vector operations (axpyi, gather/scatter)
1245// =========================================================================
1246
1247/// Sparse `y[indx] := α·x + y[indx]` (sparse vector AXPY).
1248///
1249/// `x` and `indx` must have equal length (`nnz`); each `indx[i]` indexes
1250/// into `y`.
1251pub fn axpyi<T: Scalar>(
1252    alpha: T,
1253    x: &[T],
1254    indx: &[sys::aoclsparse_int],
1255    y: &mut [T],
1256) -> Result<()> {
1257    if x.len() != indx.len() {
1258        return Err(Error::InvalidArgument(format!(
1259            "axpyi: x.len()={}, indx.len()={}",
1260            x.len(),
1261            indx.len()
1262        )));
1263    }
1264    check_index_vector("axpyi", indx.len(), indx, y.len())?;
1265    T::axpyi(alpha, x, indx, y)
1266}
1267
1268/// Sparse gather: `x[i] := y[indx[i]]` for `i ∈ [0, nnz)`.
1269pub fn gthr<T: Scalar>(y: &[T], indx: &[sys::aoclsparse_int], x: &mut [T]) -> Result<()> {
1270    if x.len() != indx.len() {
1271        return Err(Error::InvalidArgument(format!(
1272            "gthr: x.len()={}, indx.len()={}",
1273            x.len(),
1274            indx.len()
1275        )));
1276    }
1277    check_index_vector("gthr", indx.len(), indx, y.len())?;
1278    T::gthr(y, indx, x)
1279}
1280
1281/// Sparse scatter: `y[indx[i]] := x[i]` for `i ∈ [0, nnz)`.
1282pub fn sctr<T: Scalar>(x: &[T], indx: &[sys::aoclsparse_int], y: &mut [T]) -> Result<()> {
1283    if x.len() != indx.len() {
1284        return Err(Error::InvalidArgument(format!(
1285            "sctr: x.len()={}, indx.len()={}",
1286            x.len(),
1287            indx.len()
1288        )));
1289    }
1290    check_index_vector("sctr", indx.len(), indx, y.len())?;
1291    T::sctr(x, indx, y)
1292}
1293
1294// =========================================================================
1295//   Sparse triangular solve (csrsv)
1296// =========================================================================
1297
1298/// Solve `op(A) · y = α · x` where `A` is sparse triangular in CSR
1299/// format. The triangle is determined by the `descr`'s fill mode (set
1300/// via the `aoclsparse_set_mat_*` C-API; defaults to upper, non-unit).
1301pub fn csrsv<T: Scalar>(
1302    op: Trans,
1303    alpha: T,
1304    m: usize,
1305    csr_val: &[T],
1306    csr_col_ind: &[sys::aoclsparse_int],
1307    csr_row_ptr: &[sys::aoclsparse_int],
1308    descr: &MatDescr,
1309    x: &[T],
1310    y: &mut [T],
1311) -> Result<()> {
1312    check_csr_arrays(
1313        "csrsv",
1314        m,
1315        Some(m),
1316        descr.index_base(),
1317        csr_row_ptr,
1318        csr_col_ind,
1319        csr_val.len(),
1320    )?;
1321    T::csrsv(op, alpha, m, csr_val, csr_col_ind, csr_row_ptr, descr, x, y)
1322}
1323
1324// =========================================================================
1325//   Format conversion: csr → dense, csr → csc
1326// =========================================================================
1327
1328/// Storage order used when converting from CSR to a dense matrix.
1329#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1330pub enum Order {
1331    RowMajor,
1332    ColMajor,
1333}
1334
1335impl Order {
1336    pub(crate) fn raw(self) -> sys::aoclsparse_order {
1337        match self {
1338            Order::RowMajor => sys::aoclsparse_order__aoclsparse_order_row,
1339            Order::ColMajor => sys::aoclsparse_order__aoclsparse_order_column,
1340        }
1341    }
1342}
1343
1344/// Convert a CSR sparse matrix to a dense `m × n` matrix in `out`.
1345pub fn csr_to_dense<T: Scalar>(
1346    m: usize,
1347    n: usize,
1348    descr: &MatDescr,
1349    csr_val: &[T],
1350    csr_row_ptr: &[sys::aoclsparse_int],
1351    csr_col_ind: &[sys::aoclsparse_int],
1352    a: &mut [T],
1353    ld: usize,
1354    order: Order,
1355) -> Result<()> {
1356    if csr_row_ptr.len() != m + 1 {
1357        return Err(Error::InvalidArgument(format!(
1358            "csr_to_dense: csr_row_ptr length {} != m+1 = {}",
1359            csr_row_ptr.len(),
1360            m + 1
1361        )));
1362    }
1363    let needed = match order {
1364        Order::RowMajor => m.saturating_sub(1) * ld + n,
1365        Order::ColMajor => n.saturating_sub(1) * ld + m,
1366    };
1367    if a.len() < needed {
1368        return Err(Error::InvalidArgument(format!(
1369            "csr_to_dense: A length {} < needed {needed}",
1370            a.len()
1371        )));
1372    }
1373    T::csr_to_dense(m, n, descr, csr_val, csr_row_ptr, csr_col_ind, a, ld, order)
1374}
1375
1376/// Convert a CSR matrix to CSC. Output arrays must be pre-sized.
1377pub fn csr_to_csc<T: Scalar>(
1378    m: usize,
1379    n: usize,
1380    descr: &MatDescr,
1381    base_csc: IndexBase,
1382    csr_row_ptr: &[sys::aoclsparse_int],
1383    csr_col_ind: &[sys::aoclsparse_int],
1384    csr_val: &[T],
1385    csc_row_ind: &mut [sys::aoclsparse_int],
1386    csc_col_ptr: &mut [sys::aoclsparse_int],
1387    csc_val: &mut [T],
1388) -> Result<()> {
1389    let nnz = csr_val.len();
1390    if csr_col_ind.len() != nnz || csc_row_ind.len() < nnz || csc_val.len() < nnz {
1391        return Err(Error::InvalidArgument(format!(
1392            "csr_to_csc: nnz mismatch (csr_val={}, csr_col_ind={}, csc_row_ind={}, csc_val={})",
1393            nnz,
1394            csr_col_ind.len(),
1395            csc_row_ind.len(),
1396            csc_val.len()
1397        )));
1398    }
1399    if csr_row_ptr.len() != m + 1 || csc_col_ptr.len() != n + 1 {
1400        return Err(Error::InvalidArgument(format!(
1401            "csr_to_csc: row_ptr length {} != m+1 = {} or col_ptr length {} != n+1 = {}",
1402            csr_row_ptr.len(),
1403            m + 1,
1404            csc_col_ptr.len(),
1405            n + 1
1406        )));
1407    }
1408    T::csr_to_csc(
1409        m,
1410        n,
1411        descr,
1412        base_csc,
1413        csr_row_ptr,
1414        csr_col_ind,
1415        csr_val,
1416        csc_row_ind,
1417        csc_col_ptr,
1418        csc_val,
1419    )
1420}
1421
1422/// Index base for sparse-format index arrays.
1423#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1424pub enum IndexBase {
1425    /// 0-based indexing (C convention).
1426    Zero,
1427    /// 1-based indexing (Fortran convention).
1428    One,
1429}
1430
1431impl IndexBase {
1432    fn raw(self) -> sys::aoclsparse_index_base {
1433        match self {
1434            IndexBase::Zero => sys::aoclsparse_index_base__aoclsparse_index_base_zero,
1435            IndexBase::One => sys::aoclsparse_index_base__aoclsparse_index_base_one,
1436        }
1437    }
1438}
1439
1440// =========================================================================
1441//   ELLPACK and BSR mat-vec
1442// =========================================================================
1443
1444/// Compute `y := α · op(A) · x + β · y` for an ELLPACK-format `A`.
1445///
1446/// `ell_val` and `ell_col_ind` each have length `m * ell_width`, where rows
1447/// shorter than `ell_width` are padded.
1448///
1449/// AOCL only implements `op = Trans::No` for ELLPACK at present.
1450pub fn ellmv<T: Scalar>(
1451    op: Trans,
1452    alpha: T,
1453    m: usize,
1454    n: usize,
1455    ell_val: &[T],
1456    ell_col_ind: &[sys::aoclsparse_int],
1457    ell_width: usize,
1458    descr: &MatDescr,
1459    x: &[T],
1460    beta: T,
1461    y: &mut [T],
1462) -> Result<()> {
1463    let slots = m * ell_width;
1464    check_len("ellmv", "ell_val", ell_val.len(), slots)?;
1465    check_len("ellmv", "ell_col_ind", ell_col_ind.len(), slots)?;
1466    let b = base_offset(descr.index_base());
1467    if let Some(&bad) = ell_col_ind[..slots].iter().find(|&&c| {
1468        let q = i64::from(c) - b;
1469        q != -1 && (q < 0 || q as usize >= n) // -1 relative to the base is the padding slot of `csr2ell`
1470    }) {
1471        return Err(Error::InvalidArgument(format!(
1472            "ellmv: column index {bad} outside the matrix (n = {n}, base {:?})",
1473            descr.index_base()
1474        )));
1475    }
1476    T::ellmv(
1477        op,
1478        alpha,
1479        m,
1480        n,
1481        ell_val,
1482        ell_col_ind,
1483        ell_width,
1484        descr,
1485        x,
1486        beta,
1487        y,
1488    )
1489}
1490
1491/// Compute `y := α · op(A) · x + β · y` for a BSR-format `A`.
1492///
1493/// `mb` and `nb` count blocks (so `A` is `mb·bsr_dim × nb·bsr_dim`).
1494/// `bsr_val` is laid out as `nnzb` consecutive `bsr_dim × bsr_dim` blocks.
1495///
1496/// AOCL only implements `op = Trans::No` for BSR at present.
1497pub fn bsrmv<T: Scalar>(
1498    op: Trans,
1499    alpha: T,
1500    mb: usize,
1501    nb: usize,
1502    bsr_dim: usize,
1503    bsr_val: &[T],
1504    bsr_col_ind: &[sys::aoclsparse_int],
1505    bsr_row_ptr: &[sys::aoclsparse_int],
1506    descr: &MatDescr,
1507    x: &[T],
1508    beta: T,
1509    y: &mut [T],
1510) -> Result<()> {
1511    if bsr_dim == 0 {
1512        return Err(Error::InvalidArgument("bsrmv: bsr_dim is 0".into()));
1513    }
1514    check_csr_arrays(
1515        "bsrmv",
1516        mb,
1517        Some(nb),
1518        descr.index_base(),
1519        bsr_row_ptr,
1520        bsr_col_ind,
1521        bsr_val.len() / (bsr_dim * bsr_dim),
1522    )?;
1523    T::bsrmv(
1524        op,
1525        alpha,
1526        mb,
1527        nb,
1528        bsr_dim,
1529        bsr_val,
1530        bsr_col_ind,
1531        bsr_row_ptr,
1532        descr,
1533        x,
1534        beta,
1535        y,
1536    )
1537}
1538
1539// =========================================================================
1540//   High-level matrix handle (aoclsparse_matrix)
1541// =========================================================================
1542
1543/// Stage of a multi-pass sparse-sparse matrix product (see [`csr2m`]).
1544#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1545pub enum Stage {
1546    /// Analyse only; reserve nnz count without writing values.
1547    NnzCount,
1548    /// Compute values, given a prior `NnzCount` call.
1549    Finalize,
1550    /// Single-shot full computation.
1551    FullComputation,
1552}
1553
1554impl Stage {
1555    fn raw(self) -> sys::aoclsparse_request {
1556        match self {
1557            Stage::NnzCount => sys::aoclsparse_request__aoclsparse_stage_nnz_count,
1558            Stage::Finalize => sys::aoclsparse_request__aoclsparse_stage_finalize,
1559            Stage::FullComputation => sys::aoclsparse_request__aoclsparse_stage_full_computation,
1560        }
1561    }
1562}
1563
1564enum CsrStorage<T: Scalar> {
1565    /// Arrays are owned by the Rust side (we keep them alive until drop).
1566    Owned {
1567        _row_ptr: Vec<sys::aoclsparse_int>,
1568        _col_ind: Vec<sys::aoclsparse_int>,
1569        _val: Vec<T>,
1570    },
1571    /// Arrays are owned by the library; only the handle needs destroying.
1572    LibraryOwned,
1573}
1574
1575/// RAII wrapper around an `aoclsparse_matrix` handle holding a CSR matrix.
1576///
1577/// Construct from raw CSR vectors with [`SparseMatrix::from_csr`] (the
1578/// values are copied into the wrapper) or as the result of an operation
1579/// like [`csr2m`].
1580pub struct SparseMatrix<T: Scalar> {
1581    raw: sys::aoclsparse_matrix,
1582    #[allow(dead_code, reason = "kept alive so the library can keep its pointers")]
1583    storage: CsrStorage<T>,
1584    base: IndexBase,
1585    m: usize,
1586    n: usize,
1587    nnz: usize,
1588}
1589
1590impl<T: Scalar> SparseMatrix<T> {
1591    /// Build a new matrix handle from CSR arrays. The arrays are copied
1592    /// into the wrapper; the caller's slices are not retained.
1593    pub fn from_csr(
1594        base: IndexBase,
1595        m: usize,
1596        n: usize,
1597        row_ptr: &[sys::aoclsparse_int],
1598        col_ind: &[sys::aoclsparse_int],
1599        val: &[T],
1600    ) -> Result<Self> {
1601        if row_ptr.len() != m + 1 {
1602            return Err(Error::InvalidArgument(format!(
1603                "from_csr: row_ptr length {} != m+1 = {}",
1604                row_ptr.len(),
1605                m + 1
1606            )));
1607        }
1608        let nnz = val.len();
1609        if col_ind.len() != nnz {
1610            return Err(Error::InvalidArgument(format!(
1611                "from_csr: col_ind length {} != val length {nnz}",
1612                col_ind.len()
1613            )));
1614        }
1615        let mut row_ptr = row_ptr.to_vec();
1616        let mut col_ind = col_ind.to_vec();
1617        let mut val = val.to_vec();
1618        let raw = T::create_csr(
1619            base,
1620            m,
1621            n,
1622            nnz,
1623            row_ptr.as_mut_ptr(),
1624            col_ind.as_mut_ptr(),
1625            val.as_mut_ptr(),
1626        )?;
1627        Ok(Self {
1628            raw,
1629            storage: CsrStorage::Owned {
1630                _row_ptr: row_ptr,
1631                _col_ind: col_ind,
1632                _val: val,
1633            },
1634            base,
1635            m,
1636            n,
1637            nnz,
1638        })
1639    }
1640
1641    /// Adopt a handle returned by an AOCL routine that allocates its own
1642    /// CSR storage (e.g. `aoclsparse_dcsr2m`). The library will free the
1643    /// arrays when the handle is destroyed.
1644    ///
1645    /// # Safety
1646    /// `raw` must be a valid `aoclsparse_matrix` whose internal storage is
1647    /// owned by the AOCL library and whose precision matches `T`.
1648    pub unsafe fn from_library_owned(raw: sys::aoclsparse_matrix) -> Result<Self> {
1649        if raw.is_null() {
1650            return Err(Error::AllocationFailed("sparse"));
1651        }
1652        let (base, m, n, nnz, _, _, _) = T::export_csr(raw)?;
1653        Ok(Self {
1654            raw,
1655            storage: CsrStorage::LibraryOwned,
1656            base,
1657            m,
1658            n,
1659            nnz,
1660        })
1661    }
1662
1663    /// `(m, n)` dimensions of the matrix.
1664    pub fn dims(&self) -> (usize, usize) {
1665        (self.m, self.n)
1666    }
1667
1668    /// Number of explicitly stored non-zeros.
1669    pub fn nnz(&self) -> usize {
1670        self.nnz
1671    }
1672
1673    /// Index base used by this matrix's row-pointer and column-index arrays.
1674    pub fn base(&self) -> IndexBase {
1675        self.base
1676    }
1677
1678    /// Borrow the raw underlying handle for raw FFI calls.
1679    ///
1680    /// # Safety
1681    /// The returned pointer is valid only for the lifetime of `self`.
1682    /// Do not call `aoclsparse_destroy` on it.
1683    pub fn as_raw(&self) -> sys::aoclsparse_matrix {
1684        self.raw
1685    }
1686
1687    /// Read out the CSR contents as freshly allocated `Vec`s.
1688    pub fn export_csr(
1689        &self,
1690    ) -> Result<(
1691        IndexBase,
1692        Vec<sys::aoclsparse_int>,
1693        Vec<sys::aoclsparse_int>,
1694        Vec<T>,
1695    )> {
1696        let (base, m, _, nnz, row_ptr, col_ind, val) = T::export_csr(self.raw)?;
1697        let row_ptr = unsafe { std::slice::from_raw_parts(row_ptr, m + 1).to_vec() };
1698        let col_ind = unsafe { std::slice::from_raw_parts(col_ind, nnz).to_vec() };
1699        let val = unsafe { std::slice::from_raw_parts(val, nnz).to_vec() };
1700        Ok((base, row_ptr, col_ind, val))
1701    }
1702
1703    // --- Hints: tell the analysis pass how the matrix will be used.
1704    // Pair with `optimize()` to actually run the analysis.
1705
1706    /// Hint that mat-vec (`mv`) will be called `expected_calls` times in
1707    /// the given orientation `op`.
1708    pub fn set_mv_hint(
1709        &mut self,
1710        op: Trans,
1711        descr: &MatDescr,
1712        expected_calls: usize,
1713    ) -> Result<()> {
1714        let status = unsafe {
1715            sys::aoclsparse_set_mv_hint(
1716                self.raw,
1717                trans_raw(op),
1718                descr.as_raw(),
1719                expected_calls as sys::aoclsparse_int,
1720            )
1721        };
1722        check_status("sparse", status)
1723    }
1724
1725    /// Hint for triangular solve (`trsv`).
1726    pub fn set_sv_hint(
1727        &mut self,
1728        op: Trans,
1729        descr: &MatDescr,
1730        expected_calls: usize,
1731    ) -> Result<()> {
1732        let status = unsafe {
1733            sys::aoclsparse_set_sv_hint(
1734                self.raw,
1735                trans_raw(op),
1736                descr.as_raw(),
1737                expected_calls as sys::aoclsparse_int,
1738            )
1739        };
1740        check_status("sparse", status)
1741    }
1742
1743    /// Hint for sparse-dense matrix multiply (`csrmm`).
1744    pub fn set_mm_hint(
1745        &mut self,
1746        op: Trans,
1747        descr: &MatDescr,
1748        expected_calls: usize,
1749    ) -> Result<()> {
1750        let status = unsafe {
1751            sys::aoclsparse_set_mm_hint(
1752                self.raw,
1753                trans_raw(op),
1754                descr.as_raw(),
1755                expected_calls as sys::aoclsparse_int,
1756            )
1757        };
1758        check_status("sparse", status)
1759    }
1760
1761    /// Hint for sparse-sparse matrix multiply (`csr2m`).
1762    pub fn set_2m_hint(
1763        &mut self,
1764        op: Trans,
1765        descr: &MatDescr,
1766        expected_calls: usize,
1767    ) -> Result<()> {
1768        let status = unsafe {
1769            sys::aoclsparse_set_2m_hint(
1770                self.raw,
1771                trans_raw(op),
1772                descr.as_raw(),
1773                expected_calls as sys::aoclsparse_int,
1774            )
1775        };
1776        check_status("sparse", status)
1777    }
1778
1779    /// Hint for sparse triangular solve with multiple right-hand sides
1780    /// (`trsm`). `order` is the layout of the dense `B`/`X` matrices.
1781    pub fn set_sm_hint(
1782        &mut self,
1783        op: Trans,
1784        descr: &MatDescr,
1785        order: Order,
1786        expected_calls: usize,
1787    ) -> Result<()> {
1788        let status = unsafe {
1789            sys::aoclsparse_set_sm_hint(
1790                self.raw,
1791                trans_raw(op),
1792                descr.as_raw(),
1793                order.raw(),
1794                expected_calls as sys::aoclsparse_int,
1795            )
1796        };
1797        check_status("sparse", status)
1798    }
1799
1800    /// Hint for ILU smoothing.
1801    pub fn set_lu_smoother_hint(
1802        &mut self,
1803        op: Trans,
1804        descr: &MatDescr,
1805        expected_calls: usize,
1806    ) -> Result<()> {
1807        let status = unsafe {
1808            sys::aoclsparse_set_lu_smoother_hint(
1809                self.raw,
1810                trans_raw(op),
1811                descr.as_raw(),
1812                expected_calls as sys::aoclsparse_int,
1813            )
1814        };
1815        check_status("sparse", status)
1816    }
1817
1818    /// Hint for symmetric Gauss-Seidel.
1819    pub fn set_symgs_hint(
1820        &mut self,
1821        op: Trans,
1822        descr: &MatDescr,
1823        expected_calls: usize,
1824    ) -> Result<()> {
1825        let status = unsafe {
1826            sys::aoclsparse_set_symgs_hint(
1827                self.raw,
1828                trans_raw(op),
1829                descr.as_raw(),
1830                expected_calls as sys::aoclsparse_int,
1831            )
1832        };
1833        check_status("sparse", status)
1834    }
1835
1836    /// Hint for the fused dot-mat-vec routine.
1837    pub fn set_dotmv_hint(
1838        &mut self,
1839        op: Trans,
1840        descr: &MatDescr,
1841        expected_calls: usize,
1842    ) -> Result<()> {
1843        let status = unsafe {
1844            sys::aoclsparse_set_dotmv_hint(
1845                self.raw,
1846                trans_raw(op),
1847                descr.as_raw(),
1848                expected_calls as sys::aoclsparse_int,
1849            )
1850        };
1851        check_status("sparse", status)
1852    }
1853
1854    /// Hint for SOR / Gauss-Seidel sweeps.
1855    pub fn set_sorv_hint(
1856        &mut self,
1857        sor_type: SorType,
1858        descr: &MatDescr,
1859        expected_calls: usize,
1860    ) -> Result<()> {
1861        let status = unsafe {
1862            sys::aoclsparse_set_sorv_hint(
1863                self.raw,
1864                descr.as_raw(),
1865                sor_type.raw(),
1866                expected_calls as sys::aoclsparse_int,
1867            )
1868        };
1869        check_status("sparse", status)
1870    }
1871}
1872
1873impl<T: Scalar> Drop for SparseMatrix<T> {
1874    fn drop(&mut self) {
1875        if !self.raw.is_null() {
1876            unsafe {
1877                let _ = sys::aoclsparse_destroy(&mut self.raw);
1878            }
1879            self.raw = std::ptr::null_mut();
1880        }
1881    }
1882}
1883
1884impl<T: Scalar> std::fmt::Debug for SparseMatrix<T> {
1885    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1886        f.debug_struct("SparseMatrix")
1887            .field("m", &self.m)
1888            .field("n", &self.n)
1889            .field("nnz", &self.nnz)
1890            .field("base", &self.base)
1891            .finish()
1892    }
1893}
1894
1895// =========================================================================
1896//   Sparse-sparse matrix product (csr2m)
1897// =========================================================================
1898
1899/// Compute `C := op_A(A) · op_B(B)` between two CSR matrices, returning a
1900/// freshly allocated CSR result. Both inputs must have matching scalar
1901/// precision; complex precisions are not yet exposed by these wrappers.
1902///
1903/// Use `Stage::FullComputation` for a one-shot call. The two-stage form
1904/// (`NnzCount` followed by `Finalize`) is for repeated multiplies sharing
1905/// the same sparsity pattern.
1906pub fn csr2m<T: Scalar>(
1907    op_a: Trans,
1908    descr_a: &MatDescr,
1909    a: &SparseMatrix<T>,
1910    op_b: Trans,
1911    descr_b: &MatDescr,
1912    b: &SparseMatrix<T>,
1913    stage: Stage,
1914) -> Result<SparseMatrix<T>> {
1915    let mut c_raw: sys::aoclsparse_matrix = std::ptr::null_mut();
1916    let status = unsafe {
1917        // We need a per-precision dispatch. Encode by calling the matching
1918        // FFI symbol via a small helper trait.
1919        T::csr2m_ffi(
1920            trans_raw(op_a),
1921            descr_a.as_raw(),
1922            a.raw,
1923            trans_raw(op_b),
1924            descr_b.as_raw(),
1925            b.raw,
1926            stage.raw(),
1927            &mut c_raw,
1928        )
1929    };
1930    check_status("sparse", status)?;
1931    unsafe { SparseMatrix::from_library_owned(c_raw) }
1932}
1933
1934// =========================================================================
1935//   Sparse-dense matrix products (csrmm, spmmd, sp2md)
1936// =========================================================================
1937
1938/// Compute `C := α · op(A) · B + β · C` where `A` is sparse (CSR via the
1939/// matrix handle) and `B`, `C` are dense matrices laid out per `order`.
1940///
1941/// `n` is the number of columns of `B` (and `C`). `ldb` and `ldc` are
1942/// the leading dimensions of `B` and `C` respectively.
1943pub fn csrmm<T: Scalar>(
1944    op: Trans,
1945    alpha: T,
1946    a: &SparseMatrix<T>,
1947    descr: &MatDescr,
1948    order: Order,
1949    b: &[T],
1950    n: usize,
1951    ldb: usize,
1952    beta: T,
1953    c: &mut [T],
1954    ldc: usize,
1955) -> Result<()> {
1956    let (ar, ac) = opdims(op, a.m, a.n);
1957    check_dense("csrmm", "B", order, ac, n, ldb, b.len())?;
1958    check_dense("csrmm", "C", order, ar, n, ldc, c.len())?;
1959    T::csrmm(op, alpha, a.as_raw(), descr, order, b, n, ldb, beta, c, ldc)
1960}
1961
1962/// Compute `C := op(A) · B` where both `A` and `B` are sparse and `C` is
1963/// a dense matrix. `ldc` is the leading dimension of `C` per `layout`.
1964pub fn spmmd<T: Scalar>(
1965    op: Trans,
1966    a: &SparseMatrix<T>,
1967    b: &SparseMatrix<T>,
1968    layout: Order,
1969    c: &mut [T],
1970    ldc: usize,
1971) -> Result<()> {
1972    let (ar, _) = opdims(op, a.m, a.n);
1973    check_dense("spmmd", "C", layout, ar, b.n, ldc, c.len())?;
1974    T::spmmd(op, a.as_raw(), b.as_raw(), layout, c, ldc)
1975}
1976
1977/// Compute `C := α · op_A(A) · op_B(B) + β · C` where both `A` and `B`
1978/// are sparse and `C` is dense.
1979pub fn sp2md<T: Scalar>(
1980    op_a: Trans,
1981    descr_a: &MatDescr,
1982    a: &SparseMatrix<T>,
1983    op_b: Trans,
1984    descr_b: &MatDescr,
1985    b: &SparseMatrix<T>,
1986    alpha: T,
1987    beta: T,
1988    c: &mut [T],
1989    layout: Order,
1990    ldc: usize,
1991) -> Result<()> {
1992    let (ar, _) = opdims(op_a, a.m, a.n);
1993    let (_, bc) = opdims(op_b, b.m, b.n);
1994    check_dense("sp2md", "C", layout, ar, bc, ldc, c.len())?;
1995    T::sp2md(
1996        op_a,
1997        descr_a,
1998        a.as_raw(),
1999        op_b,
2000        descr_b,
2001        b.as_raw(),
2002        alpha,
2003        beta,
2004        c,
2005        layout,
2006        ldc,
2007    )
2008}
2009
2010// =========================================================================
2011//   Sparse-sparse addition and SOR sweep
2012// =========================================================================
2013
2014/// Compute `C := α · op(A) + B` returning a fresh sparse CSR matrix.
2015pub fn add<T: Scalar>(
2016    op: Trans,
2017    a: &SparseMatrix<T>,
2018    alpha: T,
2019    b: &SparseMatrix<T>,
2020) -> Result<SparseMatrix<T>> {
2021    let mut c_raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2022    let status = unsafe { T::add_ffi(trans_raw(op), a.as_raw(), alpha, b.as_raw(), &mut c_raw) };
2023    check_status("sparse", status)?;
2024    unsafe { SparseMatrix::from_library_owned(c_raw) }
2025}
2026
2027/// One step of (S)SOR / forward / backward Gauss-Seidel relaxation:
2028/// `x_new := (1 − ω) x + ω · A⁻¹ (α · b)`. Useful as a smoother
2029/// inside iterative-solver loops.
2030pub fn sorv<T: Scalar>(
2031    sor_type: SorType,
2032    descr: &MatDescr,
2033    a: &SparseMatrix<T>,
2034    omega: T,
2035    alpha: T,
2036    x: &mut [T],
2037    b: &[T],
2038) -> Result<()> {
2039    if x.len() < a.dims().1 || b.len() < a.dims().0 {
2040        return Err(Error::InvalidArgument(format!(
2041            "sorv: x.len()={}, b.len()={}, dims=({}, {})",
2042            x.len(),
2043            b.len(),
2044            a.dims().0,
2045            a.dims().1
2046        )));
2047    }
2048    T::sorv(sor_type, descr, a.as_raw(), omega, alpha, x, b)
2049}
2050
2051// =========================================================================
2052//   ILU smoother
2053// =========================================================================
2054
2055// =========================================================================
2056//   Real high-level mat-vec / triangular solve / triangular multi-RHS solve
2057// =========================================================================
2058
2059/// Real high-level mat-vec `y := α · op(A) · x + β · y` against a
2060/// `SparseMatrix<f64>` handle (per-precision; complex variants live in
2061/// the [`complex`] submodule).
2062pub fn mv_f64(
2063    op: Trans,
2064    alpha: f64,
2065    a: &SparseMatrix<f64>,
2066    descr: &MatDescr,
2067    x: &[f64],
2068    beta: f64,
2069    y: &mut [f64],
2070) -> Result<()> {
2071    let (xl, yl) = mv_lens(op, a.m, a.n);
2072    check_len("mv_f64", "x", x.len(), xl)?;
2073    check_len("mv_f64", "y", y.len(), yl)?;
2074    let status = unsafe {
2075        sys::aoclsparse_dmv(
2076            trans_raw(op),
2077            &alpha,
2078            a.as_raw(),
2079            descr.as_raw(),
2080            x.as_ptr(),
2081            &beta,
2082            y.as_mut_ptr(),
2083        )
2084    };
2085    check_status("sparse", status)
2086}
2087
2088/// `f32` mat-vec via the matrix-handle interface. See [`mv_f64`].
2089pub fn mv_f32(
2090    op: Trans,
2091    alpha: f32,
2092    a: &SparseMatrix<f32>,
2093    descr: &MatDescr,
2094    x: &[f32],
2095    beta: f32,
2096    y: &mut [f32],
2097) -> Result<()> {
2098    let (xl, yl) = mv_lens(op, a.m, a.n);
2099    check_len("mv_f32", "x", x.len(), xl)?;
2100    check_len("mv_f32", "y", y.len(), yl)?;
2101    let status = unsafe {
2102        sys::aoclsparse_smv(
2103            trans_raw(op),
2104            &alpha,
2105            a.as_raw(),
2106            descr.as_raw(),
2107            x.as_ptr(),
2108            &beta,
2109            y.as_mut_ptr(),
2110        )
2111    };
2112    check_status("sparse", status)
2113}
2114
2115/// Solve `op(A) · x = α · b` for sparse triangular `A` against a
2116/// `SparseMatrix<f64>` handle. The fill mode and unit/non-unit diag
2117/// must be set on `descr` first.
2118pub fn trsv_f64(
2119    op: Trans,
2120    alpha: f64,
2121    a: &SparseMatrix<f64>,
2122    descr: &MatDescr,
2123    b: &[f64],
2124    x: &mut [f64],
2125) -> Result<()> {
2126    check_len("trsv_f64", "b", b.len(), a.m)?;
2127    check_len("trsv_f64", "x", x.len(), a.m)?;
2128    let status = unsafe {
2129        sys::aoclsparse_dtrsv(
2130            trans_raw(op),
2131            alpha,
2132            a.as_raw(),
2133            descr.as_raw(),
2134            b.as_ptr(),
2135            x.as_mut_ptr(),
2136        )
2137    };
2138    check_status("sparse", status)
2139}
2140
2141/// `f32` triangular solve. See [`trsv_f64`].
2142pub fn trsv_f32(
2143    op: Trans,
2144    alpha: f32,
2145    a: &SparseMatrix<f32>,
2146    descr: &MatDescr,
2147    b: &[f32],
2148    x: &mut [f32],
2149) -> Result<()> {
2150    check_len("trsv_f32", "b", b.len(), a.m)?;
2151    check_len("trsv_f32", "x", x.len(), a.m)?;
2152    let status = unsafe {
2153        sys::aoclsparse_strsv(
2154            trans_raw(op),
2155            alpha,
2156            a.as_raw(),
2157            descr.as_raw(),
2158            b.as_ptr(),
2159            x.as_mut_ptr(),
2160        )
2161    };
2162    check_status("sparse", status)
2163}
2164
2165/// Multi-RHS triangular solve: `op(A) · X = α · B` for `n_rhs`
2166/// right-hand sides, `B`/`X` dense `m × n_rhs`.
2167pub fn trsm_f64(
2168    op: Trans,
2169    alpha: f64,
2170    a: &SparseMatrix<f64>,
2171    descr: &MatDescr,
2172    order: Order,
2173    b: &[f64],
2174    n_rhs: usize,
2175    ldb: usize,
2176    x: &mut [f64],
2177    ldx: usize,
2178) -> Result<()> {
2179    check_dense("trsm", "B", order, a.m, n_rhs, ldb, b.len())?;
2180    check_dense("trsm", "X", order, a.m, n_rhs, ldx, x.len())?;
2181    let status = unsafe {
2182        sys::aoclsparse_dtrsm(
2183            trans_raw(op),
2184            alpha,
2185            a.as_raw(),
2186            descr.as_raw(),
2187            order.raw(),
2188            b.as_ptr(),
2189            n_rhs as sys::aoclsparse_int,
2190            ldb as sys::aoclsparse_int,
2191            x.as_mut_ptr(),
2192            ldx as sys::aoclsparse_int,
2193        )
2194    };
2195    check_status("sparse", status)
2196}
2197
2198/// `f32` multi-RHS triangular solve. See [`trsm_f64`].
2199pub fn trsm_f32(
2200    op: Trans,
2201    alpha: f32,
2202    a: &SparseMatrix<f32>,
2203    descr: &MatDescr,
2204    order: Order,
2205    b: &[f32],
2206    n_rhs: usize,
2207    ldb: usize,
2208    x: &mut [f32],
2209    ldx: usize,
2210) -> Result<()> {
2211    check_dense("trsm", "B", order, a.m, n_rhs, ldb, b.len())?;
2212    check_dense("trsm", "X", order, a.m, n_rhs, ldx, x.len())?;
2213    let status = unsafe {
2214        sys::aoclsparse_strsm(
2215            trans_raw(op),
2216            alpha,
2217            a.as_raw(),
2218            descr.as_raw(),
2219            order.raw(),
2220            b.as_ptr(),
2221            n_rhs as sys::aoclsparse_int,
2222            ldb as sys::aoclsparse_int,
2223            x.as_mut_ptr(),
2224            ldx as sys::aoclsparse_int,
2225        )
2226    };
2227    check_status("sparse", status)
2228}
2229
2230/// Sparse vector dot product: `Σᵢ x[i] · y[indx[i]]`. `x` and `indx`
2231/// must have the same length (the nnz count).
2232pub fn doti_f64(x: &[f64], indx: &[sys::aoclsparse_int], y: &[f64]) -> Result<f64> {
2233    if x.len() != indx.len() {
2234        return Err(Error::InvalidArgument(format!(
2235            "doti: x.len()={} != indx.len()={}",
2236            x.len(),
2237            indx.len()
2238        )));
2239    }
2240    check_index_vector("doti", indx.len(), indx, y.len())?;
2241    let r = unsafe {
2242        sys::aoclsparse_ddoti(
2243            x.len() as sys::aoclsparse_int,
2244            x.as_ptr(),
2245            indx.as_ptr(),
2246            y.as_ptr(),
2247        )
2248    };
2249    Ok(r)
2250}
2251
2252/// `f32` sparse dot. See [`doti_f64`].
2253pub fn doti_f32(x: &[f32], indx: &[sys::aoclsparse_int], y: &[f32]) -> Result<f32> {
2254    if x.len() != indx.len() {
2255        return Err(Error::InvalidArgument(format!(
2256            "doti: x.len()={} != indx.len()={}",
2257            x.len(),
2258            indx.len()
2259        )));
2260    }
2261    check_index_vector("doti", indx.len(), indx, y.len())?;
2262    let r = unsafe {
2263        sys::aoclsparse_sdoti(
2264            x.len() as sys::aoclsparse_int,
2265            x.as_ptr(),
2266            indx.as_ptr(),
2267            y.as_ptr(),
2268        )
2269    };
2270    Ok(r)
2271}
2272
2273// =========================================================================
2274//   CSR ↔ ELL / DIA / BSR conversions, COO / CSC creators, value mutators,
2275//   block-CSR mat-vec, symmetric Gauss-Seidel
2276// =========================================================================
2277
2278/// Convert CSR → ELLPACK. `ell_width` is the chosen padded row length;
2279/// caller must allocate `ell_col_ind` and `ell_val` of size
2280/// `m * ell_width`. (`f64`)
2281pub fn csr2ell_f64(
2282    m: usize,
2283    descr: &MatDescr,
2284    csr_row_ptr: &[sys::aoclsparse_int],
2285    csr_col_ind: &[sys::aoclsparse_int],
2286    csr_val: &[f64],
2287    ell_col_ind: &mut [sys::aoclsparse_int],
2288    ell_val: &mut [f64],
2289    ell_width: usize,
2290) -> Result<()> {
2291    check_csr_arrays(
2292        "csr2ell",
2293        m,
2294        None,
2295        descr.index_base(),
2296        csr_row_ptr,
2297        csr_col_ind,
2298        csr_val.len(),
2299    )?;
2300    check_len("csr2ell", "ell_col_ind", ell_col_ind.len(), m * ell_width)?;
2301    check_len("csr2ell", "ell_val", ell_val.len(), m * ell_width)?;
2302    let status = unsafe {
2303        sys::aoclsparse_dcsr2ell(
2304            m as sys::aoclsparse_int,
2305            descr.as_raw(),
2306            csr_row_ptr.as_ptr(),
2307            csr_col_ind.as_ptr(),
2308            csr_val.as_ptr(),
2309            ell_col_ind.as_mut_ptr(),
2310            ell_val.as_mut_ptr(),
2311            ell_width as sys::aoclsparse_int,
2312        )
2313    };
2314    check_status("sparse", status)
2315}
2316
2317/// `f32` CSR → ELLPACK. See [`csr2ell_f64`].
2318pub fn csr2ell_f32(
2319    m: usize,
2320    descr: &MatDescr,
2321    csr_row_ptr: &[sys::aoclsparse_int],
2322    csr_col_ind: &[sys::aoclsparse_int],
2323    csr_val: &[f32],
2324    ell_col_ind: &mut [sys::aoclsparse_int],
2325    ell_val: &mut [f32],
2326    ell_width: usize,
2327) -> Result<()> {
2328    check_csr_arrays(
2329        "csr2ell",
2330        m,
2331        None,
2332        descr.index_base(),
2333        csr_row_ptr,
2334        csr_col_ind,
2335        csr_val.len(),
2336    )?;
2337    check_len("csr2ell", "ell_col_ind", ell_col_ind.len(), m * ell_width)?;
2338    check_len("csr2ell", "ell_val", ell_val.len(), m * ell_width)?;
2339    let status = unsafe {
2340        sys::aoclsparse_scsr2ell(
2341            m as sys::aoclsparse_int,
2342            descr.as_raw(),
2343            csr_row_ptr.as_ptr(),
2344            csr_col_ind.as_ptr(),
2345            csr_val.as_ptr(),
2346            ell_col_ind.as_mut_ptr(),
2347            ell_val.as_mut_ptr(),
2348            ell_width as sys::aoclsparse_int,
2349        )
2350    };
2351    check_status("sparse", status)
2352}
2353
2354/// Convert CSR → DIA (diagonal storage). `dia_offset` and `dia_val`
2355/// must be pre-allocated; `dia_num_diag` is the number of distinct
2356/// diagonals. (`f64`)
2357pub fn csr2dia_f64(
2358    m: usize,
2359    n: usize,
2360    descr: &MatDescr,
2361    csr_row_ptr: &[sys::aoclsparse_int],
2362    csr_col_ind: &[sys::aoclsparse_int],
2363    csr_val: &[f64],
2364    dia_num_diag: usize,
2365    dia_offset: &mut [sys::aoclsparse_int],
2366    dia_val: &mut [f64],
2367) -> Result<()> {
2368    check_csr_arrays(
2369        "csr2dia",
2370        m,
2371        Some(n),
2372        descr.index_base(),
2373        csr_row_ptr,
2374        csr_col_ind,
2375        csr_val.len(),
2376    )?;
2377    check_len("csr2dia", "dia_offset", dia_offset.len(), dia_num_diag)?;
2378    check_len("csr2dia", "dia_val", dia_val.len(), m * dia_num_diag)?;
2379    let status = unsafe {
2380        sys::aoclsparse_dcsr2dia(
2381            m as sys::aoclsparse_int,
2382            n as sys::aoclsparse_int,
2383            descr.as_raw(),
2384            csr_row_ptr.as_ptr(),
2385            csr_col_ind.as_ptr(),
2386            csr_val.as_ptr(),
2387            dia_num_diag as sys::aoclsparse_int,
2388            dia_offset.as_mut_ptr(),
2389            dia_val.as_mut_ptr(),
2390        )
2391    };
2392    check_status("sparse", status)
2393}
2394
2395/// `f32` CSR → DIA. See [`csr2dia_f64`].
2396pub fn csr2dia_f32(
2397    m: usize,
2398    n: usize,
2399    descr: &MatDescr,
2400    csr_row_ptr: &[sys::aoclsparse_int],
2401    csr_col_ind: &[sys::aoclsparse_int],
2402    csr_val: &[f32],
2403    dia_num_diag: usize,
2404    dia_offset: &mut [sys::aoclsparse_int],
2405    dia_val: &mut [f32],
2406) -> Result<()> {
2407    check_csr_arrays(
2408        "csr2dia",
2409        m,
2410        Some(n),
2411        descr.index_base(),
2412        csr_row_ptr,
2413        csr_col_ind,
2414        csr_val.len(),
2415    )?;
2416    check_len("csr2dia", "dia_offset", dia_offset.len(), dia_num_diag)?;
2417    check_len("csr2dia", "dia_val", dia_val.len(), m * dia_num_diag)?;
2418    let status = unsafe {
2419        sys::aoclsparse_scsr2dia(
2420            m as sys::aoclsparse_int,
2421            n as sys::aoclsparse_int,
2422            descr.as_raw(),
2423            csr_row_ptr.as_ptr(),
2424            csr_col_ind.as_ptr(),
2425            csr_val.as_ptr(),
2426            dia_num_diag as sys::aoclsparse_int,
2427            dia_offset.as_mut_ptr(),
2428            dia_val.as_mut_ptr(),
2429        )
2430    };
2431    check_status("sparse", status)
2432}
2433
2434/// Compute the number of nonzero blocks (`bsr_nnz`) and `bsr_row_ptr`
2435/// for a CSR → BSR conversion with the given `block_dim`.
2436pub fn csr2bsr_nnz(
2437    m: usize,
2438    n: usize,
2439    descr: &MatDescr,
2440    csr_row_ptr: &[sys::aoclsparse_int],
2441    csr_col_ind: &[sys::aoclsparse_int],
2442    block_dim: usize,
2443    bsr_row_ptr: &mut [sys::aoclsparse_int],
2444) -> Result<usize> {
2445    if block_dim == 0 {
2446        return Err(Error::InvalidArgument("csr2bsr_nnz: block_dim is 0".into()));
2447    }
2448    check_csr_arrays(
2449        "csr2bsr_nnz",
2450        m,
2451        Some(n),
2452        descr.index_base(),
2453        csr_row_ptr,
2454        csr_col_ind,
2455        csr_col_ind.len(),
2456    )?;
2457    check_len(
2458        "csr2bsr_nnz",
2459        "bsr_row_ptr",
2460        bsr_row_ptr.len(),
2461        m.div_ceil(block_dim) + 1,
2462    )?;
2463    let mut bsr_nnz: sys::aoclsparse_int = 0;
2464    let status = unsafe {
2465        sys::aoclsparse_csr2bsr_nnz(
2466            m as sys::aoclsparse_int,
2467            n as sys::aoclsparse_int,
2468            descr.as_raw(),
2469            csr_row_ptr.as_ptr(),
2470            csr_col_ind.as_ptr(),
2471            block_dim as sys::aoclsparse_int,
2472            bsr_row_ptr.as_mut_ptr(),
2473            &mut bsr_nnz,
2474        )
2475    };
2476    check_status("sparse", status)?;
2477    Ok(bsr_nnz as usize)
2478}
2479
2480/// Convert CSR → BSR. Run [`csr2bsr_nnz`] first to size the output. (`f64`)
2481///
2482/// `block_order` is the storage order of the values inside each block. It is a required argument of AOCL-sparse 5.3
2483/// (`aoclsparse_dcsr2bsr`); the 5.1 header the docs.rs bindings came from did not have it.
2484pub fn csr2bsr_f64(
2485    m: usize,
2486    n: usize,
2487    descr: &MatDescr,
2488    block_order: Order,
2489    csr_val: &[f64],
2490    csr_row_ptr: &[sys::aoclsparse_int],
2491    csr_col_ind: &[sys::aoclsparse_int],
2492    block_dim: usize,
2493    bsr_val: &mut [f64],
2494    bsr_row_ptr: &mut [sys::aoclsparse_int],
2495    bsr_col_ind: &mut [sys::aoclsparse_int],
2496) -> Result<()> {
2497    if block_dim == 0 {
2498        return Err(Error::InvalidArgument("csr2bsr: block_dim is 0".into()));
2499    }
2500    check_csr_arrays(
2501        "csr2bsr",
2502        m,
2503        Some(n),
2504        descr.index_base(),
2505        csr_row_ptr,
2506        csr_col_ind,
2507        csr_val.len(),
2508    )?;
2509    let mb = m.div_ceil(block_dim);
2510    check_len("csr2bsr", "bsr_row_ptr", bsr_row_ptr.len(), mb + 1)?;
2511    let mut count_ptr = vec![0 as sys::aoclsparse_int; mb + 1];
2512    let nnzb = csr2bsr_nnz(
2513        m,
2514        n,
2515        descr,
2516        csr_row_ptr,
2517        csr_col_ind,
2518        block_dim,
2519        &mut count_ptr,
2520    )?;
2521    check_len(
2522        "csr2bsr",
2523        "bsr_val",
2524        bsr_val.len(),
2525        nnzb * block_dim * block_dim,
2526    )?;
2527    check_len("csr2bsr", "bsr_col_ind", bsr_col_ind.len(), nnzb)?;
2528    let status = unsafe {
2529        sys::aoclsparse_dcsr2bsr(
2530            m as sys::aoclsparse_int,
2531            n as sys::aoclsparse_int,
2532            descr.as_raw(),
2533            block_order.raw(),
2534            csr_val.as_ptr(),
2535            csr_row_ptr.as_ptr(),
2536            csr_col_ind.as_ptr(),
2537            block_dim as sys::aoclsparse_int,
2538            bsr_val.as_mut_ptr(),
2539            bsr_row_ptr.as_mut_ptr(),
2540            bsr_col_ind.as_mut_ptr(),
2541        )
2542    };
2543    check_status("sparse", status)
2544}
2545
2546/// `f32` CSR → BSR. See [`csr2bsr_f64`].
2547pub fn csr2bsr_f32(
2548    m: usize,
2549    n: usize,
2550    descr: &MatDescr,
2551    block_order: Order,
2552    csr_val: &[f32],
2553    csr_row_ptr: &[sys::aoclsparse_int],
2554    csr_col_ind: &[sys::aoclsparse_int],
2555    block_dim: usize,
2556    bsr_val: &mut [f32],
2557    bsr_row_ptr: &mut [sys::aoclsparse_int],
2558    bsr_col_ind: &mut [sys::aoclsparse_int],
2559) -> Result<()> {
2560    if block_dim == 0 {
2561        return Err(Error::InvalidArgument("csr2bsr: block_dim is 0".into()));
2562    }
2563    check_csr_arrays(
2564        "csr2bsr",
2565        m,
2566        Some(n),
2567        descr.index_base(),
2568        csr_row_ptr,
2569        csr_col_ind,
2570        csr_val.len(),
2571    )?;
2572    let mb = m.div_ceil(block_dim);
2573    check_len("csr2bsr", "bsr_row_ptr", bsr_row_ptr.len(), mb + 1)?;
2574    let mut count_ptr = vec![0 as sys::aoclsparse_int; mb + 1];
2575    let nnzb = csr2bsr_nnz(
2576        m,
2577        n,
2578        descr,
2579        csr_row_ptr,
2580        csr_col_ind,
2581        block_dim,
2582        &mut count_ptr,
2583    )?;
2584    check_len(
2585        "csr2bsr",
2586        "bsr_val",
2587        bsr_val.len(),
2588        nnzb * block_dim * block_dim,
2589    )?;
2590    check_len("csr2bsr", "bsr_col_ind", bsr_col_ind.len(), nnzb)?;
2591    let status = unsafe {
2592        sys::aoclsparse_scsr2bsr(
2593            m as sys::aoclsparse_int,
2594            n as sys::aoclsparse_int,
2595            descr.as_raw(),
2596            block_order.raw(),
2597            csr_val.as_ptr(),
2598            csr_row_ptr.as_ptr(),
2599            csr_col_ind.as_ptr(),
2600            block_dim as sys::aoclsparse_int,
2601            bsr_val.as_mut_ptr(),
2602            bsr_row_ptr.as_mut_ptr(),
2603            bsr_col_ind.as_mut_ptr(),
2604        )
2605    };
2606    check_status("sparse", status)
2607}
2608
2609/// Block-CSR mat-vec with a per-block bitmask. `masks[i]` is a u8 bit
2610/// pattern indicating which rows of block `i` participate. `n_rows_blk`
2611/// is the block height. (`f64`)
2612pub fn blkcsrmv_f64(
2613    op: Trans,
2614    alpha: f64,
2615    m: usize,
2616    n: usize,
2617    masks: &[u8],
2618    csr_val: &[f64],
2619    csr_col_ind: &[sys::aoclsparse_int],
2620    csr_row_ptr: &[sys::aoclsparse_int],
2621    descr: &MatDescr,
2622    x: &[f64],
2623    beta: f64,
2624    y: &mut [f64],
2625    n_rows_blk: usize,
2626) -> Result<()> {
2627    let nnz = csr_val.len();
2628    let status = unsafe {
2629        sys::aoclsparse_dblkcsrmv(
2630            trans_raw(op),
2631            &alpha,
2632            m as sys::aoclsparse_int,
2633            n as sys::aoclsparse_int,
2634            nnz as sys::aoclsparse_int,
2635            masks.as_ptr(),
2636            csr_val.as_ptr(),
2637            csr_col_ind.as_ptr(),
2638            csr_row_ptr.as_ptr(),
2639            descr.as_raw(),
2640            x.as_ptr(),
2641            &beta,
2642            y.as_mut_ptr(),
2643            n_rows_blk as sys::aoclsparse_int,
2644        )
2645    };
2646    check_status("sparse", status)
2647}
2648
2649/// Symmetric Gauss-Seidel sweep `x := x + α · D⁻¹ (b − A·x)` against a
2650/// symmetric matrix handle. (`f64`)
2651///
2652/// **`alpha` (measured, AOCL 6.0.68, docs/SPARSE-WRAPPER-FINDINGS-20261127.md):** the library documents `op(A) x = α b`, but
2653/// from a zero initial guess `x` the result does not depend on `alpha` (α = 1, 2, 3 gave the same `x`); from a non-zero guess it
2654/// does (non-linearly). Do not rely on `alpha` scaling the right-hand side; scale `b` yourself.
2655pub fn symgs_f64(
2656    op: Trans,
2657    a: &SparseMatrix<f64>,
2658    descr: &MatDescr,
2659    alpha: f64,
2660    b: &[f64],
2661    x: &mut [f64],
2662) -> Result<()> {
2663    check_len("symgs_f64", "b", b.len(), a.m)?;
2664    check_len("symgs_f64", "x", x.len(), a.n)?;
2665    let status = unsafe {
2666        sys::aoclsparse_dsymgs(
2667            trans_raw(op),
2668            a.as_raw(),
2669            descr.as_raw(),
2670            alpha,
2671            b.as_ptr(),
2672            x.as_mut_ptr(),
2673        )
2674    };
2675    check_status("sparse", status)
2676}
2677
2678/// `f32` symmetric Gauss-Seidel. See [`symgs_f64`].
2679pub fn symgs_f32(
2680    op: Trans,
2681    a: &SparseMatrix<f32>,
2682    descr: &MatDescr,
2683    alpha: f32,
2684    b: &[f32],
2685    x: &mut [f32],
2686) -> Result<()> {
2687    check_len("symgs_f32", "b", b.len(), a.m)?;
2688    check_len("symgs_f32", "x", x.len(), a.n)?;
2689    let status = unsafe {
2690        sys::aoclsparse_ssymgs(
2691            trans_raw(op),
2692            a.as_raw(),
2693            descr.as_raw(),
2694            alpha,
2695            b.as_ptr(),
2696            x.as_mut_ptr(),
2697        )
2698    };
2699    check_status("sparse", status)
2700}
2701
2702/// Fused Gauss-Seidel + matrix-vector: produces both the updated `x`
2703/// and `y := A·x` in one pass. (`f64`)
2704pub fn symgs_mv_f64(
2705    op: Trans,
2706    a: &SparseMatrix<f64>,
2707    descr: &MatDescr,
2708    alpha: f64,
2709    b: &[f64],
2710    x: &mut [f64],
2711    y: &mut [f64],
2712) -> Result<()> {
2713    check_len("symgs_mv_f64", "b", b.len(), a.m)?;
2714    check_len("symgs_mv_f64", "x", x.len(), a.n)?;
2715    check_len("symgs_mv_f64", "y", y.len(), a.m)?;
2716    let status = unsafe {
2717        sys::aoclsparse_dsymgs_mv(
2718            trans_raw(op),
2719            a.as_raw(),
2720            descr.as_raw(),
2721            alpha,
2722            b.as_ptr(),
2723            x.as_mut_ptr(),
2724            y.as_mut_ptr(),
2725        )
2726    };
2727    check_status("sparse", status)
2728}
2729
2730/// `f32` fused symmetric Gauss-Seidel + mat-vec. See [`symgs_mv_f64`].
2731pub fn symgs_mv_f32(
2732    op: Trans,
2733    a: &SparseMatrix<f32>,
2734    descr: &MatDescr,
2735    alpha: f32,
2736    b: &[f32],
2737    x: &mut [f32],
2738    y: &mut [f32],
2739) -> Result<()> {
2740    check_len("symgs_mv_f32", "b", b.len(), a.m)?;
2741    check_len("symgs_mv_f32", "x", x.len(), a.n)?;
2742    check_len("symgs_mv_f32", "y", y.len(), a.m)?;
2743    let status = unsafe {
2744        sys::aoclsparse_ssymgs_mv(
2745            trans_raw(op),
2746            a.as_raw(),
2747            descr.as_raw(),
2748            alpha,
2749            b.as_ptr(),
2750            x.as_mut_ptr(),
2751            y.as_mut_ptr(),
2752        )
2753    };
2754    check_status("sparse", status)
2755}
2756
2757/// Set a single value at `(row_idx, col_idx)` in a CSR matrix handle.
2758/// Element must already exist in the sparsity pattern. (`f64`)
2759pub fn set_value_f64(
2760    a: &mut SparseMatrix<f64>,
2761    row_idx: i32,
2762    col_idx: i32,
2763    val: f64,
2764) -> Result<()> {
2765    let status = unsafe {
2766        sys::aoclsparse_dset_value(
2767            a.as_raw(),
2768            row_idx as sys::aoclsparse_int,
2769            col_idx as sys::aoclsparse_int,
2770            val,
2771        )
2772    };
2773    check_status("sparse", status)
2774}
2775
2776/// `f32` set_value. See [`set_value_f64`].
2777pub fn set_value_f32(
2778    a: &mut SparseMatrix<f32>,
2779    row_idx: i32,
2780    col_idx: i32,
2781    val: f32,
2782) -> Result<()> {
2783    let status = unsafe {
2784        sys::aoclsparse_sset_value(
2785            a.as_raw(),
2786            row_idx as sys::aoclsparse_int,
2787            col_idx as sys::aoclsparse_int,
2788            val,
2789        )
2790    };
2791    check_status("sparse", status)
2792}
2793
2794/// Update the values array of a CSR handle without rebuilding.
2795/// `len = nnz`; the new values must respect the existing sparsity
2796/// pattern. (`f64`)
2797pub fn update_values_f64(a: &mut SparseMatrix<f64>, val: &mut [f64]) -> Result<()> {
2798    let status = unsafe {
2799        sys::aoclsparse_dupdate_values(
2800            a.as_raw(),
2801            val.len() as sys::aoclsparse_int,
2802            val.as_mut_ptr(),
2803        )
2804    };
2805    check_status("sparse", status)
2806}
2807
2808/// `f32` update_values. See [`update_values_f64`].
2809pub fn update_values_f32(a: &mut SparseMatrix<f32>, val: &mut [f32]) -> Result<()> {
2810    let status = unsafe {
2811        sys::aoclsparse_supdate_values(
2812            a.as_raw(),
2813            val.len() as sys::aoclsparse_int,
2814            val.as_mut_ptr(),
2815        )
2816    };
2817    check_status("sparse", status)
2818}
2819
2820// =========================================================================
2821//   Fused dot + mat-vec, sparse rotations, strided gather/scatter,
2822//   symmetric rank-k, symmetric triple product
2823// =========================================================================
2824
2825/// Fused dot product and mat-vec: `y := α · op(A) · x + β · y` and
2826/// `d := xᵀ · y` (or `d := xᴴ · y` for complex). Saves one pass over
2827/// the matrix versus calling `mv` then `dot` separately. (`f64`)
2828pub fn dotmv_f64(
2829    op: Trans,
2830    alpha: f64,
2831    a: &SparseMatrix<f64>,
2832    descr: &MatDescr,
2833    x: &[f64],
2834    beta: f64,
2835    y: &mut [f64],
2836    d: &mut f64,
2837) -> Result<()> {
2838    let (xl, yl) = mv_lens(op, a.m, a.n);
2839    check_len("dotmv_f64", "x", x.len(), xl)?;
2840    check_len("dotmv_f64", "y", y.len(), yl)?;
2841    let status = unsafe {
2842        sys::aoclsparse_ddotmv(
2843            trans_raw(op),
2844            alpha,
2845            a.as_raw(),
2846            descr.as_raw(),
2847            x.as_ptr(),
2848            beta,
2849            y.as_mut_ptr(),
2850            d,
2851        )
2852    };
2853    check_status("sparse", status)
2854}
2855
2856/// `f32` fused dot + mat-vec. See [`dotmv_f64`].
2857pub fn dotmv_f32(
2858    op: Trans,
2859    alpha: f32,
2860    a: &SparseMatrix<f32>,
2861    descr: &MatDescr,
2862    x: &[f32],
2863    beta: f32,
2864    y: &mut [f32],
2865    d: &mut f32,
2866) -> Result<()> {
2867    let (xl, yl) = mv_lens(op, a.m, a.n);
2868    check_len("dotmv_f32", "x", x.len(), xl)?;
2869    check_len("dotmv_f32", "y", y.len(), yl)?;
2870    let status = unsafe {
2871        sys::aoclsparse_sdotmv(
2872            trans_raw(op),
2873            alpha,
2874            a.as_raw(),
2875            descr.as_raw(),
2876            x.as_ptr(),
2877            beta,
2878            y.as_mut_ptr(),
2879            d,
2880        )
2881    };
2882    check_status("sparse", status)
2883}
2884
2885/// Symmetric rank-k update from a sparse matrix:
2886/// `C := α · op(A) · op(A)ᵀ + β · C` (real) /
2887/// `C := α · op(A) · op(A)ᴴ + β · C` (complex). `C` is dense. (`f64`)
2888pub fn syrkd_f64(
2889    op_a: Trans,
2890    a: &SparseMatrix<f64>,
2891    alpha: f64,
2892    beta: f64,
2893    c: &mut [f64],
2894    order_c: Order,
2895    ldc: usize,
2896) -> Result<()> {
2897    let (r, _) = opdims(op_a, a.m, a.n);
2898    check_dense("syrkd", "C", order_c, r, r, ldc, c.len())?;
2899    let status = unsafe {
2900        sys::aoclsparse_dsyrkd(
2901            trans_raw(op_a),
2902            a.as_raw(),
2903            alpha,
2904            beta,
2905            c.as_mut_ptr(),
2906            order_c.raw(),
2907            ldc as sys::aoclsparse_int,
2908        )
2909    };
2910    check_status("sparse", status)
2911}
2912
2913/// `f32` symmetric rank-k update from sparse `A`. See [`syrkd_f64`].
2914pub fn syrkd_f32(
2915    op_a: Trans,
2916    a: &SparseMatrix<f32>,
2917    alpha: f32,
2918    beta: f32,
2919    c: &mut [f32],
2920    order_c: Order,
2921    ldc: usize,
2922) -> Result<()> {
2923    let (r, _) = opdims(op_a, a.m, a.n);
2924    check_dense("syrkd", "C", order_c, r, r, ldc, c.len())?;
2925    let status = unsafe {
2926        sys::aoclsparse_ssyrkd(
2927            trans_raw(op_a),
2928            a.as_raw(),
2929            alpha,
2930            beta,
2931            c.as_mut_ptr(),
2932            order_c.raw(),
2933            ldc as sys::aoclsparse_int,
2934        )
2935    };
2936    check_status("sparse", status)
2937}
2938
2939/// Symmetric triple product from a sparse `A` and dense `B`:
2940/// `C := α · op(A) · B · op(A)ᵀ + β · C`. (`f64`)
2941pub fn syprd_f64(
2942    op_a: Trans,
2943    a: &SparseMatrix<f64>,
2944    b: &[f64],
2945    order_b: Order,
2946    ldb: usize,
2947    alpha: f64,
2948    beta: f64,
2949    c: &mut [f64],
2950    order_c: Order,
2951    ldc: usize,
2952) -> Result<()> {
2953    let (bd, cd) = if op_a == Trans::No {
2954        (a.n, a.m)
2955    } else {
2956        (a.m, a.n)
2957    };
2958    check_dense("syprd", "B", order_b, bd, bd, ldb, b.len())?;
2959    check_dense("syprd", "C", order_c, cd, cd, ldc, c.len())?;
2960    let status = unsafe {
2961        sys::aoclsparse_dsyprd(
2962            trans_raw(op_a),
2963            a.as_raw(),
2964            b.as_ptr(),
2965            order_b.raw(),
2966            ldb as sys::aoclsparse_int,
2967            alpha,
2968            beta,
2969            c.as_mut_ptr(),
2970            order_c.raw(),
2971            ldc as sys::aoclsparse_int,
2972        )
2973    };
2974    check_status("sparse", status)
2975}
2976
2977/// `f32` symmetric triple product. See [`syprd_f64`].
2978pub fn syprd_f32(
2979    op_a: Trans,
2980    a: &SparseMatrix<f32>,
2981    b: &[f32],
2982    order_b: Order,
2983    ldb: usize,
2984    alpha: f32,
2985    beta: f32,
2986    c: &mut [f32],
2987    order_c: Order,
2988    ldc: usize,
2989) -> Result<()> {
2990    let (bd, cd) = if op_a == Trans::No {
2991        (a.n, a.m)
2992    } else {
2993        (a.m, a.n)
2994    };
2995    check_dense("syprd", "B", order_b, bd, bd, ldb, b.len())?;
2996    check_dense("syprd", "C", order_c, cd, cd, ldc, c.len())?;
2997    let status = unsafe {
2998        sys::aoclsparse_ssyprd(
2999            trans_raw(op_a),
3000            a.as_raw(),
3001            b.as_ptr(),
3002            order_b.raw(),
3003            ldb as sys::aoclsparse_int,
3004            alpha,
3005            beta,
3006            c.as_mut_ptr(),
3007            order_c.raw(),
3008            ldc as sys::aoclsparse_int,
3009        )
3010    };
3011    check_status("sparse", status)
3012}
3013
3014/// Length of `x` and `y` that `op(A)` (`m x n`) needs for a mat-vec: `y := op(A) x` has `m` rows for `op = No` and `n` for `T`/`C`.
3015pub(crate) fn mv_lens(op: Trans, m: usize, n: usize) -> (usize, usize) {
3016    match op {
3017        Trans::No => (n, m),
3018        Trans::T | Trans::C => (m, n),
3019    }
3020}
3021
3022/// The library does not check the length of the dense vectors it is handed (found in review of #45: a short `x` or `y` is read or
3023/// written past its end; access violation on AOCL 6.0.68, `tests/vector_lengths.rs`). `Err` unless `have >= need`.
3024pub(crate) fn check_len(name: &str, what: &str, have: usize, need: usize) -> Result<()> {
3025    if have < need {
3026        return Err(Error::InvalidArgument(format!(
3027            "{name}: {what}.len()={have}, the matrix needs {need}"
3028        )));
3029    }
3030    Ok(())
3031}
3032
3033fn base_offset(base: IndexBase) -> i64 {
3034    match base {
3035        IndexBase::Zero => 0,
3036        IndexBase::One => 1,
3037    }
3038}
3039
3040/// Validate the CSR arrays handed straight to a raw-array routine (no handle: `create_csr` is what refuses a malformed matrix, and
3041/// these routines bypass it): `row_ptr` has `m + 1` entries, is non-decreasing from a non-negative start, its last entry does not
3042/// exceed `col_ind` or `val`, and every column index of a stored entry lies in `[base, base + n)`. The library trusts all of this: a
3043/// column index past `n` or a `row_ptr` entry past the arrays reads outside them (access violation on AOCL 6.0.68,
3044/// `tests/raw_array_lengths.rs`).
3045pub(crate) fn check_csr_arrays(
3046    name: &str,
3047    m: usize,
3048    n: Option<usize>,
3049    base: IndexBase,
3050    row_ptr: &[sys::aoclsparse_int],
3051    col_ind: &[sys::aoclsparse_int],
3052    val_len: usize,
3053) -> Result<()> {
3054    check_len(name, "csr_row_ptr", row_ptr.len(), m + 1)?;
3055    let b = base_offset(base);
3056    let mut prev = i64::MIN;
3057    for &p in &row_ptr[..=m] {
3058        let q = i64::from(p) - b;
3059        if q < 0 || q < prev {
3060            return Err(Error::InvalidArgument(format!(
3061                "{name}: csr_row_ptr is not non-decreasing from the index base ({base:?}): entry {p}"
3062            )));
3063        }
3064        prev = q;
3065    }
3066    let (first, last) = (
3067        (i64::from(row_ptr[0]) - b) as usize,
3068        (i64::from(row_ptr[m]) - b) as usize,
3069    );
3070    if last > col_ind.len() || last > val_len {
3071        return Err(Error::InvalidArgument(format!(
3072            "{name}: csr_row_ptr says {last} stored entries, csr_col_ind has {} and csr_val has {val_len}",
3073            col_ind.len()
3074        )));
3075    }
3076    if let Some(n) = n {
3077        if let Some(&bad) = col_ind[first..last].iter().find(|&&c| {
3078            let q = i64::from(c) - b;
3079            q < 0 || q as usize >= n
3080        }) {
3081            return Err(Error::InvalidArgument(format!(
3082                "{name}: column index {bad} outside [{b}, {}) (n = {n}, base {base:?})",
3083                b + n as i64
3084            )));
3085        }
3086    }
3087    Ok(())
3088}
3089
3090/// Shape of `op(A)` for an `m x n` matrix: `(rows, cols)`.
3091pub(crate) fn opdims(op: Trans, m: usize, n: usize) -> (usize, usize) {
3092    match op {
3093        Trans::No => (m, n),
3094        Trans::T | Trans::C => (n, m),
3095    }
3096}
3097
3098/// Validate a dense `rows x cols` matrix argument with leading dimension `ld` in `order`: `ld` must be at least the minor extent and the
3099/// buffer must hold `(major - 1) * ld + minor` elements. The library does not check this (a buffer one element short is an access
3100/// violation on AOCL 6.0.68, `tests/dense_lengths.rs`). An empty matrix reads nothing.
3101pub(crate) fn check_dense(
3102    name: &str,
3103    what: &str,
3104    order: Order,
3105    rows: usize,
3106    cols: usize,
3107    ld: usize,
3108    len: usize,
3109) -> Result<()> {
3110    if rows == 0 || cols == 0 {
3111        return Ok(());
3112    }
3113    let (major, minor) = match order {
3114        Order::ColMajor => (cols, rows),
3115        Order::RowMajor => (rows, cols),
3116    };
3117    if ld < minor {
3118        return Err(Error::InvalidArgument(format!(
3119            "{name}: {what} has ld={ld}, the {rows}x{cols} {order:?} matrix needs at least {minor}"
3120        )));
3121    }
3122    let need = (major - 1) * ld + minor;
3123    if len < need {
3124        return Err(Error::InvalidArgument(format!(
3125            "{name}: {what}.len()={len}, the {rows}x{cols} {order:?} matrix with ld={ld} needs {need}"
3126        )));
3127    }
3128    Ok(())
3129}
3130
3131/// Validate an index array before the library sees it (found in review of #45: only `roti` was checked). The library does not
3132/// check: a negative or too-large index reads or writes outside the dense vector (heap corruption observed on AOCL 6.0.68), and
3133/// fewer indices than values reads past the end of `indx`. Indices are ZERO-based (these routines take no index-base argument).
3134pub(crate) fn check_index_vector(
3135    name: &str,
3136    nnz: usize,
3137    indx: &[sys::aoclsparse_int],
3138    dense_len: usize,
3139) -> Result<()> {
3140    if indx.len() != nnz {
3141        return Err(Error::InvalidArgument(format!(
3142            "{name}: {nnz} values but {} indices",
3143            indx.len()
3144        )));
3145    }
3146    if let Some(bad) = indx.iter().find(|&&i| i < 0 || (i as usize) >= dense_len) {
3147        return Err(Error::InvalidArgument(format!(
3148            "{name}: index {bad} outside the dense vector (len {dense_len})"
3149        )));
3150    }
3151    Ok(())
3152}
3153
3154/// Validate a strided access `dense[i * stride]` for `i in 0..nnz`: the stride must be positive (the library refuses it otherwise
3155/// too) and the last element must lie inside the dense vector.
3156pub(crate) fn check_stride(name: &str, nnz: usize, stride: i32, dense_len: usize) -> Result<()> {
3157    if nnz == 0 {
3158        return Ok(());
3159    }
3160    if stride <= 0 {
3161        return Err(Error::InvalidArgument(format!(
3162            "{name}: stride {stride} is not positive"
3163        )));
3164    }
3165    let last = (nnz - 1).checked_mul(stride as usize);
3166    if last.map_or(true, |l| l >= dense_len) {
3167        return Err(Error::InvalidArgument(format!(
3168            "{name}: {nnz} elements at stride {stride} do not fit in a dense vector of length {dense_len}"
3169        )));
3170    }
3171    Ok(())
3172}
3173
3174fn check_roti(name: &str, nnz: usize, indx: &[sys::aoclsparse_int], y_len: usize) -> Result<()> {
3175    check_index_vector(name, nnz, indx, y_len)
3176}
3177
3178/// Sparse rotation: simultaneously rotate `(x, y)` at indices `indx`
3179/// by `(c, s)`. `x` is sparse with `indx` indices into the dense `y`. (`f64`)
3180///
3181/// **Index base: zero-based, always.** `aoclsparse_?roti` takes no index-base argument and no descriptor (AOCL guide,
3182/// `aoclsparse_?roti()`: signature `(nnz, x, indx, y, c, s)`; its example uses `indx = {0, 3, 6, 7, 9}`), and the real library
3183/// rotates `y[indx[i]]` with `indx[i]` counted from 0 (measured on AOCL 6.0.68). A one-based vector (indices `1..=len`) is
3184/// therefore rejected with `InvalidArgument` when it reaches index `y.len()`; subtract 1 first.
3185pub fn roti_f64(
3186    x: &mut [f64],
3187    indx: &[sys::aoclsparse_int],
3188    y: &mut [f64],
3189    c: f64,
3190    s: f64,
3191) -> Result<()> {
3192    check_roti("roti_f64", x.len(), indx, y.len())?;
3193    let status = unsafe {
3194        sys::aoclsparse_droti(
3195            x.len() as sys::aoclsparse_int,
3196            x.as_mut_ptr(),
3197            indx.as_ptr(),
3198            y.as_mut_ptr(),
3199            c,
3200            s,
3201        )
3202    };
3203    check_status("sparse", status)
3204}
3205
3206/// `f32` sparse rotation. See [`roti_f64`].
3207pub fn roti_f32(
3208    x: &mut [f32],
3209    indx: &[sys::aoclsparse_int],
3210    y: &mut [f32],
3211    c: f32,
3212    s: f32,
3213) -> Result<()> {
3214    check_roti("roti_f32", x.len(), indx, y.len())?;
3215    let status = unsafe {
3216        sys::aoclsparse_sroti(
3217            x.len() as sys::aoclsparse_int,
3218            x.as_mut_ptr(),
3219            indx.as_ptr(),
3220            y.as_mut_ptr(),
3221            c,
3222            s,
3223        )
3224    };
3225    check_status("sparse", status)
3226}
3227
3228/// Strided sparse gather: `x[i] := y[i · stride]` for `i ∈ [0, nnz)`. (`f64`)
3229pub fn gthrs_f64(y: &[f64], x: &mut [f64], stride: i32) -> Result<()> {
3230    check_stride("gthrs_f64", x.len(), stride, y.len())?;
3231    let status = unsafe {
3232        sys::aoclsparse_dgthrs(
3233            x.len() as sys::aoclsparse_int,
3234            y.as_ptr(),
3235            x.as_mut_ptr(),
3236            stride as sys::aoclsparse_int,
3237        )
3238    };
3239    check_status("sparse", status)
3240}
3241/// `f32` strided gather. See [`gthrs_f64`].
3242pub fn gthrs_f32(y: &[f32], x: &mut [f32], stride: i32) -> Result<()> {
3243    check_stride("gthrs_f32", x.len(), stride, y.len())?;
3244    let status = unsafe {
3245        sys::aoclsparse_sgthrs(
3246            x.len() as sys::aoclsparse_int,
3247            y.as_ptr(),
3248            x.as_mut_ptr(),
3249            stride as sys::aoclsparse_int,
3250        )
3251    };
3252    check_status("sparse", status)
3253}
3254
3255/// Strided sparse scatter: `y[i · stride] := x[i]`. (`f64`)
3256pub fn sctrs_f64(x: &[f64], y: &mut [f64], stride: i32) -> Result<()> {
3257    check_stride("sctrs_f64", x.len(), stride, y.len())?;
3258    let status = unsafe {
3259        sys::aoclsparse_dsctrs(
3260            x.len() as sys::aoclsparse_int,
3261            x.as_ptr(),
3262            stride as sys::aoclsparse_int,
3263            y.as_mut_ptr(),
3264        )
3265    };
3266    check_status("sparse", status)
3267}
3268/// `f32` strided scatter. See [`sctrs_f64`].
3269pub fn sctrs_f32(x: &[f32], y: &mut [f32], stride: i32) -> Result<()> {
3270    check_stride("sctrs_f32", x.len(), stride, y.len())?;
3271    let status = unsafe {
3272        sys::aoclsparse_ssctrs(
3273            x.len() as sys::aoclsparse_int,
3274            x.as_ptr(),
3275            stride as sys::aoclsparse_int,
3276            y.as_mut_ptr(),
3277        )
3278    };
3279    check_status("sparse", status)
3280}
3281
3282/// Gather-and-zero: copy `y[indx[i]]` into `x[i]` and zero the source.
3283/// (`f64`)
3284pub fn gthrz_f64(y: &mut [f64], indx: &[sys::aoclsparse_int], x: &mut [f64]) -> Result<()> {
3285    check_index_vector("gthrz_f64", x.len(), indx, y.len())?;
3286    let status = unsafe {
3287        sys::aoclsparse_dgthrz(
3288            x.len() as sys::aoclsparse_int,
3289            y.as_mut_ptr(),
3290            x.as_mut_ptr(),
3291            indx.as_ptr(),
3292        )
3293    };
3294    check_status("sparse", status)
3295}
3296/// `f32` gather-and-zero. See [`gthrz_f64`].
3297pub fn gthrz_f32(y: &mut [f32], indx: &[sys::aoclsparse_int], x: &mut [f32]) -> Result<()> {
3298    check_index_vector("gthrz_f32", x.len(), indx, y.len())?;
3299    let status = unsafe {
3300        sys::aoclsparse_sgthrz(
3301            x.len() as sys::aoclsparse_int,
3302            y.as_mut_ptr(),
3303            x.as_mut_ptr(),
3304            indx.as_ptr(),
3305        )
3306    };
3307    check_status("sparse", status)
3308}
3309
3310/// `f32` SOR / forward / backward Gauss-Seidel sweep. The existing
3311/// generic [`sorv`] dispatches to this via the Scalar trait; this is
3312/// a per-precision direct alias.
3313pub fn sorv_f32(
3314    sor_type: SorType,
3315    descr: &MatDescr,
3316    a: &SparseMatrix<f32>,
3317    omega: f32,
3318    alpha: f32,
3319    x: &mut [f32],
3320    b: &[f32],
3321) -> Result<()> {
3322    if x.len() < a.dims().1 || b.len() < a.dims().0 {
3323        return Err(Error::InvalidArgument(format!(
3324            "sorv_f32: x.len()={}, b.len()={}, dims=({}, {})",
3325            x.len(),
3326            b.len(),
3327            a.dims().0,
3328            a.dims().1
3329        )));
3330    }
3331    let status = unsafe {
3332        sys::aoclsparse_ssorv(
3333            sor_type.raw(),
3334            descr.as_raw(),
3335            a.as_raw(),
3336            omega,
3337            alpha,
3338            x.as_mut_ptr(),
3339            b.as_ptr(),
3340        )
3341    };
3342    check_status("sparse", status)
3343}
3344
3345// =========================================================================
3346//   TCSR (triangular CSR): two parallel CSRs, one for L, one for U
3347// =========================================================================
3348
3349/// Build a TCSR matrix handle from two CSR sub-arrays describing the
3350/// strict-lower (`*_L`) and strict-upper (`*_U`) parts. (`f64`)
3351pub fn create_tcsr_f64(
3352    base: IndexBase,
3353    m: usize,
3354    n: usize,
3355    nnz: usize,
3356    row_ptr_l: &mut [sys::aoclsparse_int],
3357    row_ptr_u: &mut [sys::aoclsparse_int],
3358    col_idx_l: &mut [sys::aoclsparse_int],
3359    col_idx_u: &mut [sys::aoclsparse_int],
3360    val_l: &mut [f64],
3361    val_u: &mut [f64],
3362) -> Result<sys::aoclsparse_matrix> {
3363    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
3364    let status = unsafe {
3365        sys::aoclsparse_create_dtcsr(
3366            &mut raw,
3367            base.raw(),
3368            m as sys::aoclsparse_int,
3369            n as sys::aoclsparse_int,
3370            nnz as sys::aoclsparse_int,
3371            row_ptr_l.as_mut_ptr(),
3372            row_ptr_u.as_mut_ptr(),
3373            col_idx_l.as_mut_ptr(),
3374            col_idx_u.as_mut_ptr(),
3375            val_l.as_mut_ptr(),
3376            val_u.as_mut_ptr(),
3377        )
3378    };
3379    check_status("sparse", status)?;
3380    if raw.is_null() {
3381        return Err(Error::AllocationFailed("sparse"));
3382    }
3383    Ok(raw)
3384}
3385
3386/// `f32` TCSR creator. See [`create_tcsr_f64`].
3387pub fn create_tcsr_f32(
3388    base: IndexBase,
3389    m: usize,
3390    n: usize,
3391    nnz: usize,
3392    row_ptr_l: &mut [sys::aoclsparse_int],
3393    row_ptr_u: &mut [sys::aoclsparse_int],
3394    col_idx_l: &mut [sys::aoclsparse_int],
3395    col_idx_u: &mut [sys::aoclsparse_int],
3396    val_l: &mut [f32],
3397    val_u: &mut [f32],
3398) -> Result<sys::aoclsparse_matrix> {
3399    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
3400    let status = unsafe {
3401        sys::aoclsparse_create_stcsr(
3402            &mut raw,
3403            base.raw(),
3404            m as sys::aoclsparse_int,
3405            n as sys::aoclsparse_int,
3406            nnz as sys::aoclsparse_int,
3407            row_ptr_l.as_mut_ptr(),
3408            row_ptr_u.as_mut_ptr(),
3409            col_idx_l.as_mut_ptr(),
3410            col_idx_u.as_mut_ptr(),
3411            val_l.as_mut_ptr(),
3412            val_u.as_mut_ptr(),
3413        )
3414    };
3415    check_status("sparse", status)?;
3416    if raw.is_null() {
3417        return Err(Error::AllocationFailed("sparse"));
3418    }
3419    Ok(raw)
3420}
3421
3422// =========================================================================
3423//   CSC creators (real)
3424// =========================================================================
3425
3426/// Build a CSC matrix handle. Column-major analogue of CSR. (`f64`)
3427pub fn create_csc_f64(
3428    base: IndexBase,
3429    m: usize,
3430    n: usize,
3431    nnz: usize,
3432    col_ptr: &mut [sys::aoclsparse_int],
3433    row_idx: &mut [sys::aoclsparse_int],
3434    val: &mut [f64],
3435) -> Result<sys::aoclsparse_matrix> {
3436    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
3437    let status = unsafe {
3438        sys::aoclsparse_create_dcsc(
3439            &mut raw,
3440            base.raw(),
3441            m as sys::aoclsparse_int,
3442            n as sys::aoclsparse_int,
3443            nnz as sys::aoclsparse_int,
3444            col_ptr.as_mut_ptr(),
3445            row_idx.as_mut_ptr(),
3446            val.as_mut_ptr(),
3447        )
3448    };
3449    check_status("sparse", status)?;
3450    if raw.is_null() {
3451        return Err(Error::AllocationFailed("sparse"));
3452    }
3453    Ok(raw)
3454}
3455/// `f32` CSC creator. See [`create_csc_f64`].
3456pub fn create_csc_f32(
3457    base: IndexBase,
3458    m: usize,
3459    n: usize,
3460    nnz: usize,
3461    col_ptr: &mut [sys::aoclsparse_int],
3462    row_idx: &mut [sys::aoclsparse_int],
3463    val: &mut [f32],
3464) -> Result<sys::aoclsparse_matrix> {
3465    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
3466    let status = unsafe {
3467        sys::aoclsparse_create_scsc(
3468            &mut raw,
3469            base.raw(),
3470            m as sys::aoclsparse_int,
3471            n as sys::aoclsparse_int,
3472            nnz as sys::aoclsparse_int,
3473            col_ptr.as_mut_ptr(),
3474            row_idx.as_mut_ptr(),
3475            val.as_mut_ptr(),
3476        )
3477    };
3478    check_status("sparse", status)?;
3479    if raw.is_null() {
3480        return Err(Error::AllocationFailed("sparse"));
3481    }
3482    Ok(raw)
3483}
3484
3485/// Memory-usage hint to give the analysis pass.
3486#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3487pub enum MemoryUsage {
3488    /// Minimise extra memory; favour smaller working sets.
3489    Minimal,
3490    /// Allow the library to use additional memory if it speeds things up.
3491    Unrestricted,
3492}
3493
3494impl MemoryUsage {
3495    fn raw(self) -> sys::aoclsparse_memory_usage {
3496        match self {
3497            MemoryUsage::Minimal => sys::aoclsparse_memory_usage__aoclsparse_memory_usage_minimal,
3498            MemoryUsage::Unrestricted => {
3499                sys::aoclsparse_memory_usage__aoclsparse_memory_usage_unrestricted
3500            }
3501        }
3502    }
3503}
3504
3505/// Tell the library how much extra memory it may consume on this
3506/// matrix. Pair with [`optimize`].
3507pub fn set_memory_hint<T: Scalar>(mat: &mut SparseMatrix<T>, policy: MemoryUsage) -> Result<()> {
3508    let status = unsafe { sys::aoclsparse_set_memory_hint(mat.as_raw(), policy.raw()) };
3509    check_status("sparse", status)
3510}
3511
3512/// Apply one ILU(0) smoothing step in-place to `x`, with right-hand side `b`.
3513///
3514/// On the first call against a matrix this also factorizes; subsequent
3515/// calls re-use the cached factors stored on the matrix handle.
3516pub fn ilu_smoother<T: Scalar>(
3517    op: Trans,
3518    a: &SparseMatrix<T>,
3519    descr: &MatDescr,
3520    x: &mut [T],
3521    b: &[T],
3522) -> Result<()> {
3523    if x.len() < a.n || b.len() < a.m {
3524        return Err(Error::InvalidArgument(format!(
3525            "ilu_smoother: x.len()={}, b.len()={}, dims=({}, {})",
3526            x.len(),
3527            b.len(),
3528            a.m,
3529            a.n
3530        )));
3531    }
3532    T::ilu_smoother(op, a.raw, descr, x, b)
3533}
3534
3535// =========================================================================
3536//   Iterative solver (CG / GMRES) — direct interface
3537// =========================================================================
3538
3539/// RAII handle for the AOCL-Sparse iterative-solver suite.
3540///
3541/// Configure the solver type and tolerances with [`IterSolver::set_option`]
3542/// (e.g. `set_option("iterative method", "cg")` or `"gmres"`), then call
3543/// [`IterSolver::solve`] with the system matrix and right-hand side.
3544pub struct IterSolver<T: Scalar> {
3545    handle: sys::aoclsparse_itsol_handle,
3546    _marker: PhantomData<T>,
3547}
3548
3549impl<T: Scalar> IterSolver<T> {
3550    /// Initialise a new iterative-solver handle for this scalar type.
3551    pub fn new() -> Result<Self> {
3552        let mut handle: sys::aoclsparse_itsol_handle = std::ptr::null_mut();
3553        T::itsol_init(&mut handle)?;
3554        if handle.is_null() {
3555            return Err(Error::AllocationFailed("sparse"));
3556        }
3557        Ok(Self {
3558            handle,
3559            _marker: PhantomData,
3560        })
3561    }
3562
3563    /// Set a string-keyed solver option. See AOCL-Sparse's
3564    /// `aoclsparse_itsol_option_set` for the full option list. Common
3565    /// keys: `"iterative method"` (`"cg"`/`"gmres"`/`"pcg"`), `"cg
3566    /// iteration limit"`, `"cg rel tolerance"`, `"gmres preconditioner"`.
3567    pub fn set_option(&mut self, name: &str, value: &str) -> Result<()> {
3568        let c_name = CString::new(name)
3569            .map_err(|_| Error::InvalidArgument("set_option: name has interior NUL".into()))?;
3570        let c_value = CString::new(value)
3571            .map_err(|_| Error::InvalidArgument("set_option: value has interior NUL".into()))?;
3572        let status = unsafe {
3573            sys::aoclsparse_itsol_option_set(self.handle, c_name.as_ptr(), c_value.as_ptr())
3574        };
3575        check_status("sparse", status)
3576    }
3577
3578    /// Solve `A · x = b`. On entry `x` should hold an initial guess (zero
3579    /// is fine if you have nothing better); on success it contains the
3580    /// approximate solution. Returns the solver's `rinfo[100]` array of
3581    /// statistics (iteration counts, residual norms, etc.).
3582    pub fn solve(
3583        &mut self,
3584        mat: &SparseMatrix<T>,
3585        descr: &MatDescr,
3586        b: &[T],
3587        x: &mut [T],
3588    ) -> Result<Box<[T; 100]>>
3589    where
3590        T: Default,
3591    {
3592        let n = mat.n;
3593        if mat.m != mat.n {
3594            return Err(Error::InvalidArgument(format!(
3595                "iterative solve requires square matrix; got ({}, {})",
3596                mat.m, mat.n
3597            )));
3598        }
3599        let mut rinfo: Box<[T; 100]> = Box::new([T::default(); 100]);
3600        T::itsol_solve(self.handle, n, mat.raw, descr, b, x, &mut rinfo)?;
3601        Ok(rinfo)
3602    }
3603}
3604
3605impl<T: Scalar> Drop for IterSolver<T> {
3606    fn drop(&mut self) {
3607        if !self.handle.is_null() {
3608            unsafe {
3609                sys::aoclsparse_itsol_destroy(&mut self.handle);
3610            }
3611            self.handle = std::ptr::null_mut();
3612        }
3613    }
3614}
3615
3616impl<T: Scalar> std::fmt::Debug for IterSolver<T> {
3617    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3618        f.debug_struct("IterSolver").finish_non_exhaustive()
3619    }
3620}
3621
3622#[cfg(test)]
3623mod tests {
3624    use super::*;
3625
3626    #[test]
3627    fn csrmv_2x2_identity_f64() {
3628        let val = [1.0_f64, 1.0];
3629        let col: [sys::aoclsparse_int; 2] = [0, 1];
3630        let rowptr: [sys::aoclsparse_int; 3] = [0, 1, 2];
3631        let x = [3.0_f64, 4.0];
3632        let mut y = [0.0_f64; 2];
3633        let descr = MatDescr::new().unwrap();
3634        csrmv(1.0_f64, 2, 2, &val, &col, &rowptr, &descr, &x, 0.0, &mut y).unwrap();
3635        assert!((y[0] - 3.0).abs() < 1e-12);
3636        assert!((y[1] - 4.0).abs() < 1e-12);
3637    }
3638
3639    #[test]
3640    fn csrmv_simple_2x3() {
3641        let val = [1.0_f64, 2.0, 3.0];
3642        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3643        let rowptr: [sys::aoclsparse_int; 3] = [0, 2, 3];
3644        let x = [1.0_f64; 3];
3645        let mut y = [0.0_f64; 2];
3646        let descr = MatDescr::new().unwrap();
3647        csrmv(1.0_f64, 2, 3, &val, &col, &rowptr, &descr, &x, 0.0, &mut y).unwrap();
3648        assert!((y[0] - 3.0).abs() < 1e-12, "got {}", y[0]);
3649        assert!((y[1] - 3.0).abs() < 1e-12, "got {}", y[1]);
3650    }
3651
3652    #[test]
3653    fn dim_mismatch_is_error() {
3654        let val = [1.0_f64];
3655        let col: [sys::aoclsparse_int; 1] = [0];
3656        let rowptr: [sys::aoclsparse_int; 2] = [0, 1];
3657        let x = [1.0_f64];
3658        let mut y = [0.0_f64; 2];
3659        let descr = MatDescr::new().unwrap();
3660        let err = csrmv(1.0_f64, 2, 1, &val, &col, &rowptr, &descr, &x, 0.0, &mut y).unwrap_err();
3661        matches!(err, Error::InvalidArgument(_));
3662    }
3663
3664    #[test]
3665    fn axpyi_scatter() {
3666        // y = [10, 20, 30, 40], x = [1, 2], indx = [0, 2], α = 3
3667        // → y[0] += 3·1 = 13; y[2] += 3·2 = 36
3668        let mut y = [10.0_f64, 20.0, 30.0, 40.0];
3669        let x = [1.0_f64, 2.0];
3670        let indx: [sys::aoclsparse_int; 2] = [0, 2];
3671        axpyi(3.0_f64, &x, &indx, &mut y).unwrap();
3672        assert_eq!(y, [13.0, 20.0, 36.0, 40.0]);
3673    }
3674
3675    #[test]
3676    fn gthr_scatter_round_trip() {
3677        // Gather from y at indx → x; scatter x at indx → into a fresh y2.
3678        let y = [10.0_f64, 20.0, 30.0, 40.0];
3679        let indx: [sys::aoclsparse_int; 2] = [1, 3];
3680        let mut x = [0.0_f64; 2];
3681        gthr(&y, &indx, &mut x).unwrap();
3682        assert_eq!(x, [20.0, 40.0]);
3683
3684        let mut y2 = [0.0_f64; 4];
3685        sctr(&x, &indx, &mut y2).unwrap();
3686        assert_eq!(y2, [0.0, 20.0, 0.0, 40.0]);
3687    }
3688
3689    #[test]
3690    fn add_identity_plus_identity_is_2_diag() {
3691        // A = B = 2x2 identity; C = 1·A + B = 2·I.
3692        let val = [1.0_f64, 1.0];
3693        let col: [sys::aoclsparse_int; 2] = [0, 1];
3694        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
3695        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val).unwrap();
3696        let b = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val).unwrap();
3697        let c = add(Trans::No, &a, 1.0, &b).unwrap();
3698        let (_, _, _, val_c) = c.export_csr().unwrap();
3699        // Both diagonal entries should equal 2.
3700        assert_eq!(val_c.len(), 2);
3701        for v in &val_c {
3702            assert!((v - 2.0).abs() < 1e-12, "got {v}, want 2.0");
3703        }
3704    }
3705
3706    #[test]
3707    fn csrmm_2x2_identity_against_2x3_dense() {
3708        // 2×2 identity sparse A; 2×3 dense B; C = A · B should equal B.
3709        // Row-major: ldb = ldc = 3.
3710        let val = [1.0_f64, 1.0];
3711        let col: [sys::aoclsparse_int; 2] = [0, 1];
3712        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
3713        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val).unwrap();
3714        let descr = MatDescr::new().unwrap();
3715        let b: [f64; 6] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
3716        let mut c = [0.0_f64; 6];
3717        csrmm(
3718            Trans::No,
3719            1.0,
3720            &a,
3721            &descr,
3722            Order::RowMajor,
3723            &b,
3724            3,
3725            3,
3726            0.0,
3727            &mut c,
3728            3,
3729        )
3730        .unwrap();
3731        for (got, want) in c.iter().zip(b.iter()) {
3732            assert!((got - want).abs() < 1e-12, "got {got}, want {want}");
3733        }
3734    }
3735
3736    #[test]
3737    fn spmmd_identity_squared_yields_identity_dense() {
3738        // 3×3 identity * 3×3 identity = 3×3 identity dense.
3739        let val = [1.0_f64; 3];
3740        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3741        let rp: [sys::aoclsparse_int; 4] = [0, 1, 2, 3];
3742        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3743        let b = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3744        let mut c = [0.0_f64; 9];
3745        spmmd(Trans::No, &a, &b, Order::RowMajor, &mut c, 3).unwrap();
3746        // Row-major identity matrix.
3747        let expected = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
3748        for (got, want) in c.iter().zip(expected.iter()) {
3749            assert!((got - want).abs() < 1e-12, "got {got}, want {want}");
3750        }
3751    }
3752
3753    #[test]
3754    fn ellmv_2x3_f64() {
3755        // 2×3: [[1, 0, 2], [3, 4, 0]]; ell_width = 2 (max nnz/row).
3756        // Padding indices/values for the "missing" slot use index 0, value 0.
3757        let val: [f64; 4] = [1.0, 2.0, 3.0, 4.0];
3758        let col: [sys::aoclsparse_int; 4] = [0, 2, 0, 1];
3759        let descr = MatDescr::new().unwrap();
3760        let x = [10.0_f64, 20.0, 30.0];
3761        let mut y = [0.0_f64; 2];
3762        ellmv(
3763            Trans::No,
3764            1.0_f64,
3765            2,
3766            3,
3767            &val,
3768            &col,
3769            2,
3770            &descr,
3771            &x,
3772            0.0,
3773            &mut y,
3774        )
3775        .unwrap();
3776        // y[0] = 1*10 + 2*30 = 70; y[1] = 3*10 + 4*20 = 110
3777        assert!((y[0] - 70.0).abs() < 1e-12, "got {}", y[0]);
3778        assert!((y[1] - 110.0).abs() < 1e-12, "got {}", y[1]);
3779    }
3780
3781    #[test]
3782    fn bsrmv_2x2_blocks_f64() {
3783        // 4×4 matrix laid out as 2×2 blocks of size 2×2:
3784        // block (0,0) = [[1,0],[0,1]] (identity), block (1,1) = [[2,0],[0,2]]
3785        // bsr_dim = 2, mb = 2, nb = 2, nnzb = 2
3786        let val: [f64; 8] = [1.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 2.0];
3787        let col: [sys::aoclsparse_int; 2] = [0, 1];
3788        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
3789        let descr = MatDescr::new().unwrap();
3790        let x = [1.0_f64, 2.0, 3.0, 4.0];
3791        let mut y = [0.0_f64; 4];
3792        bsrmv(
3793            Trans::No,
3794            1.0_f64,
3795            2,
3796            2,
3797            2,
3798            &val,
3799            &col,
3800            &rp,
3801            &descr,
3802            &x,
3803            0.0,
3804            &mut y,
3805        )
3806        .unwrap();
3807        // y = diag([1,1,2,2]) * x = [1, 2, 6, 8]
3808        assert!((y[0] - 1.0).abs() < 1e-12);
3809        assert!((y[1] - 2.0).abs() < 1e-12);
3810        assert!((y[2] - 6.0).abs() < 1e-12);
3811        assert!((y[3] - 8.0).abs() < 1e-12);
3812    }
3813
3814    #[test]
3815    fn sparse_matrix_round_trip() {
3816        // 2×3 matrix [[1,0,2],[0,3,0]]
3817        let val = [1.0_f64, 2.0, 3.0];
3818        let col: [sys::aoclsparse_int; 3] = [0, 2, 1];
3819        let rp: [sys::aoclsparse_int; 3] = [0, 2, 3];
3820        let mat = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 3, &rp, &col, &val).unwrap();
3821        assert_eq!(mat.dims(), (2, 3));
3822        assert_eq!(mat.nnz(), 3);
3823        assert_eq!(mat.base(), IndexBase::Zero);
3824        let (base, rp2, col2, val2) = mat.export_csr().unwrap();
3825        assert_eq!(base, IndexBase::Zero);
3826        assert_eq!(rp2, [0, 2, 3]);
3827        assert_eq!(col2, [0, 2, 1]);
3828        assert_eq!(val2, [1.0, 2.0, 3.0]);
3829    }
3830
3831    #[test]
3832    fn csr2m_identity_squared_is_identity() {
3833        // 3×3 identity in CSR.
3834        let val = [1.0_f64; 3];
3835        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3836        let rp: [sys::aoclsparse_int; 4] = [0, 1, 2, 3];
3837        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3838        let b = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3839        let descr = MatDescr::new().unwrap();
3840        let c = csr2m(
3841            Trans::No,
3842            &descr,
3843            &a,
3844            Trans::No,
3845            &descr,
3846            &b,
3847            Stage::FullComputation,
3848        )
3849        .unwrap();
3850        assert_eq!(c.dims(), (3, 3));
3851        let (_, rp_c, col_c, val_c) = c.export_csr().unwrap();
3852        assert_eq!(rp_c, [0, 1, 2, 3]);
3853        assert_eq!(col_c, [0, 1, 2]);
3854        for v in &val_c {
3855            assert!((v - 1.0).abs() < 1e-12);
3856        }
3857    }
3858
3859    #[test]
3860    fn iter_solver_cg_diagonal_3x3() {
3861        // Solve diag(2,2,2) · x = b, with b = [4, 6, 10]; expected x = [2, 3, 5].
3862        let val = [2.0_f64, 2.0, 2.0];
3863        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3864        let rp: [sys::aoclsparse_int; 4] = [0, 1, 2, 3];
3865        let mat = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3866
3867        let descr = MatDescr::new().unwrap();
3868        unsafe {
3869            sys::aoclsparse_set_mat_type(
3870                descr.as_raw(),
3871                sys::aoclsparse_matrix_type__aoclsparse_matrix_type_symmetric,
3872            );
3873        }
3874
3875        let b = [4.0_f64, 6.0, 10.0];
3876        let mut x = [0.0_f64; 3];
3877        let mut solver = IterSolver::<f64>::new().unwrap();
3878        solver.set_option("iterative method", "cg").unwrap();
3879        solver.set_option("cg rel tolerance", "1e-10").unwrap();
3880        solver.set_option("cg iteration limit", "200").unwrap();
3881        solver.solve(&mat, &descr, &b, &mut x).unwrap();
3882        assert!((x[0] - 2.0).abs() < 1e-6, "x[0] = {}", x[0]);
3883        assert!((x[1] - 3.0).abs() < 1e-6, "x[1] = {}", x[1]);
3884        assert!((x[2] - 5.0).abs() < 1e-6, "x[2] = {}", x[2]);
3885    }
3886
3887    /// 4x4 CSR with two diagonal 2x2 blocks, `[[1,2],[3,4]]` and `[[5,6],[7,8]]`: asymmetric inside each block, so
3888    /// the in-block storage order shows in `bsr_val` (row-major 1,2,3,4 / column-major 1,3,2,4).
3889    #[test]
3890    fn csr2bsr_block_order_f64_and_f32() {
3891        let col: [sys::aoclsparse_int; 8] = [0, 1, 0, 1, 2, 3, 2, 3];
3892        let rowptr: [sys::aoclsparse_int; 5] = [0, 2, 4, 6, 8];
3893        let descr = MatDescr::new().unwrap();
3894        let mut bsr_rowptr = [0 as sys::aoclsparse_int; 3];
3895        let nnzb = csr2bsr_nnz(4, 4, &descr, &rowptr, &col, 2, &mut bsr_rowptr).unwrap();
3896        assert_eq!(nnzb, 2);
3897        assert_eq!(bsr_rowptr, [0, 1, 2]);
3898
3899        let val64: Vec<f64> = (1..=8).map(f64::from).collect();
3900        let val32: Vec<f32> = (1..=8).map(|v| v as f32).collect();
3901        let row_major = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
3902        let col_major = [1.0, 3.0, 2.0, 4.0, 5.0, 7.0, 6.0, 8.0];
3903        for (order, want) in [(Order::RowMajor, row_major), (Order::ColMajor, col_major)] {
3904            let mut rp = bsr_rowptr; // `bsr_row_ptr` comes from the `csr2bsr_nnz` step
3905            let mut ci = [0 as sys::aoclsparse_int; 2];
3906            let mut bv = [0.0_f64; 8];
3907            csr2bsr_f64(
3908                4, 4, &descr, order, &val64, &rowptr, &col, 2, &mut bv, &mut rp, &mut ci,
3909            )
3910            .unwrap();
3911            assert_eq!((rp, ci), ([0, 1, 2], [0, 1]), "{order:?}");
3912            assert_eq!(bv, want, "f64 {order:?}");
3913
3914            let mut rp = bsr_rowptr; // `bsr_row_ptr` comes from the `csr2bsr_nnz` step
3915            let mut ci = [0 as sys::aoclsparse_int; 2];
3916            let mut bv = [0.0_f32; 8];
3917            csr2bsr_f32(
3918                4, 4, &descr, order, &val32, &rowptr, &col, 2, &mut bv, &mut rp, &mut ci,
3919            )
3920            .unwrap();
3921            let want32: Vec<f32> = want.iter().map(|&v| v as f32).collect();
3922            assert_eq!(bv.to_vec(), want32, "f32 {order:?}");
3923        }
3924    }
3925
3926    #[test]
3927    fn csr_to_dense_round_trip() {
3928        // 2×3 CSR: [[1,0,2],[0,3,0]] → val=[1,2,3], col=[0,2,1], rp=[0,2,3]
3929        let val = [1.0_f64, 2.0, 3.0];
3930        let col: [sys::aoclsparse_int; 3] = [0, 2, 1];
3931        let rp: [sys::aoclsparse_int; 3] = [0, 2, 3];
3932        let descr = MatDescr::new().unwrap();
3933        let mut dense = [0.0_f64; 6];
3934        csr_to_dense::<f64>(
3935            2,
3936            3,
3937            &descr,
3938            &val,
3939            &rp,
3940            &col,
3941            &mut dense,
3942            3,
3943            Order::RowMajor,
3944        )
3945        .unwrap();
3946        assert_eq!(dense, [1.0, 0.0, 2.0, 0.0, 3.0, 0.0]);
3947    }
3948}