sparse-ir-basis 0.16.0

The IR basis of sparse-ir: the physical kernels, the Fourier transforms of the singular functions 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
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! Tests for FiniteTempBasis functionality
// RegularizedBoseKernel is deprecated (#273) but tested until it is removed.
#![allow(deprecated)]

use crate::basis::{FermionicBasis, FiniteTempBasis};
use crate::error::Error;
use crate::kernel::{LogisticKernel, RegularizedBoseKernel};
use crate::sve::{SVEResult, TworkType, compute_sve};
use crate::traits::{Bosonic, Fermionic};

#[test]
fn test_basis_construction() {
    let beta = 10.0;
    let omega_max = 1.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(beta * omega_max).unwrap();
    let basis = FermionicBasis::new(kernel, beta, Some(epsilon), None).unwrap();

    assert_eq!(basis.beta, beta);
    assert!((basis.omega_max() - omega_max).abs() < 1e-10);
    assert!(basis.size() > 0);
    assert!(basis.accuracy > 0.0);
    assert!(basis.accuracy < epsilon);
}

fn invalid(name: &'static str, value: &str, reason: &str) -> Error {
    Error::InvalidParameter {
        name,
        value: value.to_string(),
        reason: reason.to_string(),
    }
}

/// Invalid parameters are rejected before the SVE is computed. Before the
/// change β ≤ 0 and max_size = 0 panicked, β = NaN gave a NaN basis, and
/// ε ≥ 1 or ε = NaN panicked after the SVE (ε = 1 gave a basis of size 1).
/// `max_size` limits the basis only (issue #285), so a zero `max_size` is
/// rejected explicitly instead of by the SVE truncation.
#[test]
fn test_basis_new_rejects_invalid_parameters() {
    let kernel = LogisticKernel::new(10.0).unwrap();
    let cases = [
        (
            -1.0,
            None,
            None,
            invalid("beta", "-1.0", "must be positive and finite"),
        ),
        (
            0.0,
            None,
            None,
            invalid("beta", "0.0", "must be positive and finite"),
        ),
        (
            f64::NAN,
            None,
            None,
            invalid("beta", "NaN", "must be positive and finite"),
        ),
        (
            f64::INFINITY,
            None,
            None,
            invalid("beta", "inf", "must be positive and finite"),
        ),
        (
            10.0,
            Some(0.0),
            None,
            invalid("epsilon", "0.0", "must be in (0, 1)"),
        ),
        (
            10.0,
            Some(1.0),
            None,
            invalid("epsilon", "1.0", "must be in (0, 1)"),
        ),
        (
            10.0,
            Some(2.0),
            None,
            invalid("epsilon", "2.0", "must be in (0, 1)"),
        ),
        (
            10.0,
            Some(f64::NAN),
            None,
            invalid("epsilon", "NaN", "must be in (0, 1)"),
        ),
        (
            10.0,
            Some(1e-6),
            Some(0),
            invalid("max_size", "0", "must be positive"),
        ),
    ];
    for (beta, epsilon, max_size, expected) in cases {
        let err = FermionicBasis::new(kernel, beta, epsilon, max_size)
            .err()
            .expect("must be rejected");
        assert_eq!(
            err, expected,
            "beta = {beta}, epsilon = {epsilon:?}, max_size = {max_size:?}"
        );
    }
}

/// `from_sve_result` checks the same parameters, with `epsilon` as a
/// truncation threshold: 0 keeps every singular value.
#[test]
fn test_basis_from_sve_result_checks_its_parameters() {
    let kernel = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve(kernel, Some(1e-6), None, None, TworkType::Auto).unwrap();
    let build = |beta, epsilon, max_size| {
        FiniteTempBasis::<LogisticKernel, Fermionic>::from_sve_result(
            kernel,
            beta,
            sve.clone(),
            epsilon,
            max_size,
        )
    };
    // FiniteTempBasis does not implement Debug, so take the error with err().
    let rejected = |beta, epsilon, max_size| {
        build(beta, epsilon, max_size)
            .err()
            .expect("must be rejected")
    };
    assert_eq!(
        rejected(-1.0, None, None),
        invalid("beta", "-1.0", "must be positive and finite")
    );
    assert_eq!(
        rejected(10.0, Some(1.0), None),
        invalid("epsilon", "1.0", "must be in [0, 1)")
    );
    assert_eq!(
        rejected(10.0, Some(1e-6), Some(0)),
        invalid("max_size", "0", "must be positive")
    );
    assert_eq!(build(10.0, Some(0.0), None).unwrap().size(), sve.s().len());
}

/// An SVE on another domain than [-1, 1] × [-1, 1] cannot define the basis:
/// its Fourier transform panicked before the change.
#[test]
fn test_basis_from_sve_result_rejects_an_sve_on_another_domain() {
    let kernel = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve(kernel, Some(1e-6), None, None, TworkType::Auto).unwrap();
    let knots: Vec<f64> = sve.u().polys()[0].knots().iter().map(|x| 2.0 * x).collect();
    let u = sve.u().rescale_domain(knots, None, None).unwrap();
    let sve = SVEResult::new(u, sve.s().to_vec(), sve.v().clone(), sve.epsilon()).unwrap();
    let err = FiniteTempBasis::<LogisticKernel, Fermionic>::from_sve_result(
        kernel, 10.0, sve, None, None,
    )
    .err()
    .expect("must be rejected");
    assert!(
        matches!(
            err,
            Error::InvalidParameter {
                name: "sve_result",
                ..
            }
        ),
        "{err:?}"
    );
}

/// An SVE whose domain ends within 1e-12 inside ±1 passes the domain check.
/// Before the change its Fourier transform panicked at x = 1 (fixed in the
/// FT), and its u functions ended inside [0, β], so that evaluating them at
/// τ = 0 or β panicked. The knots of the basis functions now end exactly at
/// 0 and β (u) and ±ωmax (v).
#[test]
fn test_basis_from_an_sve_just_inside_the_unit_domain() {
    use crate::poly::PiecewiseLegendrePolyVector;

    let beta = 10.0;
    let kernel = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve(kernel, Some(1e-6), None, None, TworkType::Auto).unwrap();
    let shrink = |funcs: &PiecewiseLegendrePolyVector| {
        let mut knots = funcs.polys()[0].knots().to_vec();
        let last = knots.len() - 1;
        knots[0] = -1.0 + 1e-13;
        knots[last] = 1.0 - 1e-13;
        funcs.rescale_domain(knots, None, None).unwrap()
    };
    let (u, v) = (shrink(sve.u()), shrink(sve.v()));
    let sve = SVEResult::new(u, sve.s().to_vec(), v, sve.epsilon()).unwrap();

    let basis = FiniteTempBasis::<LogisticKernel, Fermionic>::from_sve_result(
        kernel, beta, sve, None, None,
    )
    .unwrap();
    for u in basis.u().polys() {
        assert_eq!((u.xmin(), u.xmax()), (0.0, beta));
        assert!(u.evaluate(0.0).is_finite() && u.evaluate(beta).is_finite());
    }
    let wmax = basis.omega_max();
    for v in basis.v().polys() {
        assert_eq!((v.xmin(), v.xmax()), (-wmax, wmax));
    }
}

/// The snap is a no-op for the SVE of a kernel of this crate, whose knots
/// are exactly ±1: the basis functions keep the scaled knots and widths.
#[test]
fn test_basis_knots_of_a_kernel_sve_are_the_scaled_knots() {
    let beta = 10.0;
    let kernel = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve(kernel, Some(1e-6), None, None, TworkType::Auto).unwrap();
    let x_knots = sve.u().polys()[0].knots().to_vec();
    let x_widths = sve.u().polys()[0].delta_x().to_vec();
    let basis = FiniteTempBasis::<LogisticKernel, Fermionic>::from_sve_result(
        kernel, beta, sve, None, None,
    )
    .unwrap();
    let u = &basis.u().polys()[0];
    let scaled: Vec<f64> = x_knots.iter().map(|&x| beta / 2.0 * (x + 1.0)).collect();
    let widths: Vec<f64> = x_widths.iter().map(|&dx| beta / 2.0 * dx).collect();
    assert_eq!(u.knots(), scaled);
    assert_eq!(u.delta_x(), widths);
}

#[test]
fn test_default_tau_sampling_points_conditioning() {
    // Test parameters: beta=1.0, lambda=10.0
    let beta = 1.0;
    let lambda = 10.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(lambda).unwrap();
    let basis = FermionicBasis::new(kernel, beta, Some(epsilon), None).unwrap();

    println!("\n=== Default Tau Sampling Points Test ===");
    println!("Beta: {}, Lambda: {}, Epsilon: {}", beta, lambda, epsilon);
    println!("Basis size: {}", basis.size());

    // Get default sampling points
    let tau_points = basis.default_tau_sampling_points().unwrap();
    println!("Number of sampling points: {}", tau_points.len());

    // Verify range: [-beta/2, beta/2] (matches C++ implementation)
    let beta_half = beta / 2.0;
    for &tau in &tau_points {
        assert!(
            tau >= -beta_half && tau <= beta_half,
            "tau={} out of range [{}, {}]",
            tau,
            -beta_half,
            beta_half
        );
    }

    // Verify sorted (monotonically increasing)
    for i in 1..tau_points.len() {
        assert!(
            tau_points[i] >= tau_points[i - 1],
            "Points not sorted: tau[{}]={} < tau[{}]={}",
            i,
            tau_points[i],
            i - 1,
            tau_points[i - 1]
        );
    }

    // Verify symmetry around 0 (for range [-beta/2, beta/2])
    // Points should come in pairs: tau and -tau
    let tol = 1e-10;

    for &tau in &tau_points {
        let tau_reflected = -tau;
        let has_pair = tau_points.iter().any(|&t| (t - tau_reflected).abs() < tol);
        assert!(
            has_pair || tau.abs() < tol,
            "tau={} lacks symmetric pair around 0",
            tau
        );
    }
    println!("✅ Sampling points are symmetric around 0");

    // Evaluate sampling matrix: matrix[i,l] = u_l(tau_i)
    // Use the Basis trait method which handles tau normalization
    use crate::basis_trait::Basis;
    let matrix = basis.evaluate_tau(&tau_points).unwrap();

    let num_points = tau_points.len();
    let basis_size = basis.size();
    println!("Sampling matrix shape: {}x{}", num_points, basis_size);

    let sv = crate::fitters::singular_values(matrix.host_data().unwrap(), num_points, basis_size)
        .expect("SVD computation failed");

    println!("\nSampling matrix SVD:");
    let min_dim = sv.len();
    println!("  Rank: {}", min_dim);
    println!("  First singular value: {:.6e}", sv[0]);
    println!("  Last singular value: {:.6e}", sv[min_dim - 1]);

    let condition_number = sv[0] / sv[min_dim - 1];
    println!("  Condition number: {:.6e}", condition_number);

    // Reference condition number (from Julia/C++ for beta=1, lambda=10)
    // This is approximate - actual value depends on implementation details
    let reference_cond = 25.0; // ~24.4 observed

    // Check: condition number should not be significantly worse
    // (within factor of 2 of reference)
    assert!(
        condition_number < reference_cond * 2.0,
        "Condition number too large: {:.2e} (reference: {:.2e})",
        condition_number,
        reference_cond
    );

    // Julia check: cond > 1e8 triggers warning
    assert!(
        condition_number < 1e8,
        "Sampling matrix is poorly conditioned: cond = {:.6e}",
        condition_number
    );

    println!(
        "✅ Condition number: {:.2e} (reference: {:.2e}, threshold: {:.2e})",
        condition_number,
        reference_cond,
        reference_cond * 2.0
    );
}

#[test]
fn test_regularized_bose_basis_construction() {
    let beta = 10.0;
    let omega_max = 1.0;
    let epsilon = 1e-6;

    let kernel = RegularizedBoseKernel::new(beta * omega_max).unwrap();
    let basis =
        FiniteTempBasis::<RegularizedBoseKernel, Bosonic>::new(kernel, beta, Some(epsilon), None)
            .unwrap();

    assert_eq!(basis.beta, beta);
    assert!((basis.omega_max() - omega_max).abs() < 1e-10);
    assert!(basis.size() > 0);
    assert!(basis.accuracy > 0.0);
    assert!(basis.accuracy < epsilon);

    println!("\n=== RegularizedBoseKernel Basis Test ===");
    println!(
        "Beta: {}, Omega_max: {}, Epsilon: {}",
        beta, omega_max, epsilon
    );
    println!("Basis size: {}", basis.size());
    println!("Accuracy: {:.6e}", basis.accuracy);
}

#[test]
fn test_regularized_bose_basis_different_parameters() {
    // Test with different beta and omega_max values
    let test_cases = vec![(1.0, 1.0, 1e-6), (10.0, 10.0, 1e-6), (100.0, 1.0, 1e-6)];

    for (beta, omega_max, epsilon) in test_cases {
        let kernel = RegularizedBoseKernel::new(beta * omega_max).unwrap();
        let basis = FiniteTempBasis::<RegularizedBoseKernel, Bosonic>::new(
            kernel,
            beta,
            Some(epsilon),
            None,
        )
        .unwrap();

        assert_eq!(basis.beta, beta);
        assert!((basis.omega_max() - omega_max).abs() < 1e-10);
        assert!(basis.size() > 0);
        assert!(basis.accuracy > 0.0);
        assert!(basis.accuracy < epsilon);

        println!(
            "Beta={}, Omega_max={}: size={}, accuracy={:.6e}",
            beta,
            omega_max,
            basis.size(),
            basis.accuracy
        );
    }
}

#[test]
fn test_default_omega_sampling_points_fermionic() {
    let beta = 10000.0;
    let wmax = 1.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis =
        FiniteTempBasis::<LogisticKernel, Fermionic>::new(kernel, beta, Some(epsilon), None)
            .unwrap();

    let omega_points = basis.default_omega_sampling_points().unwrap();

    // Should have same size as basis
    assert_eq!(omega_points.len(), basis.size());

    // Points should be in [-wmax, wmax]
    for &omega in &omega_points {
        assert!(
            omega.abs() <= wmax,
            "omega = {} exceeds wmax = {}",
            omega,
            wmax
        );
    }

    // Points should be sorted
    let mut sorted = omega_points.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
    assert_eq!(omega_points, sorted, "Omega points should be sorted");
}

#[test]
fn test_default_omega_sampling_points_bosonic() {
    let beta = 10000.0;
    let wmax = 1.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis =
        FiniteTempBasis::<LogisticKernel, Bosonic>::new(kernel, beta, Some(epsilon), None).unwrap();

    let omega_points = basis.default_omega_sampling_points().unwrap();

    // Should have same size as basis
    assert_eq!(omega_points.len(), basis.size());

    // Points should be in [-wmax, wmax]
    for &omega in &omega_points {
        assert!(
            omega.abs() <= wmax,
            "omega = {} exceeds wmax = {}",
            omega,
            wmax
        );
    }

    // Points should be sorted
    let mut sorted = omega_points.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
    assert_eq!(omega_points, sorted, "Omega points should be sorted");
}

#[test]
fn test_omega_points_symmetry() {
    let beta = 1000.0;
    let wmax = 2.0;
    let epsilon = 1e-8;

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis_f =
        FiniteTempBasis::<LogisticKernel, Fermionic>::new(kernel, beta, Some(epsilon), None)
            .unwrap();
    let omega_points = basis_f.default_omega_sampling_points().unwrap();

    // Check approximate symmetry: for each positive point, there should be a negative counterpart
    // (This is approximate due to the nature of the roots)
    let positive: Vec<f64> = omega_points.iter().filter(|&&x| x > 0.0).copied().collect();
    let negative: Vec<f64> = omega_points
        .iter()
        .filter(|&&x| x < 0.0)
        .map(|&x| -x)
        .collect();

    println!("Omega points: {:?}", omega_points);
    println!(
        "Number of positive: {}, negative: {}",
        positive.len(),
        negative.len()
    );
}

/// The regularized bosonic kernel in physical units,
/// K^B(τ, ω) = ω e^{-τω} / (1 - e^{-βω}) for 0 ≤ τ ≤ β, with K^B(τ, 0) = 1/β.
///
/// Reference: irbasis paper, N. Chikano, K. Yoshimi, J. Otsuki, H. Shinaoka,
/// Comput. Phys. Commun. 240, 181 (2019), arXiv:1807.05237, Eq. (3). A
/// `RegularizedBoseKernel` basis must expand it as Σ_l U_l(τ) S_l V_l(ω) with
/// S_l = sqrt(β ωmax³/2) s_l (Eq. (25)).
fn regularized_bose_kernel_physical(tau: f64, omega: f64, beta: f64) -> f64 {
    if omega == 0.0 {
        1.0 / beta
    } else if omega > 0.0 {
        omega * (-tau * omega).exp() / (1.0 - (-beta * omega).exp())
    } else {
        // Same function with non-positive exponents for ω < 0.
        omega * ((beta - tau) * omega).exp() / ((beta * omega).exp() - 1.0)
    }
}

#[test]
fn test_regularized_bose_basis_represents_physical_kernel() {
    // ωmax ≠ 1 separates ωmax^(+1) (Eq. (25)) from any other power of ωmax.
    // At ε = 1e-12 the truncation error of Σ U S V is far below 1e-8 ωmax,
    // the scale of K^B; a wrong power of ωmax is an O(1) relative error.
    for &(beta, omega_max) in &[(10.0, 2.0), (4.0, 2.5), (20.0, 0.5)] {
        let kernel = RegularizedBoseKernel::new(beta * omega_max).unwrap();
        let basis =
            FiniteTempBasis::<RegularizedBoseKernel, Bosonic>::new(kernel, beta, Some(1e-12), None)
                .unwrap();
        let s = basis.s();
        for &tau in &[0.3, 0.37 * beta, 0.8 * beta] {
            let u = basis.u().evaluate_at(tau);
            for &omega in &[-0.7 * omega_max, 0.0, 0.2 * omega_max, 0.9 * omega_max] {
                let v = basis.v().evaluate_at(omega);
                let usv: f64 = (0..basis.size()).map(|l| u[l] * s[l] * v[l]).sum();
                let exact = regularized_bose_kernel_physical(tau, omega, beta);
                assert!(
                    (usv - exact).abs() <= 1e-8 * omega_max,
                    "beta={beta}, omega_max={omega_max}, tau={tau}, omega={omega}: \
                     sum U S V = {usv}, K^B = {exact}"
                );
            }
        }
    }
}

#[test]
fn test_regularized_bose_basis_single_pole() {
    use crate::freq::MatsubaraFreq;
    use num_complex::Complex64;

    // A single bosonic pole, A(ω) = δ(ω - ω0), so Ĝ(iν) = 1/(iν - ω0). The
    // kernel takes ρ(ω) = A(ω)/ω (Eq. (2)), so G_l = -S_l V_l(ω0)/ω0 (Eq. (8)).
    let (beta, omega_max, omega0) = (10.0, 2.0, 0.6);
    let kernel = RegularizedBoseKernel::new(beta * omega_max).unwrap();
    let basis =
        FiniteTempBasis::<RegularizedBoseKernel, Bosonic>::new(kernel, beta, Some(1e-12), None)
            .unwrap();
    let v = basis.v().evaluate_at(omega0);
    let gl: Vec<f64> = (0..basis.size())
        .map(|l| -basis.s()[l] * v[l] / omega0)
        .collect();
    for n in [0_i64, 2, -4, 10] {
        let freq = MatsubaraFreq::<Bosonic>::new(n).unwrap();
        let uhat = basis.uhat().evaluate_at(&freq);
        let giv: Complex64 = gl.iter().zip(uhat.iter()).map(|(&g, &u)| u * g).sum();
        let exact = Complex64::new(1.0, 0.0) / Complex64::new(-omega0, freq.value(beta));
        assert!(
            (giv - exact).norm() <= 1e-8 * exact.norm(),
            "n={n}: sum G_l Uhat_l = {giv}, 1/(iν - ω0) = {exact}"
        );
    }
}

/// A large β with a moderate Λ is valid. `from_sve_result` scales the knots
/// and the widths separately, so their difference grows with the magnitude of
/// the knots (about β); the width check of `PiecewiseLegendrePoly::new` must
/// be relative to that magnitude and not reject such a basis.
#[test]
fn test_basis_with_a_large_beta_and_a_moderate_lambda() {
    for beta in [1e4, 1e7, 1e10] {
        let omega_max = 10.0 / beta;
        let kernel = LogisticKernel::new(beta * omega_max).unwrap();
        let basis = FermionicBasis::new(kernel, beta, Some(1e-6), None)
            .unwrap_or_else(|e| panic!("beta = {beta}: {e}"));
        let u = &basis.u().polys()[0];
        assert_eq!(u.xmax(), beta);
        for tau in [0.0, 0.5 * beta, beta] {
            assert!(u.evaluate(tau).is_finite(), "beta = {beta}, tau = {tau}");
        }
    }
}

/// default_matsubara_sampling_points_from_uhat, which the C API calls with a
/// Matsubara-space spir_funcs, selects points for functions without a
/// definite parity too (they were NotSupported, #183): a set symmetric in ±n
/// of fermionic frequencies, `size()` of them rounded up to an even number,
/// the non-negative half with `positive_only`, more with mitigate. No
/// functions give EmptyInput (it panicked on `len() - 1`).
#[test]
fn test_default_matsubara_points_from_uhat() {
    use crate::basis::default_matsubara_sampling_points_from_uhat;
    use crate::polyfourier::PiecewiseLegendreFTVector;
    use crate::sve::{SVEOptions, compute_sve_with};

    let kernel = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve_with(
        kernel,
        &SVEOptions::new()
            .epsilon(1e-6)
            .twork(TworkType::Auto)
            .full_domain(true),
    )
    .unwrap();
    let basis =
        FiniteTempBasis::<_, Fermionic>::from_sve_result(kernel, 1.0, sve, Some(1e-6), None)
            .unwrap();
    assert!(
        basis
            .uhat_full()
            .get_polys()
            .iter()
            .all(|u| u.poly.symm() == 0)
    );
    let ns = |mitigate, positive_only| -> Vec<i64> {
        default_matsubara_sampling_points_from_uhat(
            basis.uhat_full(),
            basis.size(),
            mitigate,
            positive_only,
        )
        .unwrap()
        .into_iter()
        .map(|f| f.n())
        .collect()
    };
    let full = ns(false, false);
    assert_eq!(full.len(), basis.size() + basis.size() % 2, "{full:?}");
    assert!(full.iter().all(|n| n % 2 != 0), "{full:?}");
    assert!(full.windows(2).all(|w| w[0] < w[1]), "{full:?}");
    assert!(full.iter().all(|n| full.contains(&-n)), "{full:?}");
    let positive: Vec<i64> = full.iter().copied().filter(|&n| n > 0).collect();
    assert_eq!(ns(false, true), positive);
    assert!(ns(true, false).len() > full.len());

    let empty = PiecewiseLegendreFTVector::<Fermionic>::new();
    assert_eq!(
        default_matsubara_sampling_points_from_uhat(&empty, 4, false, false).unwrap_err(),
        Error::EmptyInput { name: "uhat_full" }
    );
}

/// A basis from an SVE truncated to 2 functions has no default tau sampling
/// points: they are the roots of u_2, which is missing, and its stand-in, the
/// extrema of u_1, does not exist (u_1 is monotonic). The empty extrema were
/// indexed and panicked. Points that need only u_0 and u_1 are still
/// defined, as are the other default points.
#[test]
fn test_default_tau_points_of_an_sve_truncated_to_two_functions() {
    let kernel = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve(kernel, Some(1e-6), None, Some(2), TworkType::Auto).unwrap();
    assert_eq!(sve.s().len(), 2);
    fn check<S: crate::traits::StatisticsType + 'static>(
        basis: &FiniteTempBasis<LogisticKernel, S>,
    ) {
        let not_supported = |err: Error| {
            assert!(
                matches!(&err, Error::NotSupported { what } if what.contains("no extrema")),
                "{err:?}"
            );
        };
        not_supported(basis.default_tau_sampling_points().unwrap_err());
        for n in [2, 3, 10] {
            not_supported(
                basis
                    .default_tau_sampling_points_size_requested(n)
                    .unwrap_err(),
            );
        }
        // The roots of u_0 (none) and u_1 (one, at τ = β/2)
        assert_eq!(
            basis
                .default_tau_sampling_points_size_requested(0)
                .unwrap()
                .len(),
            0
        );
        assert_eq!(
            basis
                .default_tau_sampling_points_size_requested(1)
                .unwrap()
                .len(),
            1
        );
        assert!(!basis.default_omega_sampling_points().unwrap().is_empty());
        assert!(
            !basis
                .default_matsubara_sampling_points(false)
                .unwrap()
                .is_empty()
        );
    }
    check(
        &FiniteTempBasis::<_, Fermionic>::from_sve_result(kernel, 10.0, sve.clone(), None, None)
            .unwrap(),
    );
    check(&FiniteTempBasis::<_, Bosonic>::from_sve_result(kernel, 10.0, sve, None, None).unwrap());
}

/// default_sampling_points needs the unscaled functions of an SVE, on
/// [-1, 1]; the functions of a basis (on [0, β] and [-ωmax, ωmax]) are
/// rejected, under the name the caller gives them. It panicked.
#[test]
fn test_default_sampling_points_rejects_scaled_functions() {
    use crate::basis::default_sampling_points;

    // β = 1 and Λ = 10: u is on [0, 1] and v on [-10, 10], neither on [-1, 1].
    let basis =
        FermionicBasis::new(LogisticKernel::new(10.0).unwrap(), 1.0, Some(1e-6), None).unwrap();
    let unit = (-1.0, 1.0);
    let err = default_sampling_points(basis.u(), "u", unit, 3).unwrap_err();
    assert!(
        matches!(err, Error::InvalidParameter { name: "u", .. }),
        "{err:?}"
    );
    let err = default_sampling_points(basis.v(), "v", unit, 3).unwrap_err();
    assert!(
        matches!(err, Error::InvalidParameter { name: "v", .. }),
        "{err:?}"
    );
    assert!(default_sampling_points(basis.sve_result().u(), "u", unit, 3).is_ok());
}

/// The default Matsubara points are found once per basis and
/// `positive_only`: they are exactly the points found directly (with and
/// without parity, both statistics), also when asked for repeatedly.
#[test]
fn test_default_matsubara_points_are_reused() {
    use crate::kernel::LogisticKernelWindowed;
    use crate::traits::StatisticsType;

    fn check<K, S>(kernel: K, beta: f64)
    where
        K: crate::kernel::BasisKernel,
        S: StatisticsType + 'static,
    {
        let basis = FiniteTempBasis::<K, S>::new(kernel, beta, Some(1e-10), None).unwrap();
        let direct = |positive_only| {
            crate::basis::default_matsubara_sampling_points_from_uhat(
                basis.uhat_full(),
                basis.size(),
                false,
                positive_only,
            )
            .unwrap()
            .iter()
            .map(|f| f.n())
            .collect::<Vec<_>>()
        };
        for _ in 0..2 {
            for positive_only in [false, true] {
                assert_eq!(
                    basis
                        .default_matsubara_sampling_points_i64(positive_only)
                        .unwrap(),
                    direct(positive_only),
                    "{:?}, positive_only = {positive_only}",
                    S::STATISTICS
                );
                // The C API getter takes the cached points too
                assert_eq!(
                    basis
                        .default_matsubara_sampling_points_i64_with_mitigate(
                            positive_only,
                            false,
                            basis.size(),
                        )
                        .unwrap(),
                    direct(positive_only)
                );
            }
        }
    }
    check::<_, Fermionic>(LogisticKernel::new(1e3).unwrap(), 1e3);
    check::<_, Bosonic>(LogisticKernel::new(1e3).unwrap(), 1e3);
    check::<_, Bosonic>(RegularizedBoseKernel::new(1e3).unwrap(), 1e3);
    let windowed = LogisticKernelWindowed::from_physical(1e2, -0.3, 1.0).unwrap();
    check::<_, Fermionic>(windowed, 1e2);
    check::<_, Bosonic>(windowed, 1e2);
}

/// A kernel whose x domain is not [-1, 1] is rejected: the basis maps x to
/// τ = β (x + 1) / 2, which would leave [0, β] (found by a code review).
#[test]
fn test_basis_rejects_a_kernel_x_domain_other_than_unit() {
    use crate::kernel::{
        AbstractKernel, BasisKernel, ExpandableKernel, KernelProperties, LogisticSVEHints,
        SVEKernel,
    };
    use crate::numeric::CustomNumeric;
    use crate::traits::StatisticsType;
    use std::fmt::Debug;

    /// The logistic kernel claiming the x domain [-2, 2]
    #[derive(Debug, Clone, Copy)]
    struct WideX(LogisticKernel);

    impl AbstractKernel for WideX {
        fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
            self.0.compute(x, y)
        }
    }

    impl SVEKernel for WideX {
        type SVEHintsType<T>
            = LogisticSVEHints<T>
        where
            T: Copy + Debug + Send + Sync + CustomNumeric + 'static;

        fn xmax(&self) -> f64 {
            2.0
        }

        fn ymax(&self) -> f64 {
            self.0.ymax()
        }

        fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
        where
            T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
        {
            self.0.sve_hints::<T>(epsilon)
        }
    }

    impl KernelProperties for WideX {
        fn ypower(&self) -> i32 {
            self.0.ypower()
        }

        fn conv_radius(&self) -> f64 {
            self.0.conv_radius()
        }

        fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64 {
            self.0.regularizer::<S>(beta, omega)
        }
    }

    impl ExpandableKernel for WideX {}

    impl BasisKernel for WideX {
        fn kernel_lambda(&self) -> f64 {
            self.0.lambda()
        }
    }

    let logistic = LogisticKernel::new(10.0).unwrap();
    let sve = compute_sve(logistic, Some(1e-6), None, None, TworkType::Auto).unwrap();
    let result = FiniteTempBasis::<_, Fermionic>::from_sve_result(
        WideX(logistic),
        10.0,
        sve,
        Some(1e-6),
        None,
    );
    assert!(
        matches!(result, Err(Error::InvalidParameter { name: "kernel", .. })),
        "{:?}",
        result.err()
    );
}

/// Until #285, `FiniteTempBasis::new` truncated the SVE to `max_size`, so
/// `Some(1)` hit the same panic (and `spir_basis_new(max_size = 1)` returned
/// SPIR_INTERNAL_ERROR). It now truncates only the basis; a basis of size 1
/// must still be the leading part of the full basis.
#[test]
fn test_basis_with_max_size_one() {
    use crate::basis::FiniteTempBasis;
    use crate::kernel::LogisticKernel;
    use crate::traits::{Bosonic, Fermionic, StatisticsType};

    fn check<S: StatisticsType + 'static>() {
        let (beta, kernel) = (10.0, LogisticKernel::new(10.0).unwrap());
        let full = FiniteTempBasis::<_, S>::new(kernel, beta, Some(1e-6), None).unwrap();
        let basis = FiniteTempBasis::<_, S>::new(kernel, beta, Some(1e-6), Some(1)).unwrap();
        assert_eq!(basis.size(), 1);
        assert_eq!(basis.s(), &full.s()[..1]);
        for tau in [0.0, 0.3 * beta, beta] {
            assert_eq!(basis.u()[0].evaluate(tau), full.u()[0].evaluate(tau));
        }
        for omega in [-1.0, 0.2, 1.0] {
            assert_eq!(basis.v()[0].evaluate(omega), full.v()[0].evaluate(omega));
        }
    }
    check::<Fermionic>();
    check::<Bosonic>();
}