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    crate::check_index_vector("axpyi", indx.len(), indx, y.len())?;
1090    T::axpyi(alpha, x, indx, y)
1091}
1092
1093/// `x[i] := y[indx[i]]` (sparse gather).
1094pub fn gthr<T: ComplexScalar>(y: &[T], indx: &[sys::aoclsparse_int], x: &mut [T]) -> Result<()> {
1095    if x.len() != indx.len() {
1096        return Err(Error::InvalidArgument(format!(
1097            "gthr: x.len()={}, indx.len()={}",
1098            x.len(),
1099            indx.len()
1100        )));
1101    }
1102    crate::check_index_vector("gthr", indx.len(), indx, y.len())?;
1103    T::gthr(y, indx, x)
1104}
1105
1106/// `y[indx[i]] := x[i]` (sparse scatter).
1107pub fn sctr<T: ComplexScalar>(x: &[T], indx: &[sys::aoclsparse_int], y: &mut [T]) -> Result<()> {
1108    if x.len() != indx.len() {
1109        return Err(Error::InvalidArgument(format!(
1110            "sctr: x.len()={}, indx.len()={}",
1111            x.len(),
1112            indx.len()
1113        )));
1114    }
1115    crate::check_index_vector("sctr", indx.len(), indx, y.len())?;
1116    T::sctr(x, indx, y)
1117}
1118
1119/// Compute `y := α · op(A) · x + β · y` for a complex CSR matrix `A`.
1120pub fn mv<T: ComplexScalar>(
1121    op: Trans,
1122    alpha: T,
1123    a: &ComplexSparseMatrix<T>,
1124    descr: &MatDescr,
1125    x: &[T],
1126    beta: T,
1127    y: &mut [T],
1128) -> Result<()> {
1129    let (x_len, y_len) = match op {
1130        Trans::No => (a.n, a.m),
1131        Trans::T | Trans::C => (a.m, a.n),
1132    };
1133    if x.len() < x_len || y.len() < y_len {
1134        return Err(Error::InvalidArgument(format!(
1135            "mv: x.len()={}, y.len()={}, expected ({x_len}, {y_len})",
1136            x.len(),
1137            y.len()
1138        )));
1139    }
1140    T::mv(op, alpha, a.raw, descr, x, beta, y)
1141}
1142
1143/// Solve `op(A) · x = α · b` where `A` is sparse triangular.
1144pub fn trsv<T: ComplexScalar>(
1145    op: Trans,
1146    alpha: T,
1147    a: &ComplexSparseMatrix<T>,
1148    descr: &MatDescr,
1149    b: &[T],
1150    x: &mut [T],
1151) -> Result<()> {
1152    if b.len() < a.m || x.len() < a.m {
1153        return Err(Error::InvalidArgument(format!(
1154            "trsv: b.len()={}, x.len()={}, m={}",
1155            b.len(),
1156            x.len(),
1157            a.m
1158        )));
1159    }
1160    T::trsv(op, alpha, a.raw, descr, b, x)
1161}
1162
1163/// Compute `C := α · op(A) · B + β · C` where `A` is sparse complex
1164/// (CSR) and `B`, `C` are dense complex matrices laid out per `order`.
1165pub fn csrmm<T: ComplexScalar>(
1166    op: Trans,
1167    alpha: T,
1168    a: &ComplexSparseMatrix<T>,
1169    descr: &MatDescr,
1170    order: Order,
1171    b: &[T],
1172    n: usize,
1173    ldb: usize,
1174    beta: T,
1175    c: &mut [T],
1176    ldc: usize,
1177) -> Result<()> {
1178    T::csrmm(op, alpha, a.as_raw(), descr, order, b, n, ldb, beta, c, ldc)
1179}
1180
1181/// Compute `C := op(A) · B` where both `A` and `B` are sparse complex
1182/// matrices and `C` is dense.
1183pub fn spmmd<T: ComplexScalar>(
1184    op: Trans,
1185    a: &ComplexSparseMatrix<T>,
1186    b: &ComplexSparseMatrix<T>,
1187    layout: Order,
1188    c: &mut [T],
1189    ldc: usize,
1190) -> Result<()> {
1191    T::spmmd(op, a.as_raw(), b.as_raw(), layout, c, ldc)
1192}
1193
1194/// Compute `C := α · op_A(A) · op_B(B) + β · C` for complex sparse `A`
1195/// and `B`, dense complex `C`.
1196pub fn sp2md<T: ComplexScalar>(
1197    op_a: Trans,
1198    descr_a: &MatDescr,
1199    a: &ComplexSparseMatrix<T>,
1200    op_b: Trans,
1201    descr_b: &MatDescr,
1202    b: &ComplexSparseMatrix<T>,
1203    alpha: T,
1204    beta: T,
1205    c: &mut [T],
1206    layout: Order,
1207    ldc: usize,
1208) -> Result<()> {
1209    T::sp2md(
1210        op_a,
1211        descr_a,
1212        a.as_raw(),
1213        op_b,
1214        descr_b,
1215        b.as_raw(),
1216        alpha,
1217        beta,
1218        c,
1219        layout,
1220        ldc,
1221    )
1222}
1223
1224/// Compute `C := α · op(A) + B` returning a fresh complex CSR matrix.
1225pub fn add<T: ComplexScalar>(
1226    op: Trans,
1227    a: &ComplexSparseMatrix<T>,
1228    alpha: T,
1229    b: &ComplexSparseMatrix<T>,
1230) -> Result<ComplexSparseMatrix<T>> {
1231    let mut c_raw: sys::aoclsparse_matrix = std::ptr::null_mut();
1232    let status = unsafe { T::add_ffi(trans_raw(op), a.as_raw(), alpha, b.as_raw(), &mut c_raw) };
1233    check_status("sparse", status)?;
1234    unsafe { ComplexSparseMatrix::from_library_owned(c_raw) }
1235}
1236
1237/// One step of (S)SOR / forward / backward Gauss-Seidel relaxation for a
1238/// complex sparse matrix.
1239pub fn sorv<T: ComplexScalar>(
1240    sor_type: SorType,
1241    descr: &MatDescr,
1242    a: &ComplexSparseMatrix<T>,
1243    omega: T,
1244    alpha: T,
1245    x: &mut [T],
1246    b: &[T],
1247) -> Result<()> {
1248    if x.len() < a.dims().1 || b.len() < a.dims().0 {
1249        return Err(Error::InvalidArgument(format!(
1250            "sorv: x.len()={}, b.len()={}, dims=({}, {})",
1251            x.len(),
1252            b.len(),
1253            a.dims().0,
1254            a.dims().1
1255        )));
1256    }
1257    T::sorv(sor_type, descr, a.as_raw(), omega, alpha, x, b)
1258}
1259
1260/// One ILU(0) smoothing step on a complex matrix.
1261pub fn ilu_smoother<T: ComplexScalar>(
1262    op: Trans,
1263    a: &ComplexSparseMatrix<T>,
1264    descr: &MatDescr,
1265    x: &mut [T],
1266    b: &[T],
1267) -> Result<()> {
1268    if x.len() < a.n || b.len() < a.m {
1269        return Err(Error::InvalidArgument(format!(
1270            "ilu_smoother: x.len()={}, b.len()={}, dims=({}, {})",
1271            x.len(),
1272            b.len(),
1273            a.m,
1274            a.n
1275        )));
1276    }
1277    T::ilu_smoother(op, a.raw, descr, x, b)
1278}
1279
1280// =========================================================================
1281//   Iterative solver (CG / GMRES) for complex
1282// =========================================================================
1283
1284/// Iterative-solver handle for complex sparse systems.
1285pub struct ComplexIterSolver<T: ComplexScalar> {
1286    handle: sys::aoclsparse_itsol_handle,
1287    _marker: PhantomData<T>,
1288}
1289
1290impl<T: ComplexScalar> ComplexIterSolver<T> {
1291    /// Initialise a new handle.
1292    pub fn new() -> Result<Self> {
1293        let mut handle: sys::aoclsparse_itsol_handle = std::ptr::null_mut();
1294        T::itsol_init(&mut handle)?;
1295        if handle.is_null() {
1296            return Err(Error::AllocationFailed("sparse"));
1297        }
1298        Ok(Self {
1299            handle,
1300            _marker: PhantomData,
1301        })
1302    }
1303
1304    /// Set a string-keyed solver option (see `aoclsparse_itsol_option_set`).
1305    pub fn set_option(&mut self, name: &str, value: &str) -> Result<()> {
1306        let c_name = CString::new(name)
1307            .map_err(|_| Error::InvalidArgument("set_option: name has interior NUL".into()))?;
1308        let c_value = CString::new(value)
1309            .map_err(|_| Error::InvalidArgument("set_option: value has interior NUL".into()))?;
1310        let status = unsafe {
1311            sys::aoclsparse_itsol_option_set(self.handle, c_name.as_ptr(), c_value.as_ptr())
1312        };
1313        check_status("sparse", status)
1314    }
1315
1316    /// Solve `A · x = b`. `rinfo[100]` of solver stats is real-typed.
1317    pub fn solve(
1318        &mut self,
1319        mat: &ComplexSparseMatrix<T>,
1320        descr: &MatDescr,
1321        b: &[T],
1322        x: &mut [T],
1323    ) -> Result<Box<[T::Real; 100]>> {
1324        let n = mat.n;
1325        if mat.m != mat.n {
1326            return Err(Error::InvalidArgument(format!(
1327                "iterative solve requires square matrix; got ({}, {})",
1328                mat.m, mat.n
1329            )));
1330        }
1331        let mut rinfo: Box<[T::Real; 100]> = Box::new([T::Real::default(); 100]);
1332        T::itsol_solve(self.handle, n, mat.raw, descr, b, x, &mut rinfo)?;
1333        Ok(rinfo)
1334    }
1335}
1336
1337impl<T: ComplexScalar> Drop for ComplexIterSolver<T> {
1338    fn drop(&mut self) {
1339        if !self.handle.is_null() {
1340            unsafe {
1341                sys::aoclsparse_itsol_destroy(&mut self.handle);
1342            }
1343            self.handle = std::ptr::null_mut();
1344        }
1345    }
1346}
1347
1348impl<T: ComplexScalar> std::fmt::Debug for ComplexIterSolver<T> {
1349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1350        f.debug_struct("ComplexIterSolver").finish_non_exhaustive()
1351    }
1352}
1353
1354// =========================================================================
1355//   Complex extras: symgs, update_values, set_value, trsm, dotmv,
1356//   dotui/dotci, csr2csc, csr2dense, syrkd, syprd, gthrs/gthrz/sctrs,
1357//   TCSR/CSC creators
1358// =========================================================================
1359
1360// ----- Symmetric Gauss-Seidel (complex) -----
1361
1362/// Symmetric Gauss-Seidel sweep against a complex-symmetric handle. (`Complex64`)
1363pub fn symgs_c64(
1364    op: Trans,
1365    a: &ComplexSparseMatrix<Complex64>,
1366    descr: &MatDescr,
1367    alpha: Complex64,
1368    b: &[Complex64],
1369    x: &mut [Complex64],
1370) -> Result<()> {
1371    let alpha_raw = sys::aoclsparse_double_complex_ {
1372        real: alpha.re,
1373        imag: alpha.im,
1374    };
1375    let status = unsafe {
1376        sys::aoclsparse_zsymgs(
1377            trans_raw(op),
1378            a.as_raw(),
1379            descr.as_raw(),
1380            alpha_raw,
1381            b.as_ptr() as *const sys::aoclsparse_double_complex,
1382            x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1383        )
1384    };
1385    check_status("sparse", status)
1386}
1387
1388/// `Complex32` symmetric Gauss-Seidel. See [`symgs_c64`].
1389pub fn symgs_c32(
1390    op: Trans,
1391    a: &ComplexSparseMatrix<Complex32>,
1392    descr: &MatDescr,
1393    alpha: Complex32,
1394    b: &[Complex32],
1395    x: &mut [Complex32],
1396) -> Result<()> {
1397    let alpha_raw = sys::aoclsparse_float_complex {
1398        real: alpha.re,
1399        imag: alpha.im,
1400    };
1401    let status = unsafe {
1402        sys::aoclsparse_csymgs(
1403            trans_raw(op),
1404            a.as_raw(),
1405            descr.as_raw(),
1406            alpha_raw,
1407            b.as_ptr() as *const sys::aoclsparse_float_complex,
1408            x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1409        )
1410    };
1411    check_status("sparse", status)
1412}
1413
1414/// Fused symgs + mat-vec. (`Complex64`)
1415pub fn symgs_mv_c64(
1416    op: Trans,
1417    a: &ComplexSparseMatrix<Complex64>,
1418    descr: &MatDescr,
1419    alpha: Complex64,
1420    b: &[Complex64],
1421    x: &mut [Complex64],
1422    y: &mut [Complex64],
1423) -> Result<()> {
1424    let alpha_raw = sys::aoclsparse_double_complex_ {
1425        real: alpha.re,
1426        imag: alpha.im,
1427    };
1428    let status = unsafe {
1429        sys::aoclsparse_zsymgs_mv(
1430            trans_raw(op),
1431            a.as_raw(),
1432            descr.as_raw(),
1433            alpha_raw,
1434            b.as_ptr() as *const sys::aoclsparse_double_complex,
1435            x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1436            y.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1437        )
1438    };
1439    check_status("sparse", status)
1440}
1441
1442/// `Complex32` fused symgs + mat-vec. See [`symgs_mv_c64`].
1443pub fn symgs_mv_c32(
1444    op: Trans,
1445    a: &ComplexSparseMatrix<Complex32>,
1446    descr: &MatDescr,
1447    alpha: Complex32,
1448    b: &[Complex32],
1449    x: &mut [Complex32],
1450    y: &mut [Complex32],
1451) -> Result<()> {
1452    let alpha_raw = sys::aoclsparse_float_complex {
1453        real: alpha.re,
1454        imag: alpha.im,
1455    };
1456    let status = unsafe {
1457        sys::aoclsparse_csymgs_mv(
1458            trans_raw(op),
1459            a.as_raw(),
1460            descr.as_raw(),
1461            alpha_raw,
1462            b.as_ptr() as *const sys::aoclsparse_float_complex,
1463            x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1464            y.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1465        )
1466    };
1467    check_status("sparse", status)
1468}
1469
1470// ----- update_values / set_value (complex) -----
1471
1472/// Set a single non-zero entry on a complex CSR handle. (`Complex64`)
1473pub fn set_value_c64(
1474    a: &mut ComplexSparseMatrix<Complex64>,
1475    row_idx: i32,
1476    col_idx: i32,
1477    val: Complex64,
1478) -> Result<()> {
1479    let val_raw = sys::aoclsparse_double_complex_ {
1480        real: val.re,
1481        imag: val.im,
1482    };
1483    let status = unsafe {
1484        sys::aoclsparse_zset_value(
1485            a.as_raw(),
1486            row_idx as sys::aoclsparse_int,
1487            col_idx as sys::aoclsparse_int,
1488            val_raw,
1489        )
1490    };
1491    check_status("sparse", status)
1492}
1493/// `Complex32` set_value. See [`set_value_c64`].
1494pub fn set_value_c32(
1495    a: &mut ComplexSparseMatrix<Complex32>,
1496    row_idx: i32,
1497    col_idx: i32,
1498    val: Complex32,
1499) -> Result<()> {
1500    let val_raw = sys::aoclsparse_float_complex {
1501        real: val.re,
1502        imag: val.im,
1503    };
1504    let status = unsafe {
1505        sys::aoclsparse_cset_value(
1506            a.as_raw(),
1507            row_idx as sys::aoclsparse_int,
1508            col_idx as sys::aoclsparse_int,
1509            val_raw,
1510        )
1511    };
1512    check_status("sparse", status)
1513}
1514
1515/// Replace the values array on a complex CSR handle in place. (`Complex64`)
1516pub fn update_values_c64(
1517    a: &mut ComplexSparseMatrix<Complex64>,
1518    val: &mut [Complex64],
1519) -> Result<()> {
1520    let status = unsafe {
1521        sys::aoclsparse_zupdate_values(
1522            a.as_raw(),
1523            val.len() as sys::aoclsparse_int,
1524            val.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1525        )
1526    };
1527    check_status("sparse", status)
1528}
1529/// `Complex32` update_values. See [`update_values_c64`].
1530pub fn update_values_c32(
1531    a: &mut ComplexSparseMatrix<Complex32>,
1532    val: &mut [Complex32],
1533) -> Result<()> {
1534    let status = unsafe {
1535        sys::aoclsparse_cupdate_values(
1536            a.as_raw(),
1537            val.len() as sys::aoclsparse_int,
1538            val.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1539        )
1540    };
1541    check_status("sparse", status)
1542}
1543
1544// ----- trsm (complex) -----
1545
1546/// Multi-RHS triangular solve `op(A) · X = α · B` for complex sparse
1547/// triangular `A`. (`Complex64`)
1548pub fn trsm_c64(
1549    op: Trans,
1550    alpha: Complex64,
1551    a: &ComplexSparseMatrix<Complex64>,
1552    descr: &MatDescr,
1553    b: &[Complex64],
1554    n_rhs: usize,
1555    ldb: usize,
1556    x: &mut [Complex64],
1557    ldx: usize,
1558) -> Result<()> {
1559    let alpha_raw = sys::aoclsparse_double_complex_ {
1560        real: alpha.re,
1561        imag: alpha.im,
1562    };
1563    let status = unsafe {
1564        sys::aoclsparse_ztrsm(
1565            trans_raw(op),
1566            alpha_raw,
1567            a.as_raw(),
1568            descr.as_raw(),
1569            sys::aoclsparse_order__aoclsparse_order_row,
1570            b.as_ptr() as *const sys::aoclsparse_double_complex,
1571            n_rhs as sys::aoclsparse_int,
1572            ldb as sys::aoclsparse_int,
1573            x.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1574            ldx as sys::aoclsparse_int,
1575        )
1576    };
1577    check_status("sparse", status)
1578}
1579
1580/// `Complex32` multi-RHS triangular solve. See [`trsm_c64`].
1581pub fn trsm_c32(
1582    op: Trans,
1583    alpha: Complex32,
1584    a: &ComplexSparseMatrix<Complex32>,
1585    descr: &MatDescr,
1586    b: &[Complex32],
1587    n_rhs: usize,
1588    ldb: usize,
1589    x: &mut [Complex32],
1590    ldx: usize,
1591) -> Result<()> {
1592    let alpha_raw = sys::aoclsparse_float_complex {
1593        real: alpha.re,
1594        imag: alpha.im,
1595    };
1596    let status = unsafe {
1597        sys::aoclsparse_ctrsm(
1598            trans_raw(op),
1599            alpha_raw,
1600            a.as_raw(),
1601            descr.as_raw(),
1602            sys::aoclsparse_order__aoclsparse_order_row,
1603            b.as_ptr() as *const sys::aoclsparse_float_complex,
1604            n_rhs as sys::aoclsparse_int,
1605            ldb as sys::aoclsparse_int,
1606            x.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1607            ldx as sys::aoclsparse_int,
1608        )
1609    };
1610    check_status("sparse", status)
1611}
1612
1613// ----- dotmv (fused dot + mv) and sparse complex dot (dotui/dotci) -----
1614
1615/// Fused dot + mat-vec: `y := α A x + β y` and `d := xᵀ y`. (`Complex64`)
1616pub fn dotmv_c64(
1617    op: Trans,
1618    alpha: Complex64,
1619    a: &ComplexSparseMatrix<Complex64>,
1620    descr: &MatDescr,
1621    x: &[Complex64],
1622    beta: Complex64,
1623    y: &mut [Complex64],
1624    d: &mut Complex64,
1625) -> Result<()> {
1626    let alpha_raw = sys::aoclsparse_double_complex_ {
1627        real: alpha.re,
1628        imag: alpha.im,
1629    };
1630    let beta_raw = sys::aoclsparse_double_complex_ {
1631        real: beta.re,
1632        imag: beta.im,
1633    };
1634    let status = unsafe {
1635        sys::aoclsparse_zdotmv(
1636            trans_raw(op),
1637            alpha_raw,
1638            a.as_raw(),
1639            descr.as_raw(),
1640            x.as_ptr() as *const sys::aoclsparse_double_complex,
1641            beta_raw,
1642            y.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1643            d as *mut _ as *mut sys::aoclsparse_double_complex,
1644        )
1645    };
1646    check_status("sparse", status)
1647}
1648
1649/// `Complex32` fused dot + mat-vec. See [`dotmv_c64`].
1650pub fn dotmv_c32(
1651    op: Trans,
1652    alpha: Complex32,
1653    a: &ComplexSparseMatrix<Complex32>,
1654    descr: &MatDescr,
1655    x: &[Complex32],
1656    beta: Complex32,
1657    y: &mut [Complex32],
1658    d: &mut Complex32,
1659) -> Result<()> {
1660    let alpha_raw = sys::aoclsparse_float_complex {
1661        real: alpha.re,
1662        imag: alpha.im,
1663    };
1664    let beta_raw = sys::aoclsparse_float_complex {
1665        real: beta.re,
1666        imag: beta.im,
1667    };
1668    let status = unsafe {
1669        sys::aoclsparse_cdotmv(
1670            trans_raw(op),
1671            alpha_raw,
1672            a.as_raw(),
1673            descr.as_raw(),
1674            x.as_ptr() as *const sys::aoclsparse_float_complex,
1675            beta_raw,
1676            y.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1677            d as *mut _ as *mut sys::aoclsparse_float_complex,
1678        )
1679    };
1680    check_status("sparse", status)
1681}
1682
1683/// Sparse-vector unconjugated dot `Σ x[i] · y[indx[i]]`. (`Complex64`)
1684pub fn dotui_c64(
1685    x: &[Complex64],
1686    indx: &[sys::aoclsparse_int],
1687    y: &[Complex64],
1688) -> Result<Complex64> {
1689    crate::check_index_vector("dotui_c64", x.len(), indx, y.len())?;
1690    let mut out = Complex64::new(0.0, 0.0);
1691    let status = unsafe {
1692        sys::aoclsparse_zdotui(
1693            x.len() as sys::aoclsparse_int,
1694            x.as_ptr() as *const std::os::raw::c_void,
1695            indx.as_ptr(),
1696            y.as_ptr() as *const std::os::raw::c_void,
1697            &mut out as *mut _ as *mut std::os::raw::c_void,
1698        )
1699    };
1700    check_status("sparse", status)?;
1701    Ok(out)
1702}
1703/// `Complex32` unconjugated sparse dot. See [`dotui_c64`].
1704pub fn dotui_c32(
1705    x: &[Complex32],
1706    indx: &[sys::aoclsparse_int],
1707    y: &[Complex32],
1708) -> Result<Complex32> {
1709    crate::check_index_vector("dotui_c32", x.len(), indx, y.len())?;
1710    let mut out = Complex32::new(0.0, 0.0);
1711    let status = unsafe {
1712        sys::aoclsparse_cdotui(
1713            x.len() as sys::aoclsparse_int,
1714            x.as_ptr() as *const std::os::raw::c_void,
1715            indx.as_ptr(),
1716            y.as_ptr() as *const std::os::raw::c_void,
1717            &mut out as *mut _ as *mut std::os::raw::c_void,
1718        )
1719    };
1720    check_status("sparse", status)?;
1721    Ok(out)
1722}
1723
1724/// Sparse-vector conjugated dot `Σ conj(x[i]) · y[indx[i]]`. (`Complex64`)
1725pub fn dotci_c64(
1726    x: &[Complex64],
1727    indx: &[sys::aoclsparse_int],
1728    y: &[Complex64],
1729) -> Result<Complex64> {
1730    crate::check_index_vector("dotci_c64", x.len(), indx, y.len())?;
1731    let mut out = Complex64::new(0.0, 0.0);
1732    let status = unsafe {
1733        sys::aoclsparse_zdotci(
1734            x.len() as sys::aoclsparse_int,
1735            x.as_ptr() as *const std::os::raw::c_void,
1736            indx.as_ptr(),
1737            y.as_ptr() as *const std::os::raw::c_void,
1738            &mut out as *mut _ as *mut std::os::raw::c_void,
1739        )
1740    };
1741    check_status("sparse", status)?;
1742    Ok(out)
1743}
1744/// `Complex32` conjugated sparse dot. See [`dotci_c64`].
1745pub fn dotci_c32(
1746    x: &[Complex32],
1747    indx: &[sys::aoclsparse_int],
1748    y: &[Complex32],
1749) -> Result<Complex32> {
1750    crate::check_index_vector("dotci_c32", x.len(), indx, y.len())?;
1751    let mut out = Complex32::new(0.0, 0.0);
1752    let status = unsafe {
1753        sys::aoclsparse_cdotci(
1754            x.len() as sys::aoclsparse_int,
1755            x.as_ptr() as *const std::os::raw::c_void,
1756            indx.as_ptr(),
1757            y.as_ptr() as *const std::os::raw::c_void,
1758            &mut out as *mut _ as *mut std::os::raw::c_void,
1759        )
1760    };
1761    check_status("sparse", status)?;
1762    Ok(out)
1763}
1764
1765// ----- gthrs / gthrz / sctrs (complex) -----
1766
1767/// `Complex64` strided sparse gather. See real `gthrs_f64`.
1768pub fn gthrs_c64(y: &[Complex64], x: &mut [Complex64], stride: i32) -> Result<()> {
1769    crate::check_stride("gthrs_c64", x.len(), stride, y.len())?;
1770    let status = unsafe {
1771        sys::aoclsparse_zgthrs(
1772            x.len() as sys::aoclsparse_int,
1773            y.as_ptr() as *const std::os::raw::c_void,
1774            x.as_mut_ptr() as *mut std::os::raw::c_void,
1775            stride as sys::aoclsparse_int,
1776        )
1777    };
1778    check_status("sparse", status)
1779}
1780/// `Complex32` strided sparse gather.
1781pub fn gthrs_c32(y: &[Complex32], x: &mut [Complex32], stride: i32) -> Result<()> {
1782    crate::check_stride("gthrs_c32", x.len(), stride, y.len())?;
1783    let status = unsafe {
1784        sys::aoclsparse_cgthrs(
1785            x.len() as sys::aoclsparse_int,
1786            y.as_ptr() as *const std::os::raw::c_void,
1787            x.as_mut_ptr() as *mut std::os::raw::c_void,
1788            stride as sys::aoclsparse_int,
1789        )
1790    };
1791    check_status("sparse", status)
1792}
1793
1794/// `Complex64` gather-and-zero.
1795pub fn gthrz_c64(
1796    y: &mut [Complex64],
1797    indx: &[sys::aoclsparse_int],
1798    x: &mut [Complex64],
1799) -> Result<()> {
1800    crate::check_index_vector("gthrz_c64", x.len(), indx, y.len())?;
1801    let status = unsafe {
1802        sys::aoclsparse_zgthrz(
1803            x.len() as sys::aoclsparse_int,
1804            y.as_mut_ptr() as *mut std::os::raw::c_void,
1805            x.as_mut_ptr() as *mut std::os::raw::c_void,
1806            indx.as_ptr(),
1807        )
1808    };
1809    check_status("sparse", status)
1810}
1811/// `Complex32` gather-and-zero.
1812pub fn gthrz_c32(
1813    y: &mut [Complex32],
1814    indx: &[sys::aoclsparse_int],
1815    x: &mut [Complex32],
1816) -> Result<()> {
1817    crate::check_index_vector("gthrz_c32", x.len(), indx, y.len())?;
1818    let status = unsafe {
1819        sys::aoclsparse_cgthrz(
1820            x.len() as sys::aoclsparse_int,
1821            y.as_mut_ptr() as *mut std::os::raw::c_void,
1822            x.as_mut_ptr() as *mut std::os::raw::c_void,
1823            indx.as_ptr(),
1824        )
1825    };
1826    check_status("sparse", status)
1827}
1828
1829/// `Complex64` strided sparse scatter.
1830pub fn sctrs_c64(x: &[Complex64], y: &mut [Complex64], stride: i32) -> Result<()> {
1831    crate::check_stride("sctrs_c64", x.len(), stride, y.len())?;
1832    let status = unsafe {
1833        sys::aoclsparse_zsctrs(
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/// `Complex32` strided sparse scatter.
1843pub fn sctrs_c32(x: &[Complex32], y: &mut [Complex32], stride: i32) -> Result<()> {
1844    crate::check_stride("sctrs_c32", x.len(), stride, y.len())?;
1845    let status = unsafe {
1846        sys::aoclsparse_csctrs(
1847            x.len() as sys::aoclsparse_int,
1848            x.as_ptr() as *const std::os::raw::c_void,
1849            stride as sys::aoclsparse_int,
1850            y.as_mut_ptr() as *mut std::os::raw::c_void,
1851        )
1852    };
1853    check_status("sparse", status)
1854}
1855
1856// ----- syrkd / syprd (complex) -----
1857
1858/// Symmetric rank-k update from a complex sparse matrix. (`Complex64`)
1859pub fn syrkd_c64(
1860    op_a: Trans,
1861    a: &ComplexSparseMatrix<Complex64>,
1862    alpha: Complex64,
1863    beta: Complex64,
1864    c: &mut [Complex64],
1865    order_c: Order,
1866    ldc: usize,
1867) -> Result<()> {
1868    let alpha_raw = sys::aoclsparse_double_complex_ {
1869        real: alpha.re,
1870        imag: alpha.im,
1871    };
1872    let beta_raw = sys::aoclsparse_double_complex_ {
1873        real: beta.re,
1874        imag: beta.im,
1875    };
1876    let status = unsafe {
1877        sys::aoclsparse_zsyrkd(
1878            trans_raw(op_a),
1879            a.as_raw(),
1880            alpha_raw,
1881            beta_raw,
1882            c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1883            order_c.raw(),
1884            ldc as sys::aoclsparse_int,
1885        )
1886    };
1887    check_status("sparse", status)
1888}
1889/// `Complex32` symmetric rank-k update. See [`syrkd_c64`].
1890pub fn syrkd_c32(
1891    op_a: Trans,
1892    a: &ComplexSparseMatrix<Complex32>,
1893    alpha: Complex32,
1894    beta: Complex32,
1895    c: &mut [Complex32],
1896    order_c: Order,
1897    ldc: usize,
1898) -> Result<()> {
1899    let alpha_raw = sys::aoclsparse_float_complex {
1900        real: alpha.re,
1901        imag: alpha.im,
1902    };
1903    let beta_raw = sys::aoclsparse_float_complex {
1904        real: beta.re,
1905        imag: beta.im,
1906    };
1907    let status = unsafe {
1908        sys::aoclsparse_csyrkd(
1909            trans_raw(op_a),
1910            a.as_raw(),
1911            alpha_raw,
1912            beta_raw,
1913            c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1914            order_c.raw(),
1915            ldc as sys::aoclsparse_int,
1916        )
1917    };
1918    check_status("sparse", status)
1919}
1920
1921/// Symmetric triple product `C := α · op(A) · B · op(A)ᵀ + β · C` for
1922/// complex sparse `A`, dense `B`/`C`. (`Complex64`)
1923pub fn syprd_c64(
1924    op_a: Trans,
1925    a: &ComplexSparseMatrix<Complex64>,
1926    b: &[Complex64],
1927    order_b: Order,
1928    ldb: usize,
1929    alpha: Complex64,
1930    beta: Complex64,
1931    c: &mut [Complex64],
1932    order_c: Order,
1933    ldc: usize,
1934) -> Result<()> {
1935    let alpha_raw = sys::aoclsparse_double_complex_ {
1936        real: alpha.re,
1937        imag: alpha.im,
1938    };
1939    let beta_raw = sys::aoclsparse_double_complex_ {
1940        real: beta.re,
1941        imag: beta.im,
1942    };
1943    let status = unsafe {
1944        sys::aoclsparse_zsyprd(
1945            trans_raw(op_a),
1946            a.as_raw(),
1947            b.as_ptr() as *const sys::aoclsparse_double_complex,
1948            order_b.raw(),
1949            ldb as sys::aoclsparse_int,
1950            alpha_raw,
1951            beta_raw,
1952            c.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
1953            order_c.raw(),
1954            ldc as sys::aoclsparse_int,
1955        )
1956    };
1957    check_status("sparse", status)
1958}
1959/// `Complex32` symmetric triple product. See [`syprd_c64`].
1960pub fn syprd_c32(
1961    op_a: Trans,
1962    a: &ComplexSparseMatrix<Complex32>,
1963    b: &[Complex32],
1964    order_b: Order,
1965    ldb: usize,
1966    alpha: Complex32,
1967    beta: Complex32,
1968    c: &mut [Complex32],
1969    order_c: Order,
1970    ldc: usize,
1971) -> Result<()> {
1972    let alpha_raw = sys::aoclsparse_float_complex {
1973        real: alpha.re,
1974        imag: alpha.im,
1975    };
1976    let beta_raw = sys::aoclsparse_float_complex {
1977        real: beta.re,
1978        imag: beta.im,
1979    };
1980    let status = unsafe {
1981        sys::aoclsparse_csyprd(
1982            trans_raw(op_a),
1983            a.as_raw(),
1984            b.as_ptr() as *const sys::aoclsparse_float_complex,
1985            order_b.raw(),
1986            ldb as sys::aoclsparse_int,
1987            alpha_raw,
1988            beta_raw,
1989            c.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
1990            order_c.raw(),
1991            ldc as sys::aoclsparse_int,
1992        )
1993    };
1994    check_status("sparse", status)
1995}
1996
1997// ----- Complex CSC and TCSR creators -----
1998
1999/// Build a complex CSC matrix handle. (`Complex64`)
2000pub fn create_csc_c64(
2001    base: IndexBase,
2002    m: usize,
2003    n: usize,
2004    nnz: usize,
2005    col_ptr: &mut [sys::aoclsparse_int],
2006    row_idx: &mut [sys::aoclsparse_int],
2007    val: &mut [Complex64],
2008) -> Result<sys::aoclsparse_matrix> {
2009    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2010    let status = unsafe {
2011        sys::aoclsparse_create_zcsc(
2012            &mut raw,
2013            base.raw_for_complex(),
2014            m as sys::aoclsparse_int,
2015            n as sys::aoclsparse_int,
2016            nnz as sys::aoclsparse_int,
2017            col_ptr.as_mut_ptr(),
2018            row_idx.as_mut_ptr(),
2019            val.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
2020        )
2021    };
2022    check_status("sparse", status)?;
2023    if raw.is_null() {
2024        return Err(Error::AllocationFailed("sparse"));
2025    }
2026    Ok(raw)
2027}
2028/// `Complex32` CSC creator. See [`create_csc_c64`].
2029pub fn create_csc_c32(
2030    base: IndexBase,
2031    m: usize,
2032    n: usize,
2033    nnz: usize,
2034    col_ptr: &mut [sys::aoclsparse_int],
2035    row_idx: &mut [sys::aoclsparse_int],
2036    val: &mut [Complex32],
2037) -> Result<sys::aoclsparse_matrix> {
2038    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2039    let status = unsafe {
2040        sys::aoclsparse_create_ccsc(
2041            &mut raw,
2042            base.raw_for_complex(),
2043            m as sys::aoclsparse_int,
2044            n as sys::aoclsparse_int,
2045            nnz as sys::aoclsparse_int,
2046            col_ptr.as_mut_ptr(),
2047            row_idx.as_mut_ptr(),
2048            val.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
2049        )
2050    };
2051    check_status("sparse", status)?;
2052    if raw.is_null() {
2053        return Err(Error::AllocationFailed("sparse"));
2054    }
2055    Ok(raw)
2056}
2057
2058/// Build a complex TCSR matrix handle (parallel L / U triangular CSRs).
2059/// (`Complex64`)
2060pub fn create_tcsr_c64(
2061    base: IndexBase,
2062    m: usize,
2063    n: usize,
2064    nnz: usize,
2065    row_ptr_l: &mut [sys::aoclsparse_int],
2066    row_ptr_u: &mut [sys::aoclsparse_int],
2067    col_idx_l: &mut [sys::aoclsparse_int],
2068    col_idx_u: &mut [sys::aoclsparse_int],
2069    val_l: &mut [Complex64],
2070    val_u: &mut [Complex64],
2071) -> Result<sys::aoclsparse_matrix> {
2072    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2073    let status = unsafe {
2074        sys::aoclsparse_create_ztcsr(
2075            &mut raw,
2076            base.raw_for_complex(),
2077            m as sys::aoclsparse_int,
2078            n as sys::aoclsparse_int,
2079            nnz as sys::aoclsparse_int,
2080            row_ptr_l.as_mut_ptr(),
2081            row_ptr_u.as_mut_ptr(),
2082            col_idx_l.as_mut_ptr(),
2083            col_idx_u.as_mut_ptr(),
2084            val_l.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
2085            val_u.as_mut_ptr() as *mut sys::aoclsparse_double_complex,
2086        )
2087    };
2088    check_status("sparse", status)?;
2089    if raw.is_null() {
2090        return Err(Error::AllocationFailed("sparse"));
2091    }
2092    Ok(raw)
2093}
2094/// `Complex32` TCSR creator. See [`create_tcsr_c64`].
2095pub fn create_tcsr_c32(
2096    base: IndexBase,
2097    m: usize,
2098    n: usize,
2099    nnz: usize,
2100    row_ptr_l: &mut [sys::aoclsparse_int],
2101    row_ptr_u: &mut [sys::aoclsparse_int],
2102    col_idx_l: &mut [sys::aoclsparse_int],
2103    col_idx_u: &mut [sys::aoclsparse_int],
2104    val_l: &mut [Complex32],
2105    val_u: &mut [Complex32],
2106) -> Result<sys::aoclsparse_matrix> {
2107    let mut raw: sys::aoclsparse_matrix = std::ptr::null_mut();
2108    let status = unsafe {
2109        sys::aoclsparse_create_ctcsr(
2110            &mut raw,
2111            base.raw_for_complex(),
2112            m as sys::aoclsparse_int,
2113            n as sys::aoclsparse_int,
2114            nnz as sys::aoclsparse_int,
2115            row_ptr_l.as_mut_ptr(),
2116            row_ptr_u.as_mut_ptr(),
2117            col_idx_l.as_mut_ptr(),
2118            col_idx_u.as_mut_ptr(),
2119            val_l.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
2120            val_u.as_mut_ptr() as *mut sys::aoclsparse_float_complex,
2121        )
2122    };
2123    check_status("sparse", status)?;
2124    if raw.is_null() {
2125        return Err(Error::AllocationFailed("sparse"));
2126    }
2127    Ok(raw)
2128}
2129
2130// IndexBase helper used above. Mirrors the real API's internal `raw()`
2131// accessor without making the function public to outside crates.
2132impl IndexBase {
2133    pub(crate) fn raw_for_complex(self) -> sys::aoclsparse_index_base {
2134        match self {
2135            IndexBase::Zero => sys::aoclsparse_index_base__aoclsparse_index_base_zero,
2136            IndexBase::One => sys::aoclsparse_index_base__aoclsparse_index_base_one,
2137        }
2138    }
2139}
2140
2141#[cfg(test)]
2142mod tests {
2143    use super::*;
2144
2145    #[test]
2146    fn axpyi_c64_round_trip() {
2147        // y = [1+0i, 2+0i, 3+0i, 4+0i]; x = [10+1i, 20+2i] at indx [0, 2]; α = (3+0i).
2148        // → y[0] += 3·(10+1i) = 30+3i; y[0] = 31+3i; y[2] += 3·(20+2i) = 60+6i; y[2] = 63+6i.
2149        let mut y = [
2150            Complex64::new(1.0, 0.0),
2151            Complex64::new(2.0, 0.0),
2152            Complex64::new(3.0, 0.0),
2153            Complex64::new(4.0, 0.0),
2154        ];
2155        let x = [Complex64::new(10.0, 1.0), Complex64::new(20.0, 2.0)];
2156        let indx: [sys::aoclsparse_int; 2] = [0, 2];
2157        axpyi(Complex64::new(3.0, 0.0), &x, &indx, &mut y).unwrap();
2158        assert!((y[0].re - 31.0).abs() < 1e-12);
2159        assert!((y[0].im - 3.0).abs() < 1e-12);
2160        assert!((y[2].re - 63.0).abs() < 1e-12);
2161        assert!((y[2].im - 6.0).abs() < 1e-12);
2162        assert!((y[1].re - 2.0).abs() < 1e-12);
2163        assert!((y[3].re - 4.0).abs() < 1e-12);
2164    }
2165
2166    #[test]
2167    fn complex_sparse_matrix_round_trip_c64() {
2168        // 2×2 identity with imaginary-part = 0
2169        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2170        let col: [sys::aoclsparse_int; 2] = [0, 1];
2171        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2172        let mat =
2173            ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2174                .unwrap();
2175        assert_eq!(mat.dims(), (2, 2));
2176        assert_eq!(mat.nnz(), 2);
2177        let (base, rp2, col2, val2) = mat.export_csr().unwrap();
2178        assert_eq!(base, IndexBase::Zero);
2179        assert_eq!(rp2, [0, 1, 2]);
2180        assert_eq!(col2, [0, 1]);
2181        assert!((val2[0].re - 1.0).abs() < 1e-12);
2182    }
2183
2184    #[test]
2185    fn complex_mv_identity_c64() {
2186        // 2×2 identity matrix; A·x should equal x.
2187        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2188        let col: [sys::aoclsparse_int; 2] = [0, 1];
2189        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2190        let mat =
2191            ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2192                .unwrap();
2193        let descr = MatDescr::new().unwrap();
2194        let x = [Complex64::new(3.0, 1.0), Complex64::new(4.0, -2.0)];
2195        let mut y = [Complex64::new(0.0, 0.0); 2];
2196        mv(
2197            Trans::No,
2198            Complex64::new(1.0, 0.0),
2199            &mat,
2200            &descr,
2201            &x,
2202            Complex64::new(0.0, 0.0),
2203            &mut y,
2204        )
2205        .unwrap();
2206        assert!((y[0].re - 3.0).abs() < 1e-12);
2207        assert!((y[0].im - 1.0).abs() < 1e-12);
2208        assert!((y[1].re - 4.0).abs() < 1e-12);
2209        assert!((y[1].im + 2.0).abs() < 1e-12);
2210    }
2211
2212    #[test]
2213    fn complex_mv_identity_c32() {
2214        let val = [Complex32::new(1.0, 0.0), Complex32::new(1.0, 0.0)];
2215        let col: [sys::aoclsparse_int; 2] = [0, 1];
2216        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2217        let mat =
2218            ComplexSparseMatrix::<Complex32>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2219                .unwrap();
2220        let descr = MatDescr::new().unwrap();
2221        let x = [Complex32::new(3.0, 1.0), Complex32::new(4.0, -2.0)];
2222        let mut y = [Complex32::new(0.0, 0.0); 2];
2223        mv(
2224            Trans::No,
2225            Complex32::new(1.0, 0.0),
2226            &mat,
2227            &descr,
2228            &x,
2229            Complex32::new(0.0, 0.0),
2230            &mut y,
2231        )
2232        .unwrap();
2233        assert!((y[0].re - 3.0).abs() < 1e-6);
2234        assert!((y[0].im - 1.0).abs() < 1e-6);
2235        assert!((y[1].re - 4.0).abs() < 1e-6);
2236        assert!((y[1].im + 2.0).abs() < 1e-6);
2237    }
2238
2239    #[test]
2240    fn complex_csrmm_identity_c64() {
2241        // 2x2 identity sparse A, 2x2 dense B; C = A * B should equal B.
2242        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2243        let col: [sys::aoclsparse_int; 2] = [0, 1];
2244        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2245        let a = ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2246            .unwrap();
2247        let descr = MatDescr::new().unwrap();
2248        // 2x2 dense B (row-major, ldb = 2):
2249        // [(1, 1), (2, -1)]
2250        // [(3, 0), (4,  2)]
2251        let b = [
2252            Complex64::new(1.0, 1.0),
2253            Complex64::new(2.0, -1.0),
2254            Complex64::new(3.0, 0.0),
2255            Complex64::new(4.0, 2.0),
2256        ];
2257        let mut c = [Complex64::new(0.0, 0.0); 4];
2258        crate::complex::csrmm(
2259            Trans::No,
2260            Complex64::new(1.0, 0.0),
2261            &a,
2262            &descr,
2263            Order::RowMajor,
2264            &b,
2265            2,
2266            2,
2267            Complex64::new(0.0, 0.0),
2268            &mut c,
2269            2,
2270        )
2271        .unwrap();
2272        for (got, want) in c.iter().zip(b.iter()) {
2273            assert!((got.re - want.re).abs() < 1e-12);
2274            assert!((got.im - want.im).abs() < 1e-12);
2275        }
2276    }
2277
2278    #[test]
2279    fn complex_add_identity_plus_identity_c64() {
2280        let val = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
2281        let col: [sys::aoclsparse_int; 2] = [0, 1];
2282        let rp: [sys::aoclsparse_int; 3] = [0, 1, 2];
2283        let a = ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2284            .unwrap();
2285        let b = ComplexSparseMatrix::<Complex64>::from_csr(IndexBase::Zero, 2, 2, &rp, &col, &val)
2286            .unwrap();
2287        let c = crate::complex::add(Trans::No, &a, Complex64::new(1.0, 0.0), &b).unwrap();
2288        let (_, _, _, val_c) = c.export_csr().unwrap();
2289        assert_eq!(val_c.len(), 2);
2290        for v in &val_c {
2291            assert!((v.re - 2.0).abs() < 1e-12);
2292            assert!(v.im.abs() < 1e-12);
2293        }
2294    }
2295}