multidouble 5.2.0

Double-double, quad-double and octo-double arithmetic, scalar and 8-lane SIMD (AVX-512, AVX2, SSE2, NEON, portable) with bitwise identical results, dual numbers and LU solves
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
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
//! Double-double LU against known solutions: A x = b with x chosen first and b formed in double-double, so the
//! solve must give x back to about cond(A) u^2. Also the transpose solve, the many-right-hand-side solve (bitwise
//! the single solves), the f64 factorization, the determinant (also of the quad-double LU, under row permutations
//! and with a control without pivoting), and the unblocked/blocked dispatch.
#![allow(clippy::needless_range_loop)]
mod common;
use common::Rng;
use multidouble::dd::DD;
use multidouble::linalg::{
    clu_logdet, clu_logdet_control, clu_pivots, clu_pivots_control, gram, ld_for, CluControl, CluPivots, ColumnGroup,
    DDLu, StaircaseControl, StaircaseLu,
};
use multidouble::qd::QD;

/// a random n x n matrix, column-major with leading dimension ld, made well conditioned by a diagonal shift
fn matrix(n: usize, r: &mut Rng) -> (usize, Vec<f64>, Vec<f64>) {
    let ld = ld_for(n);
    let (mut hi, mut lo) = (vec![0.0; ld * n], vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..n {
            let mut v = DD::new(r.sym(), r.sym() * 1e-17);
            if i == j {
                v = v + DD::from_f64(2.0 + (n as f64).sqrt());
            }
            hi[j * ld + i] = v.hi;
            lo[j * ld + i] = v.lo;
        }
    }
    (ld, hi, lo)
}

/// A x (or A^T x) in double-double
fn apply(n: usize, ld: usize, hi: &[f64], lo: &[f64], x: &[DD], transpose: bool) -> Vec<DD> {
    (0..n)
        .map(|i| {
            let mut s = DD::ZERO;
            for j in 0..n {
                let k = if transpose { i * ld + j } else { j * ld + i };
                s = s + DD::new(hi[k], lo[k]) * x[j];
            }
            s
        })
        .collect()
}

fn max_rel_err(got: &[DD], want: &[DD]) -> f64 {
    let scale = want.iter().map(|w| w.hi.abs()).fold(0.0, f64::max);
    got.iter()
        .zip(want)
        .map(|(g, w)| (*g - *w).to_f64().abs() / scale)
        .fold(0.0, f64::max)
}

#[test]
fn solves_recover_the_solution() {
    let mut r = Rng(31);
    for &n in &[1usize, 5, 8, 37, 64, 130, 257] {
        for &par in &[false, true] {
            let (ld, hi, lo) = matrix(n, &mut r);
            let x: Vec<DD> = (0..n).map(|_| DD::new(r.sym(), r.sym() * 1e-17)).collect();
            let lu = DDLu::factor(n, ld, hi.clone(), lo.clone(), par).expect("factor");
            for transpose in [false, true] {
                let mut b = apply(n, ld, &hi, &lo, &x, transpose);
                if transpose {
                    lu.solve_t(&mut b)
                } else {
                    lu.solve(&mut b)
                }
                let e = max_rel_err(&b, &x);
                assert!(e < 1e-29, "n {n} par {par} transpose {transpose}: {e:e}");
            }
        }
    }
}

#[test]
fn solve_many_is_bitwise_the_single_solves() {
    let mut r = Rng(32);
    let n = 45;
    let (ld, hi, lo) = matrix(n, &mut r);
    let lu = DDLu::factor(n, ld, hi, lo, false).unwrap();
    let nrhs = 11;
    // zeros and negative zeros in some entries, so that columns are skipped in some lanes and not in others
    let b: Vec<DD> = (0..n * nrhs)
        .map(|j| match j % 7 {
            0 => DD::ZERO,
            3 => DD { hi: -0.0, lo: 0.0 },
            _ => DD::new(r.sym(), r.sym() * 1e-17),
        })
        .collect();
    for transpose in [false, true] {
        let mut bh: Vec<f64> = b.iter().map(|d| d.hi).collect();
        let mut bl: Vec<f64> = b.iter().map(|d| d.lo).collect();
        lu.solve_many(&mut bh, &mut bl, nrhs, transpose, true);
        for k in 0..nrhs {
            let mut one = b[k * n..(k + 1) * n].to_vec();
            if transpose {
                lu.solve_t(&mut one)
            } else {
                lu.solve(&mut one)
            }
            for i in 0..n {
                assert_eq!(one[i].hi.to_bits(), bh[k * n + i].to_bits());
                assert_eq!(one[i].lo.to_bits(), bl[k * n + i].to_bits());
            }
        }
    }
}

#[test]
fn f64_factorization_solves_to_f64_accuracy() {
    let mut r = Rng(33);
    for &n in &[7usize, 64, 200] {
        let (ld, hi, lo) = matrix(n, &mut r);
        let x: Vec<DD> = (0..n).map(|_| DD::from_f64(r.sym())).collect();
        let b = apply(n, ld, &hi, &lo, &x, false);
        let lu = DDLu::factor_f64(n, ld, hi.clone(), true).unwrap();
        let mut bh: Vec<f64> = b.iter().map(|d| d.to_f64()).collect();
        lu.solve_hi(&mut bh);
        let got: Vec<DD> = bh.iter().map(|&v| DD::from_f64(v)).collect();
        let e = max_rel_err(&got, &x);
        assert!(e < 1e-12, "n {n}: {e:e}");
    }
}

#[test]
fn determinant_of_a_triangular_matrix() {
    // upper triangular with diagonal 1..n: det = n!, no pivoting needed
    let n = 12;
    let ld = ld_for(n);
    let mut hi = vec![0.0; ld * n];
    for j in 0..n {
        for i in 0..=j {
            hi[j * ld + i] = if i == j { (j + 1) as f64 } else { 0.5 };
        }
    }
    let lu = DDLu::factor(n, ld, hi, vec![0.0; ld * n], false).unwrap();
    let (sign, ln) = lu.logdet();
    let want: f64 = (1..=n).map(|k| (k as f64).ln()).sum();
    assert_eq!(sign, 1.0);
    assert!((ln - want).abs() < 1e-13);
    let (pmin, pmax) = lu.pivot_range();
    assert_eq!((pmin, pmax), (1.0, n as f64));
}

#[test]
fn singular_matrix_is_reported() {
    let n = 4;
    let ld = ld_for(n);
    let hi = vec![0.0; ld * n];
    assert!(DDLu::factor(n, ld, hi, vec![0.0; ld * n], false).is_err());
}

#[test]
fn gram_matrix_is_j_transpose_j() {
    let mut r = Rng(34);
    let n = 9;
    let (ld, jh, jl) = matrix(n, &mut r);
    let b: Vec<DD> = (0..ld)
        .map(|i| if i < n { DD::new(r.sym(), 0.0) } else { DD::ZERO })
        .collect();
    let bh: Vec<f64> = b.iter().map(|d| d.hi).collect();
    let bl: Vec<f64> = b.iter().map(|d| d.lo).collect();
    let (gh, gl, g) = gram(n, ld, &jh, &jl, &bh, &bl);
    for a in 0..n {
        let col: Vec<DD> = (0..n).map(|i| DD::new(jh[a * ld + i], jl[a * ld + i])).collect();
        for c in 0..n {
            let mut s = DD::ZERO;
            for i in 0..n {
                s = s + col[i] * DD::new(jh[c * ld + i], jl[c * ld + i]);
            }
            let got = DD::new(gh[c * ld + a], gl[c * ld + a]);
            assert!((got - s).to_f64().abs() < 1e-29 * s.hi.abs().max(1.0));
        }
        let mut s = DD::ZERO;
        for i in 0..n {
            s = s + col[i] * b[i];
        }
        assert!((g[a] - s).to_f64().abs() < 1e-29 * s.hi.abs().max(1.0));
    }
}

/// Control: a solve with one factor entry perturbed in its low part misses the 1e-29 check.
#[test]
fn control_perturbed_factor_is_caught() {
    let mut r = Rng(35);
    let n = 20;
    let (ld, hi, lo) = matrix(n, &mut r);
    let x: Vec<DD> = (0..n).map(|_| DD::new(r.sym(), 0.0)).collect();
    let mut lo2 = lo.clone();
    lo2[3 * ld + 3] += 1e-20;
    let lu = DDLu::factor(n, ld, hi.clone(), lo2, false).unwrap();
    let mut b = apply(n, ld, &hi, &lo, &x, false);
    lu.solve(&mut b);
    assert!(max_rel_err(&b, &x) > 1e-29);
}

/// A x = b solved to quad-double by `solve_refine_qd`: A a random quad-double matrix (each entry with four parts,
/// diagonally shifted), the LU of A rounded to double-double, b = A x formed in quad-double for a random quad-double x.
/// Two steps give x back to 1e-58 (relative to max |x|), and four steps to the same; control: without refinement the
/// solve misses by more than 1e-40 (A's rounding to double-double alone moves x by about 1e-32).
#[test]
fn refined_solve_reaches_quad_double() {
    let mut r = Rng(41);
    for n in [1usize, 7, 8, 33, 64] {
        let qd = |r: &mut Rng, scale: f64| {
            let h = r.sym() * scale;
            QD::new(
                h,
                h * 2f64.powi(-53) * r.sym(),
                h * 2f64.powi(-106) * r.sym(),
                h * 2f64.powi(-159) * r.sym(),
            )
        };
        let a: Vec<QD> = (0..n * n)
            .map(|k| {
                let v = qd(&mut r, 1.0);
                if k % (n + 1) == 0 {
                    v + QD::from_f64(2.0 + (n as f64).sqrt())
                } else {
                    v
                }
            })
            .collect();
        let x: Vec<QD> = (0..n).map(|_| qd(&mut r, 1.0)).collect();
        let apply = |v: &[QD]| -> Vec<QD> {
            (0..n)
                .map(|i| (0..n).fold(QD::ZERO, |s, j| s + a[i * n + j] * v[j]))
                .collect()
        };
        let b = apply(&x);
        let ld = ld_for(n);
        let (mut hi, mut lo) = (vec![0.0; ld * n], vec![0.0; ld * n]);
        for i in 0..n {
            for j in 0..n {
                let d = a[i * n + j].to_dd();
                hi[j * ld + i] = d.hi;
                lo[j * ld + i] = d.lo;
            }
        }
        let lu = DDLu::factor(n, ld, hi, lo, false).unwrap();
        let resid = |v: &[QD], out: &mut [QD]| {
            let av = apply(v);
            for i in 0..n {
                out[i] = b[i] - av[i];
            }
        };
        let xmax = x.iter().map(|v| v.to_f64().abs()).fold(0.0, f64::max);
        let err = |got: &[QD]| {
            got.iter()
                .zip(&x)
                .map(|(g, w)| (*g - *w).to_f64().abs())
                .fold(0.0, f64::max)
                / xmax
        };
        let (e0, e2, e4) = (
            err(&lu.solve_refine_qd(&b, 0, resid)),
            err(&lu.solve_refine_qd(&b, 2, resid)),
            err(&lu.solve_refine_qd(&b, 4, resid)),
        );
        println!("n = {n}: error {e0:.1e} unrefined, {e2:.1e} after two steps, {e4:.1e} after four");
        assert!(
            e2 < 1e-58 && e4 < 1e-58,
            "n = {n}: refined error {e2:e} (two steps), {e4:e} (four)"
        );
        assert!(
            e0 > 1e-40,
            "control, n = {n}: the unrefined solve is already quad-double ({e0:e})"
        );
    }
}

/// A random staircase system with the multiple-shooting structure: column groups of sizes a (first), b (k middle
/// ones), a (last); row blocks of b rows, block blk coupling an input group and a target group (target -I, segments
/// run outward up to inward_from and inward after); a parameter column in every row block and row0 on the first a/2
/// unknowns. Returns the dense column-major matrix (ld_for(n)), its size and leading dimension, and the layout.
#[allow(clippy::type_complexity)]
fn staircase_system(
    a: usize,
    b: usize,
    k: usize,
    inward_from: usize,
    seed: u64,
) -> (Vec<f64>, usize, usize, Vec<ColumnGroup>, Vec<(usize, usize)>) {
    let n = 2 * a + k * b + 1;
    let ld = ld_for(n);
    let mut r = Rng(seed);
    let mut m = vec![0.0f64; ld * n];
    let goff: Vec<usize> = (0..k + 2).map(|t| if t == 0 { 0 } else { a + (t - 1) * b }).collect();
    let glen: Vec<usize> = (0..k + 2).map(|t| if t == 0 || t == k + 1 { a } else { b }).collect();
    for blk in 0..k + 1 {
        let (inp, tgt) = if blk == 0 {
            (0, 1)
        } else if blk == k {
            (k + 1, k)
        } else if blk >= inward_from {
            (blk + 1, blk)
        } else {
            (blk, blk + 1)
        };
        // near-identity propagators (as for short segments), so a long chain stays well conditioned
        let sc = 1.0 / (glen[inp] as f64).sqrt();
        for i in 0..b {
            let row = blk * b + i;
            for c in 0..glen[inp] {
                m[(goff[inp] + c) * ld + row] = 0.5 * r.sym() * sc + if c == i % glen[inp] { 1.0 } else { 0.0 };
            }
            m[(goff[tgt] + i) * ld + row] -= 1.0;
            m[(n - 1) * ld + row] = 5.0 * r.sym();
        }
    }
    for c in 0..a / 2 {
        m[c * ld + n - 1] = 0.5 * r.sym() + 0.7;
    }
    let mut groups = vec![ColumnGroup {
        param: false,
        zoff: 0,
        zlen: a,
    }];
    for t in 1..=k {
        groups.push(ColumnGroup {
            param: true,
            zoff: goff[t],
            zlen: b,
        });
    }
    groups.push(ColumnGroup {
        param: true,
        zoff: goff[k + 1],
        zlen: a,
    });
    let rblocks = (0..k + 1).map(|blk| (blk * b, b)).collect();
    (m, n, ld, groups, rblocks)
}

/// the staircase LU of the dense matrix m (row0 and the parameter at index n - 1), filled from it
fn staircase(
    m: &[f64],
    n: usize,
    ld: usize,
    groups: &[ColumnGroup],
    rblocks: &[(usize, usize)],
    control: StaircaseControl,
) -> StaircaseLu {
    let gs = groups.to_vec();
    let fill = |s: usize, w: &mut [f64], wld: usize, r0: usize| -> Result<(), String> {
        let (p, q) = (gs[s], gs[s + 1]);
        let np = p.len();
        let (roff, rlen) = rblocks[s];
        // the column of z index zi in this step: group p, then group q; the parameter -> q's copy
        let pos = |zi: usize| -> Option<usize> {
            if zi == n - 1 {
                Some(np)
            } else if zi >= p.zoff && zi < p.zoff + p.zlen {
                Some(p.param as usize + zi - p.zoff)
            } else if zi >= q.zoff && zi < q.zoff + q.zlen {
                Some(np + q.param as usize + zi - q.zoff)
            } else {
                None
            }
        };
        for zi in 0..n {
            for i in 0..rlen {
                let v = m[zi * ld + roff + i];
                if v != 0.0 {
                    let c = pos(zi).ok_or(format!("entry outside the step's groups: row {} col {zi}", roff + i))?;
                    w[c * wld + r0 + i] = v;
                }
            }
            if s == 0 {
                let v = m[zi * ld + n - 1];
                if v != 0.0 {
                    w[pos(zi).unwrap() * wld + r0 - 1] = v;
                }
            }
        }
        Ok(())
    };
    StaircaseLu::factor_control(n, groups.to_vec(), rblocks, n - 1, n - 1, fill, true, control).unwrap()
}

fn rel_dd(x: &[DD], y: &[DD]) -> f64 {
    let ym = y.iter().map(|v| v.hi.abs()).fold(0.0, f64::max);
    x.iter()
        .zip(y)
        .map(|(a, b)| ((a.hi - b.hi) + (a.lo - b.lo)).abs())
        .fold(0.0, f64::max)
        / ym
}

/// The staircase LU's solves (f64 factors, double-double solves) agree with the double-double LU of the same f64
/// matrix (the reference, exact to about cond x 1e-32) as well as the dense f64 LU's solves do (DDLu::factor_f64):
/// error <= 100 x the dense f64 error + 1e-15, plain and transposed, with outward and inward segments. The controls
/// (a pivot scaled by 1 + 1e-6; the parameter copies untied) must fail the check.
#[test]
fn staircase_lu_matches_dense() {
    for (a, b, k, inward, seed) in [
        (10, 20, 4, 9, 1),
        (16, 32, 6, 4, 2),
        (40, 80, 12, 99, 3),
        (24, 48, 13, 8, 4),
    ] {
        let (m, n, ld, groups, rblocks) = staircase_system(a, b, k, inward, seed);
        let dense = DDLu::factor(n, ld, m.clone(), vec![0.0; m.len()], false).unwrap();
        let dense64 = DDLu::factor_f64(n, ld, m.clone(), false).unwrap();
        let rhs: Vec<DD> = (0..n)
            .map(|i| DD::from_f64(((i * 37) % 11) as f64 - 5.0 + 0.1 * (i % 3) as f64))
            .collect();
        let mut res = [[0.0f64; 2]; 3];
        let mut d64 = [0.0f64; 2];
        for (ti, t) in [false, true].into_iter().enumerate() {
            let (mut x, mut y) = (rhs.clone(), rhs.clone());
            if t {
                dense64.solve_t(&mut x);
                dense.solve_t(&mut y);
            } else {
                dense64.solve(&mut x);
                dense.solve(&mut y);
            }
            d64[ti] = rel_dd(&x, &y);
        }
        for (ci, control) in [StaircaseControl::None, StaircaseControl::Pivot, StaircaseControl::Link]
            .into_iter()
            .enumerate()
        {
            let lu = staircase(&m, n, ld, &groups, &rblocks, control);
            for (ti, t) in [false, true].into_iter().enumerate() {
                let (mut x, mut y) = (rhs.clone(), rhs.clone());
                if t {
                    lu.solve_t(&mut x);
                    dense.solve_t(&mut y);
                } else {
                    lu.solve(&mut x);
                    dense.solve(&mut y);
                }
                res[ci][ti] = rel_dd(&x, &y);
            }
        }
        println!(
            "a {a} b {b} k {k} (n {n}): error against the dd LU: staircase {:.1e} (transposed {:.1e}), dense f64 LU {:.1e} \
             ({:.1e}); pivot control {:.1e} / {:.1e}; link control {:.1e} / {:.1e}",
            res[0][0], res[0][1], d64[0], d64[1], res[1][0], res[1][1], res[2][0], res[2][1]
        );
        let lim = [100.0 * d64[0] + 1e-15, 100.0 * d64[1] + 1e-15];
        assert!(
            res[0][0] <= lim[0] && res[0][1] <= lim[1],
            "staircase LU less accurate than the dense f64 LU: {:?} vs {d64:?}",
            res[0]
        );
        assert!(
            res[1][0] > lim[0] && res[1][1] > lim[1],
            "the pivot control does not fire: {:?}",
            res[1]
        );
        assert!(
            res[2][0] > lim[0] && res[2][1] > lim[1],
            "the link control does not fire: {:?}",
            res[2]
        );
    }
}

/// solve_many gives each right-hand side bitwise as solve / solve_t; a bad layout is reported
#[test]
fn staircase_solve_many_is_solve() {
    let (m, n, ld, groups, rblocks) = staircase_system(12, 24, 5, 3, 7);
    let lu = staircase(&m, n, ld, &groups, &rblocks, StaircaseControl::None);
    let k = 5;
    let mut r = Rng(3);
    let bh: Vec<f64> = (0..k * n).map(|_| 0.5 * r.sym()).collect();
    let bl = vec![0.0; k * n];
    for t in [false, true] {
        let (mut xh, mut xl) = (bh.clone(), bl.clone());
        lu.solve_many(&mut xh, &mut xl, k, t, true);
        for row in 0..k {
            let mut v: Vec<DD> = (0..n)
                .map(|i| DD {
                    hi: bh[row * n + i],
                    lo: 0.0,
                })
                .collect();
            if t {
                lu.solve_t(&mut v);
            } else {
                lu.solve(&mut v);
            }
            for i in 0..n {
                assert_eq!(v[i].hi.to_bits(), xh[row * n + i].to_bits());
                assert_eq!(v[i].lo.to_bits(), xl[row * n + i].to_bits());
            }
        }
    }
    let (lo, hi) = lu.pivot_range();
    assert!(lo > 0.0 && hi >= lo && lu.bytes() > 0);
    let mut bad = groups.clone();
    bad[0].param = true;
    assert!(StaircaseLu::factor(n, bad, &rblocks, n - 1, n - 1, |_, _, _, _| Ok(()), false).is_err());
}

/// factor checks that the column groups with the parameter, and the row blocks with row0, each cover 0..n exactly once:
/// each malformed layout below is reported. The fill writes random entries into every step's rows whatever the layout,
/// so that only this check can catch them; with the true layout the same fill factors.
#[test]
fn staircase_rejects_bad_partitions() {
    let (_, n, _, groups, rblocks) = staircase_system(6, 12, 3, 2, 5);
    let try_factor = |g: Vec<ColumnGroup>, rb: &[(usize, usize)], irow0: usize, iparam: usize| {
        let mut r = Rng(1);
        let rows: Vec<usize> = rb.iter().map(|b| b.1).collect();
        StaircaseLu::factor(
            n,
            g,
            rb,
            irow0,
            iparam,
            |s, w: &mut [f64], wld, r0| {
                let start = if s == 0 { r0 - 1 } else { r0 };
                for c in 0..w.len() / wld {
                    for i in start..r0 + rows[s] {
                        w[c * wld + i] = r.sym();
                    }
                }
                Ok(())
            },
            false,
        )
    };
    assert!(try_factor(groups.clone(), &rblocks, n - 1, n - 1).is_ok());
    let mut g = groups.clone();
    g[1].zoff -= 1; // overlaps group 0, and leaves a gap at the end of group 1
    assert!(try_factor(g, &rblocks, n - 1, n - 1).is_err());
    assert!(try_factor(groups.clone(), &rblocks, n - 1, n).is_err()); // the parameter out of range
    assert!(try_factor(groups.clone(), &rblocks, n - 1, 0).is_err()); // the parameter inside group 0
    let mut rb = rblocks.clone();
    rb.last_mut().unwrap().0 += 1; // overlaps row0, and leaves a row uncovered
    assert!(try_factor(groups.clone(), &rb, n - 1, n - 1).is_err());
    assert!(try_factor(groups.clone(), &rblocks, 0, n - 1).is_err()); // row0 inside row block 0
    assert!(try_factor(groups.clone(), &rblocks, n, n - 1).is_err()); // row0 out of range
}

// ---------------------------------------------------------------------------------------------------------------
// quad-double LU
// ---------------------------------------------------------------------------------------------------------------

use multidouble::linalg::{QDLu, QdLuControl};
use multidouble::qd::QdAcc;

fn rand_qd(r: &mut Rng) -> QD {
    QD::new(r.sym(), r.sym() * 1e-17, r.sym() * 1e-34, r.sym() * 1e-51)
}

/// a random n x n quad-double matrix in four parts, column-major with leading dimension ld_for(n), made well
/// conditioned by a diagonal shift
fn matrix_qd(n: usize, r: &mut Rng) -> (usize, [Vec<f64>; 4]) {
    let ld = ld_for(n);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..n {
            let mut v = rand_qd(r);
            if i == j {
                v = v + QD::from_f64(2.0 + (n as f64).sqrt());
            }
            for q in 0..4 {
                c[q][j * ld + i] = v.x[q];
            }
        }
    }
    (ld, c)
}

fn entry(c: &[Vec<f64>; 4], k: usize) -> QD {
    QD {
        x: std::array::from_fn(|q| c[q][k]),
    }
}

/// A x (or A^T x) in quad-double
fn apply_qd(n: usize, ld: usize, c: &[Vec<f64>; 4], x: &[QD], transpose: bool) -> Vec<QD> {
    (0..n)
        .map(|i| {
            let mut s = QdAcc::zero();
            for j in 0..n {
                let k = if transpose { i * ld + j } else { j * ld + i };
                s = s.add_prod(entry(c, k), x[j]);
            }
            s.finish()
        })
        .collect()
}

fn max_rel_err_qd(got: &[QD], want: &[QD]) -> f64 {
    let scale = want.iter().map(|w| w.x[0].abs()).fold(0.0, f64::max);
    got.iter()
        .zip(want)
        .map(|(g, w)| (*g - *w).to_f64().abs() / scale)
        .fold(0.0, f64::max)
}

/// the error of QDLu's solve and transpose solve of a random well-conditioned system of order n
fn qd_solve_errors(n: usize, seed: u64, par: bool, ctl: QdLuControl) -> f64 {
    let mut r = Rng(seed);
    let (ld, c) = matrix_qd(n, &mut r);
    let x: Vec<QD> = (0..n).map(|_| rand_qd(&mut r)).collect();
    let lu = QDLu::factor_control(n, ld, c.clone(), par, ctl).expect("factor");
    let mut worst = 0.0f64;
    for transpose in [false, true] {
        let mut b = apply_qd(n, ld, &c, &x, transpose);
        if transpose {
            lu.solve_t(&mut b);
        } else {
            lu.solve(&mut b);
        }
        worst = worst.max(max_rel_err_qd(&b, &x));
    }
    worst
}

#[test]
fn qd_lu_solves_to_quad_double() {
    for &n in &[1usize, 5, 8, 37, 64, 130] {
        for &par in &[false, true] {
            let e = qd_solve_errors(n, 61 + n as u64, par, QdLuControl::None);
            println!("QDLu n = {n}, par {par}: worst relative error {e:.1e}");
            assert!(e < 1e-57, "n = {n}: {e:e}");
        }
    }
}

/// Control: the trailing update rounded to double-double leaves the solve at double-double accuracy, which the same
/// check rejects.
#[test]
fn control_qd_lu_update_in_dd_is_caught() {
    let e = qd_solve_errors(64, 125, false, QdLuControl::UpdateDd);
    println!("QDLu with the update in double-double: worst relative error {e:.1e}");
    assert!(e > 1e-40, "{e:e}");
}

#[test]
fn qd_lu_parallel_is_bitwise_serial() {
    let mut r = Rng(62);
    let n = 200;
    let (ld, c) = matrix_qd(n, &mut r);
    let a = QDLu::factor(n, ld, c.clone(), false).unwrap();
    let b = QDLu::factor(n, ld, c, true).unwrap();
    assert_eq!(a.perm, b.perm);
    for q in 0..4 {
        assert!(
            a.c[q].iter().zip(&b.c[q]).all(|(u, v)| u.to_bits() == v.to_bits()),
            "part {q}"
        );
    }
}

/// A = H1 D H2 with Householder reflectors H1, H2 and D = diag(10^(-40 i / (n - 1))): condition number 1e40, beyond
/// double-double. The quad-double LU solves it to about 1e40 2^-209; the double-double LU of A rounded to double-double
/// has no correct digit.
#[test]
fn qd_lu_solves_what_dd_cannot() {
    let mut r = Rng(63);
    let n = 40;
    let ld = ld_for(n);
    let refl = |r: &mut Rng| -> Vec<Vec<QD>> {
        let v: Vec<QD> = (0..n).map(|_| rand_qd(r)).collect();
        let vv = v.iter().fold(QdAcc::zero(), |a, &x| a.add_prod(x, x)).finish();
        (0..n)
            .map(|i| {
                (0..n)
                    .map(|j| {
                        let e = if i == j { QD::ONE } else { QD::ZERO };
                        e - (v[i] * v[j]).mul_f(2.0) / vv
                    })
                    .collect()
            })
            .collect()
    };
    let (h1, h2) = (refl(&mut r), refl(&mut r));
    let d: Vec<QD> = (0..n)
        .map(|k| QD::from_f64(10f64.powf(-40.0 * k as f64 / (n - 1) as f64)))
        .collect();
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for i in 0..n {
        for j in 0..n {
            let s = (0..n)
                .fold(QdAcc::zero(), |a, k| a.add_prod(h1[i][k] * d[k], h2[k][j]))
                .finish();
            for q in 0..4 {
                c[q][j * ld + i] = s.x[q];
            }
        }
    }
    let x: Vec<QD> = (0..n).map(|_| rand_qd(&mut r)).collect();
    let b = apply_qd(n, ld, &c, &x, false);
    let mut bq = b.clone();
    QDLu::factor(n, ld, c.clone(), false).unwrap().solve(&mut bq);
    let eq = max_rel_err_qd(&bq, &x);
    let (hi, lo): (Vec<f64>, Vec<f64>) = (0..ld * n).map(|k| entry(&c, k).to_dd()).map(|v| (v.hi, v.lo)).unzip();
    let mut bd: Vec<DD> = b.iter().map(|v| v.to_dd()).collect();
    DDLu::factor(n, ld, hi, lo, false).unwrap().solve(&mut bd);
    let ed = max_rel_err_qd(&bd.iter().map(|&v| QD::from_dd(v)).collect::<Vec<_>>(), &x);
    println!("cond 1e40: quad-double LU error {eq:.1e}, double-double LU error {ed:.1e}");
    assert!(eq < 1e-16, "quad-double: {eq:e}");
    assert!(ed > 1e-3, "double-double: {ed:e}");
}

/// a block-bidiagonal matrix (8 x 8 blocks, zero elsewhere): the skipped zero updates leave the solve exact to
/// quad-double, and an exactly zero column is reported as singular
#[test]
fn qd_lu_sparse_and_singular() {
    let mut r = Rng(64);
    let n = 48;
    let ld = ld_for(n);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..n {
            let (bi, bj) = (i / 8, j / 8);
            if bi == bj || bi == bj + 1 {
                let mut v = rand_qd(&mut r);
                if i == j {
                    v = v + QD::from_f64(4.0);
                }
                for q in 0..4 {
                    c[q][j * ld + i] = v.x[q];
                }
            }
        }
    }
    let x: Vec<QD> = (0..n).map(|_| rand_qd(&mut r)).collect();
    let mut b = apply_qd(n, ld, &c, &x, false);
    QDLu::factor(n, ld, c.clone(), true).unwrap().solve(&mut b);
    let e = max_rel_err_qd(&b, &x);
    println!("block-bidiagonal QDLu: worst relative error {e:.1e}");
    assert!(e < 1e-58, "{e:e}");
    for q in 0..4 {
        for i in 0..n {
            c[q][5 * ld + i] = 0.0;
        }
    }
    assert!(QDLu::factor(n, ld, c, false).is_err());
}

/// part q of entry (i, j) of the pinned system's matrix, or of entry i of b when j is None: small integers over powers
/// of two, exact in f64, so that the Python tests (`pinned_system` in python/tests/test_multidouble.py) build the same
/// system. The parts overlap, so `QD::new` renormalizes them, as the Python binding does.
fn pinned_part(i: usize, j: Option<usize>, q: usize) -> f64 {
    let scale = [2f64.powi(-7), 2f64.powi(-58), 2f64.powi(-113), 2f64.powi(-168)][q];
    let t = match j {
        Some(j) => {
            ((i * 37 + j * 101 + q * 53 + i * j * 7) % 211) as f64 - 105.0 + if q == 0 && i == j { 64.0 } else { 0.0 }
        }
        None => ((i * 29 + q * 71) % 199) as f64 - 99.0,
    };
    t * scale
}

/// FNV-1a over the bits of x's parts, part 0 of every entry first, then part 1, ... (as the Python tests hash them)
fn parts_hash(x: &[QD]) -> u64 {
    let mut h = 0xcbf2_9ce4_8422_2325u64;
    for q in 0..4 {
        for v in x {
            h ^= v.x[q].to_bits();
            h = h.wrapping_mul(0x0000_0100_0000_01b3);
        }
    }
    h
}

/// The pinned system's solutions of A x = b and A^T x = b by QDLu called directly (n = 37, so the last row block is
/// partial, with row swaps), each entry renormalized by `QD::new` as the Python binding does. The Python tests check
/// `qd_solve` and `QDLu` against the same hashes, so the binding gives the Rust LU's bits; any change to the LU's bits
/// fails here. The solutions are checked to quad-double accuracy first. Control: the last bit of one entry's second
/// part flipped in b (2^-105 of it) changes the hash.
#[test]
fn qd_lu_pinned_bits() {
    let n = 37;
    let ld = ld_for(n);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..n {
            let p = |q| pinned_part(i, Some(j), q);
            let v = QD::new(p(0), p(1), p(2), p(3));
            for q in 0..4 {
                c[q][j * ld + i] = v.x[q];
            }
        }
    }
    let b: Vec<QD> = (0..n)
        .map(|i| {
            let p = |q| pinned_part(i, None, q);
            QD::new(p(0), p(1), p(2), p(3))
        })
        .collect();
    let lu = QDLu::factor(n, ld, c.clone(), false).unwrap();
    assert!((0..n).any(|k| lu.perm[k] != k), "the pinned system should pivot");
    let mut x = b.clone();
    lu.solve(&mut x);
    let mut y = b.clone();
    lu.solve_t(&mut y);
    for (sol, t) in [(&x, false), (&y, true)] {
        let r = apply_qd(n, ld, &c, sol, t);
        let e = max_rel_err_qd(&r, &b);
        println!("pinned system, transpose {t}: relative residual {e:.1e}");
        assert!(e < 1e-60, "{e:e}");
    }
    let (hx, hy) = (parts_hash(&x), parts_hash(&y));
    println!("pinned system: hashes {hx:#018x} {hy:#018x}");
    assert_eq!((hx, hy), (0x90714c6ebacc4705, 0xe34a230e39e22035));
    let mut z = b.clone();
    z[5].x[1] = f64::from_bits(z[5].x[1].to_bits() ^ 1);
    lu.solve(&mut z);
    assert_ne!(parts_hash(&z), hx);
}

// ---------------------------------------------------------------------------------------------------------------
// the sign and log-determinant of a real matrix
// ---------------------------------------------------------------------------------------------------------------

use multidouble::linalg::DdLuControl;

/// a double-double matrix as quad-double parts, the two lower parts zero
fn dd_parts_qd(hi: &[f64], lo: &[f64]) -> [Vec<f64>; 4] {
    [hi.to_vec(), lo.to_vec(), vec![0.0; hi.len()], vec![0.0; hi.len()]]
}

/// (sign, ln|det|) of the double-double and the quad-double LU of the double-double matrix (hi, lo) under the
/// controls dc and qc, None where the factorization stops at a zero pivot
fn logdets(n: usize, ld: usize, hi: &[f64], lo: &[f64], dc: DdLuControl, qc: QdLuControl) -> [Option<(f64, f64)>; 2] {
    let d = DDLu::factor_control(n, ld, hi.to_vec(), lo.to_vec(), false, dc).ok();
    let q = QDLu::factor_control(n, ld, dd_parts_qd(hi, lo), false, qc).ok();
    [d.map(|lu| lu.logdet()), q.map(|lu| lu.logdet())]
}

/// (-1)^(the number of row interchanges of an LU)
fn swap_sign(perm: &[usize]) -> f64 {
    let s = perm.iter().enumerate().filter(|&(k, &p)| p != k).count();
    if s % 2 == 0 {
        1.0
    } else {
        -1.0
    }
}

/// the sign of the permutation p, from its cycles
fn parity(p: &[usize]) -> f64 {
    let mut seen = vec![false; p.len()];
    let mut s = 1.0;
    for i in 0..p.len() {
        let (mut j, mut len) = (i, 0);
        while !seen[j] {
            seen[j] = true;
            j = p[j];
            len += 1;
        }
        if len > 0 && len % 2 == 0 {
            s = -s;
        }
    }
    s
}

/// a random permutation of 0..n (Fisher-Yates)
fn shuffle(n: usize, r: &mut Rng) -> Vec<usize> {
    let mut p: Vec<usize> = (0..n).collect();
    for i in (1..n).rev() {
        p.swap(i, (r.next_u64() % (i as u64 + 1)) as usize);
    }
    p
}

/// the column-major matrix a with its rows permuted: row i of the result is row p[i] of a
fn permute_rows(n: usize, ld: usize, a: &[f64], p: &[usize]) -> Vec<f64> {
    let mut b = a.to_vec();
    for j in 0..n {
        for i in 0..n {
            b[j * ld + i] = a[j * ld + p[i]];
        }
    }
    b
}

/// An upper triangular matrix with diagonal d_k = k + 1, negated for k % 3 == 0 (five negative entries at n = 13),
/// needs no pivoting: `QDLu::logdet` and `DDLu::logdet` give sign -1 and ln 13! to 1e-13, and the pivot range is 1 to
/// n. Controls: the same checks reject the matrix with d_1 negated (the sign) and with d_0 times 1 + 2^-40 (ln|det|
/// off by 9e-13, and the smallest pivot).
#[test]
fn qd_logdet_of_a_triangular_matrix() {
    let n = 13;
    let ld = ld_for(n);
    let mut hi = vec![0.0; ld * n];
    for j in 0..n {
        for i in 0..=j {
            hi[j * ld + i] = match (i == j, j % 3 == 0) {
                (true, true) => -((j + 1) as f64),
                (true, false) => (j + 1) as f64,
                _ => 0.5,
            };
        }
    }
    let lo = vec![0.0; ld * n];
    let want: f64 = (1..=n).map(|k| (k as f64).ln()).sum();
    // (sign right, ln|det| right, pivot range right) for the quad-double LU, which the double-double one must match
    let checks = |hi: &[f64]| -> (bool, bool, bool) {
        let lu = QDLu::factor(n, ld, dd_parts_qd(hi, &lo), false).unwrap();
        let (sign, ln) = lu.logdet();
        let dd = logdets(n, ld, hi, &lo, DdLuControl::None, QdLuControl::None)[0];
        assert_eq!(dd, Some((sign, ln)));
        (
            sign == -1.0,
            (ln - want).abs() < 1e-13,
            lu.pivot_range() == (1.0, n as f64),
        )
    };
    assert_eq!(checks(&hi), (true, true, true));
    let mut neg = hi.clone();
    neg[ld + 1] = -neg[ld + 1];
    assert!(!checks(&neg).0, "control: d_1 negated");
    let mut scaled = hi.clone();
    scaled[0] *= 1.0 + 2f64.powi(-40);
    let (_, ln_ok, range_ok) = checks(&scaled);
    assert!(!ln_ok && !range_ok, "control: d_0 scaled");
}

/// A = P U for an upper triangular U with random entries above its diagonal d_k = +-(k + 2) and a row permutation P:
/// partial pivoting finds the rows of U again with no arithmetic on them, so both LUs give the sign sign(P) prod
/// sign(d_k) and ln|det| = sum ln|d_k| bit for bit (the same f64 sum). P runs over the identity, a cyclic shift (odd
/// at n = 10), a transposition and random shuffles. Controls: the sign without its flips for the row interchanges
/// fails for every odd P, and the LU without pivoting (`NoPivot`) stops at a zero pivot wherever P moves row 0.
#[test]
fn logdet_of_a_row_permuted_triangular_matrix() {
    let mut r = Rng(91);
    let n = 10;
    let ld = ld_for(n);
    let d: Vec<f64> = (0..n)
        .map(|k| (k + 2) as f64 * if r.next_u64() & 1 == 0 { 1.0 } else { -1.0 })
        .collect();
    let mut u = vec![0.0; ld * n];
    for j in 0..n {
        for i in 0..j {
            u[j * ld + i] = r.sym();
        }
        u[j * ld + j] = d[j];
    }
    let want_ln: f64 = d.iter().map(|v| v.abs().ln()).sum();
    let want_sign: f64 = d.iter().map(|v| v.signum()).product();
    let mut perms = vec![(0..n).collect::<Vec<_>>(), (0..n).map(|i| (i + 1) % n).collect()];
    let mut t: Vec<usize> = (0..n).collect();
    t.swap(2, 7);
    perms.push(t);
    perms.extend((0..6).map(|_| shuffle(n, &mut r)));
    assert!(perms.iter().any(|p| parity(p) < 0.0) && perms.iter().any(|p| parity(p) > 0.0));
    let lo = vec![0.0; ld * n];
    for p in &perms {
        let a = permute_rows(n, ld, &u, p);
        let dd = DDLu::factor(n, ld, a.clone(), lo.clone(), false).unwrap();
        let qd = QDLu::factor(n, ld, dd_parts_qd(&a, &lo), false).unwrap();
        let want = (parity(p) * want_sign, want_ln);
        assert_eq!(dd.logdet(), want, "{p:?}");
        assert_eq!(qd.logdet(), want, "{p:?}");
        for (s, perm) in [(dd.logdet().0, &dd.perm), (qd.logdet().0, &qd.perm)] {
            let blind = s * swap_sign(perm);
            assert_eq!(blind == want.0, parity(p) > 0.0, "control: {p:?}");
        }
        if p[0] != 0 {
            let nopiv = logdets(n, ld, &a, &lo, DdLuControl::NoPivot, QdLuControl::NoPivot);
            assert_eq!(nopiv, [None, None], "control: {p:?}");
        }
    }
}

/// Permuting the rows of a random matrix leaves partial pivoting's pivots as they are (the same rows win, in another
/// order), so ln|det| and the pivot range are bit for bit those of A and the sign flips by the permutation's parity,
/// in the double-double LU (unblocked at n = 9 and 37, blocked at 130) and the quad-double one. Control: the sign
/// without its flips for the interchanges is the same for A and P A, which the check rejects for every odd P.
#[test]
fn logdet_sign_follows_row_permutations() {
    let mut r = Rng(92);
    let blind = |s: f64, perm: &[usize]| s * swap_sign(perm);
    for n in [9usize, 37, 130] {
        let (ld, hi, lo) = matrix(n, &mut r);
        let a_dd = DDLu::factor(n, ld, hi.clone(), lo.clone(), false).unwrap();
        let a_qd = QDLu::factor(n, ld, dd_parts_qd(&hi, &lo), false).unwrap();
        let mut odd = 0;
        for _ in 0..4 {
            let p = shuffle(n, &mut r);
            let s = parity(&p);
            let (ph, pl) = (permute_rows(n, ld, &hi, &p), permute_rows(n, ld, &lo, &p));
            let dd = DDLu::factor(n, ld, ph.clone(), pl.clone(), false).unwrap();
            let qd = QDLu::factor(n, ld, dd_parts_qd(&ph, &pl), false).unwrap();
            for (pa, a) in [(dd.logdet(), a_dd.logdet()), (qd.logdet(), a_qd.logdet())] {
                assert_eq!(pa, (s * a.0, a.1), "n {n}");
            }
            assert_eq!(dd.pivot_range(), a_dd.pivot_range());
            assert_eq!(qd.pivot_range(), a_qd.pivot_range());
            let (b_pa, b_a) = (blind(dd.logdet().0, &dd.perm), blind(a_dd.logdet().0, &a_dd.perm));
            assert_eq!(b_pa == s * b_a, s > 0.0, "control: n {n}");
            odd += usize::from(s < 0.0);
        }
        assert!(odd > 0, "n {n}: no odd permutation drawn");
    }
}

/// A random well-conditioned matrix with its entry (0, 0) replaced by 1.37 2^-300 needs pivoting: with it the
/// double-double and quad-double LUs agree on the sign and on ln|det| to 1e-12, in the unblocked and the blocked
/// double-double LU. Control: without pivoting (`NoPivot`) the multipliers reach 2^300 and the trailing matrix is
/// lost to rounding, so that in both precisions the factorization meets an exactly zero pivot (the rank-one update
/// cancels) or ln|det| misses by more than 100.
#[test]
fn logdet_no_pivot_control_is_caught() {
    let mut r = Rng(93);
    for n in [9usize, 40, 130] {
        let (ld, mut hi, mut lo) = matrix(n, &mut r);
        (hi[0], lo[0]) = (1.37 * 2f64.powi(-300), 0.0);
        let [d, q] = logdets(n, ld, &hi, &lo, DdLuControl::None, QdLuControl::None);
        let ((sd, ln_d), (sq, ln_q)) = (d.unwrap(), q.unwrap());
        println!("n {n}: double-double ({sd}, {ln_d}), quad-double ({sq}, {ln_q})");
        assert!(sd == sq && (ln_d - ln_q).abs() <= 1e-12 * ln_q.abs(), "n {n}");
        let nopiv = logdets(n, ld, &hi, &lo, DdLuControl::NoPivot, QdLuControl::NoPivot);
        for (name, v) in ["double-double", "quad-double"].into_iter().zip(nopiv) {
            println!("n {n}: {name} without pivoting: {v:?}");
            assert!(
                v.is_none_or(|(_, lv)| (lv - ln_q).abs() > 100.0),
                "control: n {n}, {name}"
            );
        }
    }
}

/// On random double-double matrices (n = 1, 8, 37 and 130, the last blocked in double-double) the quad-double LU's
/// sign is the double-double one's, and its ln|det| and pivot range agree to 1e-12 relative. Controls: the same
/// checks reject the quad-double LU of the matrix with row 0 negated (the sign) and of the matrix times 1 + 2^-20
/// (ln|det| off by n 9.5e-7, the pivots by 9.5e-7 relative).
#[test]
fn qd_logdet_matches_dd_logdet() {
    let mut r = Rng(94);
    let close = |a: f64, b: f64, tol: f64| (a - b).abs() <= tol * b.abs().max(1.0);
    for n in [1usize, 8, 37, 130] {
        let (ld, hi, lo) = matrix(n, &mut r);
        let dd = DDLu::factor(n, ld, hi.clone(), lo.clone(), false).unwrap();
        let ((sd, l1), (p0, p1)) = (dd.logdet(), dd.pivot_range());
        // (sign, ln|det|, pivot range) of the quad-double LU of (h, l) against the double-double LU of (hi, lo)
        let checks = |h: &[f64], l: &[f64]| -> (bool, bool, bool) {
            let qd = QDLu::factor(n, ld, dd_parts_qd(h, l), false).unwrap();
            let ((sq, l2), (q0, q1)) = (qd.logdet(), qd.pivot_range());
            (
                sd == sq,
                close(l1, l2, 1e-12),
                close(p0, q0, 1e-12) && close(p1, q1, 1e-12),
            )
        };
        assert_eq!(checks(&hi, &lo), (true, true, true), "n {n}");
        let (mut nh, mut nl) = (hi.clone(), lo.clone());
        for j in 0..n {
            nh[j * ld] = -nh[j * ld];
            nl[j * ld] = -nl[j * ld];
        }
        assert!(!checks(&nh, &nl).0, "control: row 0 negated, n {n}");
        let s = 1.0 + 2f64.powi(-20);
        let (sh, sl): (Vec<f64>, Vec<f64>) = hi.iter().zip(&lo).map(|(&h, &l)| (h * s, l * s)).unzip();
        let (_, ln_ok, range_ok) = checks(&sh, &sl);
        assert!(!ln_ok && !range_ok, "control: scaled, n {n}");
    }
}

// ---------------------------------------------------------------------------------------------------------------
// the determinant of a complex matrix
// ---------------------------------------------------------------------------------------------------------------

/// a random complex n x n matrix (column-major, leading dimension ld), well conditioned by a diagonal shift: real
/// parts (hi, lo), imaginary parts (hi, lo)
fn cmatrix(n: usize, r: &mut Rng) -> (usize, [Vec<f64>; 4]) {
    let ld = ld_for(n);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..n {
            let mut re = DD::new(r.sym(), r.sym() * 1e-17);
            let im = DD::new(r.sym(), r.sym() * 1e-17);
            if i == j {
                re = re + DD::from_f64(2.0 + (n as f64).sqrt());
            }
            c[0][j * ld + i] = re.hi;
            c[1][j * ld + i] = re.lo;
            c[2][j * ld + i] = im.hi;
            c[3][j * ld + i] = im.lo;
        }
    }
    (ld, c)
}

fn clogdet(n: usize, ld: usize, c: &[Vec<f64>; 4]) -> (f64, f64, f64, f64) {
    clu_logdet(n, ld, c[0].clone(), c[1].clone(), c[2].clone(), c[3].clone(), false).unwrap()
}

/// the difference of two angles, wrapped into (-pi, pi]
fn dang(a: f64, b: f64) -> f64 {
    let d = (a - b).rem_euclid(2.0 * std::f64::consts::PI);
    if d > std::f64::consts::PI {
        d - 2.0 * std::f64::consts::PI
    } else {
        d
    }
}

/// A real matrix (imaginary parts zero) has the ln|det| and the pivot range of `DDLu::logdet` to 1e-12 (the same
/// pivots, updated by a different accumulation), and arg det 0 or pi as its sign is. Control: a wrong sign is caught.
#[test]
fn complex_logdet_of_a_real_matrix_is_logdet() {
    let mut r = Rng(81);
    for n in [1, 7, 20, 33] {
        let (ld, hi, lo) = matrix(n, &mut r);
        let z = vec![0.0; ld * n];
        let lu = DDLu::factor(n, ld, hi.clone(), lo.clone(), false).unwrap();
        let (sign, ln) = lu.logdet();
        let (pmin, pmax) = lu.pivot_range();
        let (la, arg, cmin, cmax) = clu_logdet(n, ld, hi, lo, z.clone(), z, false).unwrap();
        assert!((la - ln).abs() <= 1e-12 * ln.abs().max(1.0), "n {n}: {la} vs {ln}");
        let want = if sign > 0.0 { 0.0 } else { std::f64::consts::PI };
        assert!(dang(arg, want).abs() <= 1e-12, "n {n}: arg {arg} for sign {sign}");
        assert!(dang(arg, want + 1.0).abs() > 0.5, "control");
        assert!((cmin - pmin).abs() <= 1e-12 * pmin && (cmax - pmax).abs() <= 1e-12 * pmax);
    }
}

/// An upper triangular matrix with diagonal (k + 1) e^{i 0.3 (k + 1)} needs no pivoting: ln|det| = sum ln (k + 1)
/// and arg det = 0.3 sum (k + 1) wrapped, to 1e-13; the pivot range is 1 to n.
#[test]
fn complex_logdet_of_a_triangular_matrix() {
    let n = 12;
    let ld = ld_for(n);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..=j {
            if i == j {
                let (rho, phi) = ((j + 1) as f64, 0.3 * (j + 1) as f64);
                c[0][j * ld + i] = rho * phi.cos();
                c[2][j * ld + i] = rho * phi.sin();
            } else {
                c[0][j * ld + i] = 0.5;
                c[2][j * ld + i] = 0.25;
            }
        }
    }
    let (la, arg, pmin, pmax) = clogdet(n, ld, &c);
    let want_ln: f64 = (1..=n).map(|k| (k as f64).ln()).sum();
    let want_arg = 0.3 * (n * (n + 1) / 2) as f64;
    assert!(
        (la - want_ln).abs() <= 1e-13 && dang(arg, want_arg).abs() <= 1e-13,
        "{la} {arg}"
    );
    assert!((pmin - 1.0).abs() <= 1e-13 && (pmax - n as f64).abs() <= 1e-12);
}

/// On random complex matrices: column 0 times e^{i theta} shifts arg det by theta and leaves ln|det| (to 1e-12); the
/// real 2n x 2n embedding [[R, -I], [I, R]] has determinant |det|^2, so `DDLu::logdet` of it gives 2 ln|det| and a
/// positive sign (to 1e-11). Controls: an entry's imaginary part scaled by 1 + 1e-3 breaks the embedding check; a
/// singular matrix is reported.
#[test]
fn complex_logdet_rotation_and_real_embedding() {
    let mut r = Rng(82);
    for n in [5, 16, 29] {
        let (ld, c) = cmatrix(n, &mut r);
        let (la, arg, _, _) = clogdet(n, ld, &c);
        let theta = 0.7f64;
        let mut rot = c.clone();
        for i in 0..n {
            let (re, im) = (DD::new(c[0][i], c[1][i]), DD::new(c[2][i], c[3][i]));
            let (cs, sn) = (DD::from_f64(theta.cos()), DD::from_f64(theta.sin()));
            let (nr, ni) = (re * cs - im * sn, re * sn + im * cs);
            rot[0][i] = nr.hi;
            rot[1][i] = nr.lo;
            rot[2][i] = ni.hi;
            rot[3][i] = ni.lo;
        }
        let (lr, ar, _, _) = clogdet(n, ld, &rot);
        assert!(
            (lr - la).abs() <= 1e-12 * la.abs().max(1.0),
            "n {n}: rotated ln {lr} vs {la}"
        );
        assert!(
            dang(ar, arg + theta).abs() <= 1e-12,
            "n {n}: rotated arg {ar} vs {arg} + {theta}"
        );
        let embed = |c: &[Vec<f64>; 4]| {
            let m = 2 * n;
            let ldm = ld_for(m);
            let (mut hi, mut lo) = (vec![0.0; ldm * m], vec![0.0; ldm * m]);
            for j in 0..n {
                for i in 0..n {
                    let (re, im) = (
                        (c[0][j * ld + i], c[1][j * ld + i]),
                        (c[2][j * ld + i], c[3][j * ld + i]),
                    );
                    hi[j * ldm + i] = re.0;
                    lo[j * ldm + i] = re.1;
                    hi[(j + n) * ldm + i + n] = re.0;
                    lo[(j + n) * ldm + i + n] = re.1;
                    hi[(j + n) * ldm + i] = -im.0;
                    lo[(j + n) * ldm + i] = -im.1;
                    hi[j * ldm + i + n] = im.0;
                    lo[j * ldm + i + n] = im.1;
                }
            }
            DDLu::factor(m, ldm, hi, lo, false).unwrap().logdet()
        };
        let (sign, ln2) = embed(&c);
        assert!(
            sign > 0.0 && (ln2 - 2.0 * la).abs() <= 1e-11 * la.abs().max(1.0),
            "n {n}: embedding {ln2} vs 2 x {la}"
        );
        let mut wrong = c.clone();
        wrong[2][0] *= 1.0 + 1e-3;
        let (_, lw) = embed(&wrong);
        assert!(
            (lw - 2.0 * la).abs() > 1e-11 * la.abs().max(1.0),
            "control: the perturbed embedding passes"
        );
    }
    let ld = ld_for(4);
    assert!(clu_logdet(
        4,
        ld,
        vec![0.0; ld * 4],
        vec![0.0; ld * 4],
        vec![0.0; ld * 4],
        vec![0.0; ld * 4],
        false
    )
    .is_err());
}

/// The parallel path of `clu_logdet` (par = true, taken above about 32768 updated entries per column step: n = 200
/// here) gives the serial path's results bit for bit: every column's update is the same operations, whichever thread
/// runs it. Control: the same matrix with one entry changed differs.
#[test]
fn complex_logdet_parallel_is_serial() {
    let mut r = Rng(83);
    let n = 200;
    let (ld, c) = cmatrix(n, &mut r);
    let serial = clogdet(n, ld, &c);
    let par = clu_logdet(n, ld, c[0].clone(), c[1].clone(), c[2].clone(), c[3].clone(), true).unwrap();
    let bits = |v: (f64, f64, f64, f64)| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits(), v.3.to_bits()];
    assert_eq!(bits(serial), bits(par));
    let mut other = c.clone();
    other[0][ld + 1] += 1e-3;
    assert_ne!(bits(serial), bits(clogdet(n, ld, &other)), "control");
}

/// Pivots of any size: the matrix scaled by 2^-530 (moduli about 1e-160, whose squares underflow), by 2^530 (about
/// 1e160, whose squares overflow) and by 2^-10 gives the same arg det, ln|det| shifted by n ln 2^e to 1e-9, and
/// every pivot scaled bit for bit (the reciprocal's scaling is exact, so the factors are those of the unscaled
/// matrix times 2^e). Control: the shift with n - 1 in place of n must miss.
#[test]
fn complex_logdet_pivots_of_any_size() {
    let mut r = Rng(84);
    let n = 12;
    let (ld, c) = cmatrix(n, &mut r);
    let (la, arg, pmin, pmax) = clogdet(n, ld, &c);
    for e in [-530i32, 530, -10] {
        let s = 2f64.powi(e);
        let scaled: [Vec<f64>; 4] = std::array::from_fn(|q| c[q].iter().map(|v| v * s).collect());
        let (ls, as_, smin, smax) = clogdet(n, ld, &scaled);
        let shift = n as f64 * s.ln();
        assert!(
            (ls - la - shift).abs() <= 1e-9 * (la.abs() + shift.abs()),
            "2^{e}: {ls} vs {la} + {shift}"
        );
        assert!(dang(as_, arg).abs() <= 1e-12, "2^{e}: arg {as_} vs {arg}");
        assert_eq!(
            (smin.to_bits(), smax.to_bits()),
            ((pmin * s).to_bits(), (pmax * s).to_bits()),
            "2^{e}: pivots"
        );
        assert!(
            (ls - la - (n - 1) as f64 * s.ln()).abs() > 1e-9 * (la.abs() + shift.abs()),
            "control"
        );
    }
}

/// A subnormal pivot under an entry of its own size: the real matrix [[1e-310, 1], [1e-310, 2]] has determinant
/// 1e-310 (the multiplier is 1, the second pivot 1), so ln|det| = ln 1e-310, arg 0; the complex matrix with the first
/// column times i has the same ln|det| and arg pi/2. Control: the second pivot taken as 2 (no elimination) misses.
#[test]
fn complex_logdet_subnormal_pivot_with_finite_multipliers() {
    let ld = ld_for(2);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * 2]);
    c[0][0] = 1e-310;
    c[0][1] = 1e-310;
    c[0][ld] = 1.0;
    c[0][ld + 1] = 2.0;
    let (la, arg, pmin, pmax) = clogdet(2, ld, &c);
    let want = 1e-310f64.ln();
    assert!(
        (la - want).abs() <= 1e-12 * want.abs() && arg.abs() <= 1e-15,
        "{la} vs {want}, arg {arg}"
    );
    assert!(
        (pmin - 1e-310).abs() <= 1e-15 * 1e-310 && (pmax - 1.0).abs() <= 1e-15,
        "pivots {pmin} {pmax}"
    );
    assert!((la - want - 2f64.ln()).abs() > 0.1, "control");
    let mut ci = c.clone();
    ci[2][0] = 1e-310;
    ci[2][1] = 1e-310;
    ci[0][0] = 0.0;
    ci[0][1] = 0.0;
    let (li, ai, _, _) = clogdet(2, ld, &ci);
    assert!((li - want).abs() <= 1e-12 * want.abs() && dang(ai, std::f64::consts::FRAC_PI_2).abs() <= 1e-15);
}

/// NaN entries: a NaN on the diagonal of a column (in a hi or a lo part), or a column of NaN, is reported as a
/// non-finite pivot (not skipped in favour of a finite entry below it, as the real LU's `pivot_search` does not either)
#[test]
fn complex_logdet_reports_nan_pivots() {
    let mut r = Rng(85);
    let n = 6;
    let (ld, c) = cmatrix(n, &mut r);
    assert!(clogdet(n, ld, &c).0.is_finite());
    let mut diag = c.clone();
    diag[2][2 * ld + 2] = f64::NAN;
    assert!(clu_logdet(
        n,
        ld,
        diag[0].clone(),
        diag[1].clone(),
        diag[2].clone(),
        diag[3].clone(),
        false
    )
    .is_err());
    for (q, i) in [(1usize, 2usize), (3, 4)] {
        let mut lo = c.clone();
        lo[q][i * ld + i] = f64::NAN;
        assert!(
            clu_logdet(n, ld, lo[0].clone(), lo[1].clone(), lo[2].clone(), lo[3].clone(), false).is_err(),
            "lo part {q}"
        );
    }
    let mut col = c.clone();
    for i in 0..n {
        col[0][3 * ld + i] = f64::NAN;
    }
    assert!(clu_logdet(
        n,
        ld,
        col[0].clone(),
        col[1].clone(),
        col[2].clone(),
        col[3].clone(),
        false
    )
    .is_err());
}

/// A complex matrix with the zero pattern of `zero(i, j)` (exact zeros there), random double-double entries elsewhere
/// (real ones when `real`, both parts of their imaginary parts the zero `imz`, +0 or -0), and `shift` added to the real part of
/// each diagonal entry
fn patterned(
    n: usize,
    r: &mut Rng,
    zero: impl Fn(usize, usize, &mut Rng) -> bool,
    real: bool,
    imz: f64,
    shift: f64,
) -> (usize, [Vec<f64>; 4]) {
    let ld = ld_for(n);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    for j in 0..n {
        for i in 0..n {
            let k = j * ld + i;
            if zero(i, j, r) {
                c[2][k] = imz;
                c[3][k] = imz;
                continue;
            }
            let mut re = DD::new(r.sym(), r.sym() * 1e-17);
            if i == j {
                re = re + DD::from_f64(shift);
            }
            c[0][k] = re.hi;
            c[1][k] = re.lo;
            if real {
                c[2][k] = imz;
                c[3][k] = imz;
            } else {
                let im = DD::new(r.sym(), r.sym() * 1e-17);
                c[2][k] = im.hi;
                c[3][k] = im.lo;
            }
        }
    }
    (ld, c)
}

/// the matrices of `complex_logdet_skipping_is_every_update`, by family: block-bidiagonal multiple-shooting layouts
/// (blocks of m rows coupling node b - 1 and node b), random sparse ones, both complex and real with imaginary parts
/// -0 (where the sign of a negative real pivot's zero imaginary part is arg +-pi), and the entries skipping must
/// not pass by: an Inf, a NaN, a non-normalized entry, and an overflow during the elimination (in one panel of the
/// blocked elimination and across panels), and a non-normalized pivot whose reciprocal is not finite
#[allow(clippy::type_complexity)]
fn skip_cases() -> Vec<(&'static str, usize, usize, [Vec<f64>; 4])> {
    let mut r = Rng(86);
    let mut out = Vec::new();
    let shooting = |m: usize| move |i: usize, j: usize, _: &mut Rng| !(j / m == i / m || j / m + 1 == i / m);
    for (k, m) in [(4usize, 8usize), (6, 12), (9, 16)] {
        let n = k * m;
        let (ld, c) = patterned(n, &mut r, shooting(m), false, 0.0, 0.0);
        out.push(("shooting", n, ld, c));
        let (ld, c) = patterned(n, &mut r, shooting(m), true, -0.0, -1.5);
        out.push(("shooting, real, -0", n, ld, c));
    }
    for (n, d) in [(9usize, 0.3f64), (40, 0.1), (97, 0.05), (130, 0.03)] {
        let sparse = move |i: usize, j: usize, r: &mut Rng| i != j && r.unit() > d;
        let (ld, c) = patterned(n, &mut r, sparse, false, 0.0, 0.5);
        out.push(("sparse", n, ld, c));
        for _ in 0..3 {
            let (ld, c) = patterned(n, &mut r, sparse, true, -0.0, -0.5);
            out.push(("sparse, real, -0", n, ld, c));
        }
    }
    // Pivot 1 at (0, 0) over the multiplier -1 in row 9, and 4 on the rest of the diagonal. Row 9's entries right of
    // column 9 are made non-finite: Inf or NaN, or 1e308 under row 0's 1.5e308, whose update at step 0 overflows. At
    // step 9 they are the pivot row, swept over zero multipliers: every update makes the columns past 9 NaN (0 Inf,
    // 0 NaN), which skipping would leave finite. A non-normalized entry (2.5, 2.5) under row 0, in a row block with no
    // multiplier at step 0, is renormalized to 5 by step 0's sweep before its column's pivot search, where its hi part
    // alone would lose to the diagonal.
    // n 24 holds one panel of the blocked elimination; n 80 puts the rows in later panels (pivot row 41, the
    // non-normalized entry at (57, 52)), so that the trailing columns' updates meet them
    for (n, pr, (ri, cj)) in [(24usize, 9usize, (17usize, 12usize)), (80, 41, (57, 52))] {
        let base = || {
            let ld = ld_for(n);
            let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
            c[0][0] = 1.0;
            c[0][pr] = -1.0;
            for j in 1..n {
                c[0][j * ld + j] = 4.0;
            }
            (ld, c)
        };
        for (name, v) in [("Inf", f64::INFINITY), ("NaN", f64::NAN), ("overflow", 1e308)] {
            let (ld, mut c) = base();
            for j in pr + 1..n {
                c[0][j * ld + pr] = v;
                if name == "overflow" {
                    c[0][j * ld] = 1.5e308;
                }
            }
            out.push((name, n, ld, c));
        }
        let (ld, mut c) = base();
        c[0][cj * ld] = 1.0;
        c[0][cj * ld + ri] = 2.5;
        c[1][cj * ld + ri] = 2.5;
        out.push(("not normalized", n, ld, c));
    }
    // a non-normalized pivot, real part (1, -1), whose reciprocal is not finite: getf2 makes the multiplier of a zero
    // entry 0 NaN, which skipping it would leave zero
    let ld = ld_for(2);
    let mut c: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * 2]);
    (c[0][0], c[1][0], c[2][0], c[0][ld], c[0][ld + 1]) = (1.0, -1.0, 1.0, 1.0, 1.0);
    out.push(("non-finite reciprocal", 2, ld, c));
    let n = 24;
    // pivot 1 at (0, 0) with no multipliers under it and a full row 0, over a real matrix with -0 imaginary parts and
    // a negative diagonal, below row 0 diagonal (and with a few entries): step 0 sweeps every column but updates no
    // block, so every later pivot is swept by row 0 alone, its row block never updated
    for extra in [0usize, 3] {
        let few =
            move |i: usize, j: usize, _: &mut Rng| i != j && !(i == 0 || (extra > 0 && (i * 7 + j).is_multiple_of(23)));
        let (ld, mut c) = patterned(n, &mut r, few, true, -0.0, -2.0);
        for i in 1..n {
            c[0][i] = 0.0;
            c[1][i] = 0.0;
        }
        c[0][0] = 1.0;
        out.push(("row 0, real, -0", n, ld, c));
    }
    // a structured matrix large enough for the parallel path (more than 32768 updated entries per step)
    let (ld, c) = patterned(256, &mut r, shooting(64), false, 0.0, 0.0);
    out.push(("shooting, parallel", 256, ld, c));
    out
}

/// Pass, written before the first run: on every matrix of `skip_cases` (block-bidiagonal and random sparse ones,
/// complex and real with -0 imaginary parts, and ones with an Inf, a NaN, a non-normalized entry or an overflow),
/// `clu_logdet` (skipping the updates that cannot change a value) gives the results of every update
/// (`CluControl::Dense`) bit for bit: ln|det|, arg det and the pivot range, or the same error, serial and parallel.
/// Controls, which must differ from every update on at least one matrix: the pivots' imaginary parts read with the
/// signs that the skipped updates left (`SignOfZero`, on the real matrices), and skipping kept on past an entry that
/// is not a finite, normalized double-double (`KeepSkipping`, on each of the nine matrices made for it, and on no
/// other).
#[test]
fn complex_logdet_skipping_is_every_update() {
    let run = |n: usize, ld: usize, c: &[Vec<f64>; 4], par: bool, control: CluControl| {
        clu_logdet_control(
            n,
            ld,
            c[0].clone(),
            c[1].clone(),
            c[2].clone(),
            c[3].clone(),
            par,
            control,
        )
        .map(|v| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits(), v.3.to_bits()])
    };
    let mut sign_fired = 0;
    let mut keep_fired = Vec::new();
    let cases = skip_cases();
    for (name, n, ld, c) in &cases {
        let dense = run(*n, *ld, c, false, CluControl::Dense);
        for par in [false, true] {
            assert_eq!(
                run(*n, *ld, c, par, CluControl::None),
                dense,
                "{name}, n {n}, par {par}"
            );
            assert_eq!(
                run(*n, *ld, c, par, CluControl::Dense),
                dense,
                "{name}, n {n}, par {par}: dense"
            );
        }
        let plain = clu_logdet(
            n.to_owned(),
            *ld,
            c[0].clone(),
            c[1].clone(),
            c[2].clone(),
            c[3].clone(),
            false,
        );
        assert_eq!(
            plain.map(|v| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits(), v.3.to_bits()]),
            dense
        );
        let sign = run(*n, *ld, c, false, CluControl::SignOfZero) != dense;
        let keep = run(*n, *ld, c, false, CluControl::KeepSkipping) != dense;
        println!(
            "{name:<20} n {n:>3}: {:?}; controls differ: sign {sign}, keep {keep}",
            dense.as_ref().map(|b| f64::from_bits(b[1]))
        );
        sign_fired += sign as usize;
        if keep {
            keep_fired.push(*name);
        }
    }
    assert!(
        sign_fired > 0,
        "control: SignOfZero matches every update on every matrix"
    );
    assert_eq!(
        keep_fired,
        [
            "Inf",
            "NaN",
            "overflow",
            "not normalized",
            "Inf",
            "NaN",
            "overflow",
            "not normalized",
            "non-finite reciprocal"
        ],
        "control: KeepSkipping"
    );
}

/// the bits of clu_pivots_control's four numbers and records
#[allow(clippy::type_complexity)]
fn pivots_bits(
    n: usize,
    ld: usize,
    c: &[Vec<f64>; 4],
    par: bool,
    control: CluControl,
) -> Result<([u64; 4], Vec<u64>, Vec<u64>, Vec<usize>), String> {
    clu_pivots_control(
        n,
        ld,
        c[0].clone(),
        c[1].clone(),
        c[2].clone(),
        c[3].clone(),
        par,
        control,
    )
    .map(|(v, p)| {
        (
            [v.0.to_bits(), v.1.to_bits(), v.2.to_bits(), v.3.to_bits()],
            p.ln_abs.iter().map(|x| x.to_bits()).collect(),
            p.arg.iter().map(|x| x.to_bits()).collect(),
            p.rows,
        )
    })
}

/// the records summed as clu_logdet sums them: ln|u_kk| in order, and pi before arg u_kk at each interchange, wrapped
/// into (-pi, pi]
fn pivots_sums(p: &CluPivots) -> (f64, f64) {
    let la = p.ln_abs.iter().fold(0.0, |a, x| a + x);
    let mut arg = 0.0f64;
    for (k, (&a, &row)) in p.arg.iter().zip(&p.rows).enumerate() {
        if row != k {
            arg += std::f64::consts::PI;
        }
        arg += a;
    }
    let two_pi = 2.0 * std::f64::consts::PI;
    let mut a = arg.rem_euclid(two_pi);
    if a > std::f64::consts::PI {
        a -= two_pi;
    }
    (la, a)
}

/// clu_pivots gives clu_logdet's four numbers, and pivots that are getf2's (`CluControl::Dense`) bit for bit at every
/// column, serial and parallel, on the skipping cases (sparse, shooting, signed zeros, non-finite entries) and on
/// random matrices up to n = 300. Summed in elimination order they give ln|det| and arg det bit for bit. Control: the
/// pivots of `SignOfZero`, which reads the skipped updates' signs of zeros, differ from getf2's on some matrix.
#[test]
fn complex_pivots_are_getf2s() {
    let mut r = Rng(87);
    let mut cases: Vec<(&str, usize, usize, [Vec<f64>; 4])> = skip_cases();
    for n in [1usize, 7, 37, 129, 300] {
        let (ld, c) = cmatrix(n, &mut r);
        cases.push(("random", n, ld, c));
    }
    let mut sign_fired = 0;
    let mut checked = 0;
    for (name, n, ld, c) in &cases {
        let dense = pivots_bits(*n, *ld, c, false, CluControl::Dense);
        for par in [false, true] {
            assert_eq!(
                pivots_bits(*n, *ld, c, par, CluControl::None),
                dense,
                "{name}, n {n}, par {par}"
            );
        }
        let plain = clu_logdet(*n, *ld, c[0].clone(), c[1].clone(), c[2].clone(), c[3].clone(), false)
            .map(|v| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits(), v.3.to_bits()]);
        assert_eq!(
            plain,
            dense.as_ref().map(|d| d.0).map_err(|e| e.clone()),
            "{name}, n {n}: clu_logdet"
        );
        if let Ok(((la, arg, _, _), p)) =
            clu_pivots(*n, *ld, c[0].clone(), c[1].clone(), c[2].clone(), c[3].clone(), false)
        {
            assert_eq!(
                (p.ln_abs.len(), p.arg.len(), p.rows.len()),
                (*n, *n, *n),
                "{name}, n {n}"
            );
            let (sl, sa) = pivots_sums(&p);
            assert_eq!(
                [sl.to_bits(), sa.to_bits()],
                [la.to_bits(), arg.to_bits()],
                "{name}, n {n}: sums"
            );
            checked += 1;
        }
        sign_fired += (pivots_bits(*n, *ld, c, false, CluControl::SignOfZero) != dense) as usize;
    }
    assert!(checked >= 20, "only {checked} matrices factored");
    assert!(
        sign_fired > 0,
        "control: SignOfZero's pivots are getf2's on every matrix"
    );
}

/// Control of the pivot comparison: one entry moved by 1e-12 relative changes a recorded pivot. Planted: a diagonal
/// matrix with decreasing |d_k| has no interchanges and pivots d_k, so ln|u_kk| = ln|d_k| and arg u_kk = arg d_k.
#[test]
fn complex_pivots_planted_and_control() {
    let mut r = Rng(88);
    let (n, (ld, c)) = (37, cmatrix(37, &mut r));
    let a = pivots_bits(n, ld, &c, false, CluControl::None).unwrap();
    let mut moved = c.clone();
    moved[0][5 * ld + 11] *= 1.0 + 1e-12;
    let b = pivots_bits(n, ld, &moved, false, CluControl::None).unwrap();
    assert_ne!(
        (a.1, a.2),
        (b.1, b.2),
        "control: a moved entry left every pivot as it was"
    );

    let (n, ld) = (12, 16);
    let mut m: [Vec<f64>; 4] = std::array::from_fn(|_| vec![0.0; ld * n]);
    let d: Vec<(f64, f64)> = (0..n)
        .map(|k| (0.5f64.powi(k as i32), -(0.25f64.powi(k as i32))))
        .collect();
    for (k, &(re, im)) in d.iter().enumerate() {
        m[0][k * ld + k] = re;
        m[2][k * ld + k] = im;
    }
    let (_, p) = clu_pivots(n, ld, m[0].clone(), m[1].clone(), m[2].clone(), m[3].clone(), false).unwrap();
    for (k, &(re, im)) in d.iter().enumerate() {
        assert!((p.ln_abs[k] - re.hypot(im).ln()).abs() < 1e-15, "k {k}");
        assert!((p.arg[k] - im.atan2(re)).abs() < 1e-15, "k {k}");
    }
    assert_eq!(p.rows, (0..n).collect::<Vec<_>>());
}

// ---------------------------------------------------------------------------------------------------------------
// pinned outputs of the double-double LUs
// ---------------------------------------------------------------------------------------------------------------

/// the bits of the pinned double-double LU outputs, by group. nudge flips the last bit of one
/// matrix entry's leading part and of one right-hand side's.
fn dd_lu_outputs(nudge: bool) -> Vec<Vec<u64>> {
    let ddb = |v: &[DD]| -> Vec<u64> { v.iter().flat_map(|d| [d.hi.to_bits(), d.lo.to_bits()]).collect() };
    let flip = |x: f64| f64::from_bits(x.to_bits() ^ 1);
    let mut r = Rng(57);
    let mut w = vec![Vec::new(); 4];
    // unblocked (n = 37, a partial last row block) and blocked (n = 100, at least BLOCKED_MIN)
    for n in [37, 100] {
        let (ld, mut hi, lo) = matrix(n, &mut r);
        let mut b: Vec<DD> = (0..n).map(|_| DD::new(r.sym(), r.sym() * 1e-17)).collect();
        if nudge {
            hi[3 * ld + 5] = flip(hi[3 * ld + 5]);
            b[5].hi = flip(b[5].hi);
        }
        let lu = DDLu::factor(n, ld, hi, lo, false).unwrap();
        w[0].extend(lu.hi.iter().chain(&lu.lo).map(|x| x.to_bits()));
        let (mut x, mut y) = (b.clone(), b.clone());
        lu.solve(&mut x);
        lu.solve_t(&mut y);
        w[1].extend([ddb(&x), ddb(&y)].concat());
        // three right-hand sides at once, row-major: b, b / 3 and -b
        let rows: Vec<DD> = [DD::ONE, DD::ONE / DD::from_f64(3.0), -DD::ONE]
            .iter()
            .flat_map(|&s| b.iter().map(move |&v| v * s))
            .collect();
        for transpose in [false, true] {
            let mut bh: Vec<f64> = rows.iter().map(|d| d.hi).collect();
            let mut bl: Vec<f64> = rows.iter().map(|d| d.lo).collect();
            lu.solve_many(&mut bh, &mut bl, 3, transpose, false);
            w[2].extend(bh.iter().chain(&bl).map(|x| x.to_bits()));
        }
    }
    // the staircase LU: f64 factors, double-double solves
    let (mut m, n, ld, groups, rblocks) = staircase_system(10, 20, 4, 9, 1);
    let mut rhs: Vec<DD> = (0..n)
        .map(|i| DD::new(r.sym(), r.sym() * 1e-17) + DD::from_f64((i % 5) as f64))
        .collect();
    if nudge {
        let k = m.iter().position(|&v| v != 0.0).unwrap();
        m[k] = flip(m[k]);
        rhs[5].hi = flip(rhs[5].hi);
    }
    let lu = staircase(&m, n, ld, &groups, &rblocks, StaircaseControl::None);
    let (mut x, mut y) = (rhs.clone(), rhs);
    lu.solve(&mut x);
    lu.solve_t(&mut y);
    w[3].extend([ddb(&x), ddb(&y)].concat());
    w
}

/// The double-double LUs' outputs pinned bit for bit on fixed systems, against hashes recorded
/// with 4.1.1: `DDLu`'s factors (unblocked and blocked), its solves and transposed solves, and
/// `solve_many`, and `StaircaseLu`'s solves. Every backend gives these bits. Control: one matrix
/// entry's and one right-hand side's last bit flipped changes every group's hash.
#[test]
fn dd_lu_pinned_bits() {
    let names = [
        "DDLu factors",
        "DDLu solve and solve_t",
        "DDLu solve_many",
        "StaircaseLu solves",
    ];
    let want: [u64; 4] = [
        0x8e3a_e860_eecc_2d17,
        0xe5e9_7df9_7f28_dfa5,
        0xb206_154b_6241_e18f,
        0xbdec_2753_3135_a6d9,
    ];
    common::assert_pinned(&names, &dd_lu_outputs(false), &dd_lu_outputs(true), &want);
}