sparse-ir-basis 0.13.0

The IR basis of sparse-ir: kernels, the singular value expansion and FiniteTempBasis
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
//! Common test utilities

use num_complex::Complex;
use num_traits::{One, Zero};
use tenferro_tensor::{TensorRank, TensorScalar, TypedTensor};

/// Column-major multi-index of linear offset `lin`.
fn unravel(mut lin: usize, shape: &[usize], idx: &mut [usize]) {
    for (i, &n) in idx.iter_mut().zip(shape) {
        *i = lin % n;
        lin /= n;
    }
}

/// Column-major linear offset of multi-index `idx`.
fn ravel(idx: &[usize], shape: &[usize]) -> usize {
    idx.iter()
        .zip(shape)
        .rev()
        .fold(0, |acc, (&i, &n)| acc * n + i)
}

/// Build a column-major tensor from an index function.
pub fn tensor_from_fn<T: TensorScalar>(
    shape: &[usize],
    mut f: impl FnMut(&[usize]) -> T,
) -> TypedTensor<T> {
    let len = shape.iter().product();
    let mut idx = vec![0; shape.len()];
    let data = (0..len)
        .map(|lin| {
            unravel(lin, shape, &mut idx);
            f(&idx)
        })
        .collect();
    TypedTensor::from_vec_col_major(shape.to_vec(), data).unwrap()
}

/// Column-major tensor filled with `value`.
pub fn tensor_filled<T: TensorScalar + Copy>(shape: &[usize], value: T) -> TypedTensor<T> {
    tensor_from_fn(shape, |_| value)
}

/// Element access by multi-index for test assertions.
pub trait At<T> {
    /// Element at multi-index `idx` (panics when out of range).
    fn at(&self, idx: &[usize]) -> T;
}

impl<T: TensorScalar + Copy + One + Zero, R: TensorRank> At<T> for TypedTensor<T, R> {
    fn at(&self, idx: &[usize]) -> T {
        *self.get(idx).unwrap()
    }
}

impl<T: Copy> At<T> for crate::matrix::Mat<T> {
    fn at(&self, idx: &[usize]) -> T {
        self[idx]
    }
}

/// Move axis from position src to position dst
///
/// Equivalent to numpy.moveaxis or libsparseir's movedim.
pub fn movedim<T: TensorScalar + Copy>(
    arr: &TypedTensor<T>,
    src: usize,
    dst: usize,
) -> TypedTensor<T> {
    let shape = arr.shape().to_vec();
    let rank = shape.len();
    assert!(
        src < rank && dst < rank,
        "src={}, dst={} must be < rank={}",
        src,
        dst,
        rank
    );

    // Output axis k reads input axis perm[k].
    let mut perm: Vec<usize> = (0..rank).collect();
    perm.remove(src);
    perm.insert(dst, src);
    let out_shape: Vec<usize> = perm.iter().map(|&p| shape[p]).collect();
    let data = arr.host_data().unwrap();
    let mut src_idx = vec![0; rank];
    tensor_from_fn(&out_shape, |idx| {
        for (k, &p) in perm.iter().enumerate() {
            src_idx[p] = idx[k];
        }
        data[ravel(&src_idx, &shape)]
    })
}

/// Simple deterministic pseudo-random number generator (LCG)
///
/// Linear Congruential Generator for reproducible random numbers in tests.
/// Uses the common parameters: a = 1664525, c = 1013904223 (from Numerical Recipes)
pub struct SimpleRng {
    state: u64,
}

impl SimpleRng {
    /// Create a new RNG with the given seed
    pub fn new(seed: u64) -> Self {
        Self { state: seed }
    }

    /// Generate next f64 in range [0, 1) (base method)
    pub fn next_f64(&mut self) -> f64 {
        self.state = self.state.wrapping_mul(1664525).wrapping_add(1013904223);
        // Map to [0, 1) using upper 48 bits
        ((self.state >> 16) as f64) / ((1u64 << 48) as f64)
    }

    /// Generate next value of type T (generic)
    pub fn next<T: RandomGenerate>(&mut self) -> T {
        T::generate(self)
    }
}

/// Trait for types that can be randomly generated from SimpleRng
pub trait RandomGenerate {
    fn generate(rng: &mut SimpleRng) -> Self;
}

impl RandomGenerate for f64 {
    fn generate(rng: &mut SimpleRng) -> Self {
        rng.next_f64()
    }
}

impl RandomGenerate for Complex<f64> {
    fn generate(rng: &mut SimpleRng) -> Self {
        // Generate independent real and imaginary parts
        let re = rng.next_f64();
        let im = rng.next_f64();
        Complex::new(re, im)
    }
}

/// Trait for computing error magnitude (real value)
pub trait ErrorNorm {
    /// Compute the error magnitude as f64
    fn error_norm(self) -> f64;
}

/// Trait for converting f64 to T (identity for f64, promote for Complex<f64>)
pub trait ConvertFromReal {
    fn from_real(value: f64) -> Self;
}

impl ConvertFromReal for f64 {
    fn from_real(value: f64) -> Self {
        value
    }
}

impl ConvertFromReal for Complex<f64> {
    fn from_real(value: f64) -> Self {
        Complex::new(value, 0.0)
    }
}

impl ErrorNorm for f64 {
    fn error_norm(self) -> f64 {
        self.abs()
    }
}

impl ErrorNorm for Complex<f64> {
    fn error_norm(self) -> f64 {
        self.norm() // sqrt(re^2 + im^2)
    }
}

/// Generate test data for both τ and Matsubara sampling (1D vectors)
///
/// Creates random coefficients and computes corresponding Green's function values
/// at both τ sampling points and Matsubara frequencies using a single-pole model.
///
/// # Type Parameters
/// * `T` - Element type for coefficients (f64 or Complex<f64>)
/// * `S` - Statistics type (Fermionic or Bosonic)
///
/// # Arguments
/// * `basis` - Finite temperature basis
/// * `tau_points` - τ sampling points
/// * `matsubara_freqs` - Matsubara frequency sampling points
/// * `seed` - Random seed for reproducible test data
///
/// # Returns
/// Tuple of (coefficients, τ values, Matsubara values)
pub fn generate_test_data_tau_and_matsubara<T, S, K>(
    basis: &crate::FiniteTempBasis<K, S>,
    tau_points: &[f64],
    matsubara_freqs: &[crate::freq::MatsubaraFreq<S>],
    seed: u64,
) -> (Vec<T>, Vec<T>, Vec<Complex<f64>>)
where
    T: RandomGenerate + ConvertFromReal + Clone + std::ops::Mul<f64, Output = T>,
    S: crate::traits::StatisticsType,
    K: crate::kernel::KernelProperties + crate::kernel::CentrosymmKernel + Clone + 'static,
{
    use crate::giwn_single_pole;

    let mut rng = SimpleRng::new(seed);
    let basis_size = basis.size();
    let beta = basis.beta();
    let wmax = basis.kernel().lambda() / beta;

    // Choose a pole position (arbitrary choice within reasonable range)
    let omega = wmax * 0.5; // Pole at half of wmax

    // Generate random coefficients scaled by singular values
    let coeffs: Vec<T> = (0..basis_size)
        .map(|l| rng.next::<T>() * basis.s()[l])
        .collect();

    // Compute G(τ) at τ sampling points
    let gtau_values: Vec<T> = tau_points
        .iter()
        .map(|&tau| {
            let g = crate::gtau_single_pole::<S>(tau, omega, beta).unwrap();
            T::from_real(g)
        })
        .collect();

    // Compute G(iν) at Matsubara frequencies
    let giwn_values: Vec<Complex<f64>> = matsubara_freqs
        .iter()
        .map(|freq| giwn_single_pole::<S>(freq, omega, beta).unwrap())
        .collect();

    (coeffs, gtau_values, giwn_values)
}

/// Generate N-dimensional test data for τ and/or Matsubara sampling using single-pole model
///
/// Creates N-dimensional tensors of coefficients and Green's function values at sampling points
/// using a single-pole model with random pole position per extra dimension.
///
/// # Type Parameters
/// * `T` - Element type for coefficients (f64 or Complex<f64>)
/// * `S` - Statistics type (Fermionic or Bosonic)
///
/// # Arguments
/// * `basis` - Finite temperature basis
/// * `tau_points` - τ sampling points (optional, pass empty slice if not needed)
/// * `matsubara_freqs` - Matsubara frequency sampling points (optional, pass empty slice if not needed)
/// * `seed` - Random seed for reproducible test data
/// * `extra_dims` - Extra dimensions beyond the sampling dimension
///
/// # Returns
/// Tuple of (coefficients tensor, τ values tensor, Matsubara values tensor)
/// - Coefficients: shape [basis_size, ...extra_dims]
/// - τ values: shape [n_tau, ...extra_dims]
/// - Matsubara values: shape [n_matsubara, ...extra_dims]
pub fn generate_nd_test_data<T, S, K>(
    basis: &crate::FiniteTempBasis<K, S>,
    tau_points: &[f64],
    matsubara_freqs: &[crate::freq::MatsubaraFreq<S>],
    seed: u64,
    extra_dims: &[usize],
) -> (
    TypedTensor<T>,
    TypedTensor<T>,
    TypedTensor<num_complex::Complex<f64>>,
)
where
    T: RandomGenerate
        + ConvertFromReal
        + TensorScalar
        + Copy
        + One
        + Zero
        + std::ops::Mul<f64, Output = T>
        + From<f64>
        + std::ops::Sub<Output = T>
        + std::ops::Mul<Output = T>,
    S: crate::traits::StatisticsType,
    K: crate::kernel::KernelProperties + crate::kernel::CentrosymmKernel + Clone + 'static,
{
    use crate::{giwn_single_pole, gtau_single_pole};

    let mut rng = SimpleRng::new(seed);
    let beta = basis.beta();
    let wmax = basis.kernel().lambda() / beta;
    let basis_size = basis.size();

    // Calculate total number of extra elements
    let total_extra: usize = extra_dims.iter().product();
    let total_extra = if total_extra == 0 { 1 } else { total_extra };

    // Create tensors
    let mut coeffs_shape = vec![basis_size];
    coeffs_shape.extend_from_slice(extra_dims);
    let mut coeffs = tensor_filled(&coeffs_shape, T::zero());

    let mut gtau_shape = vec![tau_points.len()];
    gtau_shape.extend_from_slice(extra_dims);
    let mut gtau_values = tensor_filled(&gtau_shape, T::zero());

    let mut giwn_shape = vec![matsubara_freqs.len()];
    giwn_shape.extend_from_slice(extra_dims);
    let mut giwn_values = tensor_filled(&giwn_shape, Complex::new(0.0, 0.0));

    // Generate data for each extra index
    for flat_idx in 0..total_extra {
        // Convert flat index to multi-index
        let mut extra_idx = Vec::new();
        let mut remainder = flat_idx;
        for &dim_size in extra_dims.iter().rev() {
            extra_idx.push(remainder % dim_size);
            remainder /= dim_size;
        }
        extra_idx.reverse();

        // Generate random coefficients for this slice
        for l in 0..basis_size {
            let random_base: T = rng.next();
            let random_centered = random_base * T::from(2.0) - T::from(1.0);
            let scaled_coeff = random_centered * basis.s()[l];

            let mut full_idx = vec![l];
            full_idx.extend_from_slice(&extra_idx);
            *coeffs.get_mut(&full_idx).unwrap() = scaled_coeff;
        }

        // Random pole position for this slice
        let omega = wmax * (0.3 + rng.next_f64() * 0.4); // Between 0.3*wmax and 0.7*wmax

        // Compute G(τ) values
        for (i, &tau) in tau_points.iter().enumerate() {
            let g = gtau_single_pole::<S>(tau, omega, beta).unwrap();
            let mut full_idx = vec![i];
            full_idx.extend_from_slice(&extra_idx);
            *gtau_values.get_mut(&full_idx).unwrap() = T::from_real(g);
        }

        // Compute G(iν) values
        for (i, freq) in matsubara_freqs.iter().enumerate() {
            let g = giwn_single_pole::<S>(freq, omega, beta).unwrap();
            let mut full_idx = vec![i];
            full_idx.extend_from_slice(&extra_idx);
            *giwn_values.get_mut(&full_idx).unwrap() = g;
        }
    }

    (coeffs, gtau_values, giwn_values)
}

// ============================================================================
// Condition-number oracle
// ============================================================================

/// A host matrix that the oracles accept: the internal [`crate::matrix::Mat`]
/// or a [`crate::Matrix`] (`TypedTensor` of rank 2)
pub trait ToMat<T> {
    /// Column-major copy as a `Mat`
    fn to_mat(&self) -> crate::matrix::Mat<T>;
}

impl<T: Clone> ToMat<T> for crate::matrix::Mat<T> {
    fn to_mat(&self) -> crate::matrix::Mat<T> {
        self.clone()
    }
}

impl<T: TensorScalar + Copy> ToMat<T> for crate::Matrix<T> {
    fn to_mat(&self) -> crate::matrix::Mat<T> {
        crate::matrix::Mat::from_typed(self).unwrap()
    }
}

/// Condition number `σ_max / σ_min` of a real matrix, as an independent oracle
///
/// The singular values are computed in double-double precision by the
/// nalgebra-based [`crate::tsvd::compute_svd_dtensor`], which shares no code
/// with the faer SVD that the fitters (and so the samplings' `condition_number`)
/// use.
pub fn oracle_condition_number(matrix: &impl ToMat<f64>) -> f64 {
    use crate::Df64;
    use crate::matrix::Mat;
    use crate::numeric::CustomNumeric;

    let matrix = matrix.to_mat();
    let (rows, cols) = *matrix.shape();
    let a = Mat::<Df64>::from_fn([rows, cols], |idx| Df64::from(matrix[idx]));
    let (_, s, _) = crate::tsvd::compute_svd_dtensor(&a).unwrap();
    // compute_svd_dtensor truncates below 2 eps_Df64 * σ_max; it must not have
    // dropped a singular value, or s_min below would not be σ_min.
    assert_eq!(
        s.len(),
        rows.min(cols),
        "oracle SVD dropped a singular value"
    );
    let (mut s_max, mut s_min) = (s[0], s[0]);
    for &x in &s[1..] {
        if x > s_max {
            s_max = x;
        }
        if x < s_min {
            s_min = x;
        }
    }
    (s_max / s_min).to_f64()
}

/// `[Re A; Im A]` (2n × m) of a complex n × m matrix `A`: the matrix of the
/// real least-squares problem `[Re A; Im A] x = [Re g; Im g]`
pub fn stack_re_im(a: &impl ToMat<Complex<f64>>) -> crate::matrix::Mat<f64> {
    let a = a.to_mat();
    let (n, m) = *a.shape();
    crate::matrix::Mat::<f64>::from_fn([2 * n, m], |idx| {
        let z = a[[idx[0] % n, idx[1]]];
        if idx[0] < n { z.re } else { z.im }
    })
}

/// Real embedding `[[Re A, -Im A], [Im A, Re A]]` (2n × 2m) of a complex n × m
/// matrix `A`; it has the singular values of `A`, each twice, and so the
/// condition number of `A`
pub fn realify(a: &impl ToMat<Complex<f64>>) -> crate::matrix::Mat<f64> {
    let a = a.to_mat();
    let (n, m) = *a.shape();
    crate::matrix::Mat::<f64>::from_fn([2 * n, 2 * m], |idx| {
        let z = a[[idx[0] % n, idx[1] % m]];
        match (idx[0] < n, idx[1] < m) {
            (true, true) | (false, false) => z.re,
            (true, false) => -z.im,
            (false, true) => z.im,
        }
    })
}

/// Assert that a condition number equals the oracle value
///
/// Tolerance: a backward-stable SVD returns every singular value with an
/// absolute error O(eps_mach σ_max), so σ_min, and with it κ = σ_max / σ_min,
/// carries a relative error O(eps_mach κ). The factor 100 covers the
/// dimension-dependent constant of the f64 SVD behind `value` (the
/// double-double oracle is exact at this level); the 1e-12 floor covers
/// κ = O(1).
pub fn assert_condition_number_close(label: &str, value: f64, oracle: f64) {
    let rtol = (100.0 * f64::EPSILON * oracle).max(1e-12);
    let rel_err = (value - oracle).abs() / oracle;
    println!(
        "{label}: condition number {value:.6e}, oracle {oracle:.6e}, relative error {rel_err:.3e} (bound {rtol:.3e})"
    );
    assert!(
        rel_err <= rtol,
        "{label}: condition number {value:.6e}, oracle {oracle:.6e}, \
         relative error {rel_err:.3e} > {rtol:.3e}"
    );
}