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