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
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
// RegularizedBoseKernel is deprecated (#273) but tested until it is removed.
#![allow(deprecated)]
use crate::freq::MatsubaraFreq;
use crate::matrix::MatTyped;
use crate::matsubara_sampling::{MatsubaraSampling, MatsubaraSamplingPositiveOnly};
use crate::test_utils::At;
use crate::test_utils::{ErrorNorm, generate_test_data_tau_and_matsubara};
use crate::traits::{Bosonic, Fermionic, StatisticsType};
use crate::{FiniteTempBasis, LogisticKernel, RegularizedBoseKernel};
use num_complex::Complex;

/// Test MatsubaraSampling (symmetric mode, complex coefficients) roundtrip
#[test]
fn test_matsubara_sampling_roundtrip_fermionic() {
    test_matsubara_sampling_roundtrip_generic::<Fermionic>();
}

#[test]
fn test_matsubara_sampling_roundtrip_bosonic() {
    test_matsubara_sampling_roundtrip_generic::<Bosonic>();
}

fn test_matsubara_sampling_roundtrip_generic<S: StatisticsType + 'static>() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

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

    // Create symmetric Matsubara sampling points (positive and negative)
    let sampling_points = basis.default_matsubara_sampling_points(false).unwrap();

    // Create sampling
    let sampling =
        MatsubaraSampling::with_sampling_points(&basis, sampling_points.clone()).unwrap();

    // Generate test data (we only need Matsubara values)
    let (_coeffs_random, _gtau_values, giwn_values) =
        generate_test_data_tau_and_matsubara::<Complex<f64>, S, _>(
            &basis,
            &[0.5 * beta], // dummy tau point
            &sampling_points,
            12345,
        );

    // Fit to get coefficients
    let coeffs_fitted = sampling.fit(&giwn_values).unwrap();

    // Evaluate back
    let giwn_reconstructed = sampling.evaluate(&coeffs_fitted).unwrap();

    // Check roundtrip accuracy
    let max_error = giwn_values
        .iter()
        .zip(giwn_reconstructed.iter())
        .map(|(a, b)| (*a - *b).error_norm())
        .fold(0.0f64, f64::max);

    println!(
        "MatsubaraSampling {:?} roundtrip max error: {}",
        S::STATISTICS,
        max_error
    );
    assert!(max_error < 1e-7, "Roundtrip error too large: {}", max_error);
}

/// Test MatsubaraSamplingPositiveOnly (positive frequencies only, real coefficients) roundtrip
#[test]
fn test_matsubara_sampling_positive_only_roundtrip_fermionic() {
    test_matsubara_sampling_positive_only_roundtrip_generic::<Fermionic>();
}

#[test]
fn test_matsubara_sampling_positive_only_roundtrip_bosonic() {
    test_matsubara_sampling_positive_only_roundtrip_generic::<Bosonic>();
}

fn test_matsubara_sampling_positive_only_roundtrip_generic<S: StatisticsType + 'static>() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

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

    // Use positive-only sampling points
    let sampling_points = basis.default_matsubara_sampling_points(true).unwrap();
    let _n_matsubara = sampling_points.len();

    // Create sampling
    let sampling =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, sampling_points.clone())
            .unwrap();

    // Generate test data (we only need Matsubara values)
    let (_coeffs_random, _gtau_values, giwn_values) =
        generate_test_data_tau_and_matsubara::<f64, S, _>(
            &basis,
            &[0.5 * beta], // dummy tau point
            &sampling_points,
            12345,
        );

    // Fit to get real coefficients
    let coeffs_fitted = sampling.fit(&giwn_values).unwrap();

    // Evaluate back
    let giwn_reconstructed = sampling.evaluate(&coeffs_fitted).unwrap();

    // Check roundtrip accuracy
    let max_error = giwn_values
        .iter()
        .zip(giwn_reconstructed.iter())
        .map(|(a, b)| (*a - *b).error_norm())
        .fold(0.0f64, f64::max);

    println!(
        "MatsubaraSamplingPositiveOnly {:?} roundtrip max error: {}",
        S::STATISTICS,
        max_error
    );
    assert!(max_error < 1e-7, "Roundtrip error too large: {}", max_error);
}

/// Test that basis sizes are consistent
#[test]
fn test_matsubara_sampling_dimensions() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

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

    let sampling_points = basis.default_matsubara_sampling_points(true).unwrap();

    let sampling =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, sampling_points.clone())
            .unwrap();

    assert_eq!(sampling.basis_size(), basis.size());
    assert_eq!(sampling.n_sampling_points(), sampling_points.len());
}

/// Test MatsubaraSampling evaluate_nd/fit_nd roundtrip
#[test]
fn test_matsubara_sampling_nd_roundtrip_fermionic() {
    test_matsubara_sampling_nd_roundtrip_generic::<Fermionic>();
}

#[test]
fn test_matsubara_sampling_nd_roundtrip_bosonic() {
    test_matsubara_sampling_nd_roundtrip_generic::<Bosonic>();
}

fn test_matsubara_sampling_nd_roundtrip_generic<S: StatisticsType + 'static>() {
    use crate::test_utils::generate_nd_test_data;

    use num_complex::Complex;

    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

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

    let sampling_points = basis.default_matsubara_sampling_points(false).unwrap(); // Symmetric (positive and negative)

    let sampling =
        MatsubaraSampling::with_sampling_points(&basis, sampling_points.clone()).unwrap();

    let n_k = 4;
    let n_omega = 5;

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

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

        // Evaluate and fit along target dimension
        let values_dim = sampling.evaluate_nd(None, &coeffs_dim, dim).unwrap();
        let coeffs_fitted_dim = sampling.fit_nd(None, &values_dim, dim).unwrap();

        // Move back to dim=0 for comparison
        let coeffs_fitted_0 = crate::test_utils::movedim(&coeffs_fitted_dim, dim, 0);

        // Check roundtrip
        let max_error = coeffs_0
            .host_data()
            .unwrap()
            .iter()
            .zip(coeffs_fitted_0.host_data().unwrap().iter())
            .map(|(a, b)| (*a - *b).norm())
            .fold(0.0, f64::max);

        println!(
            "MatsubaraSampling {:?} dim={} roundtrip error: {}",
            S::STATISTICS,
            dim,
            max_error
        );
        assert!(
            max_error < 1e-10,
            "ND roundtrip (dim={}) error too large: {}",
            dim,
            max_error
        );
    }
}

/// Test MatsubaraSamplingPositiveOnly evaluate_nd/fit_nd roundtrip
#[test]
fn test_matsubara_sampling_positive_only_nd_roundtrip_fermionic() {
    test_matsubara_sampling_positive_only_nd_roundtrip_generic::<Fermionic>();
}

#[test]
fn test_matsubara_sampling_positive_only_nd_roundtrip_bosonic() {
    test_matsubara_sampling_positive_only_nd_roundtrip_generic::<Bosonic>();
}

fn test_matsubara_sampling_positive_only_nd_roundtrip_generic<S: StatisticsType + 'static>() {
    use crate::test_utils::generate_nd_test_data;

    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

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

    // Use positive-only sampling points
    let sampling_points = basis.default_matsubara_sampling_points(true).unwrap();

    let sampling =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, sampling_points.clone())
            .unwrap();

    let n_k = 4;
    let n_omega = 5;

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

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

        // Evaluate and fit along target dimension
        let values_dim = sampling.evaluate_nd(None, &coeffs_dim, dim).unwrap();
        let coeffs_fitted_dim = sampling.fit_nd(None, &values_dim, dim).unwrap();

        // Move back to dim=0 for comparison
        let coeffs_fitted_0 = crate::test_utils::movedim(&coeffs_fitted_dim, dim, 0);

        // Check roundtrip
        let max_error = coeffs_0
            .host_data()
            .unwrap()
            .iter()
            .zip(coeffs_fitted_0.host_data().unwrap().iter())
            .map(|(a, b)| (*a - *b).abs())
            .fold(0.0, f64::max);

        println!(
            "MatsubaraSamplingPositiveOnly {:?} dim={} roundtrip error: {}",
            S::STATISTICS,
            dim,
            max_error
        );
        assert!(
            max_error < 1e-7,
            "ND roundtrip (dim={}) error too large: {}",
            dim,
            max_error
        );
    }
}

// ====================
// RegularizedBoseKernel MatsubaraSampling Tests
// ====================

/// Generic test for RegularizedBoseKernel MatsubaraSampling roundtrip
fn test_regularized_bose_matsubara_sampling_roundtrip_generic() {
    let beta = 10.0;
    let wmax = 1.0; // Use smaller wmax for better numerics
    let epsilon = 1e-4; // Looser tolerance for RegularizedBoseKernel

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

    let basis_size = basis.size();

    // Create custom Matsubara sampling points (ensure >= basis_size points)
    // Use simple uniform distribution: n = 0, 1, 2, ..., basis_size (for positive-only)
    let sampling_points: Vec<MatsubaraFreq<Bosonic>> = (0..basis_size + 2)
        .map(|n| MatsubaraFreq::new((2 * n) as i64).unwrap()) // Bosonic: n must be even
        .collect();

    // Also create negative frequencies for symmetric sampling
    let mut symmetric_points = sampling_points.clone();
    for n in 1..basis_size + 2 {
        symmetric_points.push(MatsubaraFreq::new(-((2 * n) as i64)).unwrap());
    }

    println!("\n=== RegularizedBose MatsubaraSampling Test ===");
    println!("Basis size: {}", basis_size);
    println!("Sampling points (symmetric): {}", symmetric_points.len());

    // Create sampling
    let sampling =
        MatsubaraSampling::with_sampling_points(&basis, symmetric_points.clone()).unwrap();

    // Generate test data (we only need Matsubara values)
    let (_coeffs_random, _gtau_values, giwn_values) =
        generate_test_data_tau_and_matsubara::<Complex<f64>, Bosonic, _>(
            &basis,
            &[0.5 * beta], // dummy tau point
            &symmetric_points,
            12345,
        );

    // Fit to get coefficients
    let coeffs_fitted = sampling.fit(&giwn_values).unwrap();

    // Evaluate back
    let giwn_reconstructed = sampling.evaluate(&coeffs_fitted).unwrap();

    // Check roundtrip accuracy
    let max_error = giwn_values
        .iter()
        .zip(giwn_reconstructed.iter())
        .map(|(a, b)| (*a - *b).error_norm())
        .fold(0.0f64, f64::max);

    println!("MatsubaraSampling roundtrip max error: {:.2e}", max_error);
    // `symmetric_points` are unsorted (0, 2, 4, ..., then -2, -4, ...) and
    // `giwn_values` follows their order. The bound 2.0 used here passed only
    // because the sampling sorted its points, so that the values were fitted
    // at the wrong frequencies (max error 1.66). With the points kept in the
    // given order, the round trip has the accuracy of the positive-only test
    // below on the same basis (eps = 1e-4), so it uses the same bound 1e-2,
    // which still fails for values taken in the wrong order.
    assert!(
        max_error < 1e-2,
        "RegularizedBose Matsubara roundtrip error too large: {}",
        max_error
    );
}

/// Generic test for RegularizedBoseKernel MatsubaraSamplingPositiveOnly roundtrip
fn test_regularized_bose_matsubara_sampling_positive_only_roundtrip_generic() {
    let beta = 10.0;
    let wmax = 1.0; // Use smaller wmax for better numerics
    let epsilon = 1e-4; // Looser tolerance for RegularizedBoseKernel

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

    let basis_size = basis.size();

    // Create custom positive-only Matsubara sampling points (ensure >= basis_size points)
    let sampling_points: Vec<MatsubaraFreq<Bosonic>> = (0..basis_size + 2)
        .map(|n| MatsubaraFreq::new((2 * n) as i64).unwrap()) // Bosonic: n must be even
        .collect();

    println!("\n=== RegularizedBose MatsubaraSamplingPositiveOnly Test ===");
    println!("Basis size: {}", basis_size);
    println!("Sampling points (positive-only): {}", sampling_points.len());

    // Create sampling
    let sampling =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, sampling_points.clone())
            .unwrap();

    // Generate test data (real coefficients for positive-only)
    let (_coeffs_random, _gtau_values, giwn_values) =
        generate_test_data_tau_and_matsubara::<Complex<f64>, Bosonic, _>(
            &basis,
            &[0.5 * beta], // dummy tau point
            &sampling_points,
            54321,
        );

    // Fit to get coefficients (should be real)
    let coeffs_fitted = sampling.fit(&giwn_values).unwrap();

    // Evaluate back
    let giwn_reconstructed = sampling.evaluate(&coeffs_fitted).unwrap();

    // Check roundtrip accuracy
    let max_error = giwn_values
        .iter()
        .zip(giwn_reconstructed.iter())
        .map(|(a, b)| (*a - *b).error_norm())
        .fold(0.0f64, f64::max);

    println!(
        "MatsubaraSamplingPositiveOnly roundtrip max error: {:.2e}",
        max_error
    );
    // RegularizedBoseKernel has lower numerical precision due to y=0 singularity
    // Looser tolerance required
    assert!(
        max_error < 1e-2,
        "RegularizedBose Matsubara positive-only roundtrip error too large: {}",
        max_error
    );
}

#[test]
fn test_regularized_bose_matsubara_sampling_roundtrip() {
    test_regularized_bose_matsubara_sampling_roundtrip_generic();
}

#[test]
fn test_regularized_bose_matsubara_sampling_positive_only_roundtrip() {
    test_regularized_bose_matsubara_sampling_positive_only_roundtrip_generic();
}

// ============================================================================
// In-place method tests
// ============================================================================

/// Test MatsubaraSampling::evaluate_nd_to matches evaluate_nd
#[test]
fn test_matsubara_sampling_evaluate_nd_to_matches() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(wmax * beta).unwrap();
    let basis = FiniteTempBasis::<_, Fermionic>::new(kernel, beta, Some(epsilon), None).unwrap();
    let sampling = MatsubaraSampling::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 (complex)
    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,
            )
        });

    // Test for dim = 0
    let expected = sampling.evaluate_nd(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),
    );
    sampling
        .evaluate_nd_to(None, &coeffs.as_view(), 0, &mut actual.as_view_mut())
        .unwrap();

    // Compare
    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).norm();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

/// Test MatsubaraSampling::fit_nd_to matches fit_nd
#[test]
fn test_matsubara_sampling_fit_nd_to_matches() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(wmax * beta).unwrap();
    let basis = FiniteTempBasis::<_, Fermionic>::new(kernel, beta, Some(epsilon), None).unwrap();
    let sampling = MatsubaraSampling::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 values (complex)
    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.2,
            )
        });

    // Test for dim = 0
    let expected = sampling.fit_nd(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),
    );
    sampling
        .fit_nd_to(None, &values.as_view(), 0, &mut actual.as_view_mut())
        .unwrap();

    // Compare
    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).norm();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

/// Test MatsubaraSamplingPositiveOnly::evaluate_nd_to matches evaluate_nd
#[test]
fn test_matsubara_sampling_positive_only_evaluate_nd_to_matches() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(wmax * beta).unwrap();
    let basis = FiniteTempBasis::<_, Fermionic>::new(kernel, beta, Some(epsilon), None).unwrap();
    let sampling = MatsubaraSamplingPositiveOnly::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 (real)
    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)
    });

    // Test for dim = 0
    let expected = sampling.evaluate_nd(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),
    );
    sampling
        .evaluate_nd_to(None, &coeffs.as_view(), 0, &mut actual.as_view_mut())
        .unwrap();

    // Compare
    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).norm();
                assert!(
                    diff < 1e-14,
                    "Mismatch at [{}, {}, {}]: expected={:?}, actual={:?}",
                    i,
                    j,
                    k,
                    e,
                    a
                );
            }
        }
    }
}

/// Test MatsubaraSamplingPositiveOnly::fit_nd_to matches fit_nd
#[test]
fn test_matsubara_sampling_positive_only_fit_nd_to_matches() {
    let beta = 10.0;
    let wmax = 10.0;
    let epsilon = 1e-6;

    let kernel = LogisticKernel::new(wmax * beta).unwrap();
    let basis = FiniteTempBasis::<_, Fermionic>::new(kernel, beta, Some(epsilon), None).unwrap();
    let sampling = MatsubaraSamplingPositiveOnly::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 values (complex)
    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.2,
            )
        });

    // Test for dim = 0
    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);
    sampling
        .fit_nd_to(None, &values.as_view(), 0, &mut actual.as_view_mut())
        .unwrap();

    // Compare
    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 MatsubaraSampling creation with specific parameters matching debug.rs
///
/// This test verifies that MatsubaraSampling can be created correctly with
/// the same parameters used in the debug example, and that the resulting
/// basis size and sampling point count match expected values (consistent with C++).
#[test]
fn test_matsubara_sampling_debug_parameters() {
    let t = 0.1;
    let wmax = 1.0;

    let beta = 1.0 / t;
    // construction of the Kernel K

    // Fermionic Basis
    // Step 1: Create kernel
    let lambda_ = beta * wmax;
    let kernel = LogisticKernel::new(lambda_).unwrap();

    // Step 2: Compute SVE and create basis
    // FiniteTempBasis::new automatically computes SVE internally
    let eps = f64::EPSILON;
    let basisf: FiniteTempBasis<LogisticKernel, Fermionic> =
        FiniteTempBasis::new(kernel, beta, Some(eps), None).unwrap();

    // Step 3: Create Matsubara sampling
    let matsf = MatsubaraSampling::new(&basisf).unwrap();

    // Verify expected values (matching C++ implementation)
    // Basis size should be 19 for these parameters
    assert_eq!(
        basisf.size(),
        19,
        "Basis size should be 19 for T=0.1, wmax=1.0"
    );

    // Number of Matsubara sampling points should be 20
    // (l_requested = 20 for Fermionic with L=19)
    assert_eq!(
        matsf.sampling_points().len(),
        20,
        "Number of Matsubara sampling points should be 20 for Fermionic basis with L=19"
    );

    // Verify sampling points are sorted
    let sampling_points = matsf.sampling_points();
    for i in 1..sampling_points.len() {
        assert!(
            sampling_points[i - 1] <= sampling_points[i],
            "Sampling points should be sorted"
        );
    }

    // Verify basis size consistency
    assert_eq!(
        matsf.basis_size(),
        basisf.size(),
        "MatsubaraSampling basis_size() should match basis.size()"
    );

    // Verify matrix dimensions
    let matrix = matsf.matrix();
    assert_eq!(
        matrix.shape()[0],
        matsf.n_sampling_points(),
        "Matrix rows should match number of sampling points"
    );
    assert_eq!(
        matrix.shape()[1],
        basisf.size(),
        "Matrix columns should match basis size"
    );
}

// ============================================================================
// condition_number (SpM-lab/sparse-ir-rs#270)
// ============================================================================

/// `A[i, l] = uhat_l(iν_i)`, built from the basis functions independently of
/// any sampling object
fn uhat_matrix<S: StatisticsType + 'static>(
    basis: &FiniteTempBasis<LogisticKernel, S>,
    points: &[MatsubaraFreq<S>],
) -> crate::matrix::Mat<Complex<f64>> {
    let uhat = basis.uhat();
    crate::matrix::Mat::<Complex<f64>>::from_fn([points.len(), basis.size()], |idx| {
        uhat[idx[1]].evaluate(&points[idx[0]])
    })
}

/// Positive-only sampling reports the condition number of the stacked real
/// matrix `[Re A; Im A]` that `fit` solves, not that of the complex matrix `A`
fn check_positive_only_condition_number<S: StatisticsType + 'static>(
    beta: f64,
    wmax: f64,
    epsilon: f64,
) {
    use crate::test_utils::{assert_condition_number_close, oracle_condition_number, stack_re_im};

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, beta, Some(epsilon), None).unwrap();
    let points = basis.default_matsubara_sampling_points(true).unwrap();
    let sampling =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, points.clone()).unwrap();

    let oracle = oracle_condition_number(&stack_re_im(&uhat_matrix(&basis, &points)));
    let label = format!(
        "positive-only {:?}, beta={beta}, wmax={wmax}, eps={epsilon:e}, L={}, n={}",
        S::STATISTICS,
        basis.size(),
        points.len()
    );
    assert_condition_number_close(&label, sampling.condition_number().unwrap(), oracle);
}

/// Full-set sampling reports the condition number of the complex matrix `A`
fn check_full_condition_number<S: StatisticsType + 'static>(beta: f64, wmax: f64, epsilon: f64) {
    use crate::test_utils::{assert_condition_number_close, oracle_condition_number, realify};

    let kernel = LogisticKernel::new(beta * wmax).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, beta, Some(epsilon), None).unwrap();
    let points = basis.default_matsubara_sampling_points(false).unwrap();
    let sampling = MatsubaraSampling::with_sampling_points(&basis, points.clone()).unwrap();

    let oracle = oracle_condition_number(&realify(&uhat_matrix(&basis, &points)));
    let label = format!(
        "full-set {:?}, beta={beta}, wmax={wmax}, eps={epsilon:e}, L={}, n={}",
        S::STATISTICS,
        basis.size(),
        points.len()
    );
    assert_condition_number_close(&label, sampling.condition_number().unwrap(), oracle);
}

#[test]
fn test_positive_only_condition_number_fermionic() {
    check_positive_only_condition_number::<Fermionic>(10.0, 1.0, 1e-6);
}

#[test]
fn test_positive_only_condition_number_bosonic() {
    check_positive_only_condition_number::<Bosonic>(10.0, 1.0, 1e-6);
    check_positive_only_condition_number::<Bosonic>(1000.0, 1.0, 1e-10);
}

#[test]
fn test_full_condition_number_fermionic() {
    check_full_condition_number::<Fermionic>(10.0, 1.0, 1e-6);
}

#[test]
fn test_full_condition_number_bosonic() {
    check_full_condition_number::<Bosonic>(10.0, 1.0, 1e-6);
    check_full_condition_number::<Bosonic>(1000.0, 1.0, 1e-10);
}

/// `from_matrix` samplings follow the same rule. The matrix is wide (5 points,
/// 8 coefficients, so `[Re A; Im A]` is 10 × 8), as for positive-only
/// sampling points, and chosen so that `cond(A)` over its 5 singular values
/// and `cond([Re A; Im A])` differ.
#[test]
fn test_positive_only_condition_number_from_matrix() {
    use crate::test_utils::{
        assert_condition_number_close, oracle_condition_number, realify, stack_re_im,
    };

    let (n, l) = (5, 8);
    let a = crate::matrix::Mat::<Complex<f64>>::from_fn([n, l], |idx| {
        let x = (idx[0] as f64 + 1.0) / n as f64;
        let j = idx[1] as i32;
        Complex::new(x.powi(j), (x * (j as f64 + 1.0)).sin())
    });
    let points: Vec<MatsubaraFreq<Bosonic>> = (0..n as i64)
        .map(|k| MatsubaraFreq::new(2 * k).unwrap())
        .collect();
    let sampling =
        MatsubaraSamplingPositiveOnly::from_matrix(points, &a.clone().into_typed()).unwrap();

    let oracle = oracle_condition_number(&stack_re_im(&a));
    let cond_complex = oracle_condition_number(&realify(&a));
    assert!(
        (oracle - cond_complex).abs() > 1e-3 * oracle,
        "test matrix must separate cond([Re A; Im A]) = {oracle:.6e} from cond(A) = {cond_complex:.6e}"
    );
    assert_condition_number_close(
        "from_matrix positive-only",
        sampling.condition_number().unwrap(),
        oracle,
    );
}

/// The default points of `basis`, reordered so that they are neither sorted
/// nor reverse-sorted: every other point, then the rest in reverse.
fn unsorted_points<S: StatisticsType + 'static>(
    basis: &FiniteTempBasis<LogisticKernel, S>,
    positive_only: bool,
) -> Vec<MatsubaraFreq<S>> {
    let sorted = basis
        .default_matsubara_sampling_points(positive_only)
        .unwrap();
    let mut points: Vec<_> = sorted.iter().step_by(2).cloned().collect();
    points.extend(sorted.iter().skip(1).step_by(2).rev().cloned());
    assert_eq!(points.len(), sorted.len());
    assert!(!points.windows(2).all(|w| w[0] <= w[1]));
    assert!(!points.windows(2).all(|w| w[0] >= w[1]));
    points
}

/// The reduced frequencies n of `points`.
fn indices<S: StatisticsType>(points: &[MatsubaraFreq<S>]) -> Vec<i64> {
    points.iter().map(|p| p.n()).collect()
}

/// Checks that `values[i]` is row i of `a` times `coeffs`, to rounding.
fn assert_rows_times<T>(a: &crate::matrix::Mat<Complex<f64>>, coeffs: &[T], values: &[Complex<f64>])
where
    T: Copy + Into<Complex<f64>>,
{
    let (n, l) = *a.shape();
    assert_eq!(values.len(), n);
    for i in 0..n {
        let terms: Vec<Complex<f64>> = (0..l).map(|j| a[[i, j]] * coeffs[j].into()).collect();
        let expected: Complex<f64> = terms.iter().sum();
        let scale: f64 = terms.iter().map(|t| t.norm()).sum();
        assert!(
            (values[i] - expected).norm() <= 1e-13 * scale,
            "row {i}: {} vs {expected}",
            values[i]
        );
    }
}

/// `from_matrix` takes the points in any order and keeps it: row i of the
/// matrix belongs to `sampling_points[i]`, which `sampling_points()` returns
/// unchanged and which labels index i of `evaluate` and `fit`. The fitters do
/// not depend on the order. Before the fix, a `debug_assert!` rejected
/// unsorted points in debug builds only.
fn check_from_matrix_keeps_the_given_order<S: StatisticsType + 'static>() {
    let kernel = LogisticKernel::new(10.0).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, 1.0, Some(1e-6), None).unwrap();
    let l = basis.size();
    // The data are exact values of these coefficients, and the default
    // points give a condition number below 1e2, so a backward-stable fit
    // recovers them to ~1e-13 (kappa * n * eps); 1e-10 leaves a margin.
    let coeffs: Vec<f64> = (0..l).map(|j| 1.0 / (1.0 + j as f64)).collect();
    let coeffs_z: Vec<Complex<f64>> = (0..l)
        .map(|j| Complex::new(1.0 / (1.0 + j as f64), 0.5 - 0.1 * j as f64))
        .collect();

    let points = unsorted_points(&basis, true);
    let a = uhat_matrix(&basis, &points);
    let sampling =
        MatsubaraSamplingPositiveOnly::from_matrix(points.clone(), &a.clone().into_typed())
            .unwrap();
    assert_eq!(indices(sampling.sampling_points()), indices(&points));
    assert!(sampling.condition_number().unwrap() < 1e2);
    let values = sampling.evaluate(&coeffs).unwrap();
    assert_rows_times(&a, &coeffs, &values);
    let fitted = sampling.fit(&values).unwrap();
    for (f, c) in fitted.iter().zip(&coeffs) {
        assert!((f - c).abs() <= 1e-10, "positive-only fit: {f} vs {c}");
    }

    let points = unsorted_points(&basis, false);
    let a = uhat_matrix(&basis, &points);
    let sampling = MatsubaraSampling::from_matrix(points.clone(), &a.clone().into_typed()).unwrap();
    assert_eq!(indices(sampling.sampling_points()), indices(&points));
    assert!(sampling.condition_number().unwrap() < 1e2);
    let values = sampling.evaluate(&coeffs_z).unwrap();
    assert_rows_times(&a, &coeffs_z, &values);
    let fitted = sampling.fit(&values).unwrap();
    for (f, c) in fitted.iter().zip(&coeffs_z) {
        assert!((f - c).norm() <= 1e-10, "full fit: {f} vs {c}");
    }
}

#[test]
fn test_from_matrix_keeps_the_given_order_fermionic() {
    check_from_matrix_keeps_the_given_order::<Fermionic>();
}

#[test]
fn test_from_matrix_keeps_the_given_order_bosonic() {
    check_from_matrix_keeps_the_given_order::<Bosonic>();
}

/// `with_sampling_points` keeps the points in the given order: it returns
/// them unchanged from `sampling_points()`, and value i of `evaluate` is at
/// `sampling_points[i]`. Before the fix, both constructors sorted the points,
/// so that values fitted in the caller's order were taken at the wrong
/// frequencies.
fn check_with_sampling_points_keeps_the_given_order<S: StatisticsType + 'static>() {
    let kernel = LogisticKernel::new(10.0).unwrap();
    let basis = FiniteTempBasis::<_, S>::new(kernel, 1.0, Some(1e-6), None).unwrap();
    let l = basis.size();
    let coeffs: Vec<f64> = (0..l).map(|j| 1.0 / (1.0 + j as f64)).collect();
    let coeffs_z: Vec<Complex<f64>> = coeffs.iter().map(|&c| Complex::new(c, 0.5 * c)).collect();

    let points = unsorted_points(&basis, true);
    let sampling =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, points.clone()).unwrap();
    assert_eq!(indices(sampling.sampling_points()), indices(&points));
    assert_rows_times(
        &uhat_matrix(&basis, &points),
        &coeffs,
        &sampling.evaluate(&coeffs).unwrap(),
    );

    let points = unsorted_points(&basis, false);
    let sampling = MatsubaraSampling::with_sampling_points(&basis, points.clone()).unwrap();
    assert_eq!(indices(sampling.sampling_points()), indices(&points));
    assert_rows_times(
        &uhat_matrix(&basis, &points),
        &coeffs_z,
        &sampling.evaluate(&coeffs_z).unwrap(),
    );
}

#[test]
fn test_with_sampling_points_keeps_the_given_order_fermionic() {
    check_with_sampling_points_keeps_the_given_order::<Fermionic>();
}

#[test]
fn test_with_sampling_points_keeps_the_given_order_bosonic() {
    check_with_sampling_points_keeps_the_given_order::<Bosonic>();
}

/// Batches with a zero extent, as (batch extents, target axis)
fn empty_batches() -> Vec<(Vec<usize>, usize)> {
    vec![
        (vec![0], 1),
        (vec![0], 0),
        (vec![0, 3], 1),
        (vec![2, 0], 2),
        (vec![0, 3], 0),
    ]
}

fn with_target(batch: &[usize], dim: usize, n: usize) -> Vec<usize> {
    let mut dims = batch.to_vec();
    dims.insert(dim, n);
    dims
}

/// Evaluating or fitting an empty batch gives an empty result of the right
/// shape. Before the fix these segfaulted in `movedim` (mdarray#21) when the
/// zero extent ended up before the last axis of a permuted view.
#[test]
fn test_matsubara_nd_with_empty_batch() {
    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let sampling = MatsubaraSampling::new(&basis).unwrap();
    let positive = MatsubaraSamplingPositiveOnly::new(&basis).unwrap();
    let l = sampling.basis_size();

    for (batch, dim) in empty_batches() {
        let dims_l = with_target(&batch, dim, l);
        let coeffs = crate::test_utils::tensor_filled::<f64>(&dims_l, 0.0);
        let coeffs_z =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_l, Complex::new(0.0, 0.0));

        for (s_np, values) in [
            (
                sampling.n_sampling_points(),
                sampling.evaluate_nd::<f64>(None, &coeffs, dim).unwrap(),
            ),
            (
                sampling.n_sampling_points(),
                sampling
                    .evaluate_nd::<Complex<f64>>(None, &coeffs_z, dim)
                    .unwrap(),
            ),
            (
                sampling.n_sampling_points(),
                sampling.evaluate_nd_real(None, &coeffs, dim).unwrap(),
            ),
            (
                positive.n_sampling_points(),
                positive.evaluate_nd(None, &coeffs, dim).unwrap(),
            ),
        ] {
            assert_eq!(values.shape(), &with_target(&batch, dim, s_np)[..]);
        }

        let dims_np = with_target(&batch, dim, sampling.n_sampling_points());
        let values =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_np, Complex::new(0.0, 0.0));
        assert_eq!(
            sampling.fit_nd(None, &values, dim).unwrap().shape(),
            &dims_l[..]
        );
        assert_eq!(
            sampling.fit_nd_real(None, &values, dim).unwrap().shape(),
            &dims_l[..]
        );
        let mut out =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_np, Complex::new(0.0, 0.0));
        sampling
            .evaluate_nd_to::<f64>(None, &coeffs.as_view(), dim, &mut out.as_view_mut())
            .unwrap();
        let mut out_l =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_l, Complex::new(0.0, 0.0));
        sampling
            .fit_nd_to(None, &values.as_view(), dim, &mut out_l.as_view_mut())
            .unwrap();

        let dims_np = with_target(&batch, dim, positive.n_sampling_points());
        let values =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_np, Complex::new(0.0, 0.0));
        assert_eq!(
            positive.fit_nd(None, &values, dim).unwrap().shape(),
            &dims_l[..]
        );
    }
}

/// The InplaceFitter methods of both Matsubara samplings accept an empty
/// batch. Before the fix, the zd fit of MatsubaraSampling along a middle
/// axis iterated a permuted view of the empty output, which mdarray 0.7.2
/// does out of bounds (mdarray#21), and wrote past its end.
#[test]
fn test_matsubara_inplace_fitter_with_empty_batch() {
    use crate::fitters::InplaceFitter;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let full = MatsubaraSampling::new(&basis).unwrap();
    let positive = MatsubaraSamplingPositiveOnly::new(&basis).unwrap();

    fn check<F: InplaceFitter>(f: &F, batch: &[usize], dim: usize) {
        let (l, np) = (f.basis_size(), f.n_points());
        let (dims_l, dims_np) = (with_target(batch, dim, l), with_target(batch, dim, np));
        let coeffs = crate::test_utils::tensor_filled::<f64>(&dims_l, 0.0);
        let coeffs_z =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_l, Complex::new(0.0, 0.0));
        let values_z =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_np, Complex::new(0.0, 0.0));
        let mut out_np =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_np, Complex::new(0.0, 0.0));
        let mut out_l = crate::test_utils::tensor_filled::<f64>(&dims_l, 0.0);
        let mut out_l_z =
            crate::test_utils::tensor_filled::<Complex<f64>>(&dims_l, Complex::new(0.0, 0.0));
        f.evaluate_nd_dz_to(None, &coeffs.as_view(), dim, &mut out_np.as_view_mut())
            .unwrap();
        f.evaluate_nd_zz_to(None, &coeffs_z.as_view(), dim, &mut out_np.as_view_mut())
            .unwrap();
        f.fit_nd_zd_to(None, &values_z.as_view(), dim, &mut out_l.as_view_mut())
            .unwrap();
        f.fit_nd_zz_to(None, &values_z.as_view(), dim, &mut out_l_z.as_view_mut())
            .unwrap();
    }

    for (batch, dim) in empty_batches() {
        check(&full, &batch, dim);
        check(&positive, &batch, dim);
    }
}

/// No sampling points is an error: the sampling matrix would have no rows.
/// It was a panic ("No sampling points given").
#[test]
fn test_matsubara_sampling_rejects_empty_sampling_points() {
    use crate::error::Error;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    assert_eq!(
        MatsubaraSampling::with_sampling_points(&basis, vec![]).err(),
        Some(Error::EmptyInput {
            name: "sampling_points"
        })
    );
}

/// Same for the positive-only sampling.
#[test]
fn test_matsubara_sampling_positive_only_rejects_empty_sampling_points() {
    use crate::error::Error;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    assert_eq!(
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, vec![]).err(),
        Some(Error::EmptyInput {
            name: "sampling_points"
        })
    );
}

/// A negative frequency in a positive-only sampling is an invalid Matsubara
/// index (spec §3); it was a panic (#247).
#[test]
fn test_matsubara_sampling_positive_only_rejects_negative_points() {
    use crate::error::Error;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let points = vec![
        MatsubaraFreq::<Fermionic>::new(1).unwrap(),
        MatsubaraFreq::<Fermionic>::new(-3).unwrap(),
    ];
    assert_eq!(
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, points).err(),
        Some(Error::InvalidMatsubaraIndex {
            n: -3,
            statistics: crate::traits::Statistics::Fermionic,
        })
    );
}

/// A matrix without columns is EmptyInput (it was a panic, mdarray#21).
#[test]
fn test_matsubara_from_matrix_rejects_zero_columns() {
    use crate::error::Error;

    let matrix = crate::matrix::Mat::<Complex<f64>>::zeros([1, 0]);
    assert_eq!(
        MatsubaraSampling::<Fermionic>::from_matrix(
            vec![MatsubaraFreq::new(1).unwrap()],
            &matrix.into_typed()
        )
        .err(),
        Some(Error::EmptyInput { name: "matrix" })
    );
}

#[test]
fn test_matsubara_positive_only_from_matrix_rejects_zero_columns() {
    use crate::error::Error;

    let matrix = crate::matrix::Mat::<Complex<f64>>::zeros([1, 0]);
    assert_eq!(
        MatsubaraSamplingPositiveOnly::<Fermionic>::from_matrix(
            vec![MatsubaraFreq::new(1).unwrap()],
            &matrix.into_typed(),
        )
        .err(),
        Some(Error::EmptyInput { name: "matrix" })
    );
}

/// The N-D methods of both Matsubara samplings check the axis first: the
/// `*_to` methods read out.shape().dim(dim) before checking the rank and
/// panicked. The InplaceFitter methods a sampling does not support are
/// NotSupported (they returned false).
#[test]
fn test_matsubara_nd_methods_check_the_axis_first() {
    use crate::error::{ArrayRole, Error};
    use crate::fitters::InplaceFitter;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();
    let full = MatsubaraSampling::new(&basis).unwrap();
    let positive = MatsubaraSamplingPositiveOnly::new(&basis).unwrap();
    let l = full.basis_size();
    let axis = Some(Error::AxisOutOfRange { axis: 1, rank: 1 });

    let coeffs = crate::test_utils::tensor_filled::<f64>(&[l], 0.0);
    let coeffs_z = crate::test_utils::tensor_filled::<Complex<f64>>(&[l], Complex::new(0.0, 0.0));
    let values = crate::test_utils::tensor_filled::<Complex<f64>>(
        &[full.n_sampling_points()],
        Complex::new(0.0, 0.0),
    );
    let values_p = crate::test_utils::tensor_filled::<Complex<f64>>(
        &[positive.n_sampling_points()],
        Complex::new(0.0, 0.0),
    );
    assert_eq!(full.evaluate_nd::<f64>(None, &coeffs, 1).err(), axis);
    assert_eq!(
        full.evaluate_nd::<Complex<f64>>(None, &coeffs_z, 1).err(),
        axis
    );
    assert_eq!(full.evaluate_nd_real(None, &coeffs, 1).err(), axis);
    assert_eq!(full.fit_nd(None, &values, 1).err(), axis);
    assert_eq!(full.fit_nd_real(None, &values, 1).err(), axis);
    assert_eq!(positive.evaluate_nd(None, &coeffs, 1).err(), axis);
    assert_eq!(positive.fit_nd(None, &values_p, 1).err(), axis);

    // `out` of rank 2 for rank-1 data, and an axis past both ranks
    let mut out = crate::test_utils::tensor_filled::<Complex<f64>>(
        &[full.n_sampling_points(), 1],
        Complex::new(0.0, 0.0),
    );
    assert_eq!(
        full.evaluate_nd_to::<f64>(None, &coeffs.as_view(), 0, &mut out.as_view_mut()),
        Err(Error::ShapeMismatch {
            which: ArrayRole::Output,
            expected: vec![full.n_sampling_points()],
            actual: vec![full.n_sampling_points(), 1],
        })
    );
    assert_eq!(
        full.evaluate_nd_to::<f64>(None, &coeffs.as_view(), 5, &mut out.as_view_mut())
            .err(),
        Some(Error::AxisOutOfRange { axis: 5, rank: 1 })
    );
    let mut out_l = crate::test_utils::tensor_filled::<f64>(&[l], 0.0);
    assert_eq!(
        positive
            .fit_nd_to(None, &values_p.as_view(), 5, &mut out_l.as_view_mut())
            .err(),
        Some(Error::AxisOutOfRange { axis: 5, rank: 1 })
    );

    // Unsupported pairs of types
    let mut out_d = crate::test_utils::tensor_filled::<f64>(&[full.n_sampling_points()], 0.0);
    let err = InplaceFitter::evaluate_nd_dd_to(
        &full,
        None,
        &coeffs.as_view(),
        0,
        &mut out_d.as_view_mut(),
    )
    .unwrap_err();
    assert!(matches!(err, Error::NotSupported { .. }), "{err:?}");
    let err = InplaceFitter::evaluate_nd_dd_to(
        &positive,
        None,
        &coeffs.as_view(),
        0,
        &mut out_d.as_view_mut(),
    )
    .unwrap_err();
    assert!(matches!(err, Error::NotSupported { .. }), "{err:?}");
}

/// Same for the 1-D methods of both Matsubara samplings.
#[test]
fn test_matsubara_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 full = MatsubaraSampling::new(&basis).unwrap();
    let positive = MatsubaraSamplingPositiveOnly::new(&basis).unwrap();
    let l = full.basis_size();
    let zero = Complex::new(0.0, 0.0);
    let input = |expected: usize, actual: usize| Error::ShapeMismatch {
        which: ArrayRole::Input,
        expected: vec![expected],
        actual: vec![actual],
    };

    assert_eq!(full.evaluate(&vec![zero; l + 1]), Err(input(l, l + 1)));
    let np = full.n_sampling_points();
    assert_eq!(full.fit(&vec![zero; np - 1]), Err(input(np, np - 1)));
    assert_eq!(positive.evaluate(&vec![0.0; l - 1]), Err(input(l, l - 1)));
    let np = positive.n_sampling_points();
    assert_eq!(positive.fit(&vec![zero; np + 3]), Err(input(np, np + 3)));
    for cond in [
        full.condition_number().unwrap(),
        positive.condition_number().unwrap(),
    ] {
        assert!(cond.is_finite() && cond >= 1.0, "{cond}");
    }
}

/// from_matrix of both Matsubara samplings checks its arguments (spec D5):
/// no points, rows that are not the points, a non-finite part of an entry,
/// and a negative point of a positive-only sampling (#247; it was accepted).
#[test]
fn test_matsubara_from_matrix_checks_its_arguments() {
    use crate::error::{ArrayRole, Error};

    let freqs = |ns: &[i64]| -> Vec<MatsubaraFreq<Fermionic>> {
        ns.iter().map(|&n| MatsubaraFreq::new(n).unwrap()).collect()
    };
    let matrix = |rows: usize| {
        crate::matrix::Mat::<Complex<f64>>::from_fn([rows, 2], |idx| {
            Complex::new(
                1.0 / (1.0 + idx[0] as f64 + idx[1] as f64),
                0.1 * idx[0] as f64,
            )
        })
    };

    for positive_only in [false, true] {
        let from = |points: Vec<MatsubaraFreq<Fermionic>>, m: crate::matrix::Mat<Complex<f64>>| {
            if positive_only {
                MatsubaraSamplingPositiveOnly::from_matrix(points, &m.into_typed()).err()
            } else {
                MatsubaraSampling::from_matrix(points, &m.into_typed()).err()
            }
        };
        assert_eq!(
            from(vec![], crate::matrix::Mat::<Complex<f64>>::zeros([0, 2])),
            Some(Error::EmptyInput {
                name: "sampling_points"
            })
        );
        assert_eq!(
            from(freqs(&[1, 3]), matrix(3)),
            Some(Error::ShapeMismatch {
                which: ArrayRole::Input,
                expected: vec![2, 2],
                actual: vec![3, 2],
            })
        );
        let mut bad = matrix(2);
        bad[[1, 0]] = Complex::new(0.5, f64::INFINITY);
        assert_eq!(
            from(freqs(&[1, 3]), bad),
            Some(Error::NonFiniteInput {
                name: "matrix",
                index: vec![1, 0],
                value: f64::INFINITY,
            })
        );
        assert_eq!(from(freqs(&[3, 1]), matrix(2)), None);
    }

    assert_eq!(
        MatsubaraSamplingPositiveOnly::from_matrix(freqs(&[1, -3]), &matrix(2).into_typed()).err(),
        Some(Error::InvalidMatsubaraIndex {
            n: -3,
            statistics: crate::traits::Statistics::Fermionic,
        })
    );
    // The full sampling takes negative frequencies.
    MatsubaraSampling::from_matrix(freqs(&[1, -3]), &matrix(2).into_typed()).unwrap();
}

/// Duplicate sampling points are accepted and kept, as on main since #291
/// (spec D6): row i belongs to sampling_points[i] also for a repeated point.
/// They only raise the condition number.
#[test]
fn test_duplicate_sampling_points_are_kept() {
    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(10.0).unwrap(),
        1.0,
        Some(1e-6),
        None,
    )
    .unwrap();

    let mut points = MatsubaraSampling::new(&basis)
        .unwrap()
        .sampling_points()
        .to_vec();
    points.push(points[0]);
    let full = MatsubaraSampling::with_sampling_points(&basis, points.clone()).unwrap();
    assert_eq!(full.sampling_points(), &points[..]);
    let (last, l) = (points.len() - 1, full.basis_size());
    for j in 0..l {
        assert_eq!(full.matrix().at(&[last, j]), full.matrix().at(&[0, j]));
    }

    let mut points = MatsubaraSamplingPositiveOnly::new(&basis)
        .unwrap()
        .sampling_points()
        .to_vec();
    points.insert(1, points[0]);
    let positive =
        MatsubaraSamplingPositiveOnly::with_sampling_points(&basis, points.clone()).unwrap();
    assert_eq!(positive.sampling_points(), &points[..]);
    for j in 0..l {
        assert_eq!(positive.matrix().at(&[1, j]), positive.matrix().at(&[0, j]));
    }

    let mut taus = crate::sampling::TauSampling::new(&basis)
        .unwrap()
        .sampling_points()
        .to_vec();
    taus.push(taus[2]);
    let tau = crate::sampling::TauSampling::with_sampling_points(&basis, taus.clone()).unwrap();
    assert_eq!(tau.sampling_points(), &taus[..]);
    let last = taus.len() - 1;
    for j in 0..l {
        assert_eq!(tau.matrix().at(&[last, j]), tau.matrix().at(&[2, j]));
    }
}

/// Fitting complex values to real coefficients solves the least-squares
/// problem over real coefficients, min ‖[Re; Im](A x - g)‖: on data no real
/// coefficient vector reproduces, `fit_real`, `fit_nd_real` (dims 0 and 1)
/// and the in-place real fit agree with the pseudo-inverse of [Re A; Im A]
/// (an independent nalgebra SVD). The real part of the complex solution,
/// which they returned before, is the same for a set of points symmetric in
/// ±n (such as the default ones) but not otherwise: here one more frequency
/// breaks the symmetry.
#[test]
fn test_matsubara_fit_real_is_real_least_squares() {
    use crate::fitters::InplaceFitter;
    use crate::test_utils::{At, tensor_filled, tensor_from_fn};
    use nalgebra::DMatrix;

    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(100.0).unwrap(),
        10.0,
        Some(1e-8),
        None,
    )
    .unwrap();
    let mut points = basis.default_matsubara_sampling_points(false).unwrap();
    let last = points.last().unwrap().n();
    points.push(crate::freq::MatsubaraFreq::new(last + 2).unwrap());
    let sampling = MatsubaraSampling::with_sampling_points(&basis, points).unwrap();
    let a = crate::matrix::Mat::from_typed(sampling.matrix()).unwrap();
    let (n, l) = *a.shape();
    let extra = 3;
    // Complex values without conjugate structure: no real fit is exact
    let value = |i: usize, j: usize| {
        let t = (i * 7 + j * 3) as f64;
        Complex::new((0.37 * t).sin(), (0.11 * t).cos())
    };

    let stacked = DMatrix::<f64>::from_fn(2 * n, l, |i, j| {
        let z = a[[i % n, j]];
        if i < n { z.re } else { z.im }
    });
    let pinv = stacked.pseudo_inverse(1e-14).unwrap();
    let expected = DMatrix::<f64>::from_fn(l, extra, |i, j| {
        (0..2 * n)
            .map(|k| {
                let g = value(k % n, j);
                pinv[(i, k)] * if k < n { g.re } else { g.im }
            })
            .sum()
    });
    let scale = expected.amax();

    let values0 = tensor_from_fn(&[n, extra], |i| value(i[0], i[1]));
    let values1 = tensor_from_fn(&[extra, n], |i| value(i[1], i[0]));
    let fit0 = sampling.fit_nd_real(None, &values0, 0).unwrap();
    let fit1 = sampling.fit_nd_real(None, &values1, 1).unwrap();
    let mut fit_inplace = tensor_filled::<f64>(&[l, extra], 0.0);
    sampling
        .fit_nd_zd_to(None, &values0.as_view(), 0, &mut fit_inplace.as_view_mut())
        .unwrap();
    let column0: Vec<Complex<f64>> = (0..n).map(|i| value(i, 0)).collect();
    let fit_vec = sampling.fit_real(&column0).unwrap();
    let complex_fit = sampling.fit(&column0).unwrap();
    for i in 0..l {
        assert!(
            (fit_vec[i] - expected[(i, 0)]).abs() < 1e-10 * scale,
            "vector ({i})"
        );
        for j in 0..extra {
            let e = expected[(i, j)];
            assert!(
                (fit0.at(&[i, j]) - e).abs() < 1e-10 * scale,
                "dim 0 ({i},{j})"
            );
            assert!(
                (fit1.at(&[j, i]) - e).abs() < 1e-10 * scale,
                "dim 1 ({i},{j})"
            );
            assert!(
                (fit_inplace.at(&[i, j]) - e).abs() < 1e-10 * scale,
                "in-place ({i},{j})"
            );
        }
    }
    let re_diff = (0..l)
        .map(|i| (complex_fit[i].re - expected[(i, 0)]).abs())
        .fold(0.0, f64::max);
    assert!(
        re_diff > 1e-6 * scale,
        "the case does not distinguish the fits"
    );
}

/// Regression: at a point set not symmetric in ±n with fewer points than
/// functions (the positive halves of the default points), `fit_real` fits
/// data that real coefficients reproduce. The real part of the complex
/// least-squares solution, which it returned before, leaves half of such
/// data unexplained (‖A x − y‖/‖y‖ ≈ 0.5).
#[test]
fn test_matsubara_fit_real_fits_asymmetric_points() {
    let basis = FiniteTempBasis::<_, Fermionic>::new(
        LogisticKernel::new(100.0).unwrap(),
        10.0,
        Some(1e-8),
        None,
    )
    .unwrap();
    let points: Vec<_> = basis
        .default_matsubara_sampling_points(false)
        .unwrap()
        .into_iter()
        .filter(|p| p.n() > 0)
        .collect();
    assert!(points.len() < basis.size());
    let sampling = MatsubaraSampling::with_sampling_points(&basis, points).unwrap();
    let coeffs: Vec<f64> = (0..basis.size()).map(|l| 1.0 / (l as f64 + 1.0)).collect();
    let values = sampling.evaluate_real(&coeffs).unwrap();
    let norm = |v: &[Complex<f64>]| v.iter().map(|z| z.norm_sqr()).sum::<f64>().sqrt();
    let residual = |fitted: &[Complex<f64>]| {
        let diff: Vec<Complex<f64>> = fitted.iter().zip(&values).map(|(a, b)| a - b).collect();
        norm(&diff) / norm(&values)
    };

    let fit = sampling.fit_real(&values).unwrap();
    let r = residual(&sampling.evaluate_real(&fit).unwrap());
    assert!(r < 1e-12, "fit_real residual {r:e}");

    let re_complex: Vec<f64> = sampling
        .fit(&values)
        .unwrap()
        .iter()
        .map(|z| z.re)
        .collect();
    let r = residual(&sampling.evaluate_real(&re_complex).unwrap());
    assert!(r > 0.1, "the case does not distinguish the fits: {r:e}");
}