Skip to main content

aocl_sparse/
complex.rs

1//! Complex-precision sparse operations (`Complex32` / `Complex64`).
2//!
3//! These mirror the real-precision API: sparse vector AXPY / gather /
4//! scatter, plus a [`ComplexSparseMatrix`] handle wrapping AOCL's
5//! `aoclsparse_matrix` and operations against it: matrix–vector product
6//! [`mv`], triangular solve [`trsv`], sparse-sparse product [`spmmd`],
7//! ILU(0) smoother [`ilu_smoother`], and the iterative-solver suite via
8//! [`ComplexIterSolver`].
9
10use std::ffi::CString;
11use std::marker::PhantomData;
12
13use aocl_sparse_sys as sys;
14use aocl_types::{sealed::Sealed, Complex32, Complex64};
15
16use crate::{check_status, trans_raw, Error, IndexBase, MatDescr, Order, Result, SorType, Trans};
17
18/// Scalar element type for the complex sparse routines (`c32`, `c64`).
19pub trait ComplexScalar: Copy + Sized + Sealed {
20    /// `y[indx] := α·x + y[indx]` (sparse vector AXPY).
21    fn axpyi(alpha: Self, x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()>;
22
23    /// `x[i] := y[indx[i]]` (gather).
24    fn gthr(y: &[Self], indx: &[sys::aoclsparse_int], x: &mut [Self]) -> Result<()>;
25
26    /// `y[indx[i]] := x[i]` (scatter).
27    fn sctr(x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()>;
28
29    /// Wrap raw CSR pointers in an `aoclsparse_matrix` handle.
30    fn create_csr(
31        base: IndexBase,
32        m: usize,
33        n: usize,
34        nnz: usize,
35        row_ptr: *mut sys::aoclsparse_int,
36        col_idx: *mut sys::aoclsparse_int,
37        val: *mut Self,
38    ) -> Result<sys::aoclsparse_matrix>;
39
40    /// Read out a library-owned CSR matrix's metadata and array pointers.
41    fn export_csr(
42        mat: sys::aoclsparse_matrix,
43    ) -> Result<(
44        IndexBase,
45        usize,
46        usize,
47        usize,
48        *mut sys::aoclsparse_int,
49        *mut sys::aoclsparse_int,
50        *mut Self,
51    )>;
52
53    /// `y := α · op(A) · x + β · y` via the high-level matrix handle.
54    fn mv(
55        op: Trans,
56        alpha: Self,
57        mat: sys::aoclsparse_matrix,
58        descr: &MatDescr,
59        x: &[Self],
60        beta: Self,
61        y: &mut [Self],
62    ) -> Result<()>;
63
64    /// Solve `op(A) · x = α · b` where `A` is sparse triangular.
65    fn trsv(
66        op: Trans,
67        alpha: Self,
68        mat: sys::aoclsparse_matrix,
69        descr: &MatDescr,
70        b: &[Self],
71        x: &mut [Self],
72    ) -> Result<()>;
73
74    /// One ILU(0) smoothing step against the matrix handle.
75    fn ilu_smoother(
76        op: Trans,
77        a: sys::aoclsparse_matrix,
78        descr: &MatDescr,
79        x: &mut [Self],
80        b: &[Self],
81    ) -> Result<()>;
82
83    /// Initialise an iterative-solver handle for this scalar type.
84    fn itsol_init(handle: &mut sys::aoclsparse_itsol_handle) -> Result<()>;
85
86    /// Run the iterative solver's forward (direct) interface.
87    fn itsol_solve(
88        handle: sys::aoclsparse_itsol_handle,
89        n: usize,
90        mat: sys::aoclsparse_matrix,
91        descr: &MatDescr,
92        b: &[Self],
93        x: &mut [Self],
94        rinfo: &mut [Self::Real; 100],
95    ) -> Result<()>;
96
97    /// `C := α · op(A) · B + β · C` where `A` is sparse (CSR via the
98    /// matrix handle) and `B`, `C` are dense.
99    fn csrmm(
100        op: Trans,
101        alpha: Self,
102        a: sys::aoclsparse_matrix,
103        descr: &MatDescr,
104        order: Order,
105        b: &[Self],
106        n: usize,
107        ldb: usize,
108        beta: Self,
109        c: &mut [Self],
110        ldc: usize,
111    ) -> Result<()>;
112
113    /// `C := op(A) · B` where both `A` and `B` are sparse and `C` is dense.
114    fn spmmd(
115        op: Trans,
116        a: sys::aoclsparse_matrix,
117        b: sys::aoclsparse_matrix,
118        layout: Order,
119        c: &mut [Self],
120        ldc: usize,
121    ) -> Result<()>;
122
123    /// `C := α · op_A(A) · op_B(B) + β · C` (sparse·sparse → dense).
124    fn sp2md(
125        op_a: Trans,
126        descr_a: &MatDescr,
127        a: sys::aoclsparse_matrix,
128        op_b: Trans,
129        descr_b: &MatDescr,
130        b: sys::aoclsparse_matrix,
131        alpha: Self,
132        beta: Self,
133        c: &mut [Self],
134        layout: Order,
135        ldc: usize,
136    ) -> Result<()>;
137
138    /// Sparse-sparse `C := α · op(A) + B`.
139    ///
140    /// # Safety
141    /// Caller must adopt the resulting handle (e.g. via
142    /// [`ComplexSparseMatrix::from_library_owned`]).
143    unsafe fn add_ffi(
144        op: sys::aoclsparse_operation,
145        a: sys::aoclsparse_matrix,
146        alpha: Self,
147        b: sys::aoclsparse_matrix,
148        out: *mut sys::aoclsparse_matrix,
149    ) -> sys::aoclsparse_status;
150
151    /// One step of (S)SOR / forward / backward Gauss-Seidel relaxation.
152    fn sorv(
153        sor_type: SorType,
154        descr: &MatDescr,
155        a: sys::aoclsparse_matrix,
156        omega: Self,
157        alpha: Self,
158        x: &mut [Self],
159        b: &[Self],
160    ) -> Result<()>;
161
162    /// Underlying real type — `f32` for `Complex32`, `f64` for `Complex64`.
163    /// Used to type the `rinfo[100]` array returned by iterative solvers,
164    /// which is real-valued even for complex problems.
165    type Real: Copy + Default;
166}
167
168// =========================================================================
169//   Complex32 (c32) impl
170// =========================================================================
171
172impl ComplexScalar for Complex32 {
173    type Real = f32;
174
175    fn axpyi(alpha: Self, x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()> {
176        let status = unsafe {
177            sys::aoclsparse_caxpyi(
178                x.len() as sys::aoclsparse_int,
179                &alpha as *const _ as *const std::os::raw::c_void,
180                x.as_ptr() as *const std::os::raw::c_void,
181                indx.as_ptr(),
182                y.as_mut_ptr() as *mut std::os::raw::c_void,
183            )
184        };
185        check_status("sparse", status)
186    }
187
188    fn gthr(y: &[Self], indx: &[sys::aoclsparse_int], x: &mut [Self]) -> Result<()> {
189        let status = unsafe {
190            sys::aoclsparse_cgthr(
191                x.len() as sys::aoclsparse_int,
192                y.as_ptr() as *const std::os::raw::c_void,
193                x.as_mut_ptr() as *mut std::os::raw::c_void,
194                indx.as_ptr(),
195            )
196        };
197        check_status("sparse", status)
198    }
199
200    fn sctr(x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()> {
201        let status = unsafe {
202            sys::aoclsparse_csctr(
203                x.len() as sys::aoclsparse_int,
204                x.as_ptr() as *const std::os::raw::c_void,
205                indx.as_ptr(),
206                y.as_mut_ptr() as *mut std::os::raw::c_void,
207            )
208        };
209        check_status("sparse", status)
210    }
211
212    fn create_csr(
213        base: IndexBase,
214        m: usize,
215        n: usize,
216        nnz: usize,
217        row_ptr: *mut sys::aoclsparse_int,
218        col_idx: *mut sys::aoclsparse_int,
219        val: *mut Self,
220    ) -> Result<sys::aoclsparse_matrix> {
221        let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
222        let status = unsafe {
223            sys::aoclsparse_create_ccsr(
224                &mut raw,
225                base.raw_for_complex(),
226                m as sys::aoclsparse_int,
227                n as sys::aoclsparse_int,
228                nnz as sys::aoclsparse_int,
229                row_ptr,
230                col_idx,
231                val as *mut sys::aoclsparse_float_complex,
232            )
233        };
234        check_status("sparse", status)?;
235        if raw.is_null() {
236            return Err(Error::AllocationFailed("sparse"));
237        }
238        Ok(raw)
239    }
240
241    fn export_csr(
242        mat: sys::aoclsparse_matrix,
243    ) -> Result<(
244        IndexBase,
245        usize,
246        usize,
247        usize,
248        *mut sys::aoclsparse_int,
249        *mut sys::aoclsparse_int,
250        *mut Self,
251    )> {
252        let mut base: sys::aoclsparse_index_base = 0;
253        let mut m: sys::aoclsparse_int = 0;
254        let mut n: sys::aoclsparse_int = 0;
255        let mut nnz: sys::aoclsparse_int = 0;
256        let mut row_ptr: *mut sys::aoclsparse_int = std::ptr::null_mut();
257        let mut col_ind: *mut sys::aoclsparse_int = std::ptr::null_mut();
258        let mut val: *mut sys::aoclsparse_float_complex = std::ptr::null_mut();
259        let status = unsafe {
260            sys::aoclsparse_export_ccsr(
261                mat,
262                &mut base,
263                &mut m,
264                &mut n,
265                &mut nnz,
266                &mut row_ptr,
267                &mut col_ind,
268                &mut val,
269            )
270        };
271        check_status("sparse", status)?;
272        let base_e = if base == sys::aoclsparse_index_base__aoclsparse_index_base_one {
273            IndexBase::One
274        } else {
275            IndexBase::Zero
276        };
277        Ok((
278            base_e,
279            m as usize,
280            n as usize,
281            nnz as usize,
282            row_ptr,
283            col_ind,
284            val as *mut Self,
285        ))
286    }
287
288    fn mv(
289        op: Trans,
290        alpha: Self,
291        mat: sys::aoclsparse_matrix,
292        descr: &MatDescr,
293        x: &[Self],
294        beta: Self,
295        y: &mut [Self],
296    ) -> Result<()> {
297        let status = unsafe {
298            sys::aoclsparse_cmv(
299                trans_raw(op),
300                &alpha as *const _ as *const sys::aoclsparse_float_complex,
301                mat,
302                descr.as_raw(),
303                x.as_ptr() as *const sys::aoclsparse_float_complex,
304                &beta as *const _ as *const sys::aoclsparse_float_complex,
305                y.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
306            )
307        };
308        check_status("sparse", status)
309    }
310
311    fn trsv(
312        op: Trans,
313        alpha: Self,
314        mat: sys::aoclsparse_matrix,
315        descr: &MatDescr,
316        b: &[Self],
317        x: &mut [Self],
318    ) -> Result<()> {
319        // aoclsparse_ctrsv takes alpha by-value (struct), unlike mv.
320        let alpha_raw = sys::aoclsparse_float_complex {
321            real: alpha.re,
322            imag: alpha.im,
323        };
324        let status = unsafe {
325            sys::aoclsparse_ctrsv(
326                trans_raw(op),
327                alpha_raw,
328                mat,
329                descr.as_raw(),
330                b.as_ptr() as *const sys::aoclsparse_float_complex,
331                x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
332            )
333        };
334        check_status("sparse", status)
335    }
336
337    fn ilu_smoother(
338        op: Trans,
339        a: sys::aoclsparse_matrix,
340        descr: &MatDescr,
341        x: &mut [Self],
342        b: &[Self],
343    ) -> Result<()> {
344        let mut precond_csr_val: *mut sys::aoclsparse_float_complex = std::ptr::null_mut();
345        let status = unsafe {
346            sys::aoclsparse_cilu_smoother(
347                trans_raw(op),
348                a,
349                descr.as_raw(),
350                &mut precond_csr_val,
351                std::ptr::null(),
352                x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
353                b.as_ptr() as *const sys::aoclsparse_float_complex,
354            )
355        };
356        check_status("sparse", status)
357    }
358
359    fn itsol_init(handle: &mut sys::aoclsparse_itsol_handle) -> Result<()> {
360        let status = unsafe { sys::aoclsparse_itsol_c_init(handle) };
361        check_status("sparse", status)
362    }
363
364    fn itsol_solve(
365        handle: sys::aoclsparse_itsol_handle,
366        n: usize,
367        mat: sys::aoclsparse_matrix,
368        descr: &MatDescr,
369        b: &[Self],
370        x: &mut [Self],
371        rinfo: &mut [f32; 100],
372    ) -> Result<()> {
373        if b.len() < n || x.len() < n {
374            return Err(Error::InvalidArgument(format!(
375                "itsol_solve: b.len()={}, x.len()={}, n={n}",
376                b.len(),
377                x.len()
378            )));
379        }
380        let status = unsafe {
381            sys::aoclsparse_itsol_c_solve(
382                handle,
383                n as sys::aoclsparse_int,
384                mat,
385                descr.as_raw(),
386                b.as_ptr() as *const sys::aoclsparse_float_complex,
387                x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
388                rinfo.as_mut_ptr(),
389                None,
390                None,
391                std::ptr::null_mut(),
392            )
393        };
394        check_status("sparse", status)
395    }
396
397    fn csrmm(
398        op: Trans,
399        alpha: Self,
400        a: sys::aoclsparse_matrix,
401        descr: &MatDescr,
402        order: Order,
403        b: &[Self],
404        n: usize,
405        ldb: usize,
406        beta: Self,
407        c: &mut [Self],
408        ldc: usize,
409    ) -> Result<()> {
410        let alpha_raw = sys::aoclsparse_float_complex {
411            real: alpha.re,
412            imag: alpha.im,
413        };
414        let beta_raw = sys::aoclsparse_float_complex {
415            real: beta.re,
416            imag: beta.im,
417        };
418        let status = unsafe {
419            sys::aoclsparse_ccsrmm(
420                trans_raw(op),
421                alpha_raw,
422                a,
423                descr.as_raw(),
424                order.raw(),
425                b.as_ptr() as *const sys::aoclsparse_float_complex,
426                n as sys::aoclsparse_int,
427                ldb as sys::aoclsparse_int,
428                beta_raw,
429                c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
430                ldc as sys::aoclsparse_int,
431            )
432        };
433        check_status("sparse", status)
434    }
435
436    fn spmmd(
437        op: Trans,
438        a: sys::aoclsparse_matrix,
439        b: sys::aoclsparse_matrix,
440        layout: Order,
441        c: &mut [Self],
442        ldc: usize,
443    ) -> Result<()> {
444        let status = unsafe {
445            sys::aoclsparse_cspmmd(
446                trans_raw(op),
447                a,
448                b,
449                layout.raw(),
450                c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
451                ldc as sys::aoclsparse_int,
452            )
453        };
454        check_status("sparse", status)
455    }
456
457    fn sp2md(
458        op_a: Trans,
459        descr_a: &MatDescr,
460        a: sys::aoclsparse_matrix,
461        op_b: Trans,
462        descr_b: &MatDescr,
463        b: sys::aoclsparse_matrix,
464        alpha: Self,
465        beta: Self,
466        c: &mut [Self],
467        layout: Order,
468        ldc: usize,
469    ) -> Result<()> {
470        let alpha_raw = sys::aoclsparse_float_complex {
471            real: alpha.re,
472            imag: alpha.im,
473        };
474        let beta_raw = sys::aoclsparse_float_complex {
475            real: beta.re,
476            imag: beta.im,
477        };
478        let status = unsafe {
479            sys::aoclsparse_csp2md(
480                trans_raw(op_a),
481                descr_a.as_raw(),
482                a,
483                trans_raw(op_b),
484                descr_b.as_raw(),
485                b,
486                alpha_raw,
487                beta_raw,
488                c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
489                layout.raw(),
490                ldc as sys::aoclsparse_int,
491            )
492        };
493        check_status("sparse", status)
494    }
495
496    unsafe fn add_ffi(
497        op: sys::aoclsparse_operation,
498        a: sys::aoclsparse_matrix,
499        alpha: Self,
500        b: sys::aoclsparse_matrix,
501        out: *mut sys::aoclsparse_matrix,
502    ) -> sys::aoclsparse_status {
503        let alpha_raw = sys::aoclsparse_float_complex {
504            real: alpha.re,
505            imag: alpha.im,
506        };
507        sys::aoclsparse_cadd(op, a, alpha_raw, b, out)
508    }
509
510    fn sorv(
511        sor_type: SorType,
512        descr: &MatDescr,
513        a: sys::aoclsparse_matrix,
514        omega: Self,
515        alpha: Self,
516        x: &mut [Self],
517        b: &[Self],
518    ) -> Result<()> {
519        let omega_raw = sys::aoclsparse_float_complex {
520            real: omega.re,
521            imag: omega.im,
522        };
523        let alpha_raw = sys::aoclsparse_float_complex {
524            real: alpha.re,
525            imag: alpha.im,
526        };
527        let status = unsafe {
528            sys::aoclsparse_csorv(
529                sor_type.raw(),
530                descr.as_raw(),
531                a,
532                omega_raw,
533                alpha_raw,
534                x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
535                b.as_ptr() as *const sys::aoclsparse_float_complex,
536            )
537        };
538        check_status("sparse", status)
539    }
540}
541
542// =========================================================================
543//   Complex64 (c64) impl
544// =========================================================================
545
546impl ComplexScalar for Complex64 {
547    type Real = f64;
548
549    fn axpyi(alpha: Self, x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()> {
550        let status = unsafe {
551            sys::aoclsparse_zaxpyi(
552                x.len() as sys::aoclsparse_int,
553                &alpha as *const _ as *const std::os::raw::c_void,
554                x.as_ptr() as *const std::os::raw::c_void,
555                indx.as_ptr(),
556                y.as_mut_ptr() as *mut std::os::raw::c_void,
557            )
558        };
559        check_status("sparse", status)
560    }
561
562    fn gthr(y: &[Self], indx: &[sys::aoclsparse_int], x: &mut [Self]) -> Result<()> {
563        let status = unsafe {
564            sys::aoclsparse_zgthr(
565                x.len() as sys::aoclsparse_int,
566                y.as_ptr() as *const std::os::raw::c_void,
567                x.as_mut_ptr() as *mut std::os::raw::c_void,
568                indx.as_ptr(),
569            )
570        };
571        check_status("sparse", status)
572    }
573
574    fn sctr(x: &[Self], indx: &[sys::aoclsparse_int], y: &mut [Self]) -> Result<()> {
575        let status = unsafe {
576            sys::aoclsparse_zsctr(
577                x.len() as sys::aoclsparse_int,
578                x.as_ptr() as *const std::os::raw::c_void,
579                indx.as_ptr(),
580                y.as_mut_ptr() as *mut std::os::raw::c_void,
581            )
582        };
583        check_status("sparse", status)
584    }
585
586    fn create_csr(
587        base: IndexBase,
588        m: usize,
589        n: usize,
590        nnz: usize,
591        row_ptr: *mut sys::aoclsparse_int,
592        col_idx: *mut sys::aoclsparse_int,
593        val: *mut Self,
594    ) -> Result<sys::aoclsparse_matrix> {
595        let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
596        let status = unsafe {
597            sys::aoclsparse_create_zcsr(
598                &mut raw,
599                base.raw_for_complex(),
600                m as sys::aoclsparse_int,
601                n as sys::aoclsparse_int,
602                nnz as sys::aoclsparse_int,
603                row_ptr,
604                col_idx,
605                val as *mut sys::aoclsparse_double_complex,
606            )
607        };
608        check_status("sparse", status)?;
609        if raw.is_null() {
610            return Err(Error::AllocationFailed("sparse"));
611        }
612        Ok(raw)
613    }
614
615    fn export_csr(
616        mat: sys::aoclsparse_matrix,
617    ) -> Result<(
618        IndexBase,
619        usize,
620        usize,
621        usize,
622        *mut sys::aoclsparse_int,
623        *mut sys::aoclsparse_int,
624        *mut Self,
625    )> {
626        let mut base: sys::aoclsparse_index_base = 0;
627        let mut m: sys::aoclsparse_int = 0;
628        let mut n: sys::aoclsparse_int = 0;
629        let mut nnz: sys::aoclsparse_int = 0;
630        let mut row_ptr: *mut sys::aoclsparse_int = std::ptr::null_mut();
631        let mut col_ind: *mut sys::aoclsparse_int = std::ptr::null_mut();
632        let mut val: *mut sys::aoclsparse_double_complex = std::ptr::null_mut();
633        let status = unsafe {
634            sys::aoclsparse_export_zcsr(
635                mat,
636                &mut base,
637                &mut m,
638                &mut n,
639                &mut nnz,
640                &mut row_ptr,
641                &mut col_ind,
642                &mut val,
643            )
644        };
645        check_status("sparse", status)?;
646        let base_e = if base == sys::aoclsparse_index_base__aoclsparse_index_base_one {
647            IndexBase::One
648        } else {
649            IndexBase::Zero
650        };
651        Ok((
652            base_e,
653            m as usize,
654            n as usize,
655            nnz as usize,
656            row_ptr,
657            col_ind,
658            val as *mut Self,
659        ))
660    }
661
662    fn mv(
663        op: Trans,
664        alpha: Self,
665        mat: sys::aoclsparse_matrix,
666        descr: &MatDescr,
667        x: &[Self],
668        beta: Self,
669        y: &mut [Self],
670    ) -> Result<()> {
671        let status = unsafe {
672            sys::aoclsparse_zmv(
673                trans_raw(op),
674                &alpha as *const _ as *const sys::aoclsparse_double_complex,
675                mat,
676                descr.as_raw(),
677                x.as_ptr() as *const sys::aoclsparse_double_complex,
678                &beta as *const _ as *const sys::aoclsparse_double_complex,
679                y.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
680            )
681        };
682        check_status("sparse", status)
683    }
684
685    fn trsv(
686        op: Trans,
687        alpha: Self,
688        mat: sys::aoclsparse_matrix,
689        descr: &MatDescr,
690        b: &[Self],
691        x: &mut [Self],
692    ) -> Result<()> {
693        let alpha_raw = sys::aoclsparse_double_complex_ {
694            real: alpha.re,
695            imag: alpha.im,
696        };
697        let status = unsafe {
698            sys::aoclsparse_ztrsv(
699                trans_raw(op),
700                alpha_raw,
701                mat,
702                descr.as_raw(),
703                b.as_ptr() as *const sys::aoclsparse_double_complex,
704                x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
705            )
706        };
707        check_status("sparse", status)
708    }
709
710    fn ilu_smoother(
711        op: Trans,
712        a: sys::aoclsparse_matrix,
713        descr: &MatDescr,
714        x: &mut [Self],
715        b: &[Self],
716    ) -> Result<()> {
717        let mut precond_csr_val: *mut sys::aoclsparse_double_complex = std::ptr::null_mut();
718        let status = unsafe {
719            sys::aoclsparse_zilu_smoother(
720                trans_raw(op),
721                a,
722                descr.as_raw(),
723                &mut precond_csr_val,
724                std::ptr::null(),
725                x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
726                b.as_ptr() as *const sys::aoclsparse_double_complex,
727            )
728        };
729        check_status("sparse", status)
730    }
731
732    fn itsol_init(handle: &mut sys::aoclsparse_itsol_handle) -> Result<()> {
733        let status = unsafe { sys::aoclsparse_itsol_z_init(handle) };
734        check_status("sparse", status)
735    }
736
737    fn itsol_solve(
738        handle: sys::aoclsparse_itsol_handle,
739        n: usize,
740        mat: sys::aoclsparse_matrix,
741        descr: &MatDescr,
742        b: &[Self],
743        x: &mut [Self],
744        rinfo: &mut [f64; 100],
745    ) -> Result<()> {
746        if b.len() < n || x.len() < n {
747            return Err(Error::InvalidArgument(format!(
748                "itsol_solve: b.len()={}, x.len()={}, n={n}",
749                b.len(),
750                x.len()
751            )));
752        }
753        let status = unsafe {
754            sys::aoclsparse_itsol_z_solve(
755                handle,
756                n as sys::aoclsparse_int,
757                mat,
758                descr.as_raw(),
759                b.as_ptr() as *const sys::aoclsparse_double_complex,
760                x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
761                rinfo.as_mut_ptr(),
762                None,
763                None,
764                std::ptr::null_mut(),
765            )
766        };
767        check_status("sparse", status)
768    }
769
770    fn csrmm(
771        op: Trans,
772        alpha: Self,
773        a: sys::aoclsparse_matrix,
774        descr: &MatDescr,
775        order: Order,
776        b: &[Self],
777        n: usize,
778        ldb: usize,
779        beta: Self,
780        c: &mut [Self],
781        ldc: usize,
782    ) -> Result<()> {
783        let alpha_raw = sys::aoclsparse_double_complex_ {
784            real: alpha.re,
785            imag: alpha.im,
786        };
787        let beta_raw = sys::aoclsparse_double_complex_ {
788            real: beta.re,
789            imag: beta.im,
790        };
791        let status = unsafe {
792            sys::aoclsparse_zcsrmm(
793                trans_raw(op),
794                alpha_raw,
795                a,
796                descr.as_raw(),
797                order.raw(),
798                b.as_ptr() as *const sys::aoclsparse_double_complex,
799                n as sys::aoclsparse_int,
800                ldb as sys::aoclsparse_int,
801                beta_raw,
802                c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
803                ldc as sys::aoclsparse_int,
804            )
805        };
806        check_status("sparse", status)
807    }
808
809    fn spmmd(
810        op: Trans,
811        a: sys::aoclsparse_matrix,
812        b: sys::aoclsparse_matrix,
813        layout: Order,
814        c: &mut [Self],
815        ldc: usize,
816    ) -> Result<()> {
817        let status = unsafe {
818            sys::aoclsparse_zspmmd(
819                trans_raw(op),
820                a,
821                b,
822                layout.raw(),
823                c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
824                ldc as sys::aoclsparse_int,
825            )
826        };
827        check_status("sparse", status)
828    }
829
830    fn sp2md(
831        op_a: Trans,
832        descr_a: &MatDescr,
833        a: sys::aoclsparse_matrix,
834        op_b: Trans,
835        descr_b: &MatDescr,
836        b: sys::aoclsparse_matrix,
837        alpha: Self,
838        beta: Self,
839        c: &mut [Self],
840        layout: Order,
841        ldc: usize,
842    ) -> Result<()> {
843        let alpha_raw = sys::aoclsparse_double_complex_ {
844            real: alpha.re,
845            imag: alpha.im,
846        };
847        let beta_raw = sys::aoclsparse_double_complex_ {
848            real: beta.re,
849            imag: beta.im,
850        };
851        let status = unsafe {
852            sys::aoclsparse_zsp2md(
853                trans_raw(op_a),
854                descr_a.as_raw(),
855                a,
856                trans_raw(op_b),
857                descr_b.as_raw(),
858                b,
859                alpha_raw,
860                beta_raw,
861                c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
862                layout.raw(),
863                ldc as sys::aoclsparse_int,
864            )
865        };
866        check_status("sparse", status)
867    }
868
869    unsafe fn add_ffi(
870        op: sys::aoclsparse_operation,
871        a: sys::aoclsparse_matrix,
872        alpha: Self,
873        b: sys::aoclsparse_matrix,
874        out: *mut sys::aoclsparse_matrix,
875    ) -> sys::aoclsparse_status {
876        let alpha_raw = sys::aoclsparse_double_complex_ {
877            real: alpha.re,
878            imag: alpha.im,
879        };
880        sys::aoclsparse_zadd(op, a, alpha_raw, b, out)
881    }
882
883    fn sorv(
884        sor_type: SorType,
885        descr: &MatDescr,
886        a: sys::aoclsparse_matrix,
887        omega: Self,
888        alpha: Self,
889        x: &mut [Self],
890        b: &[Self],
891    ) -> Result<()> {
892        let omega_raw = sys::aoclsparse_double_complex_ {
893            real: omega.re,
894            imag: omega.im,
895        };
896        let alpha_raw = sys::aoclsparse_double_complex_ {
897            real: alpha.re,
898            imag: alpha.im,
899        };
900        let status = unsafe {
901            sys::aoclsparse_zsorv(
902                sor_type.raw(),
903                descr.as_raw(),
904                a,
905                omega_raw,
906                alpha_raw,
907                x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
908                b.as_ptr() as *const sys::aoclsparse_double_complex,
909            )
910        };
911        check_status("sparse", status)
912    }
913}
914
915// =========================================================================
916//   Complex sparse matrix handle
917// =========================================================================
918
919enum CsrStorage<T: ComplexScalar> {
920    Owned {
921        _row_ptr: Vec<sys::aoclsparse_int>,
922        _col_ind: Vec<sys::aoclsparse_int>,
923        _val: Vec<T>,
924    },
925    LibraryOwned,
926}
927
928/// RAII wrapper for a complex `aoclsparse_matrix` in CSR format.
929pub struct ComplexSparseMatrix<T: ComplexScalar> {
930    raw: sys::aoclsparse_matrix,
931    #[allow(
932        dead_code,
933        reason = "owns the buffers the C library keeps pointers into"
934    )]
935    storage: CsrStorage<T>,
936    base: IndexBase,
937    m: usize,
938    n: usize,
939    nnz: usize,
940}
941
942impl<T: ComplexScalar> ComplexSparseMatrix<T> {
943    /// Build from CSR arrays. Values are copied into the wrapper.
944    pub fn from_csr(
945        base: IndexBase,
946        m: usize,
947        n: usize,
948        row_ptr: &[sys::aoclsparse_int],
949        col_ind: &[sys::aoclsparse_int],
950        val: &[T],
951    ) -> Result<Self> {
952        if row_ptr.len() != m + 1 {
953            return Err(Error::InvalidArgument(format!(
954                "complex from_csr: row_ptr length {} != m+1 = {}",
955                row_ptr.len(),
956                m + 1
957            )));
958        }
959        let nnz = val.len();
960        if col_ind.len() != nnz {
961            return Err(Error::InvalidArgument(format!(
962                "complex from_csr: col_ind length {} != val length {nnz}",
963                col_ind.len()
964            )));
965        }
966        let mut row_ptr = row_ptr.to_vec();
967        let mut col_ind = col_ind.to_vec();
968        let mut val = val.to_vec();
969        let raw = T::create_csr(
970            base,
971            m,
972            n,
973            nnz,
974            row_ptr.as_mut_ptr(),
975            col_ind.as_mut_ptr(),
976            val.as_mut_ptr(),
977        )?;
978        Ok(Self {
979            raw,
980            storage: CsrStorage::Owned {
981                _row_ptr: row_ptr,
982                _col_ind: col_ind,
983                _val: val,
984            },
985            base,
986            m,
987            n,
988            nnz,
989        })
990    }
991
992    /// Adopt a library-allocated matrix handle (e.g. the result of
993    /// [`spmmd`]).
994    ///
995    /// # Safety
996    /// `raw` must be a valid `aoclsparse_matrix` whose precision matches
997    /// `T` and whose internal storage is library-owned.
998    pub unsafe fn from_library_owned(raw: sys::aoclsparse_matrix) -> Result<Self> {
999        if raw.is_null() {
1000            return Err(Error::AllocationFailed("sparse"));
1001        }
1002        let (base, m, n, nnz, _, _, _) = T::export_csr(raw)?;
1003        Ok(Self {
1004            raw,
1005            storage: CsrStorage::LibraryOwned,
1006            base,
1007            m,
1008            n,
1009            nnz,
1010        })
1011    }
1012
1013    /// `(m, n)` dimensions.
1014    pub fn dims(&self) -> (usize, usize) {
1015        (self.m, self.n)
1016    }
1017    /// Number of explicitly stored non-zeros.
1018    pub fn nnz(&self) -> usize {
1019        self.nnz
1020    }
1021    /// Index base for row-pointer / column-index arrays.
1022    pub fn base(&self) -> IndexBase {
1023        self.base
1024    }
1025
1026    /// Borrow the raw `aoclsparse_matrix` handle. Do not call
1027    /// `aoclsparse_destroy` on it; the wrapper does.
1028    pub fn as_raw(&self) -> sys::aoclsparse_matrix {
1029        self.raw
1030    }
1031
1032    /// Read out the CSR contents as freshly allocated `Vec`s.
1033    pub fn export_csr(
1034        &self,
1035    ) -> Result<(
1036        IndexBase,
1037        Vec<sys::aoclsparse_int>,
1038        Vec<sys::aoclsparse_int>,
1039        Vec<T>,
1040    )> {
1041        let (base, m, _, nnz, row_ptr, col_ind, val) = T::export_csr(self.raw)?;
1042        let row_ptr = unsafe { std::slice::from_raw_parts(row_ptr, m + 1).to_vec() };
1043        let col_ind = unsafe { std::slice::from_raw_parts(col_ind, nnz).to_vec() };
1044        let val = unsafe { std::slice::from_raw_parts(val, nnz).to_vec() };
1045        Ok((base, row_ptr, col_ind, val))
1046    }
1047}
1048
1049impl<T: ComplexScalar> Drop for ComplexSparseMatrix<T> {
1050    fn drop(&mut self) {
1051        if !self.raw.is_null() {
1052            unsafe {
1053                let _ = sys::aoclsparse_destroy(&mut self.raw);
1054            }
1055            self.raw = std::ptr::null_mut();
1056        }
1057    }
1058}
1059
1060impl<T: ComplexScalar> std::fmt::Debug for ComplexSparseMatrix<T> {
1061    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1062        f.debug_struct("ComplexSparseMatrix")
1063            .field("m", &self.m)
1064            .field("n", &self.n)
1065            .field("nnz", &self.nnz)
1066            .field("base", &self.base)
1067            .finish()
1068    }
1069}
1070
1071// =========================================================================
1072//   Free functions
1073// =========================================================================
1074
1075/// `y[indx] := α·x + y[indx]`. `x` and `indx` must have equal length.
1076pub fn axpyi<T: ComplexScalar>(
1077    alpha: T,
1078    x: &[T],
1079    indx: &[sys::aoclsparse_int],
1080    y: &mut [T],
1081) -> Result<()> {
1082    if x.len() != indx.len() {
1083        return Err(Error::InvalidArgument(format!(
1084            "axpyi: x.len()={}, indx.len()={}",
1085            x.len(),
1086            indx.len()
1087        )));
1088    }
1089    T::axpyi(alpha, x, indx, y)
1090}
1091
1092/// `x[i] := y[indx[i]]` (sparse gather).
1093pub fn gthr<T: ComplexScalar>(y: &[T], indx: &[sys::aoclsparse_int], x: &mut [T]) -> Result<()> {
1094    if x.len() != indx.len() {
1095        return Err(Error::InvalidArgument(format!(
1096            "gthr: x.len()={}, indx.len()={}",
1097            x.len(),
1098            indx.len()
1099        )));
1100    }
1101    T::gthr(y, indx, x)
1102}
1103
1104/// `y[indx[i]] := x[i]` (sparse scatter).
1105pub fn sctr<T: ComplexScalar>(x: &[T], indx: &[sys::aoclsparse_int], y: &mut [T]) -> Result<()> {
1106    if x.len() != indx.len() {
1107        return Err(Error::InvalidArgument(format!(
1108            "sctr: x.len()={}, indx.len()={}",
1109            x.len(),
1110            indx.len()
1111        )));
1112    }
1113    T::sctr(x, indx, y)
1114}
1115
1116/// Compute `y := α · op(A) · x + β · y` for a complex CSR matrix `A`.
1117pub fn mv<T: ComplexScalar>(
1118    op: Trans,
1119    alpha: T,
1120    a: &ComplexSparseMatrix<T>,
1121    descr: &MatDescr,
1122    x: &[T],
1123    beta: T,
1124    y: &mut [T],
1125) -> Result<()> {
1126    let (x_len, y_len) = match op {
1127        Trans::No => (a.n, a.m),
1128        Trans::T | Trans::C => (a.m, a.n),
1129    };
1130    if x.len() < x_len || y.len() < y_len {
1131        return Err(Error::InvalidArgument(format!(
1132            "mv: x.len()={}, y.len()={}, expected ({x_len}, {y_len})",
1133            x.len(),
1134            y.len()
1135        )));
1136    }
1137    T::mv(op, alpha, a.raw, descr, x, beta, y)
1138}
1139
1140/// Solve `op(A) · x = α · b` where `A` is sparse triangular.
1141pub fn trsv<T: ComplexScalar>(
1142    op: Trans,
1143    alpha: T,
1144    a: &ComplexSparseMatrix<T>,
1145    descr: &MatDescr,
1146    b: &[T],
1147    x: &mut [T],
1148) -> Result<()> {
1149    if b.len() < a.m || x.len() < a.m {
1150        return Err(Error::InvalidArgument(format!(
1151            "trsv: b.len()={}, x.len()={}, m={}",
1152            b.len(),
1153            x.len(),
1154            a.m
1155        )));
1156    }
1157    T::trsv(op, alpha, a.raw, descr, b, x)
1158}
1159
1160/// Compute `C := α · op(A) · B + β · C` where `A` is sparse complex
1161/// (CSR) and `B`, `C` are dense complex matrices laid out per `order`.
1162pub fn csrmm<T: ComplexScalar>(
1163    op: Trans,
1164    alpha: T,
1165    a: &ComplexSparseMatrix<T>,
1166    descr: &MatDescr,
1167    order: Order,
1168    b: &[T],
1169    n: usize,
1170    ldb: usize,
1171    beta: T,
1172    c: &mut [T],
1173    ldc: usize,
1174) -> Result<()> {
1175    T::csrmm(op, alpha, a.as_raw(), descr, order, b, n, ldb, beta, c, ldc)
1176}
1177
1178/// Compute `C := op(A) · B` where both `A` and `B` are sparse complex
1179/// matrices and `C` is dense.
1180pub fn spmmd<T: ComplexScalar>(
1181    op: Trans,
1182    a: &ComplexSparseMatrix<T>,
1183    b: &ComplexSparseMatrix<T>,
1184    layout: Order,
1185    c: &mut [T],
1186    ldc: usize,
1187) -> Result<()> {
1188    T::spmmd(op, a.as_raw(), b.as_raw(), layout, c, ldc)
1189}
1190
1191/// Compute `C := α · op_A(A) · op_B(B) + β · C` for complex sparse `A`
1192/// and `B`, dense complex `C`.
1193pub fn sp2md<T: ComplexScalar>(
1194    op_a: Trans,
1195    descr_a: &MatDescr,
1196    a: &ComplexSparseMatrix<T>,
1197    op_b: Trans,
1198    descr_b: &MatDescr,
1199    b: &ComplexSparseMatrix<T>,
1200    alpha: T,
1201    beta: T,
1202    c: &mut [T],
1203    layout: Order,
1204    ldc: usize,
1205) -> Result<()> {
1206    T::sp2md(
1207        op_a,
1208        descr_a,
1209        a.as_raw(),
1210        op_b,
1211        descr_b,
1212        b.as_raw(),
1213        alpha,
1214        beta,
1215        c,
1216        layout,
1217        ldc,
1218    )
1219}
1220
1221/// Compute `C := α · op(A) + B` returning a fresh complex CSR matrix.
1222pub fn add<T: ComplexScalar>(
1223    op: Trans,
1224    a: &ComplexSparseMatrix<T>,
1225    alpha: T,
1226    b: &ComplexSparseMatrix<T>,
1227) -> Result<ComplexSparseMatrix<T>> {
1228    let mut c_raw: sys::aoclsparse_matrix = std::ptr::null_mut();
1229    let status = unsafe { T::add_ffi(trans_raw(op), a.as_raw(), alpha, b.as_raw(), &mut c_raw) };
1230    check_status("sparse", status)?;
1231    unsafe { ComplexSparseMatrix::from_library_owned(c_raw) }
1232}
1233
1234/// One step of (S)SOR / forward / backward Gauss-Seidel relaxation for a
1235/// complex sparse matrix.
1236pub fn sorv<T: ComplexScalar>(
1237    sor_type: SorType,
1238    descr: &MatDescr,
1239    a: &ComplexSparseMatrix<T>,
1240    omega: T,
1241    alpha: T,
1242    x: &mut [T],
1243    b: &[T],
1244) -> Result<()> {
1245    if x.len() < a.dims().1 || b.len() < a.dims().0 {
1246        return Err(Error::InvalidArgument(format!(
1247            "sorv: x.len()={}, b.len()={}, dims=({}, {})",
1248            x.len(),
1249            b.len(),
1250            a.dims().0,
1251            a.dims().1
1252        )));
1253    }
1254    T::sorv(sor_type, descr, a.as_raw(), omega, alpha, x, b)
1255}
1256
1257/// One ILU(0) smoothing step on a complex matrix.
1258pub fn ilu_smoother<T: ComplexScalar>(
1259    op: Trans,
1260    a: &ComplexSparseMatrix<T>,
1261    descr: &MatDescr,
1262    x: &mut [T],
1263    b: &[T],
1264) -> Result<()> {
1265    if x.len() < a.n || b.len() < a.m {
1266        return Err(Error::InvalidArgument(format!(
1267            "ilu_smoother: x.len()={}, b.len()={}, dims=({}, {})",
1268            x.len(),
1269            b.len(),
1270            a.m,
1271            a.n
1272        )));
1273    }
1274    T::ilu_smoother(op, a.raw, descr, x, b)
1275}
1276
1277// =========================================================================
1278//   Iterative solver (CG / GMRES) for complex
1279// =========================================================================
1280
1281/// Iterative-solver handle for complex sparse systems.
1282pub struct ComplexIterSolver<T: ComplexScalar> {
1283    handle: sys::aoclsparse_itsol_handle,
1284    _marker: PhantomData<T>,
1285}
1286
1287impl<T: ComplexScalar> ComplexIterSolver<T> {
1288    /// Initialise a new handle.
1289    pub fn new() -> Result<Self> {
1290        let mut handle: sys::aoclsparse_itsol_handle = std::ptr::null_mut();
1291        T::itsol_init(&mut handle)?;
1292        if handle.is_null() {
1293            return Err(Error::AllocationFailed("sparse"));
1294        }
1295        Ok(Self {
1296            handle,
1297            _marker: PhantomData,
1298        })
1299    }
1300
1301    /// Set a string-keyed solver option (see `aoclsparse_itsol_option_set`).
1302    pub fn set_option(&mut self, name: &str, value: &str) -> Result<()> {
1303        let c_name = CString::new(name)
1304            .map_err(|_| Error::InvalidArgument("set_option: name has interior NUL".into()))?;
1305        let c_value = CString::new(value)
1306            .map_err(|_| Error::InvalidArgument("set_option: value has interior NUL".into()))?;
1307        let status = unsafe {
1308            sys::aoclsparse_itsol_option_set(self.handle, c_name.as_ptr(), c_value.as_ptr())
1309        };
1310        check_status("sparse", status)
1311    }
1312
1313    /// Solve `A · x = b`. `rinfo[100]` of solver stats is real-typed.
1314    pub fn solve(
1315        &mut self,
1316        mat: &ComplexSparseMatrix<T>,
1317        descr: &MatDescr,
1318        b: &[T],
1319        x: &mut [T],
1320    ) -> Result<Box<[T::Real; 100]>> {
1321        let n = mat.n;
1322        if mat.m != mat.n {
1323            return Err(Error::InvalidArgument(format!(
1324                "iterative solve requires square matrix; got ({}, {})",
1325                mat.m, mat.n
1326            )));
1327        }
1328        let mut rinfo: Box<[T::Real; 100]> = Box::new([T::Real::default(); 100]);
1329        T::itsol_solve(self.handle, n, mat.raw, descr, b, x, &mut rinfo)?;
1330        Ok(rinfo)
1331    }
1332}
1333
1334impl<T: ComplexScalar> Drop for ComplexIterSolver<T> {
1335    fn drop(&mut self) {
1336        if !self.handle.is_null() {
1337            unsafe {
1338                sys::aoclsparse_itsol_destroy(&mut self.handle);
1339            }
1340            self.handle = std::ptr::null_mut();
1341        }
1342    }
1343}
1344
1345impl<T: ComplexScalar> std::fmt::Debug for ComplexIterSolver<T> {
1346    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1347        f.debug_struct("ComplexIterSolver").finish_non_exhaustive()
1348    }
1349}
1350
1351// =========================================================================
1352//   Complex extras: symgs, update_values, set_value, trsm, dotmv,
1353//   dotui/dotci, csr2csc, csr2dense, syrkd, syprd, gthrs/gthrz/sctrs,
1354//   TCSR/CSC creators
1355// =========================================================================
1356
1357// ----- Symmetric Gauss-Seidel (complex) -----
1358
1359/// Symmetric Gauss-Seidel sweep against a complex-symmetric handle. (`Complex64`)
1360pub fn symgs_c64(
1361    op: Trans,
1362    a: &ComplexSparseMatrix<Complex64>,
1363    descr: &MatDescr,
1364    alpha: Complex64,
1365    b: &[Complex64],
1366    x: &mut [Complex64],
1367) -> Result<()> {
1368    let alpha_raw = sys::aoclsparse_double_complex_ {
1369        real: alpha.re,
1370        imag: alpha.im,
1371    };
1372    let status = unsafe {
1373        sys::aoclsparse_zsymgs(
1374            trans_raw(op),
1375            a.as_raw(),
1376            descr.as_raw(),
1377            alpha_raw,
1378            b.as_ptr() as *const sys::aoclsparse_double_complex,
1379            x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1380        )
1381    };
1382    check_status("sparse", status)
1383}
1384
1385/// `Complex32` symmetric Gauss-Seidel. See [`symgs_c64`].
1386pub fn symgs_c32(
1387    op: Trans,
1388    a: &ComplexSparseMatrix<Complex32>,
1389    descr: &MatDescr,
1390    alpha: Complex32,
1391    b: &[Complex32],
1392    x: &mut [Complex32],
1393) -> Result<()> {
1394    let alpha_raw = sys::aoclsparse_float_complex {
1395        real: alpha.re,
1396        imag: alpha.im,
1397    };
1398    let status = unsafe {
1399        sys::aoclsparse_csymgs(
1400            trans_raw(op),
1401            a.as_raw(),
1402            descr.as_raw(),
1403            alpha_raw,
1404            b.as_ptr() as *const sys::aoclsparse_float_complex,
1405            x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1406        )
1407    };
1408    check_status("sparse", status)
1409}
1410
1411/// Fused symgs + mat-vec. (`Complex64`)
1412pub fn symgs_mv_c64(
1413    op: Trans,
1414    a: &ComplexSparseMatrix<Complex64>,
1415    descr: &MatDescr,
1416    alpha: Complex64,
1417    b: &[Complex64],
1418    x: &mut [Complex64],
1419    y: &mut [Complex64],
1420) -> Result<()> {
1421    let alpha_raw = sys::aoclsparse_double_complex_ {
1422        real: alpha.re,
1423        imag: alpha.im,
1424    };
1425    let status = unsafe {
1426        sys::aoclsparse_zsymgs_mv(
1427            trans_raw(op),
1428            a.as_raw(),
1429            descr.as_raw(),
1430            alpha_raw,
1431            b.as_ptr() as *const sys::aoclsparse_double_complex,
1432            x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1433            y.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1434        )
1435    };
1436    check_status("sparse", status)
1437}
1438
1439/// `Complex32` fused symgs + mat-vec. See [`symgs_mv_c64`].
1440pub fn symgs_mv_c32(
1441    op: Trans,
1442    a: &ComplexSparseMatrix<Complex32>,
1443    descr: &MatDescr,
1444    alpha: Complex32,
1445    b: &[Complex32],
1446    x: &mut [Complex32],
1447    y: &mut [Complex32],
1448) -> Result<()> {
1449    let alpha_raw = sys::aoclsparse_float_complex {
1450        real: alpha.re,
1451        imag: alpha.im,
1452    };
1453    let status = unsafe {
1454        sys::aoclsparse_csymgs_mv(
1455            trans_raw(op),
1456            a.as_raw(),
1457            descr.as_raw(),
1458            alpha_raw,
1459            b.as_ptr() as *const sys::aoclsparse_float_complex,
1460            x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1461            y.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1462        )
1463    };
1464    check_status("sparse", status)
1465}
1466
1467// ----- update_values / set_value (complex) -----
1468
1469/// Set a single non-zero entry on a complex CSR handle. (`Complex64`)
1470pub fn set_value_c64(
1471    a: &mut ComplexSparseMatrix<Complex64>,
1472    row_idx: i32,
1473    col_idx: i32,
1474    val: Complex64,
1475) -> Result<()> {
1476    let val_raw = sys::aoclsparse_double_complex_ {
1477        real: val.re,
1478        imag: val.im,
1479    };
1480    let status = unsafe {
1481        sys::aoclsparse_zset_value(
1482            a.as_raw(),
1483            row_idx as sys::aoclsparse_int,
1484            col_idx as sys::aoclsparse_int,
1485            val_raw,
1486        )
1487    };
1488    check_status("sparse", status)
1489}
1490/// `Complex32` set_value. See [`set_value_c64`].
1491pub fn set_value_c32(
1492    a: &mut ComplexSparseMatrix<Complex32>,
1493    row_idx: i32,
1494    col_idx: i32,
1495    val: Complex32,
1496) -> Result<()> {
1497    let val_raw = sys::aoclsparse_float_complex {
1498        real: val.re,
1499        imag: val.im,
1500    };
1501    let status = unsafe {
1502        sys::aoclsparse_cset_value(
1503            a.as_raw(),
1504            row_idx as sys::aoclsparse_int,
1505            col_idx as sys::aoclsparse_int,
1506            val_raw,
1507        )
1508    };
1509    check_status("sparse", status)
1510}
1511
1512/// Replace the values array on a complex CSR handle in place. (`Complex64`)
1513pub fn update_values_c64(
1514    a: &mut ComplexSparseMatrix<Complex64>,
1515    val: &mut [Complex64],
1516) -> Result<()> {
1517    let status = unsafe {
1518        sys::aoclsparse_zupdate_values(
1519            a.as_raw(),
1520            val.len() as sys::aoclsparse_int,
1521            val.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1522        )
1523    };
1524    check_status("sparse", status)
1525}
1526/// `Complex32` update_values. See [`update_values_c64`].
1527pub fn update_values_c32(
1528    a: &mut ComplexSparseMatrix<Complex32>,
1529    val: &mut [Complex32],
1530) -> Result<()> {
1531    let status = unsafe {
1532        sys::aoclsparse_cupdate_values(
1533            a.as_raw(),
1534            val.len() as sys::aoclsparse_int,
1535            val.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1536        )
1537    };
1538    check_status("sparse", status)
1539}
1540
1541// ----- trsm (complex) -----
1542
1543/// Multi-RHS triangular solve `op(A) · X = α · B` for complex sparse
1544/// triangular `A`. (`Complex64`)
1545pub fn trsm_c64(
1546    op: Trans,
1547    alpha: Complex64,
1548    a: &ComplexSparseMatrix<Complex64>,
1549    descr: &MatDescr,
1550    b: &[Complex64],
1551    n_rhs: usize,
1552    ldb: usize,
1553    x: &mut [Complex64],
1554    ldx: usize,
1555) -> Result<()> {
1556    let alpha_raw = sys::aoclsparse_double_complex_ {
1557        real: alpha.re,
1558        imag: alpha.im,
1559    };
1560    let status = unsafe {
1561        sys::aoclsparse_ztrsm(
1562            trans_raw(op),
1563            alpha_raw,
1564            a.as_raw(),
1565            descr.as_raw(),
1566            sys::aoclsparse_order__aoclsparse_order_row,
1567            b.as_ptr() as *const sys::aoclsparse_double_complex,
1568            n_rhs as sys::aoclsparse_int,
1569            ldb as sys::aoclsparse_int,
1570            x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1571            ldx as sys::aoclsparse_int,
1572        )
1573    };
1574    check_status("sparse", status)
1575}
1576
1577/// `Complex32` multi-RHS triangular solve. See [`trsm_c64`].
1578pub fn trsm_c32(
1579    op: Trans,
1580    alpha: Complex32,
1581    a: &ComplexSparseMatrix<Complex32>,
1582    descr: &MatDescr,
1583    b: &[Complex32],
1584    n_rhs: usize,
1585    ldb: usize,
1586    x: &mut [Complex32],
1587    ldx: usize,
1588) -> Result<()> {
1589    let alpha_raw = sys::aoclsparse_float_complex {
1590        real: alpha.re,
1591        imag: alpha.im,
1592    };
1593    let status = unsafe {
1594        sys::aoclsparse_ctrsm(
1595            trans_raw(op),
1596            alpha_raw,
1597            a.as_raw(),
1598            descr.as_raw(),
1599            sys::aoclsparse_order__aoclsparse_order_row,
1600            b.as_ptr() as *const sys::aoclsparse_float_complex,
1601            n_rhs as sys::aoclsparse_int,
1602            ldb as sys::aoclsparse_int,
1603            x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1604            ldx as sys::aoclsparse_int,
1605        )
1606    };
1607    check_status("sparse", status)
1608}
1609
1610// ----- dotmv (fused dot + mv) and sparse complex dot (dotui/dotci) -----
1611
1612/// Fused dot + mat-vec: `y := α A x + β y` and `d := xᵀ y`. (`Complex64`)
1613pub fn dotmv_c64(
1614    op: Trans,
1615    alpha: Complex64,
1616    a: &ComplexSparseMatrix<Complex64>,
1617    descr: &MatDescr,
1618    x: &[Complex64],
1619    beta: Complex64,
1620    y: &mut [Complex64],
1621    d: &mut Complex64,
1622) -> Result<()> {
1623    let alpha_raw = sys::aoclsparse_double_complex_ {
1624        real: alpha.re,
1625        imag: alpha.im,
1626    };
1627    let beta_raw = sys::aoclsparse_double_complex_ {
1628        real: beta.re,
1629        imag: beta.im,
1630    };
1631    let status = unsafe {
1632        sys::aoclsparse_zdotmv(
1633            trans_raw(op),
1634            alpha_raw,
1635            a.as_raw(),
1636            descr.as_raw(),
1637            x.as_ptr() as *const sys::aoclsparse_double_complex,
1638            beta_raw,
1639            y.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1640            d as *mut _ as *mut sys::aoclsparse_double_complex,
1641        )
1642    };
1643    check_status("sparse", status)
1644}
1645
1646/// `Complex32` fused dot + mat-vec. See [`dotmv_c64`].
1647pub fn dotmv_c32(
1648    op: Trans,
1649    alpha: Complex32,
1650    a: &ComplexSparseMatrix<Complex32>,
1651    descr: &MatDescr,
1652    x: &[Complex32],
1653    beta: Complex32,
1654    y: &mut [Complex32],
1655    d: &mut Complex32,
1656) -> Result<()> {
1657    let alpha_raw = sys::aoclsparse_float_complex {
1658        real: alpha.re,
1659        imag: alpha.im,
1660    };
1661    let beta_raw = sys::aoclsparse_float_complex {
1662        real: beta.re,
1663        imag: beta.im,
1664    };
1665    let status = unsafe {
1666        sys::aoclsparse_cdotmv(
1667            trans_raw(op),
1668            alpha_raw,
1669            a.as_raw(),
1670            descr.as_raw(),
1671            x.as_ptr() as *const sys::aoclsparse_float_complex,
1672            beta_raw,
1673            y.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1674            d as *mut _ as *mut sys::aoclsparse_float_complex,
1675        )
1676    };
1677    check_status("sparse", status)
1678}
1679
1680/// Sparse-vector unconjugated dot `Σ x[i] · y[indx[i]]`. (`Complex64`)
1681pub fn dotui_c64(
1682    x: &[Complex64],
1683    indx: &[sys::aoclsparse_int],
1684    y: &[Complex64],
1685) -> Result<Complex64> {
1686    let mut out = Complex64::new(0.0, 0.0);
1687    let status = unsafe {
1688        sys::aoclsparse_zdotui(
1689            x.len() as sys::aoclsparse_int,
1690            x.as_ptr() as *const std::os::raw::c_void,
1691            indx.as_ptr(),
1692            y.as_ptr() as *const std::os::raw::c_void,
1693            &mut out as *mut _ as *mut std::os::raw::c_void,
1694        )
1695    };
1696    check_status("sparse", status)?;
1697    Ok(out)
1698}
1699/// `Complex32` unconjugated sparse dot. See [`dotui_c64`].
1700pub fn dotui_c32(
1701    x: &[Complex32],
1702    indx: &[sys::aoclsparse_int],
1703    y: &[Complex32],
1704) -> Result<Complex32> {
1705    let mut out = Complex32::new(0.0, 0.0);
1706    let status = unsafe {
1707        sys::aoclsparse_cdotui(
1708            x.len() as sys::aoclsparse_int,
1709            x.as_ptr() as *const std::os::raw::c_void,
1710            indx.as_ptr(),
1711            y.as_ptr() as *const std::os::raw::c_void,
1712            &mut out as *mut _ as *mut std::os::raw::c_void,
1713        )
1714    };
1715    check_status("sparse", status)?;
1716    Ok(out)
1717}
1718
1719/// Sparse-vector conjugated dot `Σ conj(x[i]) · y[indx[i]]`. (`Complex64`)
1720pub fn dotci_c64(
1721    x: &[Complex64],
1722    indx: &[sys::aoclsparse_int],
1723    y: &[Complex64],
1724) -> Result<Complex64> {
1725    let mut out = Complex64::new(0.0, 0.0);
1726    let status = unsafe {
1727        sys::aoclsparse_zdotci(
1728            x.len() as sys::aoclsparse_int,
1729            x.as_ptr() as *const std::os::raw::c_void,
1730            indx.as_ptr(),
1731            y.as_ptr() as *const std::os::raw::c_void,
1732            &mut out as *mut _ as *mut std::os::raw::c_void,
1733        )
1734    };
1735    check_status("sparse", status)?;
1736    Ok(out)
1737}
1738/// `Complex32` conjugated sparse dot. See [`dotci_c64`].
1739pub fn dotci_c32(
1740    x: &[Complex32],
1741    indx: &[sys::aoclsparse_int],
1742    y: &[Complex32],
1743) -> Result<Complex32> {
1744    let mut out = Complex32::new(0.0, 0.0);
1745    let status = unsafe {
1746        sys::aoclsparse_cdotci(
1747            x.len() as sys::aoclsparse_int,
1748            x.as_ptr() as *const std::os::raw::c_void,
1749            indx.as_ptr(),
1750            y.as_ptr() as *const std::os::raw::c_void,
1751            &mut out as *mut _ as *mut std::os::raw::c_void,
1752        )
1753    };
1754    check_status("sparse", status)?;
1755    Ok(out)
1756}
1757
1758// ----- gthrs / gthrz / sctrs (complex) -----
1759
1760/// `Complex64` strided sparse gather. See real `gthrs_f64`.
1761pub fn gthrs_c64(y: &[Complex64], x: &mut [Complex64], stride: i32) -> Result<()> {
1762    let status = unsafe {
1763        sys::aoclsparse_zgthrs(
1764            x.len() as sys::aoclsparse_int,
1765            y.as_ptr() as *const std::os::raw::c_void,
1766            x.as_mut_ptr() as *mut std::os::raw::c_void,
1767            stride as sys::aoclsparse_int,
1768        )
1769    };
1770    check_status("sparse", status)
1771}
1772/// `Complex32` strided sparse gather.
1773pub fn gthrs_c32(y: &[Complex32], x: &mut [Complex32], stride: i32) -> Result<()> {
1774    let status = unsafe {
1775        sys::aoclsparse_cgthrs(
1776            x.len() as sys::aoclsparse_int,
1777            y.as_ptr() as *const std::os::raw::c_void,
1778            x.as_mut_ptr() as *mut std::os::raw::c_void,
1779            stride as sys::aoclsparse_int,
1780        )
1781    };
1782    check_status("sparse", status)
1783}
1784
1785/// `Complex64` gather-and-zero.
1786pub fn gthrz_c64(
1787    y: &mut [Complex64],
1788    indx: &[sys::aoclsparse_int],
1789    x: &mut [Complex64],
1790) -> Result<()> {
1791    let status = unsafe {
1792        sys::aoclsparse_zgthrz(
1793            x.len() as sys::aoclsparse_int,
1794            y.as_mut_ptr() as *mut std::os::raw::c_void,
1795            x.as_mut_ptr() as *mut std::os::raw::c_void,
1796            indx.as_ptr(),
1797        )
1798    };
1799    check_status("sparse", status)
1800}
1801/// `Complex32` gather-and-zero.
1802pub fn gthrz_c32(
1803    y: &mut [Complex32],
1804    indx: &[sys::aoclsparse_int],
1805    x: &mut [Complex32],
1806) -> Result<()> {
1807    let status = unsafe {
1808        sys::aoclsparse_cgthrz(
1809            x.len() as sys::aoclsparse_int,
1810            y.as_mut_ptr() as *mut std::os::raw::c_void,
1811            x.as_mut_ptr() as *mut std::os::raw::c_void,
1812            indx.as_ptr(),
1813        )
1814    };
1815    check_status("sparse", status)
1816}
1817
1818/// `Complex64` strided sparse scatter.
1819pub fn sctrs_c64(x: &[Complex64], y: &mut [Complex64], stride: i32) -> Result<()> {
1820    let status = unsafe {
1821        sys::aoclsparse_zsctrs(
1822            x.len() as sys::aoclsparse_int,
1823            x.as_ptr() as *const std::os::raw::c_void,
1824            stride as sys::aoclsparse_int,
1825            y.as_mut_ptr() as *mut std::os::raw::c_void,
1826        )
1827    };
1828    check_status("sparse", status)
1829}
1830/// `Complex32` strided sparse scatter.
1831pub fn sctrs_c32(x: &[Complex32], y: &mut [Complex32], stride: i32) -> Result<()> {
1832    let status = unsafe {
1833        sys::aoclsparse_csctrs(
1834            x.len() as sys::aoclsparse_int,
1835            x.as_ptr() as *const std::os::raw::c_void,
1836            stride as sys::aoclsparse_int,
1837            y.as_mut_ptr() as *mut std::os::raw::c_void,
1838        )
1839    };
1840    check_status("sparse", status)
1841}
1842
1843// ----- syrkd / syprd (complex) -----
1844
1845/// Symmetric rank-k update from a complex sparse matrix. (`Complex64`)
1846pub fn syrkd_c64(
1847    op_a: Trans,
1848    a: &ComplexSparseMatrix<Complex64>,
1849    alpha: Complex64,
1850    beta: Complex64,
1851    c: &mut [Complex64],
1852    order_c: Order,
1853    ldc: usize,
1854) -> Result<()> {
1855    let alpha_raw = sys::aoclsparse_double_complex_ {
1856        real: alpha.re,
1857        imag: alpha.im,
1858    };
1859    let beta_raw = sys::aoclsparse_double_complex_ {
1860        real: beta.re,
1861        imag: beta.im,
1862    };
1863    let status = unsafe {
1864        sys::aoclsparse_zsyrkd(
1865            trans_raw(op_a),
1866            a.as_raw(),
1867            alpha_raw,
1868            beta_raw,
1869            c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1870            order_c.raw(),
1871            ldc as sys::aoclsparse_int,
1872        )
1873    };
1874    check_status("sparse", status)
1875}
1876/// `Complex32` symmetric rank-k update. See [`syrkd_c64`].
1877pub fn syrkd_c32(
1878    op_a: Trans,
1879    a: &ComplexSparseMatrix<Complex32>,
1880    alpha: Complex32,
1881    beta: Complex32,
1882    c: &mut [Complex32],
1883    order_c: Order,
1884    ldc: usize,
1885) -> Result<()> {
1886    let alpha_raw = sys::aoclsparse_float_complex {
1887        real: alpha.re,
1888        imag: alpha.im,
1889    };
1890    let beta_raw = sys::aoclsparse_float_complex {
1891        real: beta.re,
1892        imag: beta.im,
1893    };
1894    let status = unsafe {
1895        sys::aoclsparse_csyrkd(
1896            trans_raw(op_a),
1897            a.as_raw(),
1898            alpha_raw,
1899            beta_raw,
1900            c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1901            order_c.raw(),
1902            ldc as sys::aoclsparse_int,
1903        )
1904    };
1905    check_status("sparse", status)
1906}
1907
1908/// Symmetric triple product `C := α · op(A) · B · op(A)ᵀ + β · C` for
1909/// complex sparse `A`, dense `B`/`C`. (`Complex64`)
1910pub fn syprd_c64(
1911    op_a: Trans,
1912    a: &ComplexSparseMatrix<Complex64>,
1913    b: &[Complex64],
1914    order_b: Order,
1915    ldb: usize,
1916    alpha: Complex64,
1917    beta: Complex64,
1918    c: &mut [Complex64],
1919    order_c: Order,
1920    ldc: usize,
1921) -> Result<()> {
1922    let alpha_raw = sys::aoclsparse_double_complex_ {
1923        real: alpha.re,
1924        imag: alpha.im,
1925    };
1926    let beta_raw = sys::aoclsparse_double_complex_ {
1927        real: beta.re,
1928        imag: beta.im,
1929    };
1930    let status = unsafe {
1931        sys::aoclsparse_zsyprd(
1932            trans_raw(op_a),
1933            a.as_raw(),
1934            b.as_ptr() as *const sys::aoclsparse_double_complex,
1935            order_b.raw(),
1936            ldb as sys::aoclsparse_int,
1937            alpha_raw,
1938            beta_raw,
1939            c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1940            order_c.raw(),
1941            ldc as sys::aoclsparse_int,
1942        )
1943    };
1944    check_status("sparse", status)
1945}
1946/// `Complex32` symmetric triple product. See [`syprd_c64`].
1947pub fn syprd_c32(
1948    op_a: Trans,
1949    a: &ComplexSparseMatrix<Complex32>,
1950    b: &[Complex32],
1951    order_b: Order,
1952    ldb: usize,
1953    alpha: Complex32,
1954    beta: Complex32,
1955    c: &mut [Complex32],
1956    order_c: Order,
1957    ldc: usize,
1958) -> Result<()> {
1959    let alpha_raw = sys::aoclsparse_float_complex {
1960        real: alpha.re,
1961        imag: alpha.im,
1962    };
1963    let beta_raw = sys::aoclsparse_float_complex {
1964        real: beta.re,
1965        imag: beta.im,
1966    };
1967    let status = unsafe {
1968        sys::aoclsparse_csyprd(
1969            trans_raw(op_a),
1970            a.as_raw(),
1971            b.as_ptr() as *const sys::aoclsparse_float_complex,
1972            order_b.raw(),
1973            ldb as sys::aoclsparse_int,
1974            alpha_raw,
1975            beta_raw,
1976            c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1977            order_c.raw(),
1978            ldc as sys::aoclsparse_int,
1979        )
1980    };
1981    check_status("sparse", status)
1982}
1983
1984// ----- Complex CSC and TCSR creators -----
1985
1986/// Build a complex CSC matrix handle. (`Complex64`)
1987pub fn create_csc_c64(
1988    base: IndexBase,
1989    m: usize,
1990    n: usize,
1991    nnz: usize,
1992    col_ptr: &mut [sys::aoclsparse_int],
1993    row_idx: &mut [sys::aoclsparse_int],
1994    val: &mut [Complex64],
1995) -> Result<sys::aoclsparse_matrix> {
1996    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
1997    let status = unsafe {
1998        sys::aoclsparse_create_zcsc(
1999            &mut raw,
2000            base.raw_for_complex(),
2001            m as sys::aoclsparse_int,
2002            n as sys::aoclsparse_int,
2003            nnz as sys::aoclsparse_int,
2004            col_ptr.as_mut_ptr(),
2005            row_idx.as_mut_ptr(),
2006            val.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
2007        )
2008    };
2009    check_status("sparse", status)?;
2010    if raw.is_null() {
2011        return Err(Error::AllocationFailed("sparse"));
2012    }
2013    Ok(raw)
2014}
2015/// `Complex32` CSC creator. See [`create_csc_c64`].
2016pub fn create_csc_c32(
2017    base: IndexBase,
2018    m: usize,
2019    n: usize,
2020    nnz: usize,
2021    col_ptr: &mut [sys::aoclsparse_int],
2022    row_idx: &mut [sys::aoclsparse_int],
2023    val: &mut [Complex32],
2024) -> Result<sys::aoclsparse_matrix> {
2025    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2026    let status = unsafe {
2027        sys::aoclsparse_create_ccsc(
2028            &mut raw,
2029            base.raw_for_complex(),
2030            m as sys::aoclsparse_int,
2031            n as sys::aoclsparse_int,
2032            nnz as sys::aoclsparse_int,
2033            col_ptr.as_mut_ptr(),
2034            row_idx.as_mut_ptr(),
2035            val.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
2036        )
2037    };
2038    check_status("sparse", status)?;
2039    if raw.is_null() {
2040        return Err(Error::AllocationFailed("sparse"));
2041    }
2042    Ok(raw)
2043}
2044
2045/// Build a complex TCSR matrix handle (parallel L / U triangular CSRs).
2046/// (`Complex64`)
2047pub fn create_tcsr_c64(
2048    base: IndexBase,
2049    m: usize,
2050    n: usize,
2051    nnz: usize,
2052    row_ptr_l: &mut [sys::aoclsparse_int],
2053    row_ptr_u: &mut [sys::aoclsparse_int],
2054    col_idx_l: &mut [sys::aoclsparse_int],
2055    col_idx_u: &mut [sys::aoclsparse_int],
2056    val_l: &mut [Complex64],
2057    val_u: &mut [Complex64],
2058) -> Result<sys::aoclsparse_matrix> {
2059    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2060    let status = unsafe {
2061        sys::aoclsparse_create_ztcsr(
2062            &mut raw,
2063            base.raw_for_complex(),
2064            m as sys::aoclsparse_int,
2065            n as sys::aoclsparse_int,
2066            nnz as sys::aoclsparse_int,
2067            row_ptr_l.as_mut_ptr(),
2068            row_ptr_u.as_mut_ptr(),
2069            col_idx_l.as_mut_ptr(),
2070            col_idx_u.as_mut_ptr(),
2071            val_l.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
2072            val_u.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
2073        )
2074    };
2075    check_status("sparse", status)?;
2076    if raw.is_null() {
2077        return Err(Error::AllocationFailed("sparse"));
2078    }
2079    Ok(raw)
2080}
2081/// `Complex32` TCSR creator. See [`create_tcsr_c64`].
2082pub fn create_tcsr_c32(
2083    base: IndexBase,
2084    m: usize,
2085    n: usize,
2086    nnz: usize,
2087    row_ptr_l: &mut [sys::aoclsparse_int],
2088    row_ptr_u: &mut [sys::aoclsparse_int],
2089    col_idx_l: &mut [sys::aoclsparse_int],
2090    col_idx_u: &mut [sys::aoclsparse_int],
2091    val_l: &mut [Complex32],
2092    val_u: &mut [Complex32],
2093) -> Result<sys::aoclsparse_matrix> {
2094    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2095    let status = unsafe {
2096        sys::aoclsparse_create_ctcsr(
2097            &mut raw,
2098            base.raw_for_complex(),
2099            m as sys::aoclsparse_int,
2100            n as sys::aoclsparse_int,
2101            nnz as sys::aoclsparse_int,
2102            row_ptr_l.as_mut_ptr(),
2103            row_ptr_u.as_mut_ptr(),
2104            col_idx_l.as_mut_ptr(),
2105            col_idx_u.as_mut_ptr(),
2106            val_l.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
2107            val_u.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
2108        )
2109    };
2110    check_status("sparse", status)?;
2111    if raw.is_null() {
2112        return Err(Error::AllocationFailed("sparse"));
2113    }
2114    Ok(raw)
2115}
2116
2117// IndexBase helper used above. Mirrors the real API's internal `raw()`
2118// accessor without making the function public to outside crates.
2119impl IndexBase {
2120    pub(crate) fn raw_for_complex(self) -> sys::aoclsparse_index_base {
2121        match self {
2122            IndexBase::Zero => sys::aoclsparse_index_base__aoclsparse_index_base_zero,
2123            IndexBase::One => sys::aoclsparse_index_base__aoclsparse_index_base_one,
2124        }
2125    }
2126}
2127
2128#[cfg(test)]
2129mod tests {
2130    use super::*;
2131
2132    #[test]
2133    fn axpyi_c64_round_trip() {
2134        // y = [1+0i, 2+0i, 3+0i, 4+0i]; x = [10+1i, 20+2i] at indx [0, 2]; α = (3+0i).
2135        // → y[0] += 3·(10+1i) = 30+3i; y[0] = 31+3i; y[2] += 3·(20+2i) = 60+6i; y[2] = 63+6i.
2136        let mut y = [
2137            Complex64::new(1.0, 0.0),
2138            Complex64::new(2.0, 0.0),
2139            Complex64::new(3.0, 0.0),
2140            Complex64::new(4.0, 0.0),
2141        ];
2142        let x = [Complex64::new(10.0, 1.0), Complex64::new(20.0, 2.0)];
2143        let indx: [sys::aoclsparse_int; 2] = [0, 2];
2144        axpyi(Complex64::new(3.0, 0.0), &x, &indx, &mut y).unwrap();
2145        assert!((y[0].re - 31.0).abs() < 1e-12);
2146        assert!((y[0].im - 3.0).abs() < 1e-12);
2147        assert!((y[2].re - 63.0).abs() < 1e-12);
2148        assert!((y[2].im - 6.0).abs() < 1e-12);
2149        assert!((y[1].re - 2.0).abs() < 1e-12);
2150        assert!((y[3].re - 4.0).abs() < 1e-12);
2151    }
2152
2153    #[test]
2154    fn complex_sparse_matrix_round_trip_c64() {
2155        // 2×2 identity with imaginary-part = 0
2156        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2157        let col: [sys::aoclsparse_int; 2] = [0, 1];
2158        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2159        let mat =
2160            ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2161                .unwrap();
2162        assert_eq!(mat.dims(), (2, 2));
2163        assert_eq!(mat.nnz(), 2);
2164        let (base, rp2, col2, val2) = mat.export_csr().unwrap();
2165        assert_eq!(base, IndexBase::Zero);
2166        assert_eq!(rp2, [0, 1, 2]);
2167        assert_eq!(col2, [0, 1]);
2168        assert!((val2[0].re - 1.0).abs() < 1e-12);
2169    }
2170
2171    #[test]
2172    fn complex_mv_identity_c64() {
2173        // 2×2 identity matrix; A·x should equal x.
2174        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2175        let col: [sys::aoclsparse_int; 2] = [0, 1];
2176        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2177        let mat =
2178            ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2179                .unwrap();
2180        let descr = MatDescr::new().unwrap();
2181        let x = [Complex64::new(3.0, 1.0), Complex64::new(4.0, -2.0)];
2182        let mut y = [Complex64::new(0.0, 0.0); 2];
2183        mv(
2184            Trans::No,
2185            Complex64::new(1.0, 0.0),
2186            &mat,
2187            &descr,
2188            &x,
2189            Complex64::new(0.0, 0.0),
2190            &mut y,
2191        )
2192        .unwrap();
2193        assert!((y[0].re - 3.0).abs() < 1e-12);
2194        assert!((y[0].im - 1.0).abs() < 1e-12);
2195        assert!((y[1].re - 4.0).abs() < 1e-12);
2196        assert!((y[1].im + 2.0).abs() < 1e-12);
2197    }
2198
2199    #[test]
2200    fn complex_mv_identity_c32() {
2201        let val = [Complex32::new(1.0, 0.0), Complex32::new(1.0, 0.0)];
2202        let col: [sys::aoclsparse_int; 2] = [0, 1];
2203        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2204        let mat =
2205            ComplexSparseMatrix::<Complex32>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2206                .unwrap();
2207        let descr = MatDescr::new().unwrap();
2208        let x = [Complex32::new(3.0, 1.0), Complex32::new(4.0, -2.0)];
2209        let mut y = [Complex32::new(0.0, 0.0); 2];
2210        mv(
2211            Trans::No,
2212            Complex32::new(1.0, 0.0),
2213            &mat,
2214            &descr,
2215            &x,
2216            Complex32::new(0.0, 0.0),
2217            &mut y,
2218        )
2219        .unwrap();
2220        assert!((y[0].re - 3.0).abs() < 1e-6);
2221        assert!((y[0].im - 1.0).abs() < 1e-6);
2222        assert!((y[1].re - 4.0).abs() < 1e-6);
2223        assert!((y[1].im + 2.0).abs() < 1e-6);
2224    }
2225
2226    #[test]
2227    fn complex_csrmm_identity_c64() {
2228        // 2x2 identity sparse A, 2x2 dense B; C = A * B should equal B.
2229        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2230        let col: [sys::aoclsparse_int; 2] = [0, 1];
2231        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2232        let a = ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2233            .unwrap();
2234        let descr = MatDescr::new().unwrap();
2235        // 2x2 dense B (row-major, ldb = 2):
2236        // [(1, 1), (2, -1)]
2237        // [(3, 0), (4,  2)]
2238        let b = [
2239            Complex64::new(1.0, 1.0),
2240            Complex64::new(2.0, -1.0),
2241            Complex64::new(3.0, 0.0),
2242            Complex64::new(4.0, 2.0),
2243        ];
2244        let mut c = [Complex64::new(0.0, 0.0); 4];
2245        crate::complex::csrmm(
2246            Trans::No,
2247            Complex64::new(1.0, 0.0),
2248            &a,
2249            &descr,
2250            Order::RowMajor,
2251            &b,
2252            2,
2253            2,
2254            Complex64::new(0.0, 0.0),
2255            &mut c,
2256            2,
2257        )
2258        .unwrap();
2259        for (got, want) in c.iter().zip(b.iter()) {
2260            assert!((got.re - want.re).abs() < 1e-12);
2261            assert!((got.im - want.im).abs() < 1e-12);
2262        }
2263    }
2264
2265    #[test]
2266    fn complex_add_identity_plus_identity_c64() {
2267        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2268        let col: [sys::aoclsparse_int; 2] = [0, 1];
2269        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2270        let a = ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2271            .unwrap();
2272        let b = ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2273            .unwrap();
2274        let c = crate::complex::add(Trans::No, &a, Complex64::new(1.0, 0.0), &b).unwrap();
2275        let (_, _, _, val_c) = c.export_csr().unwrap();
2276        assert_eq!(val_c.len(), 2);
2277        for v in &val_c {
2278            assert!((v.re - 2.0).abs() < 1e-12);
2279            assert!(v.im.abs() < 1e-12);
2280        }
2281    }
2282}