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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! DLR (Discrete Lehmann Representation) API for C
//!
//! This module provides the C API for Discrete Lehmann Representation (DLR),
//! which represents Green's functions as a linear combination of poles on the
//! real-frequency axis.
//!
//! Functions:
//! - Creation: spir_dlr_new, spir_dlr_new_with_poles
//! - Introspection: spir_dlr_get_npoles, spir_dlr_get_poles
//! - Conversion: spir_ir2dlr_dd, spir_ir2dlr_zz, spir_dlr2ir_dd, spir_dlr2ir_zz

use num_complex::Complex64;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;

use crate::gemm::{get_backend_handle, spir_gemm_backend};
use crate::types::{BasisType, spir_basis};
use crate::utils::{MemoryOrder, copy_tensor_to_c_array, read_tensor_nd};
use crate::{SPIR_COMPUTATION_SUCCESS, SPIR_INVALID_ARGUMENT, SPIR_NOT_SUPPORTED, StatusCode};
use sparse_ir::dlr::DiscreteLehmannRepresentation;

// ============================================================================
// Creation Functions
// ============================================================================

/// Creates a new DLR from an IR basis with default poles
///
/// # Arguments
/// * `b` - Pointer to a finite temperature basis object
/// * `status` - Pointer to store the status code
///
/// # Returns
/// Pointer to the newly created DLR basis object, or NULL if creation fails
///
/// # Safety
/// Caller must ensure `b` is a valid IR basis pointer
#[unsafe(no_mangle)]
pub extern "C" fn spir_dlr_new(b: *const spir_basis, status: *mut StatusCode) -> *mut spir_basis {
    let result = catch_unwind(AssertUnwindSafe(|| {
        // Validate inputs
        if b.is_null() {
            return (std::ptr::null_mut(), SPIR_INVALID_ARGUMENT);
        }

        let basis_ref = unsafe { &*b };

        // Create DLR based on basis type
        let dlr_type = match basis_ref.inner() {
            BasisType::LogisticFermionic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::new(ir_basis.as_ref());
                BasisType::DLRFermionic(Arc::new(dlr))
            }
            BasisType::LogisticBosonic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::new(ir_basis.as_ref());
                BasisType::DLRBosonic(Arc::new(dlr))
            }
            BasisType::RegularizedBoseFermionic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::new(ir_basis.as_ref());
                BasisType::DLRFermionic(Arc::new(dlr))
            }
            BasisType::RegularizedBoseBosonic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::new(ir_basis.as_ref());
                BasisType::DLRBosonic(Arc::new(dlr))
            }
            _ => {
                // Already a DLR, return error
                return (std::ptr::null_mut(), SPIR_INVALID_ARGUMENT);
            }
        };

        let dlr_basis = match dlr_type {
            BasisType::DLRFermionic(arc_dlr) => spir_basis::new_dlr_fermionic(arc_dlr),
            BasisType::DLRBosonic(arc_dlr) => spir_basis::new_dlr_bosonic(arc_dlr),
            _ => unreachable!(), // We know it's one of the DLR types
        };

        (Box::into_raw(Box::new(dlr_basis)), SPIR_COMPUTATION_SUCCESS)
    }));

    match result {
        Ok((ptr, code)) => {
            if !status.is_null() {
                unsafe {
                    *status = code;
                }
            }
            ptr
        }
        Err(_) => {
            if !status.is_null() {
                unsafe {
                    *status = crate::SPIR_INTERNAL_ERROR;
                }
            }
            std::ptr::null_mut()
        }
    }
}

/// Creates a new DLR with custom poles
///
/// # Arguments
/// * `b` - Pointer to a finite temperature basis object
/// * `npoles` - Number of poles to use
/// * `poles` - Array of pole locations on the real-frequency axis
/// * `status` - Pointer to store the status code
///
/// # Returns
/// Pointer to the newly created DLR basis object, or NULL if creation fails
///
/// # Safety
/// Caller must ensure `b` is valid and `poles` has `npoles` elements
#[unsafe(no_mangle)]
pub extern "C" fn spir_dlr_new_with_poles(
    b: *const spir_basis,
    npoles: libc::c_int,
    poles: *const f64,
    status: *mut StatusCode,
) -> *mut spir_basis {
    let result = catch_unwind(AssertUnwindSafe(|| {
        // Validate inputs
        if b.is_null() || poles.is_null() {
            return (std::ptr::null_mut(), SPIR_INVALID_ARGUMENT);
        }
        if npoles <= 0 {
            return (std::ptr::null_mut(), SPIR_INVALID_ARGUMENT);
        }

        let basis_ref = unsafe { &*b };
        let poles_slice = unsafe { std::slice::from_raw_parts(poles, npoles as usize) };
        let pole_vec: Vec<f64> = poles_slice.to_vec();

        // Create DLR based on basis type
        let dlr_type = match basis_ref.inner() {
            BasisType::LogisticFermionic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::with_poles(ir_basis.as_ref(), pole_vec);
                BasisType::DLRFermionic(Arc::new(dlr))
            }
            BasisType::LogisticBosonic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::with_poles(ir_basis.as_ref(), pole_vec);
                BasisType::DLRBosonic(Arc::new(dlr))
            }
            BasisType::RegularizedBoseFermionic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::with_poles(ir_basis.as_ref(), pole_vec);
                BasisType::DLRFermionic(Arc::new(dlr))
            }
            BasisType::RegularizedBoseBosonic(ir_basis) => {
                let dlr = DiscreteLehmannRepresentation::with_poles(ir_basis.as_ref(), pole_vec);
                BasisType::DLRBosonic(Arc::new(dlr))
            }
            _ => {
                // Already a DLR or invalid type
                return (std::ptr::null_mut(), SPIR_INVALID_ARGUMENT);
            }
        };

        let dlr_basis = match dlr_type {
            BasisType::DLRFermionic(arc_dlr) => spir_basis::new_dlr_fermionic(arc_dlr),
            BasisType::DLRBosonic(arc_dlr) => spir_basis::new_dlr_bosonic(arc_dlr),
            _ => unreachable!(), // We know it's one of the DLR types
        };

        (Box::into_raw(Box::new(dlr_basis)), SPIR_COMPUTATION_SUCCESS)
    }));

    match result {
        Ok((ptr, code)) => {
            if !status.is_null() {
                unsafe {
                    *status = code;
                }
            }
            ptr
        }
        Err(_) => {
            if !status.is_null() {
                unsafe {
                    *status = crate::SPIR_INTERNAL_ERROR;
                }
            }
            std::ptr::null_mut()
        }
    }
}

// ============================================================================
// Introspection Functions
// ============================================================================

/// Gets the number of poles in a DLR
///
/// # Arguments
/// * `dlr` - Pointer to a DLR basis object
/// * `num_poles` - Pointer to store the number of poles
///
/// # Returns
/// Status code
///
/// # Safety
/// Caller must ensure `dlr` is a valid DLR basis pointer
#[unsafe(no_mangle)]
pub extern "C" fn spir_dlr_get_npoles(
    dlr: *const spir_basis,
    num_poles: *mut libc::c_int,
) -> StatusCode {
    if dlr.is_null() || num_poles.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| {
        let dlr_ref = unsafe { &*dlr };

        // Get number of poles based on DLR type
        let npoles = match dlr_ref.inner() {
            BasisType::DLRFermionic(dlr) => dlr.poles.len(),
            BasisType::DLRBosonic(dlr) => dlr.poles.len(),
            _ => return SPIR_INVALID_ARGUMENT, // Not a DLR
        };

        unsafe {
            *num_poles = npoles as libc::c_int;
        }
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(crate::SPIR_INTERNAL_ERROR)
}

/// Gets the pole locations in a DLR
///
/// # Arguments
/// * `dlr` - Pointer to a DLR basis object
/// * `poles` - Pre-allocated array to store pole locations
///
/// # Returns
/// Status code
///
/// # Safety
/// Caller must ensure `dlr` is valid and `poles` has sufficient size
#[unsafe(no_mangle)]
pub extern "C" fn spir_dlr_get_poles(dlr: *const spir_basis, poles: *mut f64) -> StatusCode {
    if dlr.is_null() || poles.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| {
        let dlr_ref = unsafe { &*dlr };

        // Get poles based on DLR type
        let pole_vec = match dlr_ref.inner() {
            BasisType::DLRFermionic(dlr) => &dlr.poles,
            BasisType::DLRBosonic(dlr) => &dlr.poles,
            _ => return SPIR_INVALID_ARGUMENT, // Not a DLR
        };

        // Copy poles to output array
        for (i, &pole) in pole_vec.iter().enumerate() {
            unsafe {
                *poles.add(i) = pole;
            }
        }

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(crate::SPIR_INTERNAL_ERROR)
}

// ============================================================================
// Conversion Functions
// ============================================================================

/// Convert IR coefficients to DLR (real-valued)
///
/// # Arguments
/// * `dlr` - Pointer to a DLR basis object
/// * `order` - Memory layout order
/// * `ndim` - Number of dimensions
/// * `input_dims` - Array of input dimensions
/// * `target_dim` - Dimension to transform
/// * `input` - IR coefficients
/// * `out` - Output DLR coefficients
///
/// # Returns
/// Status code
///
/// # Safety
/// Caller must ensure pointers are valid and arrays have correct sizes
#[unsafe(no_mangle)]
pub extern "C" fn spir_ir2dlr_dd(
    dlr: *const spir_basis,
    backend: *const spir_gemm_backend,
    order: libc::c_int,
    ndim: libc::c_int,
    input_dims: *const libc::c_int,
    target_dim: libc::c_int,
    input: *const f64,
    out: *mut f64,
) -> StatusCode {
    let result = catch_unwind(AssertUnwindSafe(|| {
        if dlr.is_null() || input_dims.is_null() || input.is_null() || out.is_null() {
            return SPIR_INVALID_ARGUMENT;
        }
        if ndim <= 0 || target_dim < 0 || target_dim >= ndim {
            return SPIR_INVALID_ARGUMENT;
        }

        // Parse order
        let mem_order = match MemoryOrder::from_c_int(order) {
            Ok(o) => o,
            Err(_) => return SPIR_INVALID_ARGUMENT,
        };

        let dlr_ref = unsafe { &*dlr };
        let dims_slice = unsafe { std::slice::from_raw_parts(input_dims, ndim as usize) };
        let orig_dims: Vec<usize> = dims_slice.iter().map(|&d| d as usize).collect();

        // Read input tensor using the unified helper function
        // read_tensor_nd handles memory order internally and returns tensor with orig_dims shape
        let input_tensor = unsafe { read_tensor_nd(input, &orig_dims, mem_order) };

        // Get backend handle (NULL means use default)
        let backend_handle = unsafe { get_backend_handle(backend) };

        // Convert IR to DLR based on DLR type
        // target_dim is already correct since read_tensor_nd preserves orig_dims shape
        let result_tensor = match dlr_ref.inner() {
            BasisType::DLRFermionic(dlr) => {
                dlr.from_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            BasisType::DLRBosonic(dlr) => {
                dlr.from_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            _ => return SPIR_NOT_SUPPORTED, // Not a DLR
        };

        // Copy result to output with correct memory order
        unsafe {
            copy_tensor_to_c_array(result_tensor, out, mem_order);
        }

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(crate::SPIR_INTERNAL_ERROR)
}

/// Convert IR coefficients to DLR (complex-valued)
///
/// # Arguments
/// * `dlr` - Pointer to a DLR basis object
/// * `order` - Memory layout order
/// * `ndim` - Number of dimensions
/// * `input_dims` - Array of input dimensions
/// * `target_dim` - Dimension to transform
/// * `input` - Complex IR coefficients
/// * `out` - Output complex DLR coefficients
///
/// # Returns
/// Status code
///
/// # Safety
/// Caller must ensure pointers are valid and arrays have correct sizes
#[unsafe(no_mangle)]
pub extern "C" fn spir_ir2dlr_zz(
    dlr: *const spir_basis,
    backend: *const spir_gemm_backend,
    order: libc::c_int,
    ndim: libc::c_int,
    input_dims: *const libc::c_int,
    target_dim: libc::c_int,
    input: *const Complex64,
    out: *mut Complex64,
) -> StatusCode {
    let result = catch_unwind(AssertUnwindSafe(|| {
        if dlr.is_null() || input_dims.is_null() || input.is_null() || out.is_null() {
            return SPIR_INVALID_ARGUMENT;
        }
        if ndim <= 0 || target_dim < 0 || target_dim >= ndim {
            return SPIR_INVALID_ARGUMENT;
        }

        // Parse order
        let mem_order = match MemoryOrder::from_c_int(order) {
            Ok(o) => o,
            Err(_) => return SPIR_INVALID_ARGUMENT,
        };

        let dlr_ref = unsafe { &*dlr };
        let dims_slice = unsafe { std::slice::from_raw_parts(input_dims, ndim as usize) };
        let orig_dims: Vec<usize> = dims_slice.iter().map(|&d| d as usize).collect();

        // Read input tensor using the unified helper function
        // read_tensor_nd handles memory order internally and returns tensor with orig_dims shape
        let input_tensor = unsafe { read_tensor_nd(input, &orig_dims, mem_order) };

        // Get backend handle (NULL means use default)
        let backend_handle = unsafe { get_backend_handle(backend) };

        // Convert IR to DLR based on DLR type
        // target_dim is already correct since read_tensor_nd preserves orig_dims shape
        let result_tensor = match dlr_ref.inner() {
            BasisType::DLRFermionic(dlr) => {
                dlr.from_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            BasisType::DLRBosonic(dlr) => {
                dlr.from_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            _ => return SPIR_NOT_SUPPORTED, // Not a DLR
        };

        // Copy result to output with correct memory order
        unsafe {
            copy_tensor_to_c_array(result_tensor, out, mem_order);
        }

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(crate::SPIR_INTERNAL_ERROR)
}

/// Convert DLR coefficients to IR (real-valued)
///
/// # Arguments
/// * `dlr` - Pointer to a DLR basis object
/// * `order` - Memory layout order
/// * `ndim` - Number of dimensions
/// * `input_dims` - Array of input dimensions
/// * `target_dim` - Dimension to transform
/// * `input` - DLR coefficients
/// * `out` - Output IR coefficients
///
/// # Returns
/// Status code
///
/// # Safety
/// Caller must ensure pointers are valid and arrays have correct sizes
#[unsafe(no_mangle)]
pub extern "C" fn spir_dlr2ir_dd(
    dlr: *const spir_basis,
    backend: *const spir_gemm_backend,
    order: libc::c_int,
    ndim: libc::c_int,
    input_dims: *const libc::c_int,
    target_dim: libc::c_int,
    input: *const f64,
    out: *mut f64,
) -> StatusCode {
    let result = catch_unwind(AssertUnwindSafe(|| {
        if dlr.is_null() || input_dims.is_null() || input.is_null() || out.is_null() {
            return SPIR_INVALID_ARGUMENT;
        }
        if ndim <= 0 || target_dim < 0 || target_dim >= ndim {
            return SPIR_INVALID_ARGUMENT;
        }

        // Parse order
        let mem_order = match MemoryOrder::from_c_int(order) {
            Ok(o) => o,
            Err(_) => return SPIR_INVALID_ARGUMENT,
        };

        let dlr_ref = unsafe { &*dlr };
        let dims_slice = unsafe { std::slice::from_raw_parts(input_dims, ndim as usize) };
        let orig_dims: Vec<usize> = dims_slice.iter().map(|&d| d as usize).collect();

        // Read input tensor using the unified helper function
        // read_tensor_nd handles memory order internally and returns tensor with orig_dims shape
        let input_tensor = unsafe { read_tensor_nd(input, &orig_dims, mem_order) };

        // Get backend handle (NULL means use default)
        let backend_handle = unsafe { get_backend_handle(backend) };

        // Convert DLR to IR based on DLR type
        // target_dim is already correct since read_tensor_nd preserves orig_dims shape
        let result_tensor = match dlr_ref.inner() {
            BasisType::DLRFermionic(dlr) => {
                dlr.to_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            BasisType::DLRBosonic(dlr) => {
                dlr.to_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            _ => return SPIR_NOT_SUPPORTED, // Not a DLR
        };

        // Copy result to output with correct memory order
        unsafe {
            copy_tensor_to_c_array(result_tensor, out, mem_order);
        }

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(crate::SPIR_INTERNAL_ERROR)
}

/// Convert DLR coefficients to IR (complex-valued)
///
/// # Arguments
/// * `dlr` - Pointer to a DLR basis object
/// * `order` - Memory layout order
/// * `ndim` - Number of dimensions
/// * `input_dims` - Array of input dimensions
/// * `target_dim` - Dimension to transform
/// * `input` - Complex DLR coefficients
/// * `out` - Output complex IR coefficients
///
/// # Returns
/// Status code
///
/// # Safety
/// Caller must ensure pointers are valid and arrays have correct sizes
#[unsafe(no_mangle)]
pub extern "C" fn spir_dlr2ir_zz(
    dlr: *const spir_basis,
    backend: *const spir_gemm_backend,
    order: libc::c_int,
    ndim: libc::c_int,
    input_dims: *const libc::c_int,
    target_dim: libc::c_int,
    input: *const Complex64,
    out: *mut Complex64,
) -> StatusCode {
    let result = catch_unwind(AssertUnwindSafe(|| {
        if dlr.is_null() || input_dims.is_null() || input.is_null() || out.is_null() {
            return SPIR_INVALID_ARGUMENT;
        }
        if ndim <= 0 || target_dim < 0 || target_dim >= ndim {
            return SPIR_INVALID_ARGUMENT;
        }

        // Parse order
        let mem_order = match MemoryOrder::from_c_int(order) {
            Ok(o) => o,
            Err(_) => return SPIR_INVALID_ARGUMENT,
        };

        let dlr_ref = unsafe { &*dlr };
        let dims_slice = unsafe { std::slice::from_raw_parts(input_dims, ndim as usize) };
        let orig_dims: Vec<usize> = dims_slice.iter().map(|&d| d as usize).collect();

        // Read input tensor using the unified helper function
        // read_tensor_nd handles memory order internally and returns tensor with orig_dims shape
        let input_tensor = unsafe { read_tensor_nd(input, &orig_dims, mem_order) };

        // Get backend handle (NULL means use default)
        let backend_handle = unsafe { get_backend_handle(backend) };

        // Convert DLR to IR based on DLR type
        // target_dim is already correct since read_tensor_nd preserves orig_dims shape
        let result_tensor = match dlr_ref.inner() {
            BasisType::DLRFermionic(dlr) => {
                dlr.to_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            BasisType::DLRBosonic(dlr) => {
                dlr.to_ir_nd(backend_handle, &input_tensor, target_dim as usize)
            }
            _ => return SPIR_NOT_SUPPORTED, // Not a DLR
        };

        // Copy result to output with correct memory order
        unsafe {
            copy_tensor_to_c_array(result_tensor, out, mem_order);
        }

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(crate::SPIR_INTERNAL_ERROR)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SPIR_COMPUTATION_SUCCESS;
    use crate::basis::spir_basis_new;
    use crate::kernel::spir_logistic_kernel_new;
    use crate::sve::spir_sve_result_new;

    #[test]
    fn test_dlr_creation() {
        // Ensure clean state before test (BLAS backend should be default Faer)
        sparse_ir::gemm::clear_blas_backend();
        unsafe {
            // Create kernel
            let mut kernel_status = crate::SPIR_INTERNAL_ERROR;
            let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);
            assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);
            assert!(!kernel.is_null());

            // Create SVE result
            let mut sve_status = crate::SPIR_INTERNAL_ERROR;
            let sve = spir_sve_result_new(kernel, 1e-6, -1, -1, 0, &mut sve_status);
            assert_eq!(sve_status, SPIR_COMPUTATION_SUCCESS);
            assert!(!sve.is_null());

            // Create IR basis (Fermionic)
            let mut basis_status = crate::SPIR_INTERNAL_ERROR;
            let basis = spir_basis_new(1, 10.0, 1.0, 1e-6, kernel, sve, -1, &mut basis_status);
            assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);
            assert!(!basis.is_null());

            // Create DLR
            let mut dlr_status = crate::SPIR_INTERNAL_ERROR;
            let dlr = spir_dlr_new(basis, &mut dlr_status);
            assert_eq!(dlr_status, SPIR_COMPUTATION_SUCCESS);
            assert!(!dlr.is_null());

            // Get number of poles
            let mut npoles = 0;
            let status = spir_dlr_get_npoles(dlr, &mut npoles);
            assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
            assert!(npoles > 0);
            debug_println!("DLR has {} poles", npoles);

            // Get poles
            let mut poles = vec![0.0; npoles as usize];
            let status = spir_dlr_get_poles(dlr, poles.as_mut_ptr());
            assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
            debug_println!("First 3 poles: {:?}", &poles[0..3.min(npoles as usize)]);

            // Test get_u funcs from DLR
            let mut u_status = crate::SPIR_INTERNAL_ERROR;
            let u_funcs = crate::basis::spir_basis_get_u(dlr, &mut u_status);
            assert_eq!(u_status, SPIR_COMPUTATION_SUCCESS);
            assert!(!u_funcs.is_null());
            debug_println!("✓ Got u funcs from DLR");

            // Evaluate u at tau=0.5
            let tau = 0.5;
            let mut u_values = vec![0.0; npoles as usize];
            let status = crate::funcs::spir_funcs_eval(u_funcs, tau, u_values.as_mut_ptr());
            assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
            println!(
                "✓ Evaluated u at τ={}: {:?}",
                tau,
                &u_values[0..3.min(npoles as usize)]
            );

            // Test get_uhat funcs from DLR
            let mut uhat_status = crate::SPIR_INTERNAL_ERROR;
            let uhat_funcs = crate::basis::spir_basis_get_uhat(dlr, &mut uhat_status);
            assert_eq!(uhat_status, SPIR_COMPUTATION_SUCCESS);
            assert!(!uhat_funcs.is_null());
            debug_println!("✓ Got uhat funcs from DLR");

            // Evaluate uhat at Matsubara frequency n=1
            let n_matsu = 1i64;
            let mut uhat_values = vec![num_complex::Complex64::new(0.0, 0.0); npoles as usize];
            let status =
                crate::funcs::spir_funcs_eval_matsu(uhat_funcs, n_matsu, uhat_values.as_mut_ptr());
            assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
            println!(
                "✓ Evaluated uhat at n={}: |uhat|={:?}",
                n_matsu,
                &uhat_values[0..3.min(npoles as usize)]
                    .iter()
                    .map(|v| v.norm())
                    .collect::<Vec<_>>()
            );

            // Cleanup
            crate::funcs::spir_funcs_release(uhat_funcs);
            crate::funcs::spir_funcs_release(u_funcs);
            crate::basis::spir_basis_release(dlr);
            crate::basis::spir_basis_release(basis);
            crate::sve::spir_sve_result_release(sve);
            crate::kernel::spir_kernel_release(kernel);
        }
    }
}