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
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
// RegularizedBoseKernel is deprecated (#273) but tested until it is removed.
#![allow(deprecated)]
use crate::basis::FiniteTempBasis;
use crate::kernel::{CentrosymmKernel, KernelProperties};
use crate::kernel::{LogisticKernel, RegularizedBoseKernel};
use crate::sampling::TauSampling;
use crate::test_utils::At;
use crate::traits::{Bosonic, Fermionic, StatisticsType};
use num_complex::Complex;

use crate::test_utils::{ErrorNorm, movedim};

/// Test for evaluate_nd/fit_nd roundtrip (real)
fn test_evaluate_nd_roundtrip_real<S>()
where
    S: StatisticsType + 'static,
    LogisticKernel: KernelProperties + CentrosymmKernel + Clone + 'static,
{
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, beta, epsilon, None).unwrap();
    let sampling = TauSampling::new(&basis).unwrap();

    let n_k = 5;
    let n_omega = 7;

    // Test for all dimensions (dim = 0, 1, 2)
    for dim in 0..3 {
        // Generate random test data (dim=0 format: [basis_size, n_k, n_omega])
        let (coeffs_0, _gtau_0, _giwn_0) = crate::test_utils::generate_nd_test_data::<f64, _, _>(
            &basis,
            sampling.sampling_points(),
            &[],
            42 + dim as u64,
            &[n_k, n_omega],
        );

        // Move to target dimension
        let coeffs_dim = movedim(&coeffs_0, 0, dim);

        // Evaluate along target dimension
        let evaluated_values = sampling.evaluate_nd(None, &coeffs_dim, dim).unwrap();

        // Fit back along target dimension
        let fitted_coeffs_dim = sampling.fit_nd(None, &evaluated_values, dim).unwrap();

        // Move back to dim=0 for comparison
        let fitted_coeffs_0 = movedim(&fitted_coeffs_dim, dim, 0);

        let basis_size = basis.size();

        // Check roundtrip
        for k in 0..n_k {
            for omega in 0..n_omega {
                for l in 0..basis_size {
                    let orig = coeffs_0.at(&[l, k, omega]);
                    let fitted = fitted_coeffs_0.at(&[l, k, omega]);
                    let abs_error = (orig - fitted).abs();

                    assert!(
                        abs_error < 1e-10,
                        "ND roundtrip (dim={}) error at ({},{},{}): error={}",
                        dim,
                        l,
                        k,
                        omega,
                        abs_error
                    );
                }
            }
        }
    }
}

#[test]
fn test_evaluate_nd_fermionic_real() {
    test_evaluate_nd_roundtrip_real::<Fermionic>();
}

#[test]
fn test_evaluate_nd_bosonic_real() {
    test_evaluate_nd_roundtrip_real::<Bosonic>();
}

/// Test for evaluate_nd/fit_nd roundtrip (complex)
fn test_evaluate_nd_roundtrip_complex<S>()
where
    S: StatisticsType + 'static,
    LogisticKernel: KernelProperties + CentrosymmKernel + Clone + 'static,
{
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, beta, epsilon, None).unwrap();
    let sampling = TauSampling::new(&basis).unwrap();

    let n_k = 5;
    let n_omega = 7;

    for dim in 0..3 {
        let (coeffs_0, _gtau_0, _giwn_0) =
            crate::test_utils::generate_nd_test_data::<Complex<f64>, _, _>(
                &basis,
                sampling.sampling_points(),
                &[],
                42 + dim as u64,
                &[n_k, n_omega],
            );

        let coeffs_dim = movedim(&coeffs_0, 0, dim);
        let evaluated_values = sampling.evaluate_nd_zz(None, &coeffs_dim, dim).unwrap();
        let fitted_coeffs_dim = sampling.fit_nd_zz(None, &evaluated_values, dim).unwrap();
        let fitted_coeffs_0 = movedim(&fitted_coeffs_dim, dim, 0);

        let basis_size = basis.size();

        for k in 0..n_k {
            for omega in 0..n_omega {
                for l in 0..basis_size {
                    let orig = coeffs_0.at(&[l, k, omega]);
                    let fitted = fitted_coeffs_0.at(&[l, k, omega]);
                    let abs_error = (orig - fitted).error_norm();

                    assert!(
                        abs_error < 1e-10,
                        "ND roundtrip (dim={}) error at ({},{},{}): error={}",
                        dim,
                        l,
                        k,
                        omega,
                        abs_error
                    );
                }
            }
        }
    }
}

#[test]
fn test_evaluate_nd_fermionic_complex() {
    test_evaluate_nd_roundtrip_complex::<Fermionic>();
}

#[test]
fn test_evaluate_nd_bosonic_complex() {
    test_evaluate_nd_roundtrip_complex::<Bosonic>();
}

// ====================
// RegularizedBoseKernel TauSampling Tests
// ====================

/// Test for RegularizedBoseKernel evaluate_nd/fit_nd roundtrip (real)
fn test_regularized_bose_evaluate_nd_roundtrip_real() {
    let beta = 10.0;
    let wmax = 1.0;
    let epsilon = Some(1e-4);

    let kernel = RegularizedBoseKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, Bosonic>::new(kernel, beta, epsilon, None).unwrap();
    let sampling = TauSampling::new(&basis).unwrap();

    let n_k = 5;
    let n_omega = 7;

    for dim in 0..3 {
        let (coeffs_0, _gtau_0, _giwn_0) = crate::test_utils::generate_nd_test_data::<f64, _, _>(
            &basis,
            sampling.sampling_points(),
            &[],
            42 + dim as u64,
            &[n_k, n_omega],
        );

        let coeffs_dim = movedim(&coeffs_0, 0, dim);
        let evaluated_values = sampling.evaluate_nd(None, &coeffs_dim, dim).unwrap();
        let fitted_coeffs_dim = sampling.fit_nd(None, &evaluated_values, dim).unwrap();
        let fitted_coeffs_0 = movedim(&fitted_coeffs_dim, dim, 0);

        let basis_size = basis.size();
        let mut max_error = 0.0;
        for k in 0..n_k {
            for omega in 0..n_omega {
                for l in 0..basis_size {
                    let orig = coeffs_0.at(&[l, k, omega]);
                    let fitted = fitted_coeffs_0.at(&[l, k, omega]);
                    let abs_error = (orig - fitted).abs();
                    if abs_error > max_error {
                        max_error = abs_error;
                    }
                }
            }
        }

        assert!(
            max_error < 1e-7,
            "RegularizedBose ND roundtrip (dim={}) error too large: {}",
            dim,
            max_error
        );
    }
}

/// Test for RegularizedBoseKernel evaluate_nd/fit_nd roundtrip (complex)
fn test_regularized_bose_evaluate_nd_roundtrip_complex() {
    let beta = 10.0;
    let wmax = 1.0;
    let epsilon = Some(1e-4);

    let kernel = RegularizedBoseKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, Bosonic>::new(kernel, beta, epsilon, None).unwrap();
    let sampling = TauSampling::new(&basis).unwrap();

    let n_k = 5;
    let n_omega = 7;

    for dim in 0..3 {
        let (coeffs_0, _gtau_0, _giwn_0) =
            crate::test_utils::generate_nd_test_data::<Complex<f64>, _, _>(
                &basis,
                sampling.sampling_points(),
                &[],
                42 + dim as u64,
                &[n_k, n_omega],
            );

        let coeffs_dim = movedim(&coeffs_0, 0, dim);
        let evaluated_values = sampling.evaluate_nd_zz(None, &coeffs_dim, dim).unwrap();
        let fitted_coeffs_dim = sampling.fit_nd_zz(None, &evaluated_values, dim).unwrap();
        let fitted_coeffs_0 = movedim(&fitted_coeffs_dim, dim, 0);

        let basis_size = basis.size();
        let mut max_error = 0.0;
        for k in 0..n_k {
            for omega in 0..n_omega {
                for l in 0..basis_size {
                    let orig = coeffs_0.at(&[l, k, omega]);
                    let fitted = fitted_coeffs_0.at(&[l, k, omega]);
                    let abs_error = (orig - fitted).error_norm();
                    if abs_error > max_error {
                        max_error = abs_error;
                    }
                }
            }
        }

        assert!(
            max_error < 1e-7,
            "RegularizedBose ND roundtrip (dim={}) error too large: {}",
            dim,
            max_error
        );
    }
}

#[test]
fn test_regularized_bose_evaluate_nd_real() {
    test_regularized_bose_evaluate_nd_roundtrip_real();
}

#[test]
fn test_regularized_bose_evaluate_nd_complex() {
    test_regularized_bose_evaluate_nd_roundtrip_complex();
}

/// Test that evaluate_nd_to produces identical results to evaluate_nd
#[test]
fn test_evaluate_nd_to_matches_fermionic_real() {
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    let coeffs = crate::test_utils::tensor_from_fn::<f64>(&[basis_size, n_k, n_omega], |idx| {
        (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5) * (idx[2] as f64 + 0.3)
    });

    let expected = sampling.evaluate_nd(None, &coeffs, 0).unwrap();

    let mut actual = crate::test_utils::tensor_filled::<f64>(&[n_points, n_k, n_omega], 0.0);
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .evaluate_nd_to(None, &coeffs.as_view(), 0, &mut actual_view)
            .unwrap();
    }

    let expected_shape = expected.shape().to_vec();
    let actual_shape = actual.shape().to_vec();
    assert_eq!(expected_shape, actual_shape);

    for i in 0..n_points {
        for j in 0..n_k {
            for k in 0..n_omega {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).abs();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

#[test]
fn test_evaluate_nd_to_matches_fermionic_complex() {
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    let coeffs =
        crate::test_utils::tensor_from_fn::<Complex<f64>>(&[basis_size, n_k, n_omega], |idx| {
            Complex::new(
                (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5),
                idx[2] as f64 * 0.3,
            )
        });

    let expected = sampling.evaluate_nd_zz(None, &coeffs, 0).unwrap();

    let mut actual = crate::test_utils::tensor_filled::<Complex<f64>>(
        &[n_points, n_k, n_omega],
        Complex::new(0.0, 0.0),
    );
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .evaluate_nd_zz_to(None, &coeffs.as_view(), 0, &mut actual_view)
            .unwrap();
    }

    let expected_shape = expected.shape().to_vec();
    let actual_shape = actual.shape().to_vec();
    assert_eq!(expected_shape, actual_shape);

    for i in 0..n_points {
        for j in 0..n_k {
            for k in 0..n_omega {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).error_norm();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

/// Test that fit_nd_to produces identical results to fit_nd
#[test]
fn test_fit_nd_to_matches_fermionic_real() {
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    let values = crate::test_utils::tensor_from_fn::<f64>(&[n_points, n_k, n_omega], |idx| {
        (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5) * (idx[2] as f64 + 0.3)
    });

    let expected = sampling.fit_nd(None, &values, 0).unwrap();

    let mut actual = crate::test_utils::tensor_filled::<f64>(&[basis_size, n_k, n_omega], 0.0);
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .fit_nd_to(None, &values.as_view(), 0, &mut actual_view)
            .unwrap();
    }

    let expected_shape = expected.shape().to_vec();
    let actual_shape = actual.shape().to_vec();
    assert_eq!(expected_shape, actual_shape);

    for i in 0..basis_size {
        for j in 0..n_k {
            for k in 0..n_omega {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).abs();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

#[test]
fn test_fit_nd_to_matches_fermionic_complex() {
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    let values =
        crate::test_utils::tensor_from_fn::<Complex<f64>>(&[n_points, n_k, n_omega], |idx| {
            Complex::new(
                (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5),
                idx[2] as f64 * 0.3,
            )
        });

    let expected = sampling.fit_nd_zz(None, &values, 0).unwrap();

    let mut actual = crate::test_utils::tensor_filled::<Complex<f64>>(
        &[basis_size, n_k, n_omega],
        Complex::new(0.0, 0.0),
    );
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .fit_nd_zz_to(None, &values.as_view(), 0, &mut actual_view)
            .unwrap();
    }

    let expected_shape = expected.shape().to_vec();
    let actual_shape = actual.shape().to_vec();
    assert_eq!(expected_shape, actual_shape);

    for i in 0..basis_size {
        for j in 0..n_k {
            for k in 0..n_omega {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).error_norm();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

// ============================================================================
// Tests for evaluate_nd_to at different dims
// ============================================================================

#[test]
fn test_evaluate_nd_to_dim0() {
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    let coeffs = crate::test_utils::tensor_from_fn::<f64>(&[basis_size, n_k, n_omega], |idx| {
        (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5) * (idx[2] as f64 + 0.3)
    });

    let expected = sampling.evaluate_nd(None, &coeffs, 0).unwrap();

    let mut actual = crate::test_utils::tensor_filled::<f64>(&[n_points, n_k, n_omega], 0.0);
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .evaluate_nd_to(None, &coeffs.as_view(), 0, &mut actual_view)
            .unwrap();
    }

    for i in 0..n_points {
        for j in 0..n_k {
            for k in 0..n_omega {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).abs();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

#[test]
fn test_evaluate_nd_to_dim1() {
    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    // Create test coefficients with basis_size in middle dimension
    let coeffs = crate::test_utils::tensor_from_fn::<f64>(&[n_k, basis_size, n_omega], |idx| {
        (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5) * (idx[2] as f64 + 0.3)
    });

    // Expected result
    let expected = sampling.evaluate_nd(None, &coeffs, 1).unwrap();

    // Actual result using to_viewmut
    let mut actual = crate::test_utils::tensor_filled::<f64>(&[n_k, n_points, n_omega], 0.0);
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .evaluate_nd_to(None, &coeffs.as_view(), 1, &mut actual_view)
            .unwrap();
    }

    // Compare
    for i in 0..n_k {
        for j in 0..n_points {
            for k in 0..n_omega {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).abs();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

#[test]
fn test_evaluate_nd_to_dim_last() {
    // Test dim == N-1 (last dimension) fast path

    let beta = 1.0;
    let wmax = 10.0;
    let epsilon = Some(1e-6);

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

    let basis_size = basis.size();
    let n_points = sampling.n_sampling_points();
    let n_k = 3;
    let n_omega = 4;

    // Create test coefficients with basis_size in LAST dimension (dim=2)
    let coeffs = crate::test_utils::tensor_from_fn::<f64>(&[n_k, n_omega, basis_size], |idx| {
        (idx[0] as f64 + 1.0) * (idx[1] as f64 + 0.5) * (idx[2] as f64 + 0.3)
    });

    // Expected result (dim=2, which is rank-1)
    let expected = sampling.evaluate_nd(None, &coeffs, 2).unwrap();

    // Actual result using to_viewmut (should use fast path for dim == N-1)
    let mut actual = crate::test_utils::tensor_filled::<f64>(&[n_k, n_omega, n_points], 0.0);
    {
        let mut actual_view = actual.as_view_mut();
        sampling
            .evaluate_nd_to(None, &coeffs.as_view(), 2, &mut actual_view)
            .unwrap();
    }

    // Compare
    for i in 0..n_k {
        for j in 0..n_omega {
            for k in 0..n_points {
                let e = expected.at(&[i, j, k]);
                let a = actual.at(&[i, j, k]);
                let diff = (e - a).abs();
                assert!(
                    diff < 1e-12,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}, diff={}",
                    i,
                    j,
                    k,
                    e,
                    a,
                    diff
                );
            }
        }
    }
}

/// TauSampling reports the condition number of its real sampling matrix
fn check_tau_condition_number<S: StatisticsType + 'static>() {
    use crate::test_utils::{assert_condition_number_close, oracle_condition_number};

    let (beta, wmax, epsilon) = (10.0, 1.0, 1e-6);
    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, beta, Some(epsilon), None).unwrap();
    let sampling = TauSampling::new(&basis).unwrap();

    let oracle = oracle_condition_number(sampling.matrix());
    let label = format!(
        "tau {:?}, beta={beta}, wmax={wmax}, eps={epsilon:e}, L={}, n={}",
        S::STATISTICS,
        basis.size(),
        sampling.n_sampling_points()
    );
    assert_condition_number_close(&label, sampling.condition_number().unwrap(), oracle);
}

#[test]
fn test_tau_condition_number_fermionic() {
    check_tau_condition_number::<Fermionic>();
}

#[test]
fn test_tau_condition_number_bosonic() {
    check_tau_condition_number::<Bosonic>();
}

/// `out` of `TauSampling::*_nd_to` must match the input on every axis, not
/// only in rank and target extent. Before PR-0, `evaluate_nd_to` with coeffs
/// of shape [L, 50] and an out view of shape [n_points, 1] wrote the
/// 49 × n_points values that do not fit past the end of the view; PR-0 made
/// it a panic, and it is ShapeMismatch of the output now.
#[test]
fn test_nd_to_rejects_out_with_wrong_batch_extent() {
    use crate::error::{ArrayRole, Error};
    use tenferro_tensor::TypedTensorViewMut;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let sampling = TauSampling::new(&basis).unwrap();
    let (l, np, extra) = (sampling.basis_size(), sampling.n_sampling_points(), 50);
    const CANARY: f64 = -12345.0;

    // Each call gets a buffer large enough for the correct output, and a view
    // that claims only its first `extra` = 1 column.
    let run = |fit: bool, complex: bool| -> (Result<(), Error>, usize, bool) {
        let (n_in, n_out) = if fit { (np, l) } else { (l, np) };
        if complex {
            let canary = Complex::new(CANARY, -CANARY);
            let mut buffer = vec![canary; n_out * extra];
            let input = crate::test_utils::tensor_filled::<Complex<f64>>(
                &[n_in, extra],
                Complex::new(1.0, 0.5),
            );
            let result = {
                // The view covers only the first column of `buffer`.
                let mut out =
                    TypedTensorViewMut::from_slice([n_out, 1], [1, n_out as isize], 0, &mut buffer)
                        .unwrap();
                if fit {
                    sampling.fit_nd_zz_to(None, &input.as_view(), 0, &mut out)
                } else {
                    sampling.evaluate_nd_zz_to(None, &input.as_view(), 0, &mut out)
                }
            };
            (result, n_out, buffer.iter().all(|&x| x == canary))
        } else {
            let mut buffer = vec![CANARY; n_out * extra];
            let input = crate::test_utils::tensor_filled::<f64>(&[n_in, extra], 1.0);
            let result = {
                // The view covers only the first column of `buffer`.
                let mut out =
                    TypedTensorViewMut::from_slice([n_out, 1], [1, n_out as isize], 0, &mut buffer)
                        .unwrap();
                if fit {
                    sampling.fit_nd_to(None, &input.as_view(), 0, &mut out)
                } else {
                    sampling.evaluate_nd_to(None, &input.as_view(), 0, &mut out)
                }
            };
            (result, n_out, buffer.iter().all(|&x| x == CANARY))
        }
    };

    for fit in [false, true] {
        for complex in [false, true] {
            let (result, n_out, untouched) = run(fit, complex);
            assert_eq!(
                result,
                Err(Error::ShapeMismatch {
                    which: ArrayRole::Output,
                    expected: vec![n_out, extra],
                    actual: vec![n_out, 1],
                }),
                "fit={fit}, complex={complex}"
            );
            assert!(
                untouched,
                "fit={fit}, complex={complex}: out buffer written"
            );
        }
    }
}

/// Extents of `dims` permuted as `movedim(_, src, dst)` does
fn moved_dims(dims: &[usize], src: usize, dst: usize) -> Vec<usize> {
    let mut moved = dims.to_vec();
    let d = moved.remove(src);
    moved.insert(dst, d);
    moved
}

/// Every zero-extent array must move to an empty array of the permuted
/// shape. (With mdarray 0.7.2, `movedim` of e.g. a [2, 0] array from axis 1
/// to 0 segfaulted, https://github.com/fre-hu/mdarray/issues/21.)
#[test]
fn test_movedim_with_zero_extent() {
    use crate::sampling::movedim;

    for dims in [
        vec![0usize, 3],
        vec![2, 0],
        vec![0, 2, 3],
        vec![2, 0, 3],
        vec![2, 3, 0],
        vec![0, 0, 4],
    ] {
        let arr = crate::test_utils::tensor_filled::<f64>(&dims, 0.0);
        for src in 0..dims.len() {
            for dst in 0..dims.len() {
                let moved = movedim(&arr, src, dst);
                assert_eq!(moved.shape(), &moved_dims(&dims, src, dst)[..]);
                assert_eq!(moved.n_elements(), 0);
            }
        }
    }

    // A non-empty array still moves its elements
    let arr = crate::test_utils::tensor_from_fn::<f64>(&[2, 3, 4], |idx| {
        (100 * idx[0] + 10 * idx[1] + idx[2]) as f64
    });
    let moved = movedim(&arr, 2, 0);
    assert_eq!(moved.shape(), &[4, 2, 3]);
    assert_eq!(moved.at(&[3, 1, 2]), arr.at(&[1, 2, 3]));
}

/// movedim checks both axes also when they are equal: an axis past the rank
/// was returned as a copy of the array.
#[test]
#[should_panic(expected = "src axis 2 out of bounds for rank 2")]
fn test_movedim_rejects_equal_axes_past_the_rank() {
    use crate::sampling::movedim;

    let arr = crate::test_utils::tensor_filled::<f64>(&[2, 3], 0.0);
    let _ = movedim(&arr, 2, 2);
}

/// Evaluating or fitting an empty batch gives an empty result of the right
/// shape, for every target axis
#[test]
fn test_tau_nd_with_empty_batch() {
    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let sampling = TauSampling::new(&basis).unwrap();
    let (l, np) = (sampling.basis_size(), sampling.n_sampling_points());

    for (batch, dim) in [
        (vec![0usize, 3], 0),
        (vec![3, 0], 1),
        (vec![0, 3], 2),
        (vec![2, 0], 1),
    ] {
        let mut dims = batch.clone();
        dims.insert(dim, l);
        let mut expected = batch.clone();
        expected.insert(dim, np);

        let coeffs = crate::test_utils::tensor_filled::<f64>(&dims, 0.0);
        let values = sampling.evaluate_nd(None, &coeffs, dim).unwrap();
        assert_eq!(values.shape(), &expected[..]);
        let fitted = sampling.fit_nd(None, &values, dim).unwrap();
        assert_eq!(fitted.shape(), &dims[..]);

        let coeffs_z =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims, Complex::new(0.0, 0.0));
        let values_z = sampling.evaluate_nd_zz(None, &coeffs_z, dim).unwrap();
        assert_eq!(values_z.shape(), &expected[..]);
        let fitted_z = sampling.fit_nd_zz(None, &values_z, dim).unwrap();
        assert_eq!(fitted_z.shape(), &dims[..]);
    }
}

/// A sampling matrix without columns describes no basis function. Before
/// PR-0 `from_matrix` accepted it and the first fit or condition number
/// segfaulted in the SVD (mdarray#21); PR-0 made it a panic, and it is
/// EmptyInput now.
#[test]
fn test_from_matrix_rejects_zero_columns() {
    use crate::error::Error;

    let matrix = crate::matrix::Mat::<f64>::zeros([3, 0]);
    assert_eq!(
        TauSampling::<Fermionic>::from_matrix(vec![0.1, 0.2, 0.3], &matrix.into_typed()).err(),
        Some(Error::EmptyInput { name: "matrix" })
    );
}

/// from_matrix checks its arguments (spec D5): no points, a matrix whose
/// rows are not the points, and NaN or infinite points or entries are
/// errors (they panicked, or failed at the first fit). The points only label
/// the rows: without β, any finite τ is accepted and kept.
#[test]
fn test_tau_from_matrix_checks_its_arguments() {
    use crate::error::{ArrayRole, Error};

    let matrix = |rows: usize| {
        crate::matrix::Mat::<f64>::from_fn([rows, 2], |idx| {
            1.0 / (1.0 + idx[0] as f64 + idx[1] as f64)
        })
    };
    let from = |points: Vec<f64>, m: crate::matrix::Mat<f64>| {
        TauSampling::<Bosonic>::from_matrix(points, &m.into_typed())
    };

    assert_eq!(
        from(vec![], crate::matrix::Mat::<f64>::zeros([0, 2])).err(),
        Some(Error::EmptyInput {
            name: "sampling_points"
        })
    );
    assert_eq!(
        from(vec![0.1, 0.2, 0.3], matrix(2)).err(),
        Some(Error::ShapeMismatch {
            which: ArrayRole::Input,
            expected: vec![3, 2],
            actual: vec![2, 2],
        })
    );
    for tau in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
        let err = from(vec![0.1, tau, 0.3], matrix(3)).err().unwrap();
        assert!(
            matches!(&err, Error::NonFiniteInput { name: "sampling_points", index, value }
                if index == &vec![1] && (value.is_nan() == tau.is_nan()) && (tau.is_nan() || *value == tau)),
            "{err:?}"
        );
    }
    let mut bad = matrix(3);
    bad[[2, 1]] = f64::NAN;
    let err = from(vec![0.1, 0.2, 0.3], bad).err().unwrap();
    assert!(
        matches!(&err, Error::NonFiniteInput { name: "matrix", index, value }
            if index == &vec![2, 1] && value.is_nan()),
        "{err:?}"
    );

    // Finite points outside any [-β, β] are labels, kept as given.
    let points = vec![1e300, -7.5, -0.0];
    let sampling = from(points.clone(), matrix(3)).unwrap();
    assert_eq!(sampling.sampling_points(), &points[..]);
}

/// A tau sampling point outside [-β, β] or NaN is OutOfDomain (from
/// Basis::evaluate_tau), and no points is EmptyInput; both were panics.
#[test]
fn test_tau_sampling_rejects_invalid_points() {
    use crate::error::Error;

    let beta = 10.0;
    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(beta).unwrap(),
        beta,
        Some(1e-6),
        None,
    )
    .unwrap();
    for tau in [beta * 1.5, -beta * 1.5, f64::NAN, f64::INFINITY] {
        let err = TauSampling::with_sampling_points(&basis, vec![0.5, tau])
            .err()
            .unwrap();
        assert!(
            matches!(err, Error::OutOfDomain { name: "tau", value, domain }
                if (value == tau || (value.is_nan() && tau.is_nan())) && domain == (-beta, beta)),
            "{err:?}"
        );
    }
    assert_eq!(
        TauSampling::with_sampling_points(&basis, vec![]).err(),
        Some(Error::EmptyInput {
            name: "sampling_points"
        })
    );
    // ±β are inside the domain.
    TauSampling::with_sampling_points(&basis, vec![-beta, 0.0, beta]).unwrap();
}

/// The N-D methods of TauSampling report an axis that is not an axis of the
/// input and an input of the wrong extent along it (they panicked), before
/// allocating the output.
#[test]
fn test_tau_nd_methods_check_the_axis_and_the_input() {
    use crate::error::{ArrayRole, Error};

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let sampling = TauSampling::new(&basis).unwrap();
    let (l, np) = (sampling.basis_size(), sampling.n_sampling_points());

    let coeffs = crate::test_utils::tensor_filled::<f64>(&[l, 3], 0.0);
    let values = crate::test_utils::tensor_filled::<f64>(&[np, 3], 0.0);
    let coeffs_z =
        crate::test_utils::tensor_filled::<Complex<f64>>(&[l, 3], Complex::new(0.0, 0.0));
    let values_z =
        crate::test_utils::tensor_filled::<Complex<f64>>(&[np, 3], Complex::new(0.0, 0.0));
    let axis = Some(Error::AxisOutOfRange { axis: 2, rank: 2 });
    assert_eq!(sampling.evaluate_nd(None, &coeffs, 2).err(), axis);
    assert_eq!(sampling.fit_nd(None, &values, 2).err(), axis);
    assert_eq!(sampling.evaluate_nd_zz(None, &coeffs_z, 2).err(), axis);
    assert_eq!(sampling.fit_nd_zz(None, &values_z, 2).err(), axis);

    // Inputs of the wrong extent along `dim` (the default τ points are as
    // many as the basis functions here, so l + 1 and np + 1 are both wrong)
    let values_bad = crate::test_utils::tensor_filled::<f64>(&[l + 1, 3], 0.0);
    let coeffs_bad = crate::test_utils::tensor_filled::<f64>(&[np + 1, 3], 0.0);
    assert_eq!(
        sampling.fit_nd(None, &values_bad, 0).err(),
        Some(Error::ShapeMismatch {
            which: ArrayRole::Input,
            expected: vec![np, 3],
            actual: vec![l + 1, 3],
        })
    );
    assert_eq!(
        sampling.evaluate_nd(None, &coeffs_bad, 0).err(),
        Some(Error::ShapeMismatch {
            which: ArrayRole::Input,
            expected: vec![l, 3],
            actual: vec![np + 1, 3],
        })
    );
}

/// The 1-D methods of TauSampling report values or coefficients of the
/// wrong length, and an `out` of the wrong length, as ShapeMismatch (they
/// panicked), writing nothing.
#[test]
fn test_tau_1d_methods_check_the_lengths() {
    use crate::error::{ArrayRole, Error};

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let sampling = TauSampling::new(&basis).unwrap();
    let (l, np) = (sampling.basis_size(), sampling.n_sampling_points());
    let input = |expected: usize, actual: usize| Error::ShapeMismatch {
        which: ArrayRole::Input,
        expected: vec![expected],
        actual: vec![actual],
    };

    assert_eq!(sampling.evaluate(&vec![0.0; l + 1]), Err(input(l, l + 1)));
    assert_eq!(sampling.fit(&vec![0.0; np + 1]), Err(input(np, np + 1)));
    assert_eq!(
        sampling.evaluate_zz(&vec![Complex::new(0.0, 0.0); l - 1]),
        Err(input(l, l - 1))
    );
    assert_eq!(
        sampling.fit_zz(&vec![Complex::new(0.0, 0.0); 0]),
        Err(input(np, 0))
    );

    let mut out = vec![-1.0; np + 2];
    assert_eq!(
        sampling.evaluate_to(&vec![0.0; l], &mut out),
        Err(Error::ShapeMismatch {
            which: ArrayRole::Output,
            expected: vec![np],
            actual: vec![np + 2],
        })
    );
    assert!(out.iter().all(|&x| x == -1.0));
    let mut out = vec![-1.0; l];
    assert_eq!(
        sampling.fit_to(&vec![0.0; np + 1], &mut out),
        Err(input(np, np + 1))
    );
    assert!(out.iter().all(|&x| x == -1.0));

    // The condition number of a default sampling is finite and at least 1.
    let cond = sampling.condition_number().unwrap();
    assert!(cond.is_finite() && cond >= 1.0, "{cond}");
}