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    T::csrmv(
1220        Trans::No,
1221        alpha,
1222        m,
1223        n,
1224        csr_val,
1225        csr_col_ind,
1226        csr_row_ptr,
1227        descr,
1228        x,
1229        beta,
1230        y,
1231    )
1232}
1233
1234// =========================================================================
1235//   Sparse vector operations (axpyi, gather/scatter)
1236// =========================================================================
1237
1238/// Sparse `y[indx] := α·x + y[indx]` (sparse vector AXPY).
1239///
1240/// `x` and `indx` must have equal length (`nnz`); each `indx[i]` indexes
1241/// into `y`.
1242pub fn axpyi<T: Scalar>(
1243    alpha: T,
1244    x: &[T],
1245    indx: &[sys::aoclsparse_int],
1246    y: &mut [T],
1247) -> Result<()> {
1248    if x.len() != indx.len() {
1249        return Err(Error::InvalidArgument(format!(
1250            "axpyi: x.len()={}, indx.len()={}",
1251            x.len(),
1252            indx.len()
1253        )));
1254    }
1255    T::axpyi(alpha, x, indx, y)
1256}
1257
1258/// Sparse gather: `x[i] := y[indx[i]]` for `i ∈ [0, nnz)`.
1259pub fn gthr<T: Scalar>(y: &[T], indx: &[sys::aoclsparse_int], x: &mut [T]) -> Result<()> {
1260    if x.len() != indx.len() {
1261        return Err(Error::InvalidArgument(format!(
1262            "gthr: x.len()={}, indx.len()={}",
1263            x.len(),
1264            indx.len()
1265        )));
1266    }
1267    T::gthr(y, indx, x)
1268}
1269
1270/// Sparse scatter: `y[indx[i]] := x[i]` for `i ∈ [0, nnz)`.
1271pub fn sctr<T: Scalar>(x: &[T], indx: &[sys::aoclsparse_int], y: &mut [T]) -> Result<()> {
1272    if x.len() != indx.len() {
1273        return Err(Error::InvalidArgument(format!(
1274            "sctr: x.len()={}, indx.len()={}",
1275            x.len(),
1276            indx.len()
1277        )));
1278    }
1279    T::sctr(x, indx, y)
1280}
1281
1282// =========================================================================
1283//   Sparse triangular solve (csrsv)
1284// =========================================================================
1285
1286/// Solve `op(A) · y = α · x` where `A` is sparse triangular in CSR
1287/// format. The triangle is determined by the `descr`'s fill mode (set
1288/// via the `aoclsparse_set_mat_*` C-API; defaults to upper, non-unit).
1289pub fn csrsv<T: Scalar>(
1290    op: Trans,
1291    alpha: T,
1292    m: usize,
1293    csr_val: &[T],
1294    csr_col_ind: &[sys::aoclsparse_int],
1295    csr_row_ptr: &[sys::aoclsparse_int],
1296    descr: &MatDescr,
1297    x: &[T],
1298    y: &mut [T],
1299) -> Result<()> {
1300    T::csrsv(op, alpha, m, csr_val, csr_col_ind, csr_row_ptr, descr, x, y)
1301}
1302
1303// =========================================================================
1304//   Format conversion: csr → dense, csr → csc
1305// =========================================================================
1306
1307/// Storage order used when converting from CSR to a dense matrix.
1308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1309pub enum Order {
1310    RowMajor,
1311    ColMajor,
1312}
1313
1314impl Order {
1315    pub(crate) fn raw(self) -> sys::aoclsparse_order {
1316        match self {
1317            Order::RowMajor => sys::aoclsparse_order__aoclsparse_order_row,
1318            Order::ColMajor => sys::aoclsparse_order__aoclsparse_order_column,
1319        }
1320    }
1321}
1322
1323/// Convert a CSR sparse matrix to a dense `m × n` matrix in `out`.
1324pub fn csr_to_dense<T: Scalar>(
1325    m: usize,
1326    n: usize,
1327    descr: &MatDescr,
1328    csr_val: &[T],
1329    csr_row_ptr: &[sys::aoclsparse_int],
1330    csr_col_ind: &[sys::aoclsparse_int],
1331    a: &mut [T],
1332    ld: usize,
1333    order: Order,
1334) -> Result<()> {
1335    if csr_row_ptr.len() != m + 1 {
1336        return Err(Error::InvalidArgument(format!(
1337            "csr_to_dense: csr_row_ptr length {} != m+1 = {}",
1338            csr_row_ptr.len(),
1339            m + 1
1340        )));
1341    }
1342    let needed = match order {
1343        Order::RowMajor => m.saturating_sub(1) * ld + n,
1344        Order::ColMajor => n.saturating_sub(1) * ld + m,
1345    };
1346    if a.len() < needed {
1347        return Err(Error::InvalidArgument(format!(
1348            "csr_to_dense: A length {} < needed {needed}",
1349            a.len()
1350        )));
1351    }
1352    T::csr_to_dense(m, n, descr, csr_val, csr_row_ptr, csr_col_ind, a, ld, order)
1353}
1354
1355/// Convert a CSR matrix to CSC. Output arrays must be pre-sized.
1356pub fn csr_to_csc<T: Scalar>(
1357    m: usize,
1358    n: usize,
1359    descr: &MatDescr,
1360    base_csc: IndexBase,
1361    csr_row_ptr: &[sys::aoclsparse_int],
1362    csr_col_ind: &[sys::aoclsparse_int],
1363    csr_val: &[T],
1364    csc_row_ind: &mut [sys::aoclsparse_int],
1365    csc_col_ptr: &mut [sys::aoclsparse_int],
1366    csc_val: &mut [T],
1367) -> Result<()> {
1368    let nnz = csr_val.len();
1369    if csr_col_ind.len() != nnz || csc_row_ind.len() < nnz || csc_val.len() < nnz {
1370        return Err(Error::InvalidArgument(format!(
1371            "csr_to_csc: nnz mismatch (csr_val={}, csr_col_ind={}, csc_row_ind={}, csc_val={})",
1372            nnz,
1373            csr_col_ind.len(),
1374            csc_row_ind.len(),
1375            csc_val.len()
1376        )));
1377    }
1378    if csr_row_ptr.len() != m + 1 || csc_col_ptr.len() != n + 1 {
1379        return Err(Error::InvalidArgument(format!(
1380            "csr_to_csc: row_ptr length {} != m+1 = {} or col_ptr length {} != n+1 = {}",
1381            csr_row_ptr.len(),
1382            m + 1,
1383            csc_col_ptr.len(),
1384            n + 1
1385        )));
1386    }
1387    T::csr_to_csc(
1388        m,
1389        n,
1390        descr,
1391        base_csc,
1392        csr_row_ptr,
1393        csr_col_ind,
1394        csr_val,
1395        csc_row_ind,
1396        csc_col_ptr,
1397        csc_val,
1398    )
1399}
1400
1401/// Index base for sparse-format index arrays.
1402#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1403pub enum IndexBase {
1404    /// 0-based indexing (C convention).
1405    Zero,
1406    /// 1-based indexing (Fortran convention).
1407    One,
1408}
1409
1410impl IndexBase {
1411    fn raw(self) -> sys::aoclsparse_index_base {
1412        match self {
1413            IndexBase::Zero => sys::aoclsparse_index_base__aoclsparse_index_base_zero,
1414            IndexBase::One => sys::aoclsparse_index_base__aoclsparse_index_base_one,
1415        }
1416    }
1417}
1418
1419// =========================================================================
1420//   ELLPACK and BSR mat-vec
1421// =========================================================================
1422
1423/// Compute `y := α · op(A) · x + β · y` for an ELLPACK-format `A`.
1424///
1425/// `ell_val` and `ell_col_ind` each have length `m * ell_width`, where rows
1426/// shorter than `ell_width` are padded.
1427///
1428/// AOCL only implements `op = Trans::No` for ELLPACK at present.
1429pub fn ellmv<T: Scalar>(
1430    op: Trans,
1431    alpha: T,
1432    m: usize,
1433    n: usize,
1434    ell_val: &[T],
1435    ell_col_ind: &[sys::aoclsparse_int],
1436    ell_width: usize,
1437    descr: &MatDescr,
1438    x: &[T],
1439    beta: T,
1440    y: &mut [T],
1441) -> Result<()> {
1442    T::ellmv(
1443        op,
1444        alpha,
1445        m,
1446        n,
1447        ell_val,
1448        ell_col_ind,
1449        ell_width,
1450        descr,
1451        x,
1452        beta,
1453        y,
1454    )
1455}
1456
1457/// Compute `y := α · op(A) · x + β · y` for a BSR-format `A`.
1458///
1459/// `mb` and `nb` count blocks (so `A` is `mb·bsr_dim × nb·bsr_dim`).
1460/// `bsr_val` is laid out as `nnzb` consecutive `bsr_dim × bsr_dim` blocks.
1461///
1462/// AOCL only implements `op = Trans::No` for BSR at present.
1463pub fn bsrmv<T: Scalar>(
1464    op: Trans,
1465    alpha: T,
1466    mb: usize,
1467    nb: usize,
1468    bsr_dim: usize,
1469    bsr_val: &[T],
1470    bsr_col_ind: &[sys::aoclsparse_int],
1471    bsr_row_ptr: &[sys::aoclsparse_int],
1472    descr: &MatDescr,
1473    x: &[T],
1474    beta: T,
1475    y: &mut [T],
1476) -> Result<()> {
1477    T::bsrmv(
1478        op,
1479        alpha,
1480        mb,
1481        nb,
1482        bsr_dim,
1483        bsr_val,
1484        bsr_col_ind,
1485        bsr_row_ptr,
1486        descr,
1487        x,
1488        beta,
1489        y,
1490    )
1491}
1492
1493// =========================================================================
1494//   High-level matrix handle (aoclsparse_matrix)
1495// =========================================================================
1496
1497/// Stage of a multi-pass sparse-sparse matrix product (see [`csr2m`]).
1498#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1499pub enum Stage {
1500    /// Analyse only; reserve nnz count without writing values.
1501    NnzCount,
1502    /// Compute values, given a prior `NnzCount` call.
1503    Finalize,
1504    /// Single-shot full computation.
1505    FullComputation,
1506}
1507
1508impl Stage {
1509    fn raw(self) -> sys::aoclsparse_request {
1510        match self {
1511            Stage::NnzCount => sys::aoclsparse_request__aoclsparse_stage_nnz_count,
1512            Stage::Finalize => sys::aoclsparse_request__aoclsparse_stage_finalize,
1513            Stage::FullComputation => sys::aoclsparse_request__aoclsparse_stage_full_computation,
1514        }
1515    }
1516}
1517
1518enum CsrStorage<T: Scalar> {
1519    /// Arrays are owned by the Rust side (we keep them alive until drop).
1520    Owned {
1521        _row_ptr: Vec<sys::aoclsparse_int>,
1522        _col_ind: Vec<sys::aoclsparse_int>,
1523        _val: Vec<T>,
1524    },
1525    /// Arrays are owned by the library; only the handle needs destroying.
1526    LibraryOwned,
1527}
1528
1529/// RAII wrapper around an `aoclsparse_matrix` handle holding a CSR matrix.
1530///
1531/// Construct from raw CSR vectors with [`SparseMatrix::from_csr`] (the
1532/// values are copied into the wrapper) or as the result of an operation
1533/// like [`csr2m`].
1534pub struct SparseMatrix<T: Scalar> {
1535    raw: sys::aoclsparse_matrix,
1536    #[allow(dead_code, reason = "kept alive so the library can keep its pointers")]
1537    storage: CsrStorage<T>,
1538    base: IndexBase,
1539    m: usize,
1540    n: usize,
1541    nnz: usize,
1542}
1543
1544impl<T: Scalar> SparseMatrix<T> {
1545    /// Build a new matrix handle from CSR arrays. The arrays are copied
1546    /// into the wrapper; the caller's slices are not retained.
1547    pub fn from_csr(
1548        base: IndexBase,
1549        m: usize,
1550        n: usize,
1551        row_ptr: &[sys::aoclsparse_int],
1552        col_ind: &[sys::aoclsparse_int],
1553        val: &[T],
1554    ) -> Result<Self> {
1555        if row_ptr.len() != m + 1 {
1556            return Err(Error::InvalidArgument(format!(
1557                "from_csr: row_ptr length {} != m+1 = {}",
1558                row_ptr.len(),
1559                m + 1
1560            )));
1561        }
1562        let nnz = val.len();
1563        if col_ind.len() != nnz {
1564            return Err(Error::InvalidArgument(format!(
1565                "from_csr: col_ind length {} != val length {nnz}",
1566                col_ind.len()
1567            )));
1568        }
1569        let mut row_ptr = row_ptr.to_vec();
1570        let mut col_ind = col_ind.to_vec();
1571        let mut val = val.to_vec();
1572        let raw = T::create_csr(
1573            base,
1574            m,
1575            n,
1576            nnz,
1577            row_ptr.as_mut_ptr(),
1578            col_ind.as_mut_ptr(),
1579            val.as_mut_ptr(),
1580        )?;
1581        Ok(Self {
1582            raw,
1583            storage: CsrStorage::Owned {
1584                _row_ptr: row_ptr,
1585                _col_ind: col_ind,
1586                _val: val,
1587            },
1588            base,
1589            m,
1590            n,
1591            nnz,
1592        })
1593    }
1594
1595    /// Adopt a handle returned by an AOCL routine that allocates its own
1596    /// CSR storage (e.g. `aoclsparse_dcsr2m`). The library will free the
1597    /// arrays when the handle is destroyed.
1598    ///
1599    /// # Safety
1600    /// `raw` must be a valid `aoclsparse_matrix` whose internal storage is
1601    /// owned by the AOCL library and whose precision matches `T`.
1602    pub unsafe fn from_library_owned(raw: sys::aoclsparse_matrix) -> Result<Self> {
1603        if raw.is_null() {
1604            return Err(Error::AllocationFailed("sparse"));
1605        }
1606        let (base, m, n, nnz, _, _, _) = T::export_csr(raw)?;
1607        Ok(Self {
1608            raw,
1609            storage: CsrStorage::LibraryOwned,
1610            base,
1611            m,
1612            n,
1613            nnz,
1614        })
1615    }
1616
1617    /// `(m, n)` dimensions of the matrix.
1618    pub fn dims(&self) -> (usize, usize) {
1619        (self.m, self.n)
1620    }
1621
1622    /// Number of explicitly stored non-zeros.
1623    pub fn nnz(&self) -> usize {
1624        self.nnz
1625    }
1626
1627    /// Index base used by this matrix's row-pointer and column-index arrays.
1628    pub fn base(&self) -> IndexBase {
1629        self.base
1630    }
1631
1632    /// Borrow the raw underlying handle for raw FFI calls.
1633    ///
1634    /// # Safety
1635    /// The returned pointer is valid only for the lifetime of `self`.
1636    /// Do not call `aoclsparse_destroy` on it.
1637    pub fn as_raw(&self) -> sys::aoclsparse_matrix {
1638        self.raw
1639    }
1640
1641    /// Read out the CSR contents as freshly allocated `Vec`s.
1642    pub fn export_csr(
1643        &self,
1644    ) -> Result<(
1645        IndexBase,
1646        Vec<sys::aoclsparse_int>,
1647        Vec<sys::aoclsparse_int>,
1648        Vec<T>,
1649    )> {
1650        let (base, m, _, nnz, row_ptr, col_ind, val) = T::export_csr(self.raw)?;
1651        let row_ptr = unsafe { std::slice::from_raw_parts(row_ptr, m + 1).to_vec() };
1652        let col_ind = unsafe { std::slice::from_raw_parts(col_ind, nnz).to_vec() };
1653        let val = unsafe { std::slice::from_raw_parts(val, nnz).to_vec() };
1654        Ok((base, row_ptr, col_ind, val))
1655    }
1656
1657    // --- Hints: tell the analysis pass how the matrix will be used.
1658    // Pair with `optimize()` to actually run the analysis.
1659
1660    /// Hint that mat-vec (`mv`) will be called `expected_calls` times in
1661    /// the given orientation `op`.
1662    pub fn set_mv_hint(
1663        &mut self,
1664        op: Trans,
1665        descr: &MatDescr,
1666        expected_calls: usize,
1667    ) -> Result<()> {
1668        let status = unsafe {
1669            sys::aoclsparse_set_mv_hint(
1670                self.raw,
1671                trans_raw(op),
1672                descr.as_raw(),
1673                expected_calls as sys::aoclsparse_int,
1674            )
1675        };
1676        check_status("sparse", status)
1677    }
1678
1679    /// Hint for triangular solve (`trsv`).
1680    pub fn set_sv_hint(
1681        &mut self,
1682        op: Trans,
1683        descr: &MatDescr,
1684        expected_calls: usize,
1685    ) -> Result<()> {
1686        let status = unsafe {
1687            sys::aoclsparse_set_sv_hint(
1688                self.raw,
1689                trans_raw(op),
1690                descr.as_raw(),
1691                expected_calls as sys::aoclsparse_int,
1692            )
1693        };
1694        check_status("sparse", status)
1695    }
1696
1697    /// Hint for sparse-dense matrix multiply (`csrmm`).
1698    pub fn set_mm_hint(
1699        &mut self,
1700        op: Trans,
1701        descr: &MatDescr,
1702        expected_calls: usize,
1703    ) -> Result<()> {
1704        let status = unsafe {
1705            sys::aoclsparse_set_mm_hint(
1706                self.raw,
1707                trans_raw(op),
1708                descr.as_raw(),
1709                expected_calls as sys::aoclsparse_int,
1710            )
1711        };
1712        check_status("sparse", status)
1713    }
1714
1715    /// Hint for sparse-sparse matrix multiply (`csr2m`).
1716    pub fn set_2m_hint(
1717        &mut self,
1718        op: Trans,
1719        descr: &MatDescr,
1720        expected_calls: usize,
1721    ) -> Result<()> {
1722        let status = unsafe {
1723            sys::aoclsparse_set_2m_hint(
1724                self.raw,
1725                trans_raw(op),
1726                descr.as_raw(),
1727                expected_calls as sys::aoclsparse_int,
1728            )
1729        };
1730        check_status("sparse", status)
1731    }
1732
1733    /// Hint for sparse triangular solve with multiple right-hand sides
1734    /// (`trsm`). `order` is the layout of the dense `B`/`X` matrices.
1735    pub fn set_sm_hint(
1736        &mut self,
1737        op: Trans,
1738        descr: &MatDescr,
1739        order: Order,
1740        expected_calls: usize,
1741    ) -> Result<()> {
1742        let status = unsafe {
1743            sys::aoclsparse_set_sm_hint(
1744                self.raw,
1745                trans_raw(op),
1746                descr.as_raw(),
1747                order.raw(),
1748                expected_calls as sys::aoclsparse_int,
1749            )
1750        };
1751        check_status("sparse", status)
1752    }
1753
1754    /// Hint for ILU smoothing.
1755    pub fn set_lu_smoother_hint(
1756        &mut self,
1757        op: Trans,
1758        descr: &MatDescr,
1759        expected_calls: usize,
1760    ) -> Result<()> {
1761        let status = unsafe {
1762            sys::aoclsparse_set_lu_smoother_hint(
1763                self.raw,
1764                trans_raw(op),
1765                descr.as_raw(),
1766                expected_calls as sys::aoclsparse_int,
1767            )
1768        };
1769        check_status("sparse", status)
1770    }
1771
1772    /// Hint for symmetric Gauss-Seidel.
1773    pub fn set_symgs_hint(
1774        &mut self,
1775        op: Trans,
1776        descr: &MatDescr,
1777        expected_calls: usize,
1778    ) -> Result<()> {
1779        let status = unsafe {
1780            sys::aoclsparse_set_symgs_hint(
1781                self.raw,
1782                trans_raw(op),
1783                descr.as_raw(),
1784                expected_calls as sys::aoclsparse_int,
1785            )
1786        };
1787        check_status("sparse", status)
1788    }
1789
1790    /// Hint for the fused dot-mat-vec routine.
1791    pub fn set_dotmv_hint(
1792        &mut self,
1793        op: Trans,
1794        descr: &MatDescr,
1795        expected_calls: usize,
1796    ) -> Result<()> {
1797        let status = unsafe {
1798            sys::aoclsparse_set_dotmv_hint(
1799                self.raw,
1800                trans_raw(op),
1801                descr.as_raw(),
1802                expected_calls as sys::aoclsparse_int,
1803            )
1804        };
1805        check_status("sparse", status)
1806    }
1807
1808    /// Hint for SOR / Gauss-Seidel sweeps.
1809    pub fn set_sorv_hint(
1810        &mut self,
1811        sor_type: SorType,
1812        descr: &MatDescr,
1813        expected_calls: usize,
1814    ) -> Result<()> {
1815        let status = unsafe {
1816            sys::aoclsparse_set_sorv_hint(
1817                self.raw,
1818                descr.as_raw(),
1819                sor_type.raw(),
1820                expected_calls as sys::aoclsparse_int,
1821            )
1822        };
1823        check_status("sparse", status)
1824    }
1825}
1826
1827impl<T: Scalar> Drop for SparseMatrix<T> {
1828    fn drop(&mut self) {
1829        if !self.raw.is_null() {
1830            unsafe {
1831                let _ = sys::aoclsparse_destroy(&mut self.raw);
1832            }
1833            self.raw = std::ptr::null_mut();
1834        }
1835    }
1836}
1837
1838impl<T: Scalar> std::fmt::Debug for SparseMatrix<T> {
1839    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1840        f.debug_struct("SparseMatrix")
1841            .field("m", &self.m)
1842            .field("n", &self.n)
1843            .field("nnz", &self.nnz)
1844            .field("base", &self.base)
1845            .finish()
1846    }
1847}
1848
1849// =========================================================================
1850//   Sparse-sparse matrix product (csr2m)
1851// =========================================================================
1852
1853/// Compute `C := op_A(A) · op_B(B)` between two CSR matrices, returning a
1854/// freshly allocated CSR result. Both inputs must have matching scalar
1855/// precision; complex precisions are not yet exposed by these wrappers.
1856///
1857/// Use `Stage::FullComputation` for a one-shot call. The two-stage form
1858/// (`NnzCount` followed by `Finalize`) is for repeated multiplies sharing
1859/// the same sparsity pattern.
1860pub fn csr2m<T: Scalar>(
1861    op_a: Trans,
1862    descr_a: &MatDescr,
1863    a: &SparseMatrix<T>,
1864    op_b: Trans,
1865    descr_b: &MatDescr,
1866    b: &SparseMatrix<T>,
1867    stage: Stage,
1868) -> Result<SparseMatrix<T>> {
1869    let mut c_raw: sys::aoclsparse_matrix = std::ptr::null_mut();
1870    let status = unsafe {
1871        // We need a per-precision dispatch. Encode by calling the matching
1872        // FFI symbol via a small helper trait.
1873        T::csr2m_ffi(
1874            trans_raw(op_a),
1875            descr_a.as_raw(),
1876            a.raw,
1877            trans_raw(op_b),
1878            descr_b.as_raw(),
1879            b.raw,
1880            stage.raw(),
1881            &mut c_raw,
1882        )
1883    };
1884    check_status("sparse", status)?;
1885    unsafe { SparseMatrix::from_library_owned(c_raw) }
1886}
1887
1888// =========================================================================
1889//   Sparse-dense matrix products (csrmm, spmmd, sp2md)
1890// =========================================================================
1891
1892/// Compute `C := α · op(A) · B + β · C` where `A` is sparse (CSR via the
1893/// matrix handle) and `B`, `C` are dense matrices laid out per `order`.
1894///
1895/// `n` is the number of columns of `B` (and `C`). `ldb` and `ldc` are
1896/// the leading dimensions of `B` and `C` respectively.
1897pub fn csrmm<T: Scalar>(
1898    op: Trans,
1899    alpha: T,
1900    a: &SparseMatrix<T>,
1901    descr: &MatDescr,
1902    order: Order,
1903    b: &[T],
1904    n: usize,
1905    ldb: usize,
1906    beta: T,
1907    c: &mut [T],
1908    ldc: usize,
1909) -> Result<()> {
1910    T::csrmm(op, alpha, a.as_raw(), descr, order, b, n, ldb, beta, c, ldc)
1911}
1912
1913/// Compute `C := op(A) · B` where both `A` and `B` are sparse and `C` is
1914/// a dense matrix. `ldc` is the leading dimension of `C` per `layout`.
1915pub fn spmmd<T: Scalar>(
1916    op: Trans,
1917    a: &SparseMatrix<T>,
1918    b: &SparseMatrix<T>,
1919    layout: Order,
1920    c: &mut [T],
1921    ldc: usize,
1922) -> Result<()> {
1923    T::spmmd(op, a.as_raw(), b.as_raw(), layout, c, ldc)
1924}
1925
1926/// Compute `C := α · op_A(A) · op_B(B) + β · C` where both `A` and `B`
1927/// are sparse and `C` is dense.
1928pub fn sp2md<T: Scalar>(
1929    op_a: Trans,
1930    descr_a: &MatDescr,
1931    a: &SparseMatrix<T>,
1932    op_b: Trans,
1933    descr_b: &MatDescr,
1934    b: &SparseMatrix<T>,
1935    alpha: T,
1936    beta: T,
1937    c: &mut [T],
1938    layout: Order,
1939    ldc: usize,
1940) -> Result<()> {
1941    T::sp2md(
1942        op_a,
1943        descr_a,
1944        a.as_raw(),
1945        op_b,
1946        descr_b,
1947        b.as_raw(),
1948        alpha,
1949        beta,
1950        c,
1951        layout,
1952        ldc,
1953    )
1954}
1955
1956// =========================================================================
1957//   Sparse-sparse addition and SOR sweep
1958// =========================================================================
1959
1960/// Compute `C := α · op(A) + B` returning a fresh sparse CSR matrix.
1961pub fn add<T: Scalar>(
1962    op: Trans,
1963    a: &SparseMatrix<T>,
1964    alpha: T,
1965    b: &SparseMatrix<T>,
1966) -> Result<SparseMatrix<T>> {
1967    let mut c_raw: sys::aoclsparse_matrix = std::ptr::null_mut();
1968    let status = unsafe { T::add_ffi(trans_raw(op), a.as_raw(), alpha, b.as_raw(), &mut c_raw) };
1969    check_status("sparse", status)?;
1970    unsafe { SparseMatrix::from_library_owned(c_raw) }
1971}
1972
1973/// One step of (S)SOR / forward / backward Gauss-Seidel relaxation:
1974/// `x_new := (1 − ω) x + ω · A⁻¹ (α · b)`. Useful as a smoother
1975/// inside iterative-solver loops.
1976pub fn sorv<T: Scalar>(
1977    sor_type: SorType,
1978    descr: &MatDescr,
1979    a: &SparseMatrix<T>,
1980    omega: T,
1981    alpha: T,
1982    x: &mut [T],
1983    b: &[T],
1984) -> Result<()> {
1985    if x.len() < a.dims().1 || b.len() < a.dims().0 {
1986        return Err(Error::InvalidArgument(format!(
1987            "sorv: x.len()={}, b.len()={}, dims=({}, {})",
1988            x.len(),
1989            b.len(),
1990            a.dims().0,
1991            a.dims().1
1992        )));
1993    }
1994    T::sorv(sor_type, descr, a.as_raw(), omega, alpha, x, b)
1995}
1996
1997// =========================================================================
1998//   ILU smoother
1999// =========================================================================
2000
2001// =========================================================================
2002//   Real high-level mat-vec / triangular solve / triangular multi-RHS solve
2003// =========================================================================
2004
2005/// Real high-level mat-vec `y := α · op(A) · x + β · y` against a
2006/// `SparseMatrix<f64>` handle (per-precision; complex variants live in
2007/// the [`complex`] submodule).
2008pub fn mv_f64(
2009    op: Trans,
2010    alpha: f64,
2011    a: &SparseMatrix<f64>,
2012    descr: &MatDescr,
2013    x: &[f64],
2014    beta: f64,
2015    y: &mut [f64],
2016) -> Result<()> {
2017    let status = unsafe {
2018        sys::aoclsparse_dmv(
2019            trans_raw(op),
2020            &alpha,
2021            a.as_raw(),
2022            descr.as_raw(),
2023            x.as_ptr(),
2024            &beta,
2025            y.as_mut_ptr(),
2026        )
2027    };
2028    check_status("sparse", status)
2029}
2030
2031/// `f32` mat-vec via the matrix-handle interface. See [`mv_f64`].
2032pub fn mv_f32(
2033    op: Trans,
2034    alpha: f32,
2035    a: &SparseMatrix<f32>,
2036    descr: &MatDescr,
2037    x: &[f32],
2038    beta: f32,
2039    y: &mut [f32],
2040) -> Result<()> {
2041    let status = unsafe {
2042        sys::aoclsparse_smv(
2043            trans_raw(op),
2044            &alpha,
2045            a.as_raw(),
2046            descr.as_raw(),
2047            x.as_ptr(),
2048            &beta,
2049            y.as_mut_ptr(),
2050        )
2051    };
2052    check_status("sparse", status)
2053}
2054
2055/// Solve `op(A) · x = α · b` for sparse triangular `A` against a
2056/// `SparseMatrix<f64>` handle. The fill mode and unit/non-unit diag
2057/// must be set on `descr` first.
2058pub fn trsv_f64(
2059    op: Trans,
2060    alpha: f64,
2061    a: &SparseMatrix<f64>,
2062    descr: &MatDescr,
2063    b: &[f64],
2064    x: &mut [f64],
2065) -> Result<()> {
2066    let status = unsafe {
2067        sys::aoclsparse_dtrsv(
2068            trans_raw(op),
2069            alpha,
2070            a.as_raw(),
2071            descr.as_raw(),
2072            b.as_ptr(),
2073            x.as_mut_ptr(),
2074        )
2075    };
2076    check_status("sparse", status)
2077}
2078
2079/// `f32` triangular solve. See [`trsv_f64`].
2080pub fn trsv_f32(
2081    op: Trans,
2082    alpha: f32,
2083    a: &SparseMatrix<f32>,
2084    descr: &MatDescr,
2085    b: &[f32],
2086    x: &mut [f32],
2087) -> Result<()> {
2088    let status = unsafe {
2089        sys::aoclsparse_strsv(
2090            trans_raw(op),
2091            alpha,
2092            a.as_raw(),
2093            descr.as_raw(),
2094            b.as_ptr(),
2095            x.as_mut_ptr(),
2096        )
2097    };
2098    check_status("sparse", status)
2099}
2100
2101/// Multi-RHS triangular solve: `op(A) · X = α · B` for `n_rhs`
2102/// right-hand sides, `B`/`X` dense `m × n_rhs`.
2103pub fn trsm_f64(
2104    op: Trans,
2105    alpha: f64,
2106    a: &SparseMatrix<f64>,
2107    descr: &MatDescr,
2108    order: Order,
2109    b: &[f64],
2110    n_rhs: usize,
2111    ldb: usize,
2112    x: &mut [f64],
2113    ldx: usize,
2114) -> Result<()> {
2115    let status = unsafe {
2116        sys::aoclsparse_dtrsm(
2117            trans_raw(op),
2118            alpha,
2119            a.as_raw(),
2120            descr.as_raw(),
2121            order.raw(),
2122            b.as_ptr(),
2123            n_rhs as sys::aoclsparse_int,
2124            ldb as sys::aoclsparse_int,
2125            x.as_mut_ptr(),
2126            ldx as sys::aoclsparse_int,
2127        )
2128    };
2129    check_status("sparse", status)
2130}
2131
2132/// `f32` multi-RHS triangular solve. See [`trsm_f64`].
2133pub fn trsm_f32(
2134    op: Trans,
2135    alpha: f32,
2136    a: &SparseMatrix<f32>,
2137    descr: &MatDescr,
2138    order: Order,
2139    b: &[f32],
2140    n_rhs: usize,
2141    ldb: usize,
2142    x: &mut [f32],
2143    ldx: usize,
2144) -> Result<()> {
2145    let status = unsafe {
2146        sys::aoclsparse_strsm(
2147            trans_raw(op),
2148            alpha,
2149            a.as_raw(),
2150            descr.as_raw(),
2151            order.raw(),
2152            b.as_ptr(),
2153            n_rhs as sys::aoclsparse_int,
2154            ldb as sys::aoclsparse_int,
2155            x.as_mut_ptr(),
2156            ldx as sys::aoclsparse_int,
2157        )
2158    };
2159    check_status("sparse", status)
2160}
2161
2162/// Sparse vector dot product: `Σᵢ x[i] · y[indx[i]]`. `x` and `indx`
2163/// must have the same length (the nnz count).
2164pub fn doti_f64(x: &[f64], indx: &[sys::aoclsparse_int], y: &[f64]) -> Result<f64> {
2165    if x.len() != indx.len() {
2166        return Err(Error::InvalidArgument(format!(
2167            "doti: x.len()={} != indx.len()={}",
2168            x.len(),
2169            indx.len()
2170        )));
2171    }
2172    let r = unsafe {
2173        sys::aoclsparse_ddoti(
2174            x.len() as sys::aoclsparse_int,
2175            x.as_ptr(),
2176            indx.as_ptr(),
2177            y.as_ptr(),
2178        )
2179    };
2180    Ok(r)
2181}
2182
2183/// `f32` sparse dot. See [`doti_f64`].
2184pub fn doti_f32(x: &[f32], indx: &[sys::aoclsparse_int], y: &[f32]) -> Result<f32> {
2185    if x.len() != indx.len() {
2186        return Err(Error::InvalidArgument(format!(
2187            "doti: x.len()={} != indx.len()={}",
2188            x.len(),
2189            indx.len()
2190        )));
2191    }
2192    let r = unsafe {
2193        sys::aoclsparse_sdoti(
2194            x.len() as sys::aoclsparse_int,
2195            x.as_ptr(),
2196            indx.as_ptr(),
2197            y.as_ptr(),
2198        )
2199    };
2200    Ok(r)
2201}
2202
2203// =========================================================================
2204//   CSR ↔ ELL / DIA / BSR conversions, COO / CSC creators, value mutators,
2205//   block-CSR mat-vec, symmetric Gauss-Seidel
2206// =========================================================================
2207
2208/// Convert CSR → ELLPACK. `ell_width` is the chosen padded row length;
2209/// caller must allocate `ell_col_ind` and `ell_val` of size
2210/// `m * ell_width`. (`f64`)
2211pub fn csr2ell_f64(
2212    m: usize,
2213    descr: &MatDescr,
2214    csr_row_ptr: &[sys::aoclsparse_int],
2215    csr_col_ind: &[sys::aoclsparse_int],
2216    csr_val: &[f64],
2217    ell_col_ind: &mut [sys::aoclsparse_int],
2218    ell_val: &mut [f64],
2219    ell_width: usize,
2220) -> Result<()> {
2221    let status = unsafe {
2222        sys::aoclsparse_dcsr2ell(
2223            m as sys::aoclsparse_int,
2224            descr.as_raw(),
2225            csr_row_ptr.as_ptr(),
2226            csr_col_ind.as_ptr(),
2227            csr_val.as_ptr(),
2228            ell_col_ind.as_mut_ptr(),
2229            ell_val.as_mut_ptr(),
2230            ell_width as sys::aoclsparse_int,
2231        )
2232    };
2233    check_status("sparse", status)
2234}
2235
2236/// `f32` CSR → ELLPACK. See [`csr2ell_f64`].
2237pub fn csr2ell_f32(
2238    m: usize,
2239    descr: &MatDescr,
2240    csr_row_ptr: &[sys::aoclsparse_int],
2241    csr_col_ind: &[sys::aoclsparse_int],
2242    csr_val: &[f32],
2243    ell_col_ind: &mut [sys::aoclsparse_int],
2244    ell_val: &mut [f32],
2245    ell_width: usize,
2246) -> Result<()> {
2247    let status = unsafe {
2248        sys::aoclsparse_scsr2ell(
2249            m as sys::aoclsparse_int,
2250            descr.as_raw(),
2251            csr_row_ptr.as_ptr(),
2252            csr_col_ind.as_ptr(),
2253            csr_val.as_ptr(),
2254            ell_col_ind.as_mut_ptr(),
2255            ell_val.as_mut_ptr(),
2256            ell_width as sys::aoclsparse_int,
2257        )
2258    };
2259    check_status("sparse", status)
2260}
2261
2262/// Convert CSR → DIA (diagonal storage). `dia_offset` and `dia_val`
2263/// must be pre-allocated; `dia_num_diag` is the number of distinct
2264/// diagonals. (`f64`)
2265pub fn csr2dia_f64(
2266    m: usize,
2267    n: usize,
2268    descr: &MatDescr,
2269    csr_row_ptr: &[sys::aoclsparse_int],
2270    csr_col_ind: &[sys::aoclsparse_int],
2271    csr_val: &[f64],
2272    dia_num_diag: usize,
2273    dia_offset: &mut [sys::aoclsparse_int],
2274    dia_val: &mut [f64],
2275) -> Result<()> {
2276    let status = unsafe {
2277        sys::aoclsparse_dcsr2dia(
2278            m as sys::aoclsparse_int,
2279            n as sys::aoclsparse_int,
2280            descr.as_raw(),
2281            csr_row_ptr.as_ptr(),
2282            csr_col_ind.as_ptr(),
2283            csr_val.as_ptr(),
2284            dia_num_diag as sys::aoclsparse_int,
2285            dia_offset.as_mut_ptr(),
2286            dia_val.as_mut_ptr(),
2287        )
2288    };
2289    check_status("sparse", status)
2290}
2291
2292/// `f32` CSR → DIA. See [`csr2dia_f64`].
2293pub fn csr2dia_f32(
2294    m: usize,
2295    n: usize,
2296    descr: &MatDescr,
2297    csr_row_ptr: &[sys::aoclsparse_int],
2298    csr_col_ind: &[sys::aoclsparse_int],
2299    csr_val: &[f32],
2300    dia_num_diag: usize,
2301    dia_offset: &mut [sys::aoclsparse_int],
2302    dia_val: &mut [f32],
2303) -> Result<()> {
2304    let status = unsafe {
2305        sys::aoclsparse_scsr2dia(
2306            m as sys::aoclsparse_int,
2307            n as sys::aoclsparse_int,
2308            descr.as_raw(),
2309            csr_row_ptr.as_ptr(),
2310            csr_col_ind.as_ptr(),
2311            csr_val.as_ptr(),
2312            dia_num_diag as sys::aoclsparse_int,
2313            dia_offset.as_mut_ptr(),
2314            dia_val.as_mut_ptr(),
2315        )
2316    };
2317    check_status("sparse", status)
2318}
2319
2320/// Compute the number of nonzero blocks (`bsr_nnz`) and `bsr_row_ptr`
2321/// for a CSR → BSR conversion with the given `block_dim`.
2322pub fn csr2bsr_nnz(
2323    m: usize,
2324    n: usize,
2325    descr: &MatDescr,
2326    csr_row_ptr: &[sys::aoclsparse_int],
2327    csr_col_ind: &[sys::aoclsparse_int],
2328    block_dim: usize,
2329    bsr_row_ptr: &mut [sys::aoclsparse_int],
2330) -> Result<usize> {
2331    let mut bsr_nnz: sys::aoclsparse_int = 0;
2332    let status = unsafe {
2333        sys::aoclsparse_csr2bsr_nnz(
2334            m as sys::aoclsparse_int,
2335            n as sys::aoclsparse_int,
2336            descr.as_raw(),
2337            csr_row_ptr.as_ptr(),
2338            csr_col_ind.as_ptr(),
2339            block_dim as sys::aoclsparse_int,
2340            bsr_row_ptr.as_mut_ptr(),
2341            &mut bsr_nnz,
2342        )
2343    };
2344    check_status("sparse", status)?;
2345    Ok(bsr_nnz as usize)
2346}
2347
2348/// Convert CSR → BSR. Run [`csr2bsr_nnz`] first to size the output. (`f64`)
2349///
2350/// `block_order` is the storage order of the values inside each block. It is a required argument of AOCL-sparse 5.3
2351/// (`aoclsparse_dcsr2bsr`); the 5.1 header the docs.rs bindings came from did not have it.
2352pub fn csr2bsr_f64(
2353    m: usize,
2354    n: usize,
2355    descr: &MatDescr,
2356    block_order: Order,
2357    csr_val: &[f64],
2358    csr_row_ptr: &[sys::aoclsparse_int],
2359    csr_col_ind: &[sys::aoclsparse_int],
2360    block_dim: usize,
2361    bsr_val: &mut [f64],
2362    bsr_row_ptr: &mut [sys::aoclsparse_int],
2363    bsr_col_ind: &mut [sys::aoclsparse_int],
2364) -> Result<()> {
2365    let status = unsafe {
2366        sys::aoclsparse_dcsr2bsr(
2367            m as sys::aoclsparse_int,
2368            n as sys::aoclsparse_int,
2369            descr.as_raw(),
2370            block_order.raw(),
2371            csr_val.as_ptr(),
2372            csr_row_ptr.as_ptr(),
2373            csr_col_ind.as_ptr(),
2374            block_dim as sys::aoclsparse_int,
2375            bsr_val.as_mut_ptr(),
2376            bsr_row_ptr.as_mut_ptr(),
2377            bsr_col_ind.as_mut_ptr(),
2378        )
2379    };
2380    check_status("sparse", status)
2381}
2382
2383/// `f32` CSR → BSR. See [`csr2bsr_f64`].
2384pub fn csr2bsr_f32(
2385    m: usize,
2386    n: usize,
2387    descr: &MatDescr,
2388    block_order: Order,
2389    csr_val: &[f32],
2390    csr_row_ptr: &[sys::aoclsparse_int],
2391    csr_col_ind: &[sys::aoclsparse_int],
2392    block_dim: usize,
2393    bsr_val: &mut [f32],
2394    bsr_row_ptr: &mut [sys::aoclsparse_int],
2395    bsr_col_ind: &mut [sys::aoclsparse_int],
2396) -> Result<()> {
2397    let status = unsafe {
2398        sys::aoclsparse_scsr2bsr(
2399            m as sys::aoclsparse_int,
2400            n as sys::aoclsparse_int,
2401            descr.as_raw(),
2402            block_order.raw(),
2403            csr_val.as_ptr(),
2404            csr_row_ptr.as_ptr(),
2405            csr_col_ind.as_ptr(),
2406            block_dim as sys::aoclsparse_int,
2407            bsr_val.as_mut_ptr(),
2408            bsr_row_ptr.as_mut_ptr(),
2409            bsr_col_ind.as_mut_ptr(),
2410        )
2411    };
2412    check_status("sparse", status)
2413}
2414
2415/// Block-CSR mat-vec with a per-block bitmask. `masks[i]` is a u8 bit
2416/// pattern indicating which rows of block `i` participate. `n_rows_blk`
2417/// is the block height. (`f64`)
2418pub fn blkcsrmv_f64(
2419    op: Trans,
2420    alpha: f64,
2421    m: usize,
2422    n: usize,
2423    masks: &[u8],
2424    csr_val: &[f64],
2425    csr_col_ind: &[sys::aoclsparse_int],
2426    csr_row_ptr: &[sys::aoclsparse_int],
2427    descr: &MatDescr,
2428    x: &[f64],
2429    beta: f64,
2430    y: &mut [f64],
2431    n_rows_blk: usize,
2432) -> Result<()> {
2433    let nnz = csr_val.len();
2434    let status = unsafe {
2435        sys::aoclsparse_dblkcsrmv(
2436            trans_raw(op),
2437            &alpha,
2438            m as sys::aoclsparse_int,
2439            n as sys::aoclsparse_int,
2440            nnz as sys::aoclsparse_int,
2441            masks.as_ptr(),
2442            csr_val.as_ptr(),
2443            csr_col_ind.as_ptr(),
2444            csr_row_ptr.as_ptr(),
2445            descr.as_raw(),
2446            x.as_ptr(),
2447            &beta,
2448            y.as_mut_ptr(),
2449            n_rows_blk as sys::aoclsparse_int,
2450        )
2451    };
2452    check_status("sparse", status)
2453}
2454
2455/// Symmetric Gauss-Seidel sweep `x := x + α · D⁻¹ (b − A·x)` against a
2456/// symmetric matrix handle. (`f64`)
2457pub fn symgs_f64(
2458    op: Trans,
2459    a: &SparseMatrix<f64>,
2460    descr: &MatDescr,
2461    alpha: f64,
2462    b: &[f64],
2463    x: &mut [f64],
2464) -> Result<()> {
2465    let status = unsafe {
2466        sys::aoclsparse_dsymgs(
2467            trans_raw(op),
2468            a.as_raw(),
2469            descr.as_raw(),
2470            alpha,
2471            b.as_ptr(),
2472            x.as_mut_ptr(),
2473        )
2474    };
2475    check_status("sparse", status)
2476}
2477
2478/// `f32` symmetric Gauss-Seidel. See [`symgs_f64`].
2479pub fn symgs_f32(
2480    op: Trans,
2481    a: &SparseMatrix<f32>,
2482    descr: &MatDescr,
2483    alpha: f32,
2484    b: &[f32],
2485    x: &mut [f32],
2486) -> Result<()> {
2487    let status = unsafe {
2488        sys::aoclsparse_ssymgs(
2489            trans_raw(op),
2490            a.as_raw(),
2491            descr.as_raw(),
2492            alpha,
2493            b.as_ptr(),
2494            x.as_mut_ptr(),
2495        )
2496    };
2497    check_status("sparse", status)
2498}
2499
2500/// Fused Gauss-Seidel + matrix-vector: produces both the updated `x`
2501/// and `y := A·x` in one pass. (`f64`)
2502pub fn symgs_mv_f64(
2503    op: Trans,
2504    a: &SparseMatrix<f64>,
2505    descr: &MatDescr,
2506    alpha: f64,
2507    b: &[f64],
2508    x: &mut [f64],
2509    y: &mut [f64],
2510) -> Result<()> {
2511    let status = unsafe {
2512        sys::aoclsparse_dsymgs_mv(
2513            trans_raw(op),
2514            a.as_raw(),
2515            descr.as_raw(),
2516            alpha,
2517            b.as_ptr(),
2518            x.as_mut_ptr(),
2519            y.as_mut_ptr(),
2520        )
2521    };
2522    check_status("sparse", status)
2523}
2524
2525/// `f32` fused symmetric Gauss-Seidel + mat-vec. See [`symgs_mv_f64`].
2526pub fn symgs_mv_f32(
2527    op: Trans,
2528    a: &SparseMatrix<f32>,
2529    descr: &MatDescr,
2530    alpha: f32,
2531    b: &[f32],
2532    x: &mut [f32],
2533    y: &mut [f32],
2534) -> Result<()> {
2535    let status = unsafe {
2536        sys::aoclsparse_ssymgs_mv(
2537            trans_raw(op),
2538            a.as_raw(),
2539            descr.as_raw(),
2540            alpha,
2541            b.as_ptr(),
2542            x.as_mut_ptr(),
2543            y.as_mut_ptr(),
2544        )
2545    };
2546    check_status("sparse", status)
2547}
2548
2549/// Set a single value at `(row_idx, col_idx)` in a CSR matrix handle.
2550/// Element must already exist in the sparsity pattern. (`f64`)
2551pub fn set_value_f64(
2552    a: &mut SparseMatrix<f64>,
2553    row_idx: i32,
2554    col_idx: i32,
2555    val: f64,
2556) -> Result<()> {
2557    let status = unsafe {
2558        sys::aoclsparse_dset_value(
2559            a.as_raw(),
2560            row_idx as sys::aoclsparse_int,
2561            col_idx as sys::aoclsparse_int,
2562            val,
2563        )
2564    };
2565    check_status("sparse", status)
2566}
2567
2568/// `f32` set_value. See [`set_value_f64`].
2569pub fn set_value_f32(
2570    a: &mut SparseMatrix<f32>,
2571    row_idx: i32,
2572    col_idx: i32,
2573    val: f32,
2574) -> Result<()> {
2575    let status = unsafe {
2576        sys::aoclsparse_sset_value(
2577            a.as_raw(),
2578            row_idx as sys::aoclsparse_int,
2579            col_idx as sys::aoclsparse_int,
2580            val,
2581        )
2582    };
2583    check_status("sparse", status)
2584}
2585
2586/// Update the values array of a CSR handle without rebuilding.
2587/// `len = nnz`; the new values must respect the existing sparsity
2588/// pattern. (`f64`)
2589pub fn update_values_f64(a: &mut SparseMatrix<f64>, val: &mut [f64]) -> Result<()> {
2590    let status = unsafe {
2591        sys::aoclsparse_dupdate_values(
2592            a.as_raw(),
2593            val.len() as sys::aoclsparse_int,
2594            val.as_mut_ptr(),
2595        )
2596    };
2597    check_status("sparse", status)
2598}
2599
2600/// `f32` update_values. See [`update_values_f64`].
2601pub fn update_values_f32(a: &mut SparseMatrix<f32>, val: &mut [f32]) -> Result<()> {
2602    let status = unsafe {
2603        sys::aoclsparse_supdate_values(
2604            a.as_raw(),
2605            val.len() as sys::aoclsparse_int,
2606            val.as_mut_ptr(),
2607        )
2608    };
2609    check_status("sparse", status)
2610}
2611
2612// =========================================================================
2613//   Fused dot + mat-vec, sparse rotations, strided gather/scatter,
2614//   symmetric rank-k, symmetric triple product
2615// =========================================================================
2616
2617/// Fused dot product and mat-vec: `y := α · op(A) · x + β · y` and
2618/// `d := xᵀ · y` (or `d := xᴴ · y` for complex). Saves one pass over
2619/// the matrix versus calling `mv` then `dot` separately. (`f64`)
2620pub fn dotmv_f64(
2621    op: Trans,
2622    alpha: f64,
2623    a: &SparseMatrix<f64>,
2624    descr: &MatDescr,
2625    x: &[f64],
2626    beta: f64,
2627    y: &mut [f64],
2628    d: &mut f64,
2629) -> Result<()> {
2630    let status = unsafe {
2631        sys::aoclsparse_ddotmv(
2632            trans_raw(op),
2633            alpha,
2634            a.as_raw(),
2635            descr.as_raw(),
2636            x.as_ptr(),
2637            beta,
2638            y.as_mut_ptr(),
2639            d,
2640        )
2641    };
2642    check_status("sparse", status)
2643}
2644
2645/// `f32` fused dot + mat-vec. See [`dotmv_f64`].
2646pub fn dotmv_f32(
2647    op: Trans,
2648    alpha: f32,
2649    a: &SparseMatrix<f32>,
2650    descr: &MatDescr,
2651    x: &[f32],
2652    beta: f32,
2653    y: &mut [f32],
2654    d: &mut f32,
2655) -> Result<()> {
2656    let status = unsafe {
2657        sys::aoclsparse_sdotmv(
2658            trans_raw(op),
2659            alpha,
2660            a.as_raw(),
2661            descr.as_raw(),
2662            x.as_ptr(),
2663            beta,
2664            y.as_mut_ptr(),
2665            d,
2666        )
2667    };
2668    check_status("sparse", status)
2669}
2670
2671/// Symmetric rank-k update from a sparse matrix:
2672/// `C := α · op(A) · op(A)ᵀ + β · C` (real) /
2673/// `C := α · op(A) · op(A)ᴴ + β · C` (complex). `C` is dense. (`f64`)
2674pub fn syrkd_f64(
2675    op_a: Trans,
2676    a: &SparseMatrix<f64>,
2677    alpha: f64,
2678    beta: f64,
2679    c: &mut [f64],
2680    order_c: Order,
2681    ldc: usize,
2682) -> Result<()> {
2683    let status = unsafe {
2684        sys::aoclsparse_dsyrkd(
2685            trans_raw(op_a),
2686            a.as_raw(),
2687            alpha,
2688            beta,
2689            c.as_mut_ptr(),
2690            order_c.raw(),
2691            ldc as sys::aoclsparse_int,
2692        )
2693    };
2694    check_status("sparse", status)
2695}
2696
2697/// `f32` symmetric rank-k update from sparse `A`. See [`syrkd_f64`].
2698pub fn syrkd_f32(
2699    op_a: Trans,
2700    a: &SparseMatrix<f32>,
2701    alpha: f32,
2702    beta: f32,
2703    c: &mut [f32],
2704    order_c: Order,
2705    ldc: usize,
2706) -> Result<()> {
2707    let status = unsafe {
2708        sys::aoclsparse_ssyrkd(
2709            trans_raw(op_a),
2710            a.as_raw(),
2711            alpha,
2712            beta,
2713            c.as_mut_ptr(),
2714            order_c.raw(),
2715            ldc as sys::aoclsparse_int,
2716        )
2717    };
2718    check_status("sparse", status)
2719}
2720
2721/// Symmetric triple product from a sparse `A` and dense `B`:
2722/// `C := α · op(A) · B · op(A)ᵀ + β · C`. (`f64`)
2723pub fn syprd_f64(
2724    op_a: Trans,
2725    a: &SparseMatrix<f64>,
2726    b: &[f64],
2727    order_b: Order,
2728    ldb: usize,
2729    alpha: f64,
2730    beta: f64,
2731    c: &mut [f64],
2732    order_c: Order,
2733    ldc: usize,
2734) -> Result<()> {
2735    let status = unsafe {
2736        sys::aoclsparse_dsyprd(
2737            trans_raw(op_a),
2738            a.as_raw(),
2739            b.as_ptr(),
2740            order_b.raw(),
2741            ldb as sys::aoclsparse_int,
2742            alpha,
2743            beta,
2744            c.as_mut_ptr(),
2745            order_c.raw(),
2746            ldc as sys::aoclsparse_int,
2747        )
2748    };
2749    check_status("sparse", status)
2750}
2751
2752/// `f32` symmetric triple product. See [`syprd_f64`].
2753pub fn syprd_f32(
2754    op_a: Trans,
2755    a: &SparseMatrix<f32>,
2756    b: &[f32],
2757    order_b: Order,
2758    ldb: usize,
2759    alpha: f32,
2760    beta: f32,
2761    c: &mut [f32],
2762    order_c: Order,
2763    ldc: usize,
2764) -> Result<()> {
2765    let status = unsafe {
2766        sys::aoclsparse_ssyprd(
2767            trans_raw(op_a),
2768            a.as_raw(),
2769            b.as_ptr(),
2770            order_b.raw(),
2771            ldb as sys::aoclsparse_int,
2772            alpha,
2773            beta,
2774            c.as_mut_ptr(),
2775            order_c.raw(),
2776            ldc as sys::aoclsparse_int,
2777        )
2778    };
2779    check_status("sparse", status)
2780}
2781
2782/// Sparse rotation: simultaneously rotate `(x, y)` at indices `indx`
2783/// by `(c, s)`. `x` is sparse with `indx` indices into the dense `y`. (`f64`)
2784pub fn roti_f64(
2785    x: &mut [f64],
2786    indx: &[sys::aoclsparse_int],
2787    y: &mut [f64],
2788    c: f64,
2789    s: f64,
2790) -> Result<()> {
2791    let status = unsafe {
2792        sys::aoclsparse_droti(
2793            x.len() as sys::aoclsparse_int,
2794            x.as_mut_ptr(),
2795            indx.as_ptr(),
2796            y.as_mut_ptr(),
2797            c,
2798            s,
2799        )
2800    };
2801    check_status("sparse", status)
2802}
2803
2804/// `f32` sparse rotation. See [`roti_f64`].
2805pub fn roti_f32(
2806    x: &mut [f32],
2807    indx: &[sys::aoclsparse_int],
2808    y: &mut [f32],
2809    c: f32,
2810    s: f32,
2811) -> Result<()> {
2812    let status = unsafe {
2813        sys::aoclsparse_sroti(
2814            x.len() as sys::aoclsparse_int,
2815            x.as_mut_ptr(),
2816            indx.as_ptr(),
2817            y.as_mut_ptr(),
2818            c,
2819            s,
2820        )
2821    };
2822    check_status("sparse", status)
2823}
2824
2825/// Strided sparse gather: `x[i] := y[i · stride]` for `i ∈ [0, nnz)`. (`f64`)
2826pub fn gthrs_f64(y: &[f64], x: &mut [f64], stride: i32) -> Result<()> {
2827    let status = unsafe {
2828        sys::aoclsparse_dgthrs(
2829            x.len() as sys::aoclsparse_int,
2830            y.as_ptr(),
2831            x.as_mut_ptr(),
2832            stride as sys::aoclsparse_int,
2833        )
2834    };
2835    check_status("sparse", status)
2836}
2837/// `f32` strided gather. See [`gthrs_f64`].
2838pub fn gthrs_f32(y: &[f32], x: &mut [f32], stride: i32) -> Result<()> {
2839    let status = unsafe {
2840        sys::aoclsparse_sgthrs(
2841            x.len() as sys::aoclsparse_int,
2842            y.as_ptr(),
2843            x.as_mut_ptr(),
2844            stride as sys::aoclsparse_int,
2845        )
2846    };
2847    check_status("sparse", status)
2848}
2849
2850/// Strided sparse scatter: `y[i · stride] := x[i]`. (`f64`)
2851pub fn sctrs_f64(x: &[f64], y: &mut [f64], stride: i32) -> Result<()> {
2852    let status = unsafe {
2853        sys::aoclsparse_dsctrs(
2854            x.len() as sys::aoclsparse_int,
2855            x.as_ptr(),
2856            stride as sys::aoclsparse_int,
2857            y.as_mut_ptr(),
2858        )
2859    };
2860    check_status("sparse", status)
2861}
2862/// `f32` strided scatter. See [`sctrs_f64`].
2863pub fn sctrs_f32(x: &[f32], y: &mut [f32], stride: i32) -> Result<()> {
2864    let status = unsafe {
2865        sys::aoclsparse_ssctrs(
2866            x.len() as sys::aoclsparse_int,
2867            x.as_ptr(),
2868            stride as sys::aoclsparse_int,
2869            y.as_mut_ptr(),
2870        )
2871    };
2872    check_status("sparse", status)
2873}
2874
2875/// Gather-and-zero: copy `y[indx[i]]` into `x[i]` and zero the source.
2876/// (`f64`)
2877pub fn gthrz_f64(y: &mut [f64], indx: &[sys::aoclsparse_int], x: &mut [f64]) -> Result<()> {
2878    let status = unsafe {
2879        sys::aoclsparse_dgthrz(
2880            x.len() as sys::aoclsparse_int,
2881            y.as_mut_ptr(),
2882            x.as_mut_ptr(),
2883            indx.as_ptr(),
2884        )
2885    };
2886    check_status("sparse", status)
2887}
2888/// `f32` gather-and-zero. See [`gthrz_f64`].
2889pub fn gthrz_f32(y: &mut [f32], indx: &[sys::aoclsparse_int], x: &mut [f32]) -> Result<()> {
2890    let status = unsafe {
2891        sys::aoclsparse_sgthrz(
2892            x.len() as sys::aoclsparse_int,
2893            y.as_mut_ptr(),
2894            x.as_mut_ptr(),
2895            indx.as_ptr(),
2896        )
2897    };
2898    check_status("sparse", status)
2899}
2900
2901/// `f32` SOR / forward / backward Gauss-Seidel sweep. The existing
2902/// generic [`sorv`] dispatches to this via the Scalar trait; this is
2903/// a per-precision direct alias.
2904pub fn sorv_f32(
2905    sor_type: SorType,
2906    descr: &MatDescr,
2907    a: &SparseMatrix<f32>,
2908    omega: f32,
2909    alpha: f32,
2910    x: &mut [f32],
2911    b: &[f32],
2912) -> Result<()> {
2913    let status = unsafe {
2914        sys::aoclsparse_ssorv(
2915            sor_type.raw(),
2916            descr.as_raw(),
2917            a.as_raw(),
2918            omega,
2919            alpha,
2920            x.as_mut_ptr(),
2921            b.as_ptr(),
2922        )
2923    };
2924    check_status("sparse", status)
2925}
2926
2927// =========================================================================
2928//   TCSR (triangular CSR): two parallel CSRs, one for L, one for U
2929// =========================================================================
2930
2931/// Build a TCSR matrix handle from two CSR sub-arrays describing the
2932/// strict-lower (`*_L`) and strict-upper (`*_U`) parts. (`f64`)
2933pub fn create_tcsr_f64(
2934    base: IndexBase,
2935    m: usize,
2936    n: usize,
2937    nnz: usize,
2938    row_ptr_l: &mut [sys::aoclsparse_int],
2939    row_ptr_u: &mut [sys::aoclsparse_int],
2940    col_idx_l: &mut [sys::aoclsparse_int],
2941    col_idx_u: &mut [sys::aoclsparse_int],
2942    val_l: &mut [f64],
2943    val_u: &mut [f64],
2944) -> Result<sys::aoclsparse_matrix> {
2945    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2946    let status = unsafe {
2947        sys::aoclsparse_create_dtcsr(
2948            &mut raw,
2949            base.raw(),
2950            m as sys::aoclsparse_int,
2951            n as sys::aoclsparse_int,
2952            nnz as sys::aoclsparse_int,
2953            row_ptr_l.as_mut_ptr(),
2954            row_ptr_u.as_mut_ptr(),
2955            col_idx_l.as_mut_ptr(),
2956            col_idx_u.as_mut_ptr(),
2957            val_l.as_mut_ptr(),
2958            val_u.as_mut_ptr(),
2959        )
2960    };
2961    check_status("sparse", status)?;
2962    if raw.is_null() {
2963        return Err(Error::AllocationFailed("sparse"));
2964    }
2965    Ok(raw)
2966}
2967
2968/// `f32` TCSR creator. See [`create_tcsr_f64`].
2969pub fn create_tcsr_f32(
2970    base: IndexBase,
2971    m: usize,
2972    n: usize,
2973    nnz: usize,
2974    row_ptr_l: &mut [sys::aoclsparse_int],
2975    row_ptr_u: &mut [sys::aoclsparse_int],
2976    col_idx_l: &mut [sys::aoclsparse_int],
2977    col_idx_u: &mut [sys::aoclsparse_int],
2978    val_l: &mut [f32],
2979    val_u: &mut [f32],
2980) -> Result<sys::aoclsparse_matrix> {
2981    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2982    let status = unsafe {
2983        sys::aoclsparse_create_stcsr(
2984            &mut raw,
2985            base.raw(),
2986            m as sys::aoclsparse_int,
2987            n as sys::aoclsparse_int,
2988            nnz as sys::aoclsparse_int,
2989            row_ptr_l.as_mut_ptr(),
2990            row_ptr_u.as_mut_ptr(),
2991            col_idx_l.as_mut_ptr(),
2992            col_idx_u.as_mut_ptr(),
2993            val_l.as_mut_ptr(),
2994            val_u.as_mut_ptr(),
2995        )
2996    };
2997    check_status("sparse", status)?;
2998    if raw.is_null() {
2999        return Err(Error::AllocationFailed("sparse"));
3000    }
3001    Ok(raw)
3002}
3003
3004// =========================================================================
3005//   CSC creators (real)
3006// =========================================================================
3007
3008/// Build a CSC matrix handle. Column-major analogue of CSR. (`f64`)
3009pub fn create_csc_f64(
3010    base: IndexBase,
3011    m: usize,
3012    n: usize,
3013    nnz: usize,
3014    col_ptr: &mut [sys::aoclsparse_int],
3015    row_idx: &mut [sys::aoclsparse_int],
3016    val: &mut [f64],
3017) -> Result<sys::aoclsparse_matrix> {
3018    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
3019    let status = unsafe {
3020        sys::aoclsparse_create_dcsc(
3021            &mut raw,
3022            base.raw(),
3023            m as sys::aoclsparse_int,
3024            n as sys::aoclsparse_int,
3025            nnz as sys::aoclsparse_int,
3026            col_ptr.as_mut_ptr(),
3027            row_idx.as_mut_ptr(),
3028            val.as_mut_ptr(),
3029        )
3030    };
3031    check_status("sparse", status)?;
3032    if raw.is_null() {
3033        return Err(Error::AllocationFailed("sparse"));
3034    }
3035    Ok(raw)
3036}
3037/// `f32` CSC creator. See [`create_csc_f64`].
3038pub fn create_csc_f32(
3039    base: IndexBase,
3040    m: usize,
3041    n: usize,
3042    nnz: usize,
3043    col_ptr: &mut [sys::aoclsparse_int],
3044    row_idx: &mut [sys::aoclsparse_int],
3045    val: &mut [f32],
3046) -> Result<sys::aoclsparse_matrix> {
3047    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
3048    let status = unsafe {
3049        sys::aoclsparse_create_scsc(
3050            &mut raw,
3051            base.raw(),
3052            m as sys::aoclsparse_int,
3053            n as sys::aoclsparse_int,
3054            nnz as sys::aoclsparse_int,
3055            col_ptr.as_mut_ptr(),
3056            row_idx.as_mut_ptr(),
3057            val.as_mut_ptr(),
3058        )
3059    };
3060    check_status("sparse", status)?;
3061    if raw.is_null() {
3062        return Err(Error::AllocationFailed("sparse"));
3063    }
3064    Ok(raw)
3065}
3066
3067/// Memory-usage hint to give the analysis pass.
3068#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3069pub enum MemoryUsage {
3070    /// Minimise extra memory; favour smaller working sets.
3071    Minimal,
3072    /// Allow the library to use additional memory if it speeds things up.
3073    Unrestricted,
3074}
3075
3076impl MemoryUsage {
3077    fn raw(self) -> sys::aoclsparse_memory_usage {
3078        match self {
3079            MemoryUsage::Minimal => sys::aoclsparse_memory_usage__aoclsparse_memory_usage_minimal,
3080            MemoryUsage::Unrestricted => {
3081                sys::aoclsparse_memory_usage__aoclsparse_memory_usage_unrestricted
3082            }
3083        }
3084    }
3085}
3086
3087/// Tell the library how much extra memory it may consume on this
3088/// matrix. Pair with [`optimize`].
3089pub fn set_memory_hint<T: Scalar>(mat: &mut SparseMatrix<T>, policy: MemoryUsage) -> Result<()> {
3090    let status = unsafe { sys::aoclsparse_set_memory_hint(mat.as_raw(), policy.raw()) };
3091    check_status("sparse", status)
3092}
3093
3094/// Apply one ILU(0) smoothing step in-place to `x`, with right-hand side `b`.
3095///
3096/// On the first call against a matrix this also factorizes; subsequent
3097/// calls re-use the cached factors stored on the matrix handle.
3098pub fn ilu_smoother<T: Scalar>(
3099    op: Trans,
3100    a: &SparseMatrix<T>,
3101    descr: &MatDescr,
3102    x: &mut [T],
3103    b: &[T],
3104) -> Result<()> {
3105    if x.len() < a.n || b.len() < a.m {
3106        return Err(Error::InvalidArgument(format!(
3107            "ilu_smoother: x.len()={}, b.len()={}, dims=({}, {})",
3108            x.len(),
3109            b.len(),
3110            a.m,
3111            a.n
3112        )));
3113    }
3114    T::ilu_smoother(op, a.raw, descr, x, b)
3115}
3116
3117// =========================================================================
3118//   Iterative solver (CG / GMRES) — direct interface
3119// =========================================================================
3120
3121/// RAII handle for the AOCL-Sparse iterative-solver suite.
3122///
3123/// Configure the solver type and tolerances with [`IterSolver::set_option`]
3124/// (e.g. `set_option("iterative method", "cg")` or `"gmres"`), then call
3125/// [`IterSolver::solve`] with the system matrix and right-hand side.
3126pub struct IterSolver<T: Scalar> {
3127    handle: sys::aoclsparse_itsol_handle,
3128    _marker: PhantomData<T>,
3129}
3130
3131impl<T: Scalar> IterSolver<T> {
3132    /// Initialise a new iterative-solver handle for this scalar type.
3133    pub fn new() -> Result<Self> {
3134        let mut handle: sys::aoclsparse_itsol_handle = std::ptr::null_mut();
3135        T::itsol_init(&mut handle)?;
3136        if handle.is_null() {
3137            return Err(Error::AllocationFailed("sparse"));
3138        }
3139        Ok(Self {
3140            handle,
3141            _marker: PhantomData,
3142        })
3143    }
3144
3145    /// Set a string-keyed solver option. See AOCL-Sparse's
3146    /// `aoclsparse_itsol_option_set` for the full option list. Common
3147    /// keys: `"iterative method"` (`"cg"`/`"gmres"`/`"pcg"`), `"cg
3148    /// iteration limit"`, `"cg rel tolerance"`, `"gmres preconditioner"`.
3149    pub fn set_option(&mut self, name: &str, value: &str) -> Result<()> {
3150        let c_name = CString::new(name)
3151            .map_err(|_| Error::InvalidArgument("set_option: name has interior NUL".into()))?;
3152        let c_value = CString::new(value)
3153            .map_err(|_| Error::InvalidArgument("set_option: value has interior NUL".into()))?;
3154        let status = unsafe {
3155            sys::aoclsparse_itsol_option_set(self.handle, c_name.as_ptr(), c_value.as_ptr())
3156        };
3157        check_status("sparse", status)
3158    }
3159
3160    /// Solve `A · x = b`. On entry `x` should hold an initial guess (zero
3161    /// is fine if you have nothing better); on success it contains the
3162    /// approximate solution. Returns the solver's `rinfo[100]` array of
3163    /// statistics (iteration counts, residual norms, etc.).
3164    pub fn solve(
3165        &mut self,
3166        mat: &SparseMatrix<T>,
3167        descr: &MatDescr,
3168        b: &[T],
3169        x: &mut [T],
3170    ) -> Result<Box<[T; 100]>>
3171    where
3172        T: Default,
3173    {
3174        let n = mat.n;
3175        if mat.m != mat.n {
3176            return Err(Error::InvalidArgument(format!(
3177                "iterative solve requires square matrix; got ({}, {})",
3178                mat.m, mat.n
3179            )));
3180        }
3181        let mut rinfo: Box<[T; 100]> = Box::new([T::default(); 100]);
3182        T::itsol_solve(self.handle, n, mat.raw, descr, b, x, &mut rinfo)?;
3183        Ok(rinfo)
3184    }
3185}
3186
3187impl<T: Scalar> Drop for IterSolver<T> {
3188    fn drop(&mut self) {
3189        if !self.handle.is_null() {
3190            unsafe {
3191                sys::aoclsparse_itsol_destroy(&mut self.handle);
3192            }
3193            self.handle = std::ptr::null_mut();
3194        }
3195    }
3196}
3197
3198impl<T: Scalar> std::fmt::Debug for IterSolver<T> {
3199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3200        f.debug_struct("IterSolver").finish_non_exhaustive()
3201    }
3202}
3203
3204#[cfg(test)]
3205mod tests {
3206    use super::*;
3207
3208    #[test]
3209    fn csrmv_2x2_identity_f64() {
3210        let val = [1.0_f64, 1.0];
3211        let col: [sys::aoclsparse_int; 2] = [0, 1];
3212        let rowptr: [sys::aoclsparse_int; 3] = [0, 1, 2];
3213        let x = [3.0_f64, 4.0];
3214        let mut y = [0.0_f64; 2];
3215        let descr = MatDescr::new().unwrap();
3216        csrmv(1.0_f64, 2, 2, &val, &col, &rowptr, &descr, &x, 0.0, &mut y).unwrap();
3217        assert!((y[0] - 3.0).abs() < 1e-12);
3218        assert!((y[1] - 4.0).abs() < 1e-12);
3219    }
3220
3221    #[test]
3222    fn csrmv_simple_2x3() {
3223        let val = [1.0_f64, 2.0, 3.0];
3224        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3225        let rowptr: [sys::aoclsparse_int; 3] = [0, 2, 3];
3226        let x = [1.0_f64; 3];
3227        let mut y = [0.0_f64; 2];
3228        let descr = MatDescr::new().unwrap();
3229        csrmv(1.0_f64, 2, 3, &val, &col, &rowptr, &descr, &x, 0.0, &mut y).unwrap();
3230        assert!((y[0] - 3.0).abs() < 1e-12, "got {}", y[0]);
3231        assert!((y[1] - 3.0).abs() < 1e-12, "got {}", y[1]);
3232    }
3233
3234    #[test]
3235    fn dim_mismatch_is_error() {
3236        let val = [1.0_f64];
3237        let col: [sys::aoclsparse_int; 1] = [0];
3238        let rowptr: [sys::aoclsparse_int; 2] = [0, 1];
3239        let x = [1.0_f64];
3240        let mut y = [0.0_f64; 2];
3241        let descr = MatDescr::new().unwrap();
3242        let err = csrmv(1.0_f64, 2, 1, &val, &col, &rowptr, &descr, &x, 0.0, &mut y).unwrap_err();
3243        matches!(err, Error::InvalidArgument(_));
3244    }
3245
3246    #[test]
3247    fn axpyi_scatter() {
3248        // y = [10, 20, 30, 40], x = [1, 2], indx = [0, 2], α = 3
3249        // → y[0] += 3·1 = 13; y[2] += 3·2 = 36
3250        let mut y = [10.0_f64, 20.0, 30.0, 40.0];
3251        let x = [1.0_f64, 2.0];
3252        let indx: [sys::aoclsparse_int; 2] = [0, 2];
3253        axpyi(3.0_f64, &x, &indx, &mut y).unwrap();
3254        assert_eq!(y, [13.0, 20.0, 36.0, 40.0]);
3255    }
3256
3257    #[test]
3258    fn gthr_scatter_round_trip() {
3259        // Gather from y at indx → x; scatter x at indx → into a fresh y2.
3260        let y = [10.0_f64, 20.0, 30.0, 40.0];
3261        let indx: [sys::aoclsparse_int; 2] = [1, 3];
3262        let mut x = [0.0_f64; 2];
3263        gthr(&y, &indx, &mut x).unwrap();
3264        assert_eq!(x, [20.0, 40.0]);
3265
3266        let mut y2 = [0.0_f64; 4];
3267        sctr(&x, &indx, &mut y2).unwrap();
3268        assert_eq!(y2, [0.0, 20.0, 0.0, 40.0]);
3269    }
3270
3271    #[test]
3272    fn add_identity_plus_identity_is_2_diag() {
3273        // A = B = 2x2 identity; C = 1·A + B = 2·I.
3274        let val = [1.0_f64, 1.0];
3275        let col: [sys::aoclsparse_int; 2] = [0, 1];
3276        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
3277        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val).unwrap();
3278        let b = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val).unwrap();
3279        let c = add(Trans::No, &a, 1.0, &b).unwrap();
3280        let (_, _, _, val_c) = c.export_csr().unwrap();
3281        // Both diagonal entries should equal 2.
3282        assert_eq!(val_c.len(), 2);
3283        for v in &val_c {
3284            assert!((v - 2.0).abs() < 1e-12, "got {v}, want 2.0");
3285        }
3286    }
3287
3288    #[test]
3289    fn csrmm_2x2_identity_against_2x3_dense() {
3290        // 2×2 identity sparse A; 2×3 dense B; C = A · B should equal B.
3291        // Row-major: ldb = ldc = 3.
3292        let val = [1.0_f64, 1.0];
3293        let col: [sys::aoclsparse_int; 2] = [0, 1];
3294        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
3295        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val).unwrap();
3296        let descr = MatDescr::new().unwrap();
3297        let b: [f64; 6] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
3298        let mut c = [0.0_f64; 6];
3299        csrmm(
3300            Trans::No,
3301            1.0,
3302            &a,
3303            &descr,
3304            Order::RowMajor,
3305            &b,
3306            3,
3307            3,
3308            0.0,
3309            &mut c,
3310            3,
3311        )
3312        .unwrap();
3313        for (got, want) in c.iter().zip(b.iter()) {
3314            assert!((got - want).abs() < 1e-12, "got {got}, want {want}");
3315        }
3316    }
3317
3318    #[test]
3319    fn spmmd_identity_squared_yields_identity_dense() {
3320        // 3×3 identity * 3×3 identity = 3×3 identity dense.
3321        let val = [1.0_f64; 3];
3322        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3323        let rp: [sys::aoclsparse_int; 4] = [0, 1, 2, 3];
3324        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3325        let b = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3326        let mut c = [0.0_f64; 9];
3327        spmmd(Trans::No, &a, &b, Order::RowMajor, &mut c, 3).unwrap();
3328        // Row-major identity matrix.
3329        let expected = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
3330        for (got, want) in c.iter().zip(expected.iter()) {
3331            assert!((got - want).abs() < 1e-12, "got {got}, want {want}");
3332        }
3333    }
3334
3335    #[test]
3336    fn ellmv_2x3_f64() {
3337        // 2×3: [[1, 0, 2], [3, 4, 0]]; ell_width = 2 (max nnz/row).
3338        // Padding indices/values for the "missing" slot use index 0, value 0.
3339        let val: [f64; 4] = [1.0, 2.0, 3.0, 4.0];
3340        let col: [sys::aoclsparse_int; 4] = [0, 2, 0, 1];
3341        let descr = MatDescr::new().unwrap();
3342        let x = [10.0_f64, 20.0, 30.0];
3343        let mut y = [0.0_f64; 2];
3344        ellmv(
3345            Trans::No,
3346            1.0_f64,
3347            2,
3348            3,
3349            &val,
3350            &col,
3351            2,
3352            &descr,
3353            &x,
3354            0.0,
3355            &mut y,
3356        )
3357        .unwrap();
3358        // y[0] = 1*10 + 2*30 = 70; y[1] = 3*10 + 4*20 = 110
3359        assert!((y[0] - 70.0).abs() < 1e-12, "got {}", y[0]);
3360        assert!((y[1] - 110.0).abs() < 1e-12, "got {}", y[1]);
3361    }
3362
3363    #[test]
3364    fn bsrmv_2x2_blocks_f64() {
3365        // 4×4 matrix laid out as 2×2 blocks of size 2×2:
3366        // block (0,0) = [[1,0],[0,1]] (identity), block (1,1) = [[2,0],[0,2]]
3367        // bsr_dim = 2, mb = 2, nb = 2, nnzb = 2
3368        let val: [f64; 8] = [1.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 2.0];
3369        let col: [sys::aoclsparse_int; 2] = [0, 1];
3370        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
3371        let descr = MatDescr::new().unwrap();
3372        let x = [1.0_f64, 2.0, 3.0, 4.0];
3373        let mut y = [0.0_f64; 4];
3374        bsrmv(
3375            Trans::No,
3376            1.0_f64,
3377            2,
3378            2,
3379            2,
3380            &val,
3381            &col,
3382            &rp,
3383            &descr,
3384            &x,
3385            0.0,
3386            &mut y,
3387        )
3388        .unwrap();
3389        // y = diag([1,1,2,2]) * x = [1, 2, 6, 8]
3390        assert!((y[0] - 1.0).abs() < 1e-12);
3391        assert!((y[1] - 2.0).abs() < 1e-12);
3392        assert!((y[2] - 6.0).abs() < 1e-12);
3393        assert!((y[3] - 8.0).abs() < 1e-12);
3394    }
3395
3396    #[test]
3397    fn sparse_matrix_round_trip() {
3398        // 2×3 matrix [[1,0,2],[0,3,0]]
3399        let val = [1.0_f64, 2.0, 3.0];
3400        let col: [sys::aoclsparse_int; 3] = [0, 2, 1];
3401        let rp: [sys::aoclsparse_int; 3] = [0, 2, 3];
3402        let mat = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 2, 3, &rp, &col, &val).unwrap();
3403        assert_eq!(mat.dims(), (2, 3));
3404        assert_eq!(mat.nnz(), 3);
3405        assert_eq!(mat.base(), IndexBase::Zero);
3406        let (base, rp2, col2, val2) = mat.export_csr().unwrap();
3407        assert_eq!(base, IndexBase::Zero);
3408        assert_eq!(rp2, [0, 2, 3]);
3409        assert_eq!(col2, [0, 2, 1]);
3410        assert_eq!(val2, [1.0, 2.0, 3.0]);
3411    }
3412
3413    #[test]
3414    fn csr2m_identity_squared_is_identity() {
3415        // 3×3 identity in CSR.
3416        let val = [1.0_f64; 3];
3417        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3418        let rp: [sys::aoclsparse_int; 4] = [0, 1, 2, 3];
3419        let a = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3420        let b = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3421        let descr = MatDescr::new().unwrap();
3422        let c = csr2m(
3423            Trans::No,
3424            &descr,
3425            &a,
3426            Trans::No,
3427            &descr,
3428            &b,
3429            Stage::FullComputation,
3430        )
3431        .unwrap();
3432        assert_eq!(c.dims(), (3, 3));
3433        let (_, rp_c, col_c, val_c) = c.export_csr().unwrap();
3434        assert_eq!(rp_c, [0, 1, 2, 3]);
3435        assert_eq!(col_c, [0, 1, 2]);
3436        for v in &val_c {
3437            assert!((v - 1.0).abs() < 1e-12);
3438        }
3439    }
3440
3441    #[test]
3442    fn iter_solver_cg_diagonal_3x3() {
3443        // Solve diag(2,2,2) · x = b, with b = [4, 6, 10]; expected x = [2, 3, 5].
3444        let val = [2.0_f64, 2.0, 2.0];
3445        let col: [sys::aoclsparse_int; 3] = [0, 1, 2];
3446        let rp: [sys::aoclsparse_int; 4] = [0, 1, 2, 3];
3447        let mat = SparseMatrix::<f64>::from_csr(IndexBase::Zero, 3, 3, &rp, &col, &val).unwrap();
3448
3449        let descr = MatDescr::new().unwrap();
3450        unsafe {
3451            sys::aoclsparse_set_mat_type(
3452                descr.as_raw(),
3453                sys::aoclsparse_matrix_type__aoclsparse_matrix_type_symmetric,
3454            );
3455        }
3456
3457        let b = [4.0_f64, 6.0, 10.0];
3458        let mut x = [0.0_f64; 3];
3459        let mut solver = IterSolver::<f64>::new().unwrap();
3460        solver.set_option("iterative method", "cg").unwrap();
3461        solver.set_option("cg rel tolerance", "1e-10").unwrap();
3462        solver.set_option("cg iteration limit", "200").unwrap();
3463        solver.solve(&mat, &descr, &b, &mut x).unwrap();
3464        assert!((x[0] - 2.0).abs() < 1e-6, "x[0] = {}", x[0]);
3465        assert!((x[1] - 3.0).abs() < 1e-6, "x[1] = {}", x[1]);
3466        assert!((x[2] - 5.0).abs() < 1e-6, "x[2] = {}", x[2]);
3467    }
3468
3469    /// 4x4 CSR with two diagonal 2x2 blocks, `[[1,2],[3,4]]` and `[[5,6],[7,8]]`: asymmetric inside each block, so
3470    /// the in-block storage order shows in `bsr_val` (row-major 1,2,3,4 / column-major 1,3,2,4).
3471    #[test]
3472    fn csr2bsr_block_order_f64_and_f32() {
3473        let col: [sys::aoclsparse_int; 8] = [0, 1, 0, 1, 2, 3, 2, 3];
3474        let rowptr: [sys::aoclsparse_int; 5] = [0, 2, 4, 6, 8];
3475        let descr = MatDescr::new().unwrap();
3476        let mut bsr_rowptr = [0 as sys::aoclsparse_int; 3];
3477        let nnzb = csr2bsr_nnz(4, 4, &descr, &rowptr, &col, 2, &mut bsr_rowptr).unwrap();
3478        assert_eq!(nnzb, 2);
3479        assert_eq!(bsr_rowptr, [0, 1, 2]);
3480
3481        let val64: Vec<f64> = (1..=8).map(f64::from).collect();
3482        let val32: Vec<f32> = (1..=8).map(|v| v as f32).collect();
3483        let row_major = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
3484        let col_major = [1.0, 3.0, 2.0, 4.0, 5.0, 7.0, 6.0, 8.0];
3485        for (order, want) in [(Order::RowMajor, row_major), (Order::ColMajor, col_major)] {
3486            let mut rp = bsr_rowptr; // `bsr_row_ptr` comes from the `csr2bsr_nnz` step
3487            let mut ci = [0 as sys::aoclsparse_int; 2];
3488            let mut bv = [0.0_f64; 8];
3489            csr2bsr_f64(
3490                4, 4, &descr, order, &val64, &rowptr, &col, 2, &mut bv, &mut rp, &mut ci,
3491            )
3492            .unwrap();
3493            assert_eq!((rp, ci), ([0, 1, 2], [0, 1]), "{order:?}");
3494            assert_eq!(bv, want, "f64 {order:?}");
3495
3496            let mut rp = bsr_rowptr; // `bsr_row_ptr` comes from the `csr2bsr_nnz` step
3497            let mut ci = [0 as sys::aoclsparse_int; 2];
3498            let mut bv = [0.0_f32; 8];
3499            csr2bsr_f32(
3500                4, 4, &descr, order, &val32, &rowptr, &col, 2, &mut bv, &mut rp, &mut ci,
3501            )
3502            .unwrap();
3503            let want32: Vec<f32> = want.iter().map(|&v| v as f32).collect();
3504            assert_eq!(bv.to_vec(), want32, "f32 {order:?}");
3505        }
3506    }
3507
3508    #[test]
3509    fn csr_to_dense_round_trip() {
3510        // 2×3 CSR: [[1,0,2],[0,3,0]] → val=[1,2,3], col=[0,2,1], rp=[0,2,3]
3511        let val = [1.0_f64, 2.0, 3.0];
3512        let col: [sys::aoclsparse_int; 3] = [0, 2, 1];
3513        let rp: [sys::aoclsparse_int; 3] = [0, 2, 3];
3514        let descr = MatDescr::new().unwrap();
3515        let mut dense = [0.0_f64; 6];
3516        csr_to_dense::<f64>(
3517            2,
3518            3,
3519            &descr,
3520            &val,
3521            &rp,
3522            &col,
3523            &mut dense,
3524            3,
3525            Order::RowMajor,
3526        )
3527        .unwrap();
3528        assert_eq!(dense, [1.0, 0.0, 2.0, 0.0, 3.0, 0.0]);
3529    }
3530}