sparse-ir-capi 0.8.4

C API for SparseIR Rust implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! GEMM (Matrix Multiplication) C-API
//!
//! This module provides C-API functions for registering external BLAS implementations.
//! These functions allow users to inject their own BLAS libraries (OpenBLAS, MKL, Accelerate, etc.)
//! at runtime without recompiling.
//!
//! # API Functions
//! - `spir_gemm_backend_new_from_fblas_lp64`: Create backend from LP64 BLAS (32-bit integers)
//! - `spir_gemm_backend_new_from_fblas_ilp64`: Create backend from ILP64 BLAS (64-bit integers)
//! - `spir_gemm_backend_release`: Release backend handle
//!
//! # Example (C)
//! ```c
//! // Link against BLAS library (e.g., OpenBLAS, MKL, Accelerate)
//! // Fortran BLAS functions typically have trailing underscore
//!
//! // Create backend from Fortran BLAS (or pass NULL to use default backend)
//! spir_gemm_backend* backend = spir_gemm_backend_new_from_fblas_lp64(
//!     (void*)dgemm_,
//!     (void*)zgemm_
//! );
//!
//! // Use backend in evaluate/fit functions (pass NULL to use default backend)
//! // ...
//!
//! // Release backend when done
//! spir_gemm_backend_release(backend);
//! ```

use sparse_ir::gemm::{
    Dgemm64FnPtr, DgemmFnPtr, ExternalBlas64Backend, ExternalBlasBackend, GemmBackendHandle,
    Zgemm64FnPtr, ZgemmFnPtr,
};

//==============================================================================
// Backend Handle C-API
//==============================================================================

/// Opaque pointer type for GEMM backend handle
///
/// This type wraps a `GemmBackendHandle` and provides a C-compatible interface.
/// The handle can be created, cloned, and passed to evaluate/fit functions.
///
/// Note: The internal structure is hidden using a void pointer to prevent exposing GemmBackendHandle to C.
#[repr(C)]
pub struct spir_gemm_backend {
    pub(crate) _private: *const std::ffi::c_void,
}

impl spir_gemm_backend {
    /// Get a reference to the inner GemmBackendHandle
    pub(crate) fn inner(&self) -> &GemmBackendHandle {
        unsafe { &*(self._private as *const GemmBackendHandle) }
    }

    pub(crate) fn new(handle: GemmBackendHandle) -> Self {
        Self {
            _private: Box::into_raw(Box::new(handle)) as *const std::ffi::c_void,
        }
    }
}

impl Drop for spir_gemm_backend {
    fn drop(&mut self) {
        if !self._private.is_null() {
            unsafe {
                let _ = Box::from_raw(
                    self._private as *const GemmBackendHandle as *mut GemmBackendHandle,
                );
            }
        }
    }
}

impl Clone for spir_gemm_backend {
    fn clone(&self) -> Self {
        // GemmBackendHandle is already Arc-based, so we can clone the inner handle
        let inner = self.inner().clone();
        Self::new(inner)
    }
}

/// Create GEMM backend from Fortran BLAS function pointers (LP64)
///
/// Creates a new backend handle from Fortran BLAS function pointers.
///
/// # Arguments
/// * `dgemm` - Function pointer to Fortran BLAS dgemm (double precision)
/// * `zgemm` - Function pointer to Fortran BLAS zgemm (complex double precision)
///
/// # Returns
/// * Pointer to `spir_gemm_backend` on success
/// * `NULL` if function pointers are null
///
/// # Safety
/// The provided function pointers must:
/// - Be valid Fortran BLAS function pointers following the standard Fortran BLAS interface
/// - Use 32-bit integers for all dimension parameters (LP64 interface)
/// - Be thread-safe (will be called from multiple threads)
/// - Remain valid for the entire lifetime of the backend handle
///
/// The returned pointer must be freed with `spir_gemm_backend_free` when no longer needed.
#[unsafe(no_mangle)]
pub extern "C" fn spir_gemm_backend_new_from_fblas_lp64(
    dgemm: *const libc::c_void,
    zgemm: *const libc::c_void,
) -> *mut spir_gemm_backend {
    // Validate input
    if dgemm.is_null() || zgemm.is_null() {
        return std::ptr::null_mut();
    }

    // Catch panics (e.g. OOM from Box::new) to prevent unwinding across FFI boundary
    let result = std::panic::catch_unwind(|| {
        // Cast to Fortran BLAS function pointer types
        let dgemm_fn: DgemmFnPtr = unsafe { std::mem::transmute(dgemm) };
        let zgemm_fn: ZgemmFnPtr = unsafe { std::mem::transmute(zgemm) };

        // Create backend
        let backend = ExternalBlasBackend::new(dgemm_fn, zgemm_fn);

        // Wrap in handle
        let handle = GemmBackendHandle::new(Box::new(backend));
        Box::into_raw(Box::new(spir_gemm_backend::new(handle)))
    });

    result.unwrap_or(std::ptr::null_mut())
}

/// Create GEMM backend from Fortran BLAS function pointers (ILP64)
///
/// Creates a new backend handle from Fortran BLAS function pointers with 64-bit integers.
///
/// # Arguments
/// * `dgemm64` - Function pointer to Fortran BLAS dgemm (double precision, 64-bit integers)
/// * `zgemm64` - Function pointer to Fortran BLAS zgemm (complex double precision, 64-bit integers)
///
/// # Returns
/// * Pointer to `spir_gemm_backend` on success
/// * `NULL` if function pointers are null
///
/// # Safety
/// The provided function pointers must:
/// - Be valid Fortran BLAS function pointers following the standard Fortran BLAS interface
/// - Use 64-bit integers for all dimension parameters (ILP64 interface)
/// - Be thread-safe (will be called from multiple threads)
/// - Remain valid for the entire lifetime of the backend handle
///
/// The returned pointer must be freed with `spir_gemm_backend_free` when no longer needed.
#[unsafe(no_mangle)]
pub extern "C" fn spir_gemm_backend_new_from_fblas_ilp64(
    dgemm64: *const libc::c_void,
    zgemm64: *const libc::c_void,
) -> *mut spir_gemm_backend {
    // Validate input
    if dgemm64.is_null() || zgemm64.is_null() {
        return std::ptr::null_mut();
    }

    // Catch panics (e.g. OOM from Box::new) to prevent unwinding across FFI boundary
    let result = std::panic::catch_unwind(|| {
        // Cast to Fortran BLAS function pointer types
        let dgemm64_fn: Dgemm64FnPtr = unsafe { std::mem::transmute(dgemm64) };
        let zgemm64_fn: Zgemm64FnPtr = unsafe { std::mem::transmute(zgemm64) };

        // Create backend
        let backend = ExternalBlas64Backend::new(dgemm64_fn, zgemm64_fn);

        // Wrap in handle
        let handle = GemmBackendHandle::new(Box::new(backend));
        Box::into_raw(Box::new(spir_gemm_backend::new(handle)))
    });

    result.unwrap_or(std::ptr::null_mut())
}

/// Release GEMM backend handle
///
/// Releases the memory associated with a backend handle.
///
/// # Arguments
/// * `backend` - Pointer to backend handle (can be NULL)
///
/// # Safety
/// The pointer must have been created by `spir_gemm_backend_new_from_fblas_lp64` or
/// `spir_gemm_backend_new_from_fblas_ilp64`.
/// After calling this function, the pointer must not be used again.
#[unsafe(no_mangle)]
pub extern "C" fn spir_gemm_backend_release(backend: *mut spir_gemm_backend) {
    if !backend.is_null() {
        unsafe {
            let _ = Box::from_raw(backend);
        }
    }
}

/// Get backend handle from opaque pointer (internal use)
///
/// # Safety
/// The pointer must be valid and not null.
/// The returned reference is only valid while the backend pointer is valid.
/// The caller must ensure the backend pointer remains valid for the lifetime of the returned reference.
pub(crate) unsafe fn get_backend_handle<'a>(
    backend: *const spir_gemm_backend,
) -> Option<&'a GemmBackendHandle> {
    if backend.is_null() {
        None
    } else {
        unsafe { Some((*backend).inner()) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Mock Fortran BLAS functions for testing
    unsafe extern "C" fn mock_dgemm(
        _transa: *const libc::c_char,
        _transb: *const libc::c_char,
        _m: *const libc::c_int,
        _n: *const libc::c_int,
        _k: *const libc::c_int,
        _alpha: *const libc::c_double,
        _a: *const libc::c_double,
        _lda: *const libc::c_int,
        _b: *const libc::c_double,
        _ldb: *const libc::c_int,
        _beta: *const libc::c_double,
        _c: *mut libc::c_double,
        _ldc: *const libc::c_int,
    ) {
        // Mock implementation - does nothing
    }

    unsafe extern "C" fn mock_zgemm(
        _transa: *const libc::c_char,
        _transb: *const libc::c_char,
        _m: *const libc::c_int,
        _n: *const libc::c_int,
        _k: *const libc::c_int,
        _alpha: *const num_complex::Complex<f64>,
        _a: *const num_complex::Complex<f64>,
        _lda: *const libc::c_int,
        _b: *const num_complex::Complex<f64>,
        _ldb: *const libc::c_int,
        _beta: *const num_complex::Complex<f64>,
        _c: *mut num_complex::Complex<f64>,
        _ldc: *const libc::c_int,
    ) {
        // Mock implementation - does nothing
    }

    unsafe extern "C" fn mock_dgemm64(
        _transa: *const libc::c_char,
        _transb: *const libc::c_char,
        _m: *const i64,
        _n: *const i64,
        _k: *const i64,
        _alpha: *const libc::c_double,
        _a: *const libc::c_double,
        _lda: *const i64,
        _b: *const libc::c_double,
        _ldb: *const i64,
        _beta: *const libc::c_double,
        _c: *mut libc::c_double,
        _ldc: *const i64,
    ) {
        // Mock implementation - does nothing
    }

    unsafe extern "C" fn mock_zgemm64(
        _transa: *const libc::c_char,
        _transb: *const libc::c_char,
        _m: *const i64,
        _n: *const i64,
        _k: *const i64,
        _alpha: *const num_complex::Complex<f64>,
        _a: *const num_complex::Complex<f64>,
        _lda: *const i64,
        _b: *const num_complex::Complex<f64>,
        _ldb: *const i64,
        _beta: *const num_complex::Complex<f64>,
        _c: *mut num_complex::Complex<f64>,
        _ldc: *const i64,
    ) {
        // Mock implementation - does nothing
    }

    #[test]
    fn test_backend_new_from_fblas_lp64_success() {
        unsafe {
            let backend = spir_gemm_backend_new_from_fblas_lp64(
                mock_dgemm as *const _,
                mock_zgemm as *const _,
            );
            assert!(!backend.is_null(), "Backend should not be null");
            spir_gemm_backend_release(backend);
        }
    }

    #[test]
    fn test_backend_new_from_fblas_ilp64_success() {
        unsafe {
            let backend = spir_gemm_backend_new_from_fblas_ilp64(
                mock_dgemm64 as *const _,
                mock_zgemm64 as *const _,
            );
            assert!(!backend.is_null(), "Backend should not be null");
            spir_gemm_backend_release(backend);
        }
    }

    #[test]
    fn test_backend_new_from_fblas_lp64_null_dgemm() {
        unsafe {
            let backend =
                spir_gemm_backend_new_from_fblas_lp64(std::ptr::null(), mock_zgemm as *const _);
            assert!(
                backend.is_null(),
                "Backend should be null when dgemm is null"
            );
        }
    }

    #[test]
    fn test_backend_new_from_fblas_lp64_null_zgemm() {
        unsafe {
            let backend =
                spir_gemm_backend_new_from_fblas_lp64(mock_dgemm as *const _, std::ptr::null());
            assert!(
                backend.is_null(),
                "Backend should be null when zgemm is null"
            );
        }
    }

    #[test]
    fn test_backend_new_from_fblas_ilp64_null_pointers() {
        unsafe {
            let backend =
                spir_gemm_backend_new_from_fblas_ilp64(std::ptr::null(), std::ptr::null());
            assert!(
                backend.is_null(),
                "Backend should be null when pointers are null"
            );
        }
    }

    #[test]
    fn test_backend_release_null() {
        unsafe {
            // Should not panic when releasing null pointer
            spir_gemm_backend_release(std::ptr::null_mut());
        }
    }

    // System BLAS integration tests (only when system-blas feature is enabled)
    #[cfg(all(test, feature = "system-blas"))]
    mod system_blas_tests {
        use super::*;
        use blas_sys::{dgemm_, zgemm_};
        use mdarray::tensor;
        use sparse_ir::gemm::matmul_par;

        // Helper to create backend from blas-sys functions
        unsafe fn create_blas_backend() -> *mut spir_gemm_backend {
            unsafe {
                spir_gemm_backend_new_from_fblas_lp64(
                    dgemm_ as *const _,
                    // Cast zgemm_ to match our function pointer type (memory layout is compatible)
                    unsafe {
                        std::mem::transmute::<
                            unsafe extern "C" fn(
                                *const libc::c_char,
                                *const libc::c_char,
                                *const libc::c_int,
                                *const libc::c_int,
                                *const libc::c_int,
                                *const blas_sys::c_double_complex,
                                *const blas_sys::c_double_complex,
                                *const libc::c_int,
                                *const blas_sys::c_double_complex,
                                *const libc::c_int,
                                *const blas_sys::c_double_complex,
                                *mut blas_sys::c_double_complex,
                                *const libc::c_int,
                            ),
                            sparse_ir::gemm::ZgemmFnPtr,
                        >(zgemm_)
                    } as *const _,
                )
            }
        }

        #[test]
        fn test_default_backend_matrix_multiplication_f64() {
            unsafe {
                // Use default backend (NULL means use default)
                let backend = std::ptr::null();

                // Test matrix multiplication: C = A * B
                // A = [[1.0, 2.0], [3.0, 4.0]]
                // B = [[5.0, 6.0], [7.0, 8.0]]
                // Expected: C = [[19.0, 22.0], [43.0, 50.0]]
                let a: mdarray::DTensor<f64, 2> = tensor![[1.0, 2.0], [3.0, 4.0]];
                let b: mdarray::DTensor<f64, 2> = tensor![[5.0, 6.0], [7.0, 8.0]];
                let backend_handle = get_backend_handle(backend);
                let c = matmul_par(&a, &b, backend_handle);

                // Verify results
                assert!(
                    (c[[0, 0]] - 19.0).abs() < 1e-10,
                    "c[0,0] should be 19.0, got {}",
                    c[[0, 0]]
                );
                assert!((c[[0, 1]] - 22.0).abs() < 1e-10, "c[0,1] should be 22.0");
                assert!((c[[1, 0]] - 43.0).abs() < 1e-10, "c[1,0] should be 43.0");
                assert!((c[[1, 1]] - 50.0).abs() < 1e-10, "c[1,1] should be 50.0");
            }
        }

        #[test]
        fn test_lp64_backend_matrix_multiplication_f64() {
            unsafe {
                // Create backend from system BLAS (LP64)
                let backend = create_blas_backend();
                assert!(!backend.is_null());

                // Test matrix multiplication: C = A * B
                // A = [[1.0, 2.0], [3.0, 4.0]]
                // B = [[5.0, 6.0], [7.0, 8.0]]
                // Expected: C = [[19.0, 22.0], [43.0, 50.0]]
                let a: mdarray::DTensor<f64, 2> = tensor![[1.0, 2.0], [3.0, 4.0]];
                let b: mdarray::DTensor<f64, 2> = tensor![[5.0, 6.0], [7.0, 8.0]];
                let backend_handle = get_backend_handle(backend);
                let c = matmul_par(&a, &b, backend_handle);

                // Verify results
                assert!(
                    (c[[0, 0]] - 19.0).abs() < 1e-10,
                    "c[0,0] should be 19.0, got {}",
                    c[[0, 0]]
                );
                assert!((c[[0, 1]] - 22.0).abs() < 1e-10, "c[0,1] should be 22.0");
                assert!((c[[1, 0]] - 43.0).abs() < 1e-10, "c[1,0] should be 43.0");
                assert!((c[[1, 1]] - 50.0).abs() < 1e-10, "c[1,1] should be 50.0");

                // Clean up
                spir_gemm_backend_release(backend);
            }
        }

        #[test]
        fn test_default_backend_matrix_multiplication_complex() {
            unsafe {
                // Use default backend (NULL means use default)
                let backend = std::ptr::null();

                // Test complex matrix multiplication
                let a: mdarray::DTensor<num_complex::Complex<f64>, 2> = tensor![
                    [
                        num_complex::Complex::new(1.0, 0.0),
                        num_complex::Complex::new(2.0, 0.0)
                    ],
                    [
                        num_complex::Complex::new(3.0, 0.0),
                        num_complex::Complex::new(4.0, 0.0)
                    ]
                ];
                let b: mdarray::DTensor<num_complex::Complex<f64>, 2> = tensor![
                    [
                        num_complex::Complex::new(5.0, 0.0),
                        num_complex::Complex::new(6.0, 0.0)
                    ],
                    [
                        num_complex::Complex::new(7.0, 0.0),
                        num_complex::Complex::new(8.0, 0.0)
                    ]
                ];
                let backend_handle = get_backend_handle(backend);
                let c = matmul_par(&a, &b, backend_handle);

                // Verify results (same as real case)
                assert!((c[[0, 0]].re - 19.0).abs() < 1e-10);
                assert!((c[[0, 1]].re - 22.0).abs() < 1e-10);
                assert!((c[[1, 0]].re - 43.0).abs() < 1e-10);
                assert!((c[[1, 1]].re - 50.0).abs() < 1e-10);
                assert!(c[[0, 0]].im.abs() < 1e-10);
            }
        }

        #[test]
        fn test_lp64_backend_matrix_multiplication_complex() {
            unsafe {
                // Create backend from system BLAS (LP64)
                let backend = create_blas_backend();
                assert!(!backend.is_null());

                // Test complex matrix multiplication
                let a: mdarray::DTensor<num_complex::Complex<f64>, 2> = tensor![
                    [
                        num_complex::Complex::new(1.0, 0.0),
                        num_complex::Complex::new(2.0, 0.0)
                    ],
                    [
                        num_complex::Complex::new(3.0, 0.0),
                        num_complex::Complex::new(4.0, 0.0)
                    ]
                ];
                let b: mdarray::DTensor<num_complex::Complex<f64>, 2> = tensor![
                    [
                        num_complex::Complex::new(5.0, 0.0),
                        num_complex::Complex::new(6.0, 0.0)
                    ],
                    [
                        num_complex::Complex::new(7.0, 0.0),
                        num_complex::Complex::new(8.0, 0.0)
                    ]
                ];
                let backend_handle = get_backend_handle(backend);
                let c = matmul_par(&a, &b, backend_handle);

                // Verify results (same as real case)
                assert!((c[[0, 0]].re - 19.0).abs() < 1e-10);
                assert!((c[[0, 1]].re - 22.0).abs() < 1e-10);
                assert!((c[[1, 0]].re - 43.0).abs() < 1e-10);
                assert!((c[[1, 1]].re - 50.0).abs() < 1e-10);
                assert!(c[[0, 0]].im.abs() < 1e-10);

                // Clean up
                spir_gemm_backend_release(backend);
            }
        }

        #[test]
        fn test_default_backend_larger_matrix() {
            unsafe {
                // Use default backend (NULL means use default)
                let backend = std::ptr::null();

                // Test with larger matrices (3x2 * 2x4 = 3x4)
                let a: mdarray::DTensor<f64, 2> = tensor![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
                let b: mdarray::DTensor<f64, 2> =
                    tensor![[7.0, 8.0, 9.0, 10.0], [11.0, 12.0, 13.0, 14.0]];
                let backend_handle = get_backend_handle(backend);
                let c = matmul_par(&a, &b, backend_handle);

                // Verify some results
                // First row: [1*7+2*11, 1*8+2*12, 1*9+2*13, 1*10+2*14] = [29, 32, 35, 38]
                assert!((c[[0, 0]] - 29.0).abs() < 1e-10);
                assert!((c[[0, 1]] - 32.0).abs() < 1e-10);
                assert!((c[[0, 2]] - 35.0).abs() < 1e-10);
                assert!((c[[0, 3]] - 38.0).abs() < 1e-10);
            }
        }

        #[test]
        fn test_lp64_backend_larger_matrix() {
            unsafe {
                // Create backend from system BLAS (LP64)
                let backend = create_blas_backend();
                assert!(!backend.is_null());

                // Test with larger matrices (3x2 * 2x4 = 3x4)
                let a: mdarray::DTensor<f64, 2> = tensor![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
                let b: mdarray::DTensor<f64, 2> =
                    tensor![[7.0, 8.0, 9.0, 10.0], [11.0, 12.0, 13.0, 14.0]];
                let backend_handle = get_backend_handle(backend);
                let c = matmul_par(&a, &b, backend_handle);

                // Verify some results
                // First row: [1*7+2*11, 1*8+2*12, 1*9+2*13, 1*10+2*14] = [29, 32, 35, 38]
                assert!((c[[0, 0]] - 29.0).abs() < 1e-10);
                assert!((c[[0, 1]] - 32.0).abs() < 1e-10);
                assert!((c[[0, 2]] - 35.0).abs() < 1e-10);
                assert!((c[[0, 3]] - 38.0).abs() < 1e-10);

                // Clean up
                spir_gemm_backend_release(backend);
            }
        }
    }
}