Skip to main content

aocl_sparse/
lib.rs

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