ruxla-kernels 0.1.0

Internal crate of ruxla (use the `ruxla` crate): semantics of ruxla's operations, shared by the native backend and the IR interpreter
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
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
//! Linear algebra on batches of row-major matrices: Cholesky, triangular
//! solves, LU, QR, symmetric eigendecomposition, and SVD.
//!
//! The results follow the conventions of the LAPACK routines that JAX calls
//! on CPU, so that ruxla computes what JAX computes (up to rounding, since
//! the algorithms differ in their order of operations):
//!
//! - [`cholesky`] (`potrf`): the lower factor in the lower triangle; the
//!   strictly upper triangle of the input is left as it is; a matrix that
//!   is not positive definite gives NaNs everywhere, as JAX returns;
//! - [`triangular_solve`] (`trsm`): only the triangle given by `lower` is
//!   read (and not the diagonal for a unit diagonal);
//! - [`lu`] (`getrf`): partial pivoting choosing the first row with the
//!   largest absolute value in the column, row swaps applied to whole rows,
//!   and the multipliers scaled by the reciprocal of the pivot;
//! - [`qr`] (`geqrf` and `orgqr`): Householder reflectors with LAPACK's
//!   `larfg` convention (`beta = -sign(alpha) * norm`), so the signs of `Q`
//!   and of the diagonal of `R` match LAPACK's;
//! - [`eigh`] (`syevd`): eigenvalues in ascending order, only the triangle
//!   given by `lower` read;
//! - [`svd`] (`gesdd`): singular values in descending order.
//!
//! Eigenvectors and singular vectors are only defined up to sign (and up to
//! a basis of each repeated eigenvalue), which LAPACK leaves to its
//! algorithm. ruxla computes the eigendecomposition as LAPACK's `syev`
//! does (the reduction to tridiagonal form and the implicit QL or QR
//! algorithm, `steqr`), and the singular value decomposition as `gesvd`
//! does (the reduction to bidiagonal form and `bdsqr`; one-sided Jacobi
//! rotations on request), and then makes the component of largest magnitude of
//! each eigenvector (of each left singular vector) positive, which is
//! continuous in the input. Inputs with
//! infinities or NaNs give NaNs for `eigh` and `svd` (where LAPACK reports
//! an error, which JAX turns into NaNs).
//!
//! Complex matrices (`c64`, `c128`) follow the conventions of the complex
//! LAPACK routines (`zpotrf`, `ztrsm`, `zgetrf`, `zgeqrf` and `zungqr`,
//! `zheevd`, `zgesdd`): conjugate transposes in place of transposes, the
//! pivots of `getrf` chosen by `|re| + |im|` (BLAS's `izamax`), Householder
//! reflectors with `zlarfg`'s convention (a real `beta`), and real
//! eigenvalues and singular values. Eigenvectors and singular vectors are
//! defined up to a phase; ruxla makes the component of largest magnitude of
//! each real and positive.

use std::ops::{Add, Div, Mul, Neg, Sub};

use crate::complex::Complex;
use crate::dtype::Element;

mod bidiagonal;
mod eig;
mod products;
mod tridiagonal;
pub use eig::{Cx, eig, hessenberg, schur};
pub use products::{cholesky_update, symmetric_product};
pub use tridiagonal::{tridiagonal, tridiagonal_solve};

mod sealed {
    pub trait Sealed {}
    impl Sealed for f32 {}
    impl Sealed for f64 {}
    impl Sealed for super::Complex<f32> {}
    impl Sealed for super::Complex<f64> {}
}

/// The real element types of linear algebra: `f32` and `f64`.
pub trait LinalgFloat: LinalgScalar<LinalgReal = Self> + PartialOrd + sealed::Sealed {
    /// The machine epsilon (`dlamch('E')` is half of it).
    const EPSILON: Self;
    /// The smallest positive normal number (`dlamch('S')`).
    const MIN_POSITIVE: Self;
    /// The square root.
    fn sqrt(self) -> Self;
    /// `sqrt(self^2 + other^2)` without undue overflow.
    fn hypot(self, other: Self) -> Self;
    /// `|self|` with the sign of `sign`.
    fn copysign(self, sign: Self) -> Self;
    /// Whether the value is NaN.
    fn is_nan(self) -> bool;
    /// The complex type of this real type (`c64` for `f32`).
    type Complex: LinalgScalar<LinalgReal = Self>;
}

/// The element types of linear algebra: `f32`, `f64`, `c64`, and `c128`.
pub trait LinalgScalar:
    Element<Real = <Self as LinalgScalar>::LinalgReal>
    + Add<Output = Self>
    + Sub<Output = Self>
    + Mul<Output = Self>
    + Div<Output = Self>
    + Neg<Output = Self>
    + PartialEq
    + sealed::Sealed
{
    /// The real type of the absolute values (`Self` for real types; the
    /// element type's `Real`, whose `re`, `im`, and `from_parts` the
    /// algorithms use).
    type LinalgReal: LinalgFloat;
    /// Whether the type is complex.
    const IS_COMPLEX: bool;
    /// Zero.
    const ZERO: Self;
    /// One.
    const ONE: Self;
    /// NaN (in both parts for complex types).
    const NAN: Self;
    /// The complex conjugate (the value itself for real types).
    fn conj(self) -> Self;
    /// The absolute value (the modulus for complex types).
    fn abs(self) -> Self::LinalgReal;
    /// `|re| + |im|`, by which BLAS's `izamax` compares complex values (the
    /// absolute value for real types).
    fn abs1(self) -> Self::LinalgReal;
    /// `|x|^2`.
    fn abs2(self) -> Self::LinalgReal;
    /// `self * r` for a real `r`.
    fn scale(self, r: Self::LinalgReal) -> Self;
    /// Whether the value is finite (in both parts).
    fn is_finite(self) -> bool;
    /// The principal square root (NaN for negative real numbers).
    fn csqrt(self) -> Self;
    /// The value of a real number.
    fn from_real(r: Self::LinalgReal) -> Self {
        Self::from_parts(r, Self::LinalgReal::ZERO)
    }
}

macro_rules! impl_linalg_float {
    ($($t:ty)*) => {$(
        impl LinalgScalar for $t {
            type LinalgReal = $t;
            const IS_COMPLEX: bool = false;
            const ZERO: Self = 0.0;
            const ONE: Self = 1.0;
            const NAN: Self = <$t>::NAN;
            #[inline]
            fn conj(self) -> Self {
                self
            }
            #[inline]
            fn abs(self) -> Self {
                <$t>::abs(self)
            }
            #[inline]
            fn abs1(self) -> Self {
                <$t>::abs(self)
            }
            #[inline]
            fn abs2(self) -> Self {
                self * self
            }
            #[inline]
            fn scale(self, r: Self) -> Self {
                self * r
            }
            #[inline]
            fn is_finite(self) -> bool {
                <$t>::is_finite(self)
            }
            #[inline]
            fn csqrt(self) -> Self {
                <$t>::sqrt(self)
            }
            #[inline]
            fn from_real(r: Self) -> Self {
                r
            }
        }

        impl LinalgFloat for $t {
            type Complex = Complex<$t>;
            const EPSILON: Self = <$t>::EPSILON;
            const MIN_POSITIVE: Self = <$t>::MIN_POSITIVE;
            #[inline]
            fn sqrt(self) -> Self {
                <$t>::sqrt(self)
            }
            #[inline]
            fn hypot(self, other: Self) -> Self {
                <$t>::hypot(self, other)
            }
            #[inline]
            fn copysign(self, sign: Self) -> Self {
                <$t>::copysign(self, sign)
            }
            #[inline]
            fn is_nan(self) -> bool {
                <$t>::is_nan(self)
            }
        }

        impl LinalgScalar for Complex<$t> {
            type LinalgReal = $t;
            const IS_COMPLEX: bool = true;
            const ZERO: Self = Complex::new(0.0, 0.0);
            const ONE: Self = Complex::new(1.0, 0.0);
            const NAN: Self = Complex::new(<$t>::NAN, <$t>::NAN);
            #[inline]
            fn conj(self) -> Self {
                Complex::new(self.re, -self.im)
            }
            #[inline]
            fn abs(self) -> $t {
                self.re.hypot(self.im)
            }
            #[inline]
            fn abs1(self) -> $t {
                self.re.abs() + self.im.abs()
            }
            #[inline]
            fn abs2(self) -> $t {
                self.re * self.re + self.im * self.im
            }
            #[inline]
            fn scale(self, r: $t) -> Self {
                Complex::new(self.re * r, self.im * r)
            }
            #[inline]
            fn is_finite(self) -> bool {
                self.re.is_finite() && self.im.is_finite()
            }
            #[inline]
            fn csqrt(self) -> Self {
                self.sqrt()
            }
        }
    )*};
}
impl_linalg_float!(f32 f64);

/// The Cholesky factorization `A = L L^H` of each `n x n` matrix of a batch
/// of `batch` matrices, reading the lower triangle (LAPACK's `potrf` with
/// `uplo = 'L'`; only the real part of the diagonal is read).
///
/// The result has `L` in the lower triangle and the strictly upper triangle
/// of the input. A matrix that is not positive definite (or has NaNs) gives
/// NaNs everywhere.
///
/// # Panics
///
/// Panics if `a` does not have `batch * n * n` elements.
pub fn cholesky<T: LinalgScalar>(a: &[T], batch: usize, n: usize) -> Vec<T> {
    assert_eq!(a.len(), batch * n * n, "cholesky: wrong number of elements");
    let mut out = a.to_vec();
    for m in out.chunks_exact_mut((n * n).max(1)).filter(|_| n > 0) {
        if !cholesky_one(m, n) {
            m.fill(T::NAN);
        }
    }
    out
}

/// Factors one matrix in place (the lower triangle); returns `false` if it
/// is not positive definite. Left-looking, as LAPACK's `potf2`.
fn cholesky_one<T: LinalgScalar>(a: &mut [T], n: usize) -> bool {
    for j in 0..n {
        let mut ajj = a[j * n + j].re();
        for k in 0..j {
            ajj = ajj - a[j * n + k].abs2();
        }
        if ajj.is_nan() || ajj <= T::LinalgReal::ZERO {
            return false;
        }
        let ajj = ajj.sqrt();
        a[j * n + j] = T::from_real(ajj);
        let r = T::LinalgReal::ONE / ajj;
        for i in j + 1..n {
            let mut v = a[i * n + j];
            for k in 0..j {
                v = v - a[i * n + k] * a[j * n + k].conj();
            }
            a[i * n + j] = v.scale(r);
        }
    }
    true
}

/// The options of [`triangular_solve`], as in `lax.linalg.triangular_solve`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TriangularSolveOptions {
    /// Solve `op(A) X = B` if true, `X op(A) = B` if false.
    pub left_side: bool,
    /// Use the lower triangle of `A` if true, the upper if false.
    pub lower: bool,
    /// `op(A) = A^T` if true, `A` if false.
    pub transpose_a: bool,
    /// Conjugate `A` in `op(A)` (no effect for real numbers).
    pub conjugate_a: bool,
    /// Assume that the diagonal of `A` is all ones (it is not read).
    pub unit_diagonal: bool,
}

/// Solves `op(A) X = B` or `X op(A) = B` for each pair of a batch, where
/// `A` is triangular (`k x k`, `k = m` on the left side and `n` on the
/// right) and `B` is `m x n` (LAPACK's `trsm`).
///
/// # Panics
///
/// Panics if the slices do not have `batch` matrices of those sizes.
pub fn triangular_solve<T: LinalgScalar>(
    a: &[T],
    b: &[T],
    batch: usize,
    m: usize,
    n: usize,
    options: TriangularSolveOptions,
) -> Vec<T> {
    let k = if options.left_side { m } else { n };
    assert_eq!(a.len(), batch * k * k, "triangular_solve: wrong size of a");
    assert_eq!(b.len(), batch * m * n, "triangular_solve: wrong size of b");
    let mut out = b.to_vec();
    if k == 0 || m * n == 0 {
        return out;
    }
    let conjugate = options.conjugate_a && T::IS_COMPLEX;
    for (a, x) in a.chunks_exact(k * k).zip(out.chunks_exact_mut(m * n)) {
        let conj_a: Vec<T>;
        let a = if conjugate {
            conj_a = a.iter().map(|v| v.conj()).collect();
            &conj_a[..]
        } else {
            a
        };
        if options.left_side {
            // Each column of X solves op(A) x = b.
            solve_vectors(
                a,
                k,
                options.lower,
                options.transpose_a,
                options.unit_diagonal,
                n,
                |i, c| i * n + c,
                x,
            );
        } else {
            // Each row of X solves op(A)^T x = b.
            solve_vectors(
                a,
                k,
                options.lower,
                !options.transpose_a,
                options.unit_diagonal,
                m,
                |i, r| r * n + i,
                x,
            );
        }
    }
    out
}

/// Solves `M x = b` in place for `count` vectors, where `M = A` or `A^T`
/// (`transpose`) for the triangle of `A` given by `lower`, and element `i`
/// of vector `v` is `x[index(i, v)]`.
#[allow(clippy::too_many_arguments)] // The parameters of a BLAS routine.
fn solve_vectors<T: LinalgScalar>(
    a: &[T],
    k: usize,
    lower: bool,
    transpose: bool,
    unit_diagonal: bool,
    count: usize,
    index: impl Fn(usize, usize) -> usize,
    x: &mut [T],
) {
    // M[i][j] for the stored triangle.
    let at = |i: usize, j: usize| {
        if transpose {
            a[j * k + i]
        } else {
            a[i * k + j]
        }
    };
    // M is lower triangular when A's lower triangle is used untransposed or
    // its upper triangle transposed.
    let forward = lower != transpose;
    for v in 0..count {
        let mut solve_row = |i: usize, js: &mut dyn Iterator<Item = usize>| {
            let mut s = x[index(i, v)];
            for j in js {
                s = s - at(i, j) * x[index(j, v)];
            }
            if !unit_diagonal {
                s = s / at(i, i);
            }
            x[index(i, v)] = s;
        };
        if forward {
            for i in 0..k {
                solve_row(i, &mut (0..i));
            }
        } else {
            for i in (0..k).rev() {
                solve_row(i, &mut (i + 1..k));
            }
        }
    }
}

/// The LU factorization with partial pivoting `P A = L U` of each `m x n`
/// matrix of a batch (LAPACK's `getrf`).
///
/// Returns the factors (`L` below the diagonal with an implicit unit
/// diagonal, `U` on and above it), the pivots (`min(m, n)` row swaps per
/// matrix, 0-based: row `i` was swapped with row `pivots[i]`), and the
/// permutation (`m` per matrix: row `i` of `P A` is row `permutation[i]` of
/// `A`).
///
/// # Panics
///
/// Panics if `a` does not have `batch * m * n` elements, or if `m` does not
/// fit in an `i32`.
pub fn lu<T: LinalgScalar>(
    a: &[T],
    batch: usize,
    m: usize,
    n: usize,
) -> (Vec<T>, Vec<i32>, Vec<i32>) {
    assert_eq!(a.len(), batch * m * n, "lu: wrong number of elements");
    assert!(i32::try_from(m).is_ok(), "lu: too many rows for i32 pivots");
    let k = m.min(n);
    let mut out = a.to_vec();
    let mut pivots = vec![0i32; batch * k];
    for b in 0..batch {
        let mat = &mut out[b * m * n..(b + 1) * m * n];
        let piv = &mut pivots[b * k..(b + 1) * k];
        lu_one(mat, m, n, piv);
    }
    let permutation = lu_pivots_to_permutation(&pivots, batch, k, m);
    (out, pivots, permutation)
}

/// Factors one matrix in place, right-looking as LAPACK's `getf2`.
fn lu_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize, pivots: &mut [i32]) {
    for j in 0..m.min(n) {
        // BLAS's `iamax`: the first index of the largest magnitude (`|re| +
        // |im|` for complex values; NaNs compare false, so they are only
        // chosen if they come first).
        let mut p = j;
        let mut max = a[j * n + j].abs1();
        for i in j + 1..m {
            let v = a[i * n + j].abs1();
            if v > max {
                max = v;
                p = i;
            }
        }
        pivots[j] = p as i32;
        if a[p * n + j] != T::ZERO {
            if p != j {
                for c in 0..n {
                    a.swap(j * n + c, p * n + c);
                }
            }
            let pivot = a[j * n + j];
            if pivot.abs() >= T::LinalgReal::MIN_POSITIVE {
                let r = T::ONE / pivot;
                for i in j + 1..m {
                    a[i * n + j] = a[i * n + j] * r;
                }
            } else {
                for i in j + 1..m {
                    a[i * n + j] = a[i * n + j] / pivot;
                }
            }
        }
        // The rank-one update of the trailing matrix.
        for i in j + 1..m {
            let l = a[i * n + j];
            for c in j + 1..n {
                a[i * n + c] = a[i * n + c] - l * a[j * n + c];
            }
        }
    }
}

/// Converts the pivots of [`lu`] (`k` row swaps per batch element) into
/// permutations of `size` elements: starting from the identity, swaps
/// element `i` with element `pivots[i]` for each `i` in order (as
/// `lax.linalg.lu_pivots_to_permutation`). Pivots out of range leave the
/// permutation unchanged at that step.
///
/// # Panics
///
/// Panics if `pivots` does not have `batch * k` elements.
pub fn lu_pivots_to_permutation(pivots: &[i32], batch: usize, k: usize, size: usize) -> Vec<i32> {
    assert_eq!(
        pivots.len(),
        batch * k,
        "lu_pivots_to_permutation: wrong size"
    );
    let mut out = Vec::with_capacity(batch * size);
    for b in 0..batch {
        let start = out.len();
        out.extend((0..size).map(|i| i as i32));
        let perm = &mut out[start..];
        for (i, &p) in pivots[b * k..(b + 1) * k].iter().enumerate() {
            if i < size && p >= 0 && (p as usize) < size {
                perm.swap(i, p as usize);
            }
        }
    }
    out
}

/// The 2-norm of a vector, scaled to avoid overflow and underflow (as BLAS's
/// `nrm2`, over the real and imaginary parts for complex vectors).
fn norm2<T: LinalgScalar>(x: impl Iterator<Item = T> + Clone) -> T::LinalgReal {
    let parts = x.flat_map(|v| {
        let im = T::IS_COMPLEX.then(|| v.im());
        std::iter::once(v.re()).chain(im)
    });
    let zero = T::LinalgReal::ZERO;
    let mut scale = zero;
    for v in parts.clone() {
        let a = v.abs();
        if a > scale || a.is_nan() {
            scale = a;
        }
    }
    if scale == zero || !scale.is_finite() {
        return scale;
    }
    let mut sum = zero;
    for v in parts {
        let s = v / scale;
        sum = sum + s * s;
    }
    scale * sum.sqrt()
}

/// LAPACK's `larfg` (`zlarfg` for complex numbers): the Householder
/// reflector `H = I - tau v v^H` with `v = [1, x']` such that `H^H [alpha,
/// x] = [beta, 0]` with a real `beta`. Overwrites `x` with `x'` and returns
/// `(beta, tau)`.
fn larfg<T: LinalgScalar>(alpha: T, x: &mut [T]) -> (T, T) {
    let xnorm = norm2(x.iter().copied());
    let zero = T::LinalgReal::ZERO;
    let one = T::LinalgReal::ONE;
    if xnorm == zero && alpha.im() == zero {
        return (alpha, T::ZERO);
    }
    // `dlapy3(re(alpha), im(alpha), xnorm)` (`hypot` for real numbers).
    let lapy = |alpha: T, xnorm: T::LinalgReal| {
        if T::IS_COMPLEX {
            alpha.re().hypot(alpha.im()).hypot(xnorm)
        } else {
            alpha.re().hypot(xnorm)
        }
    };
    let mut alpha = alpha;
    let mut xnorm = xnorm;
    let mut beta = -lapy(alpha, xnorm).copysign(alpha.re());
    // Rescale tiny vectors, as `larfg` does, so that `tau` is accurate.
    let safmin =
        T::LinalgReal::MIN_POSITIVE / (T::LinalgReal::EPSILON * from_f64::<T::LinalgReal>(0.5));
    let rsafmn = one / safmin;
    let mut knt = 0;
    if beta.abs() < safmin {
        while beta.abs() < safmin && knt < 20 {
            knt += 1;
            for v in x.iter_mut() {
                *v = v.scale(rsafmn);
            }
            beta = beta * rsafmn;
            alpha = alpha.scale(rsafmn);
        }
        xnorm = norm2(x.iter().copied());
        beta = -lapy(alpha, xnorm).copysign(alpha.re());
    }
    let tau = T::from_parts((beta - alpha.re()) / beta, -alpha.im() / beta);
    let r = T::ONE / (alpha - T::from_real(beta));
    for v in x.iter_mut() {
        *v = *v * r;
    }
    for _ in 0..knt {
        beta = beta * safmin;
    }
    (T::from_real(beta), tau)
}

fn from_f64<T: LinalgFloat>(v: f64) -> T {
    crate::dtype::cast::<f64, T>(v)
}

/// Applies `H = I - tau v v^H` from the left to the columns `c0..c1` of
/// the rows `r0..m` of the `? x n` matrix `a`, where `v[0] = 1` and
/// `v[1..]` is stored in column `vc` below row `r0` (LAPACK's `larf`).
#[allow(clippy::too_many_arguments)] // Matrix, reflector, and block bounds.
fn apply_reflector<T: LinalgScalar>(
    a: &mut [T],
    n: usize,
    m: usize,
    r0: usize,
    vc: usize,
    tau: T,
    c0: usize,
    c1: usize,
) {
    if tau == T::ZERO || c0 >= c1 {
        return;
    }
    let v: Vec<T> = (r0..m)
        .map(|i| if i == r0 { T::ONE } else { a[i * n + vc] })
        .collect();
    // `w = v^H A`, then `A -= v (tau w)`, row by row (each sum still runs
    // over the rows in order, so the rounding is that of the column-wise
    // loops).
    let mut w = vec![T::ZERO; c1 - c0];
    for (i, vi) in (r0..m).zip(&v) {
        let vi = vi.conj();
        for (wc, x) in w.iter_mut().zip(&a[i * n + c0..i * n + c1]) {
            *wc = *wc + vi * *x;
        }
    }
    for wc in &mut w {
        *wc = tau * *wc;
    }
    for (i, &vi) in (r0..m).zip(&v) {
        for (x, &tw) in a[i * n + c0..i * n + c1].iter_mut().zip(&w) {
            *x = *x - vi * tw;
        }
    }
}

/// The QR decomposition `A = Q R` of each `m x n` matrix of a batch, as
/// `lax.linalg.qr` computes it with LAPACK's `geqrf` and `orgqr` (`ungqr`
/// for complex numbers).
///
/// With `full_matrices`, `Q` is `m x m` and `R` is `m x n`; otherwise `Q` is
/// `m x k` and `R` is `k x n`, where `k = min(m, n)`.
///
/// # Panics
///
/// Panics if `a` does not have `batch * m * n` elements.
pub fn qr<T: LinalgScalar>(
    a: &[T],
    batch: usize,
    m: usize,
    n: usize,
    full_matrices: bool,
) -> (Vec<T>, Vec<T>) {
    let (q, r, _) = qr_impl(a, batch, m, n, full_matrices, false);
    (q, r)
}

/// The QR decomposition with column pivoting `A P = Q R` of each `m x n`
/// matrix of a batch, as `lax.linalg.qr(pivoting=True)` computes it with
/// LAPACK's `geqp3` (its unblocked `laqp2`): at each step, the column of
/// largest remaining norm (the first one, if several) is moved forward,
/// and the norms are downdated, or recomputed where the downdate loses
/// accuracy.
///
/// Returns `Q` and `R` (as [`qr`]) and the permutations (`n` per matrix,
/// 0-based: column `j` of `A P` is column `p[j]` of `A`; zeros for empty
/// matrices, as JAX returns).
///
/// # Panics
///
/// Panics if `a` does not have `batch * m * n` elements, or if `n` does not
/// fit in an `i32`.
pub fn qr_pivoting<T: LinalgScalar>(
    a: &[T],
    batch: usize,
    m: usize,
    n: usize,
    full_matrices: bool,
) -> (Vec<T>, Vec<T>, Vec<i32>) {
    assert!(
        i32::try_from(n).is_ok(),
        "qr: too many columns for i32 pivots"
    );
    qr_impl(a, batch, m, n, full_matrices, true)
}

fn qr_impl<T: LinalgScalar>(
    a: &[T],
    batch: usize,
    m: usize,
    n: usize,
    full_matrices: bool,
    pivoting: bool,
) -> (Vec<T>, Vec<T>, Vec<i32>) {
    assert_eq!(a.len(), batch * m * n, "qr: wrong number of elements");
    let k = m.min(n);
    let kq = if full_matrices { m } else { k };
    let mut q_out = Vec::with_capacity(batch * m * kq);
    let mut r_out = Vec::with_capacity(batch * kq * n);
    let mut p_out = Vec::with_capacity(if pivoting { batch * n } else { 0 });
    for mat in a.chunks_exact((m * n).max(1)).take(batch) {
        let mut r = mat.to_vec();
        let taus = if pivoting {
            let (taus, jpvt) = geqp3_one(&mut r, m, n);
            p_out.extend(jpvt);
            taus
        } else {
            geqrf_one(&mut r, m, n)
        };
        // `orgqr` on the first `kq` columns of the reflectors (padded with
        // zero columns if there are fewer).
        let mut q = vec![T::ZERO; m * kq];
        for i in 0..m {
            for j in 0..kq.min(n) {
                q[i * kq + j] = r[i * n + j];
            }
        }
        orgqr_one(&mut q, m, kq, &taus);
        q_out.extend_from_slice(&q);
        for i in 0..kq {
            for j in 0..n {
                r_out.push(if j >= i && i < m {
                    r[i * n + j]
                } else {
                    T::ZERO
                });
            }
        }
    }
    // A batch of empty matrices still has `batch` (empty or identity) Qs,
    // and zero permutations.
    if m * n == 0 {
        q_out.clear();
        r_out.clear();
        p_out.clear();
        for _ in 0..batch {
            let mut q = vec![T::ZERO; m * kq];
            orgqr_one(&mut q, m, kq, &[]);
            q_out.extend_from_slice(&q);
            r_out.extend(std::iter::repeat_n(T::ZERO, kq * n));
            if pivoting {
                p_out.extend(std::iter::repeat_n(0, n));
            }
        }
    }
    (q_out, r_out, p_out)
}

/// LAPACK's `geqp3` (`laqp2`) on one matrix in place, with all columns
/// free: `R` on and above the diagonal, the reflectors below it; returns
/// the `min(m, n)` factors `tau` and the 0-based column permutation.
fn geqp3_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize) -> (Vec<T>, Vec<i32>) {
    let k = m.min(n);
    let mut jpvt: Vec<i32> = (0..n as i32).collect();
    let mut vn1: Vec<T::LinalgReal> = (0..n)
        .map(|j| norm2((0..m).map(|r| a[r * n + j])))
        .collect();
    let mut vn2 = vn1.clone();
    let zero = T::LinalgReal::ZERO;
    let one = T::LinalgReal::ONE;
    // `sqrt(dlamch('Epsilon'))`, LAPACK's epsilon being half the machine
    // epsilon.
    let tol3z = (T::LinalgReal::EPSILON * from_f64::<T::LinalgReal>(0.5)).sqrt();
    let mut taus = Vec::with_capacity(k);
    for i in 0..k {
        // BLAS's `idamax` over the remaining norms.
        let mut pvt = i;
        let mut max = vn1[i];
        for (j, &v) in vn1.iter().enumerate().skip(i + 1) {
            if v > max {
                max = v;
                pvt = j;
            }
        }
        if pvt != i {
            for r in 0..m {
                a.swap(r * n + pvt, r * n + i);
            }
            jpvt.swap(pvt, i);
            vn1[pvt] = vn1[i];
            vn2[pvt] = vn2[i];
        }
        let mut x: Vec<T> = (i + 1..m).map(|r| a[r * n + i]).collect();
        let (beta, tau) = larfg(a[i * n + i], &mut x);
        for (r, v) in (i + 1..m).zip(x) {
            a[r * n + i] = v;
        }
        a[i * n + i] = beta;
        apply_reflector(a, n, m, i, i, tau.conj(), i + 1, n);
        taus.push(tau);
        // Downdate the norms of the remaining columns.
        for j in i + 1..n {
            if vn1[j] == zero {
                continue;
            }
            let ratio = a[i * n + j].abs() / vn1[j];
            let temp = one - ratio * ratio;
            let temp = if temp > zero { temp } else { zero };
            let scale = vn1[j] / vn2[j];
            let temp2 = temp * scale * scale;
            if temp2 <= tol3z {
                if i + 1 < m {
                    vn1[j] = norm2((i + 1..m).map(|r| a[r * n + j]));
                    vn2[j] = vn1[j];
                } else {
                    vn1[j] = zero;
                    vn2[j] = zero;
                }
            } else {
                vn1[j] = vn1[j] * temp.sqrt();
            }
        }
    }
    (taus, jpvt)
}

/// The first `n` columns of the product `Q = H_0 H_1 ... H_{k-1}` of the
/// Householder reflectors stored below the diagonal of the first `k`
/// columns of each `m x n` matrix of a batch (`m >= n >= k`), as LAPACK's
/// `orgqr` (`ungqr`) and `lax.linalg.householder_product`.
///
/// # Panics
///
/// Panics if the slices do not have `batch` matrices and `batch` vectors of
/// `k` factors, or if `m < n` or `n < k`.
pub fn householder_product<T: LinalgScalar>(
    a: &[T],
    taus: &[T],
    batch: usize,
    m: usize,
    n: usize,
    k: usize,
) -> Vec<T> {
    assert!(m >= n && n >= k, "householder_product: needs m >= n >= k");
    assert_eq!(
        a.len(),
        batch * m * n,
        "householder_product: wrong size of a"
    );
    assert_eq!(
        taus.len(),
        batch * k,
        "householder_product: wrong size of taus"
    );
    let mut out = a.to_vec();
    for b in 0..batch {
        orgqr_one(
            &mut out[b * m * n..(b + 1) * m * n],
            m,
            n,
            &taus[b * k..(b + 1) * k],
        );
    }
    out
}

/// Multiplies each `rows x cols` matrix `c` of a batch by `Q` (`Q^H` with
/// `transpose`) from the left (`left`) or the right, where `Q = H_0 ...
/// H_{k-1}` is given by the reflectors below the diagonal of the first `k`
/// columns of the `m x n` matrix `a` (`m` = `rows` from the left, `cols`
/// from the right) and the factors `taus`, without forming `Q` (LAPACK's
/// `ormqr`, `unmqr`, and `lax.linalg.ormqr`).
///
/// # Panics
///
/// Panics if the slices do not have the sizes of a batch of these.
#[allow(clippy::too_many_arguments)] // The shapes and options of `ormqr`.
pub fn ormqr<T: LinalgScalar>(
    a: &[T],
    taus: &[T],
    c: &[T],
    batch: usize,
    (m, n, k): (usize, usize, usize),
    (rows, cols): (usize, usize),
    left: bool,
    transpose: bool,
) -> Vec<T> {
    assert_eq!(a.len(), batch * m * n, "ormqr: wrong size of a");
    assert_eq!(taus.len(), batch * k, "ormqr: wrong size of taus");
    assert_eq!(c.len(), batch * rows * cols, "ormqr: wrong size of c");
    assert_eq!(
        if left { rows } else { cols },
        m,
        "ormqr: incompatible shapes"
    );
    let mut out = c.to_vec();
    for b in 0..batch {
        let a = &a[b * m * n..(b + 1) * m * n];
        let taus = &taus[b * k..(b + 1) * k];
        let c = &mut out[b * rows * cols..(b + 1) * rows * cols];
        // `Q c` and `c Q^H` apply the reflectors in reverse order.
        let reverse = left != transpose;
        for step in 0..k {
            let i = if reverse { k - 1 - step } else { step };
            let tau = if transpose { taus[i].conj() } else { taus[i] };
            if tau == T::ZERO {
                continue;
            }
            // `v[r]` for `r >= i` (`v[i] = 1`).
            let v = |r: usize| if r == i { T::ONE } else { a[r * n + i] };
            if left {
                // `c := c - tau v (v^H c)`.
                for col in 0..cols {
                    let mut w = T::ZERO;
                    for r in i..m {
                        w = w + v(r).conj() * c[r * cols + col];
                    }
                    let tw = tau * w;
                    for r in i..m {
                        c[r * cols + col] = c[r * cols + col] - v(r) * tw;
                    }
                }
            } else {
                // `c := c - tau (c v) v^H`.
                for row in 0..rows {
                    let mut w = T::ZERO;
                    for r in i..m {
                        w = w + c[row * cols + r] * v(r);
                    }
                    let tw = w * tau;
                    for r in i..m {
                        c[row * cols + r] = c[row * cols + r] - tw * v(r).conj();
                    }
                }
            }
        }
    }
    out
}

/// LAPACK's `geqr2` on one matrix in place: `R` on and above the diagonal,
/// the reflectors below it; returns the `min(m, n)` factors `tau`.
fn geqrf_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize) -> Vec<T> {
    let k = m.min(n);
    let mut taus = Vec::with_capacity(k);
    for i in 0..k {
        let mut x: Vec<T> = (i + 1..m).map(|r| a[r * n + i]).collect();
        let (beta, tau) = larfg(a[i * n + i], &mut x);
        for (r, v) in (i + 1..m).zip(x) {
            a[r * n + i] = v;
        }
        a[i * n + i] = beta;
        // `geqr2` applies `H^H` to the rest of the matrix.
        apply_reflector(a, n, m, i, i, tau.conj(), i + 1, n);
        taus.push(tau);
    }
    taus
}

/// LAPACK's `org2r` (`ung2r`) on one `m x nq` matrix in place: forms the
/// first `nq` columns of `Q = H_0 H_1 ... H_{k-1}` from the reflectors
/// stored below the diagonal of its first `k = taus.len()` columns.
fn orgqr_one<T: LinalgScalar>(a: &mut [T], m: usize, nq: usize, taus: &[T]) {
    let k = taus.len();
    // Columns k..nq start as columns of the identity.
    for j in k..nq {
        for i in 0..m {
            a[i * nq + j] = T::ZERO;
        }
        if j < m {
            a[j * nq + j] = T::ONE;
        }
    }
    for i in (0..k).rev() {
        if i + 1 < nq {
            a[i * nq + i] = T::ONE;
            apply_reflector(a, nq, m, i, i, taus[i], i + 1, nq);
        }
        for r in i + 1..m {
            a[r * nq + i] = -taus[i] * a[r * nq + i];
        }
        a[i * nq + i] = T::ONE - taus[i];
        for r in 0..i {
            a[r * nq + i] = T::ZERO;
        }
    }
}

/// Makes the component of largest magnitude of column `c` of the `rows x
/// cols` matrix `v` real and positive (the first one, if several have it):
/// negates the column for real numbers, multiplies it by a phase for
/// complex ones. Returns the factor applied, if any.
fn normalize_phase<T: LinalgScalar>(v: &mut [T], rows: usize, cols: usize, c: usize) -> Option<T> {
    let mut best = 0;
    let mut max = T::LinalgReal::ZERO;
    for r in 0..rows {
        let a = v[r * cols + c].abs();
        if a > max {
            max = a;
            best = r;
        }
    }
    if rows == 0 {
        return None;
    }
    let z = v[best * cols + c];
    if !T::IS_COMPLEX {
        if z.re() < T::LinalgReal::ZERO {
            for r in 0..rows {
                v[r * cols + c] = -v[r * cols + c];
            }
            return Some(-T::ONE);
        }
        return None;
    }
    if z.im() == T::LinalgReal::ZERO && z.re() >= T::LinalgReal::ZERO {
        return None;
    }
    // `conj(z) / |z|`; the component itself becomes exactly `|z|`.
    let f = T::from_parts(z.re() / max, -z.im() / max);
    for r in 0..rows {
        v[r * cols + c] = v[r * cols + c] * f;
    }
    v[best * cols + c] = T::from_real(max);
    Some(f)
}

/// The phase that makes the off-diagonal element `x` of a rotation real:
/// `(|x|, conj(x) / |x|)`; real numbers keep their sign (`(x, 1)`), so that
/// the rotations of real matrices are the plain Jacobi rotations.
fn rotation_phase<T: LinalgScalar>(x: T) -> (T::LinalgReal, Option<T>) {
    if T::IS_COMPLEX {
        let mag = x.abs();
        (mag, Some(T::from_parts(x.re() / mag, -x.im() / mag)))
    } else {
        (x.re(), None)
    }
}

/// The maximum number of Jacobi sweeps; they converge quadratically, in
/// about ten sweeps for any size in practice.
const MAX_SWEEPS: usize = 60;

/// The eigendecomposition `A = V diag(w) V^H` of each Hermitian (symmetric
/// for real numbers) `n x n` matrix of a batch, reading the triangle given
/// by `lower` (LAPACK's `syevd` and `heevd`; only the real part of the
/// diagonal is read), by the reduction to tridiagonal form and the QL or QR
/// algorithm (LAPACK's `syev`), or with `jacobi`, by cyclic Jacobi
/// rotations.
///
/// Returns the eigenvectors (`V`, one per column) and the real eigenvalues
/// (`w`, in ascending order, which `sort_eigenvalues = false` allows but
/// does not require changing). Matrices with infinities or NaNs in the
/// triangle give NaNs.
///
/// # Panics
///
/// Panics if `a` does not have `batch * n * n` elements.
pub fn eigh<T: LinalgScalar>(
    a: &[T],
    batch: usize,
    n: usize,
    lower: bool,
    jacobi: bool,
) -> (Vec<T>, Vec<T::LinalgReal>) {
    assert_eq!(a.len(), batch * n * n, "eigh: wrong number of elements");
    let mut vs = Vec::with_capacity(batch * n * n);
    let mut ws = Vec::with_capacity(batch * n);
    for b in 0..batch {
        let mat = &a[b * n * n..(b + 1) * n * n];
        let (v, w) = eigh_one(mat, n, lower, jacobi);
        vs.extend(v);
        ws.extend(w);
    }
    (vs, ws)
}

fn eigh_one<T: LinalgScalar>(
    a: &[T],
    n: usize,
    lower: bool,
    jacobi: bool,
) -> (Vec<T>, Vec<T::LinalgReal>) {
    // The Hermitian matrix of the triangle.
    let mut s = vec![T::ZERO; n * n];
    let mut finite = true;
    for i in 0..n {
        for j in 0..=i {
            // Element (i, j) of the lower triangle.
            let v = if lower {
                a[i * n + j]
            } else {
                a[j * n + i].conj()
            };
            finite &= v.is_finite();
            if i == j {
                s[i * n + i] = T::from_real(v.re());
            } else {
                s[i * n + j] = v;
                s[j * n + i] = v.conj();
            }
        }
    }
    if !finite {
        return (vec![T::NAN; n * n], vec![T::LinalgReal::NAN; n]);
    }
    let solved = if jacobi {
        Some(eigh_jacobi(s, n))
    } else {
        tridiagonal::eigh_tridiagonal(&s, n)
    };
    let Some((mut sorted, w)) = solved else {
        return (vec![T::NAN; n * n], vec![T::LinalgReal::NAN; n]);
    };
    for c in 0..n {
        normalize_phase(&mut sorted, n, n, c);
    }
    (sorted, w)
}

/// The eigendecomposition of the Hermitian `n x n` matrix `s` (both
/// triangles) by cyclic Jacobi rotations: the eigenvectors (columns) and
/// the eigenvalues in ascending order.
fn eigh_jacobi<T: LinalgScalar>(mut s: Vec<T>, n: usize) -> (Vec<T>, Vec<T::LinalgReal>) {
    let mut v = vec![T::ZERO; n * n];
    for i in 0..n {
        v[i * n + i] = T::ONE;
    }
    // Rotations below this size of the off-diagonal element change nothing
    // representable.
    let fro = norm2(s.iter().copied());
    let floor = fmax(
        T::LinalgReal::MIN_POSITIVE,
        fro * T::LinalgReal::EPSILON * T::LinalgReal::EPSILON,
    );
    let one = T::LinalgReal::ONE;
    for _ in 0..MAX_SWEEPS {
        let mut rotated = false;
        for p in 0..n {
            for q in p + 1..n {
                let apq = s[p * n + q];
                let (app, aqq) = (s[p * n + p].re(), s[q * n + q].re());
                // Skip elements negligible relative to the diagonal, which
                // gives eigenvalues with high relative accuracy.
                let mag = apq.abs();
                if mag <= floor || mag <= T::LinalgReal::EPSILON * (app.abs() * aqq.abs()).sqrt() {
                    continue;
                }
                rotated = true;
                // For complex matrices, column q is first multiplied by the
                // phase `u` that makes element (p, q) real.
                let (apq, u) = rotation_phase(apq);
                let phase = |x: T| u.map_or(x, |u| x * u);
                let theta = (aqq - app) / (apq + apq);
                let t = one.copysign(theta) / (theta.abs() + one.hypot(theta));
                let c = one / one.hypot(t);
                let sn = t * c;
                s[p * n + p] = T::from_real(app - t * apq);
                s[q * n + q] = T::from_real(aqq + t * apq);
                s[p * n + q] = T::ZERO;
                s[q * n + p] = T::ZERO;
                for r in 0..n {
                    if r != p && r != q {
                        let (arp, arq) = (s[r * n + p], phase(s[r * n + q]));
                        let np = arp.scale(c) - arq.scale(sn);
                        let nq = arp.scale(sn) + arq.scale(c);
                        s[r * n + p] = np;
                        s[p * n + r] = np.conj();
                        s[r * n + q] = nq;
                        s[q * n + r] = nq.conj();
                    }
                    let (vrp, vrq) = (v[r * n + p], phase(v[r * n + q]));
                    v[r * n + p] = vrp.scale(c) - vrq.scale(sn);
                    v[r * n + q] = vrp.scale(sn) + vrq.scale(c);
                }
            }
        }
        if !rotated {
            break;
        }
    }
    // Ascending eigenvalues; the sort is stable.
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by(|&i, &j| {
        s[i * n + i]
            .re()
            .partial_cmp(&s[j * n + j].re())
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    let w: Vec<T::LinalgReal> = order.iter().map(|&i| s[i * n + i].re()).collect();
    let mut sorted = vec![T::ZERO; n * n];
    for (c, &i) in order.iter().enumerate() {
        for r in 0..n {
            sorted[r * n + c] = v[r * n + i];
        }
    }
    (sorted, w)
}

/// The larger of two values (the first if either is NaN).
fn fmax<T: LinalgFloat>(a: T, b: T) -> T {
    if b > a { b } else { a }
}

/// The singular value decomposition `A = U diag(s) V^H` of each `m x n`
/// matrix of a batch (what JAX computes with LAPACK's `gesdd`), by
/// bidiagonalization and the QR algorithm (LAPACK's `gesvd`), or with
/// `jacobi`, by one-sided Jacobi rotations.
///
/// Returns the real singular values (`min(m, n)` per matrix, in descending
/// order), and, with `compute_uv`, `U` and `V^H`: `m x m` and `n x n` with
/// `full_matrices`, `m x k` and `k x n` otherwise (`k = min(m, n)`).
/// Matrices with infinities or NaNs, and matrices on which the QR
/// algorithm does not converge, give NaNs.
///
/// # Panics
///
/// Panics if `a` does not have `batch * m * n` elements.
pub fn svd<T: LinalgScalar>(
    a: &[T],
    batch: usize,
    m: usize,
    n: usize,
    full_matrices: bool,
    compute_uv: bool,
    jacobi: bool,
) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
    assert_eq!(a.len(), batch * m * n, "svd: wrong number of elements");
    let k = m.min(n);
    let (ucols, vrows) = if full_matrices { (m, n) } else { (k, k) };
    let mut s_out = Vec::with_capacity(batch * k);
    let mut u_out = Vec::new();
    let mut vt_out = Vec::new();
    for b in 0..batch {
        let mat = &a[b * m * n..(b + 1) * m * n];
        let (s, u, vt) = svd_one(mat, m, n, ucols, vrows, jacobi);
        s_out.extend(s);
        if compute_uv {
            u_out.extend(u);
            vt_out.extend(vt);
        }
    }
    (s_out, u_out, vt_out)
}

/// The SVD of one matrix: `s`, `U` (`m x ucols`), and `V^H` (`vrows x n`),
/// by bidiagonalization (or one-sided Jacobi rotations with `jacobi`).
fn svd_one<T: LinalgScalar>(
    a: &[T],
    m: usize,
    n: usize,
    ucols: usize,
    vrows: usize,
    jacobi: bool,
) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
    let k = m.min(n);
    if a.iter().any(|v| !v.is_finite()) {
        return (
            vec![T::LinalgReal::NAN; k],
            vec![T::NAN; m * ucols],
            vec![T::NAN; vrows * n],
        );
    }
    // One-sided Jacobi on the columns of the taller orientation: `g` is
    // `rows x cols` with `rows >= cols`, `g = A` or `A^H`, stored by columns
    // (`g[c * rows + r]`, so that the rotations read contiguous memory), and
    // so is the accumulated rotation `w`.
    let tall = m >= n;
    let (rows, cols) = if tall { (m, n) } else { (n, m) };
    let mut g = vec![T::ZERO; rows * cols];
    for i in 0..m {
        for j in 0..n {
            if tall {
                g[j * rows + i] = a[i * n + j];
            } else {
                g[i * rows + j] = a[i * n + j].conj();
            }
        }
    }
    let solved = if jacobi {
        Some(svd_jacobi(g, rows, cols))
    } else {
        let mut row_major = vec![T::ZERO; rows * cols];
        for c in 0..cols {
            for r in 0..rows {
                row_major[r * cols + c] = g[c * rows + r];
            }
        }
        bidiagonal::svd_bidiagonal(&row_major, rows, cols)
    };
    let Some((s, mut left, mut right)) = solved else {
        return (
            vec![T::LinalgReal::NAN; k],
            vec![T::NAN; m * ucols],
            vec![T::NAN; vrows * n],
        );
    };
    // Phases: the largest component of each left singular vector of A (the
    // columns of U) is real and positive; V follows for nonzero singular
    // values.
    let (u_full, v_full) = if tall {
        (&mut left, &mut right)
    } else {
        (&mut right, &mut left)
    };
    let (urows, vdim) = (m, n);
    for c in 0..urows {
        let factor = normalize_phase(u_full, urows, urows, c);
        if let Some(f) = factor
            && c < k
            && s[c] > T::LinalgReal::ZERO
        {
            for r in 0..vdim {
                v_full[r * vdim + c] = if T::IS_COMPLEX {
                    v_full[r * vdim + c] * f
                } else {
                    -v_full[r * vdim + c]
                };
            }
        }
    }
    for c in 0..vdim {
        let paired = s.get(c).is_some_and(|&sc| sc > T::LinalgReal::ZERO);
        if !paired {
            normalize_phase(v_full, vdim, vdim, c);
        }
    }
    let mut u = Vec::with_capacity(m * ucols);
    for r in 0..m {
        u.extend_from_slice(&u_full[r * m..r * m + ucols]);
    }
    let mut vt = Vec::with_capacity(vrows * n);
    for c in 0..vrows {
        for r in 0..n {
            vt.push(v_full[r * n + c].conj());
        }
    }
    (s, u, vt)
}

/// The one-sided Jacobi SVD of `g` (`rows x cols`, `rows >= cols`, stored
/// by columns: `g[c * rows + r]`): the singular values in descending order,
/// the left singular vectors completed to an orthonormal basis (`rows x
/// rows`, row-major), and the right ones (`cols x cols`).
#[allow(clippy::type_complexity)] // the three factors
fn svd_jacobi<T: LinalgScalar>(
    mut g: Vec<T>,
    rows: usize,
    cols: usize,
) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
    let mut w = vec![T::ZERO; cols * cols];
    for i in 0..cols {
        w[i * cols + i] = T::ONE;
    }
    // `g_i^H g_j`.
    let col_dot = |g: &[T], i: usize, j: usize| {
        let (gi, gj) = (&g[i * rows..(i + 1) * rows], &g[j * rows..(j + 1) * rows]);
        gi.iter()
            .zip(gj)
            .fold(T::ZERO, |s, (&x, &y)| s + x.conj() * y)
    };
    // Rotates the columns `i < j` of a matrix stored by columns of `len`.
    let rotate = |x: &mut [T], len: usize, i: usize, j: usize, c, s, phase: &dyn Fn(T) -> T| {
        let (head, tail) = x.split_at_mut(j * len);
        let (xi, xj) = (&mut head[i * len..(i + 1) * len], &mut tail[..len]);
        for (a, b) in xi.iter_mut().zip(xj.iter_mut()) {
            let (gi, gj) = (*a, phase(*b));
            *a = gi.scale(c) - gj.scale(s);
            *b = gi.scale(s) + gj.scale(c);
        }
    };
    let one = T::LinalgReal::ONE;
    let fro = norm2(g.iter().copied());
    let floor = fmax(
        T::LinalgReal::MIN_POSITIVE,
        fro * fro * T::LinalgReal::EPSILON * T::LinalgReal::EPSILON,
    );
    for _ in 0..MAX_SWEEPS {
        let mut rotated = false;
        for i in 0..cols {
            for j in i + 1..cols {
                let alpha = col_dot(&g, i, i).re();
                let beta = col_dot(&g, j, j).re();
                let gamma = col_dot(&g, i, j);
                let mag = gamma.abs();
                if mag <= floor || mag <= T::LinalgReal::EPSILON * (alpha * beta).sqrt() {
                    continue;
                }
                rotated = true;
                // For complex matrices, column j is first multiplied by the
                // phase that makes `g_i^H g_j` real.
                let (gamma, u) = rotation_phase(gamma);
                let phase = |x: T| u.map_or(x, |u| x * u);
                let zeta = (beta - alpha) / (gamma + gamma);
                let t = one.copysign(zeta) / (zeta.abs() + one.hypot(zeta));
                let c = one / one.hypot(t);
                let s = c * t;
                rotate(&mut g, rows, i, j, c, s, &phase);
                rotate(&mut w, cols, i, j, c, s, &phase);
            }
        }
        if !rotated {
            break;
        }
    }
    // Singular values are the norms of the columns, in descending order.
    let norms: Vec<T::LinalgReal> = (0..cols)
        .map(|c| norm2(g[c * rows..(c + 1) * rows].iter().copied()))
        .collect();
    let mut order: Vec<usize> = (0..cols).collect();
    order.sort_by(|&i, &j| {
        norms[j]
            .partial_cmp(&norms[i])
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    let s: Vec<T::LinalgReal> = order.iter().map(|&i| norms[i]).collect();
    // `left` (`rows x rows`): the normalized columns, completed to an
    // orthonormal basis; `right` (`cols x cols`): the rotations.
    let mut left = vec![T::ZERO; rows * rows];
    let mut have = vec![false; rows];
    let mut right = vec![T::ZERO; cols * cols];
    for (c, &i) in order.iter().enumerate() {
        let norm = norms[i];
        if norm > T::LinalgReal::ZERO {
            let r = one / norm;
            for row in 0..rows {
                left[row * rows + c] = g[i * rows + row].scale(r);
            }
            have[c] = true;
        }
        for row in 0..cols {
            right[row * cols + c] = w[i * cols + row];
        }
    }
    complete_basis(&mut left, rows, &mut have);
    (s, left, right)
}

/// Fills the columns of the `d x d` matrix `q` not marked in `have` so that
/// its columns are orthonormal, given that the marked ones are: each step
/// takes the standard basis vector with the largest component orthogonal to
/// the columns so far (orthogonalized twice).
fn complete_basis<T: LinalgScalar>(q: &mut [T], d: usize, have: &mut [bool]) {
    for c in 0..d {
        if have[c] {
            continue;
        }
        let mut best: Option<(T::LinalgReal, Vec<T>)> = None;
        for e in 0..d {
            let mut v = vec![T::ZERO; d];
            v[e] = T::ONE;
            for _ in 0..2 {
                for j in (0..d).filter(|&j| have[j]) {
                    let mut dot = T::ZERO;
                    for r in 0..d {
                        dot = dot + q[r * d + j].conj() * v[r];
                    }
                    for r in 0..d {
                        v[r] = v[r] - dot * q[r * d + j];
                    }
                }
            }
            let norm = norm2(v.iter().copied());
            if best.as_ref().is_none_or(|(b, _)| norm > *b) {
                best = Some((norm, v));
            }
        }
        let (norm, v) = best.expect("d > 0");
        let r = T::LinalgReal::ONE / norm;
        for row in 0..d {
            q[row * d + c] = v[row].scale(r);
        }
        have[c] = true;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn matmul(a: &[f64], b: &[f64], m: usize, k: usize, n: usize) -> Vec<f64> {
        let mut c = vec![0.0; m * n];
        for i in 0..m {
            for j in 0..n {
                c[i * n + j] = (0..k).map(|l| a[i * k + l] * b[l * n + j]).sum();
            }
        }
        c
    }

    fn transpose(a: &[f64], m: usize, n: usize) -> Vec<f64> {
        let mut t = vec![0.0; m * n];
        for i in 0..m {
            for j in 0..n {
                t[j * m + i] = a[i * n + j];
            }
        }
        t
    }

    fn assert_close(a: &[f64], b: &[f64], tol: f64) {
        assert_eq!(a.len(), b.len());
        for (i, (x, y)) in a.iter().zip(b).enumerate() {
            assert!(
                (x - y).abs() <= tol,
                "element {i}: {x} vs {y}\n{a:?}\n{b:?}"
            );
        }
    }

    /// A deterministic pseudo-random matrix.
    fn matrix(m: usize, n: usize, seed: u64) -> Vec<f64> {
        let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
        (0..m * n)
            .map(|_| {
                s = s
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
            })
            .collect()
    }

    fn eye(n: usize) -> Vec<f64> {
        let mut e = vec![0.0; n * n];
        for i in 0..n {
            e[i * n + i] = 1.0;
        }
        e
    }

    #[test]
    fn cholesky_of_a_textbook_matrix() {
        let a = [4.0, 12.0, -16.0, 12.0, 37.0, -43.0, -16.0, -43.0, 98.0];
        let l = cholesky(&a, 1, 3);
        // The upper triangle of the input is kept.
        assert_eq!(l, [2.0, 12.0, -16.0, 6.0, 1.0, -43.0, -8.0, 5.0, 3.0]);
        let bad = cholesky(&[1.0, 2.0, 2.0, 1.0], 1, 2);
        assert!(bad.iter().all(|v| v.is_nan()));
        assert!(cholesky::<f32>(&[], 0, 3).is_empty());
    }

    #[test]
    fn triangular_solves_invert_products() {
        let n = 4;
        let a = matrix(n, n, 1);
        let b = matrix(n, 3, 2);
        let bt = matrix(3, n, 3);
        for lower in [false, true] {
            for transpose_a in [false, true] {
                for unit_diagonal in [false, true] {
                    // The triangular matrix the solve uses.
                    let mut t = vec![0.0; n * n];
                    for i in 0..n {
                        for j in 0..n {
                            let keep = if lower { j <= i } else { j >= i };
                            if keep {
                                t[i * n + j] = if i == j {
                                    if unit_diagonal {
                                        1.0
                                    } else {
                                        a[i * n + j] + 3.0
                                    }
                                } else {
                                    a[i * n + j]
                                };
                            }
                        }
                    }
                    let mut stored = a.clone();
                    for i in 0..n {
                        stored[i * n + i] = if unit_diagonal {
                            f64::NAN
                        } else {
                            a[i * n + i] + 3.0
                        };
                    }
                    let op = if transpose_a {
                        transpose(&t, n, n)
                    } else {
                        t.clone()
                    };
                    let options = TriangularSolveOptions {
                        left_side: true,
                        lower,
                        transpose_a,
                        conjugate_a: false,
                        unit_diagonal,
                    };
                    let x = triangular_solve(&stored, &b, 1, n, 3, options);
                    assert_close(&matmul(&op, &x, n, n, 3), &b, 1e-12);
                    let options = TriangularSolveOptions {
                        left_side: false,
                        ..options
                    };
                    let x = triangular_solve(&stored, &bt, 1, 3, n, options);
                    assert_close(&matmul(&x, &op, 3, n, n), &bt, 1e-12);
                }
            }
        }
    }

    #[test]
    fn lu_pivots_by_the_largest_magnitude() {
        let a = [1.0, 2.0, -4.0, 3.0, 4.0, 1.0];
        // 3 x 2: the first column's largest magnitude is -4 (row 1).
        let (lu_, piv, perm) = lu(&a, 1, 3, 2);
        assert_eq!(piv, [1, 2]);
        assert_eq!(perm, [1, 2, 0]);
        // Rebuild P A = L U.
        let l = [1.0, 0.0, lu_[2], 1.0, lu_[4], lu_[5]];
        let u = [lu_[0], lu_[1], 0.0, lu_[3]];
        let pa: Vec<f64> = perm
            .iter()
            .flat_map(|&r| a[r as usize * 2..r as usize * 2 + 2].to_vec())
            .collect();
        assert_close(&matmul(&l, &u, 3, 2, 2), &pa, 1e-12);
        // Ties pick the first row; a zero column is not swapped.
        let (_, piv, _) = lu(&[0.0, 1.0, 0.0, 2.0], 1, 2, 2);
        assert_eq!(piv, [0, 1]);
        let (_, piv, _) = lu(&[-2.0, 1.0, 2.0, 1.0], 1, 2, 2);
        assert_eq!(piv, [0, 1]);
        assert_eq!(lu_pivots_to_permutation(&[2, 2, 2], 1, 3, 4), [2, 0, 1, 3]);
    }

    #[test]
    fn qr_follows_lapack_signs() {
        for (m, n) in [(4, 3), (3, 4), (3, 3), (1, 1), (5, 2)] {
            let a = matrix(m, n, (m * 10 + n) as u64);
            for full in [false, true] {
                let (q, r) = qr(&a, 1, m, n, full);
                let kq = if full { m } else { m.min(n) };
                assert_close(&matmul(&q, &r, m, kq, n), &a, 1e-12);
                let qtq = matmul(&transpose(&q, m, kq), &q, kq, m, kq);
                assert_close(&qtq, &eye(kq), 1e-12);
                for i in 0..kq {
                    for j in 0..i.min(n) {
                        assert_eq!(r[i * n + j], 0.0);
                    }
                }
            }
        }
        // larfg's convention: beta = -sign(alpha) * norm.
        let (q, r) = qr(&[3.0, 4.0], 1, 2, 1, false);
        assert_close(&r, &[-5.0], 1e-15);
        assert_close(&q, &[-0.6, -0.8], 1e-15);
        // Empty matrices give identity Qs.
        let (q, r) = qr::<f64>(&[], 2, 2, 0, true);
        assert_eq!(q, [1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0]);
        assert!(r.is_empty());
    }

    #[test]
    fn eigh_diagonalizes() {
        let n = 5;
        let b = matrix(n, n, 7);
        let a = matmul(&b, &transpose(&b, n, n), n, n, n);
        for (lower, jacobi) in [(true, false), (false, false), (true, true), (false, true)] {
            // Garbage in the unused triangle.
            let mut stored = a.clone();
            for i in 0..n {
                for j in 0..n {
                    if (lower && j > i) || (!lower && j < i) {
                        stored[i * n + j] = 1e3;
                    }
                }
            }
            let (v, w) = eigh(&stored, 1, n, lower, jacobi);
            assert!(w.windows(2).all(|p| p[0] <= p[1]));
            let mut vw = v.clone();
            for r in 0..n {
                for c in 0..n {
                    vw[r * n + c] *= w[c];
                }
            }
            assert_close(&matmul(&vw, &transpose(&v, n, n), n, n, n), &a, 1e-12);
            assert_close(&matmul(&transpose(&v, n, n), &v, n, n, n), &eye(n), 1e-12);
        }
        let (v, w) = eigh(&[f64::NAN, 0.0, 0.0, 1.0], 1, 2, true, false);
        assert!(v.iter().chain(&w).all(|x| x.is_nan()));
    }

    #[test]
    fn svd_reconstructs() {
        for (m, n) in [(4, 3), (3, 4), (3, 3), (5, 1), (1, 4), (2, 0), (0, 3)] {
            let mut a = matrix(m, n, (m * 7 + n) as u64);
            if m == 4 && n == 3 {
                // Rank deficient: the last column repeats the first.
                for i in 0..m {
                    a[i * n + 2] = a[i * n];
                }
            }
            let k = m.min(n);
            for (full, jacobi) in [(false, false), (true, false), (false, true), (true, true)] {
                let (s, u, vt) = svd(&a, 1, m, n, full, true, jacobi);
                assert!(s.windows(2).all(|p| p[0] >= p[1]));
                let (uc, vr) = if full { (m, n) } else { (k, k) };
                let mut us = vec![0.0; m * vr];
                for i in 0..m {
                    for j in 0..k {
                        us[i * vr + j] = u[i * uc + j] * s[j];
                    }
                }
                assert_close(&matmul(&us, &vt, m, vr, n), &a, 1e-12);
                assert_close(
                    &matmul(&transpose(&u, m, uc), &u, uc, m, uc),
                    &eye(uc),
                    1e-12,
                );
                assert_close(
                    &matmul(&vt, &transpose(&vt, vr, n), vr, n, vr),
                    &eye(vr),
                    1e-12,
                );
                let (s2, u2, vt2) = svd(&a, 1, m, n, full, false, jacobi);
                assert_eq!(s2, s);
                assert!(u2.is_empty() && vt2.is_empty());
            }
        }
    }

    type Z = Complex<f64>;

    fn z(re: f64, im: f64) -> Z {
        Complex::new(re, im)
    }

    fn cmatrix(m: usize, n: usize, seed: u64) -> Vec<Z> {
        let re = matrix(m, n, seed);
        let im = matrix(m, n, seed + 1000);
        re.into_iter().zip(im).map(|(a, b)| z(a, b)).collect()
    }

    fn cmatmul(a: &[Z], b: &[Z], m: usize, k: usize, n: usize) -> Vec<Z> {
        let mut c = vec![Z::ZERO; m * n];
        for i in 0..m {
            for j in 0..n {
                let mut s = Z::ZERO;
                for l in 0..k {
                    s = s + a[i * k + l] * b[l * n + j];
                }
                c[i * n + j] = s;
            }
        }
        c
    }

    /// The conjugate transpose.
    fn adjoint(a: &[Z], m: usize, n: usize) -> Vec<Z> {
        let mut t = vec![Z::ZERO; m * n];
        for i in 0..m {
            for j in 0..n {
                t[j * m + i] = a[i * n + j].conj();
            }
        }
        t
    }

    fn ceye(n: usize) -> Vec<Z> {
        let mut e = vec![Z::ZERO; n * n];
        for i in 0..n {
            e[i * n + i] = Z::ONE;
        }
        e
    }

    fn assert_cclose(a: &[Z], b: &[Z], tol: f64) {
        assert_eq!(a.len(), b.len());
        for (i, (x, y)) in a.iter().zip(b).enumerate() {
            assert!((*x - *y).abs() <= tol, "element {i}: {x:?} vs {y:?}");
        }
    }

    /// A Hermitian positive definite matrix `B B^H + n I`.
    fn hpd(n: usize, seed: u64) -> Vec<Z> {
        let b = cmatrix(n, n, seed);
        let mut a = cmatmul(&b, &adjoint(&b, n, n), n, n, n);
        for i in 0..n {
            a[i * n + i] = a[i * n + i] + z(n as f64, 0.0);
        }
        a
    }

    #[test]
    fn complex_cholesky_reconstructs() {
        let n = 4;
        let a = hpd(n, 1);
        let l = cholesky(&a, 1, n);
        let mut lower = vec![Z::ZERO; n * n];
        for i in 0..n {
            assert_eq!(l[i * n + i].im, 0.0);
            for j in 0..=i {
                lower[i * n + j] = l[i * n + j];
            }
            for j in i + 1..n {
                assert_eq!(l[i * n + j], a[i * n + j], "the upper triangle is kept");
            }
        }
        assert_cclose(&cmatmul(&lower, &adjoint(&lower, n, n), n, n, n), &a, 1e-12);
    }

    #[test]
    fn complex_triangular_solves_conjugate() {
        let n = 3;
        let mut a = cmatrix(n, n, 5);
        for i in 0..n {
            a[i * n + i] = a[i * n + i] + z(3.0, 0.0);
        }
        let b = cmatrix(n, 2, 6);
        for transpose_a in [false, true] {
            for conjugate_a in [false, true] {
                let mut t = vec![Z::ZERO; n * n];
                for i in 0..n {
                    for j in 0..=i {
                        t[i * n + j] = a[i * n + j];
                    }
                }
                let mut op = if transpose_a {
                    adjoint(&adjoint(&adjoint(&t, n, n), n, n), n, n)
                        .iter()
                        .map(|v| v.conj())
                        .collect()
                } else {
                    t.clone()
                };
                if conjugate_a {
                    op = op.iter().map(|v| v.conj()).collect();
                }
                let options = TriangularSolveOptions {
                    left_side: true,
                    lower: true,
                    transpose_a,
                    conjugate_a,
                    unit_diagonal: false,
                };
                let x = triangular_solve(&a, &b, 1, n, 2, options);
                assert_cclose(&cmatmul(&op, &x, n, n, 2), &b, 1e-12);
            }
        }
    }

    #[test]
    fn complex_lu_pivots_by_abs1() {
        // `izamax` compares |re| + |im|: 2.9 + 2.9i (5.8, modulus 4.1) is
        // chosen over 4.5 (4.5, modulus 4.5).
        let a = [z(4.5, 0.0), z(1.0, 0.0), z(2.9, 2.9), z(1.0, 1.0)];
        let (_, piv, _) = lu(&a, 1, 2, 2);
        assert_eq!(piv, [1, 1]);
        let (m, n) = (4, 3);
        let a = cmatrix(m, n, 9);
        let (f, _, perm) = lu(&a, 1, m, n);
        let mut l = vec![Z::ZERO; m * n];
        let mut u = vec![Z::ZERO; n * n];
        for i in 0..m {
            for j in 0..n {
                if j < i {
                    l[i * n + j] = f[i * n + j];
                } else {
                    if i == j {
                        l[i * n + j] = Z::ONE;
                    }
                    if i < n {
                        u[i * n + j] = f[i * n + j];
                    }
                }
            }
        }
        let pa: Vec<Z> = perm
            .iter()
            .flat_map(|&r| a[r as usize * n..(r as usize + 1) * n].to_vec())
            .collect();
        assert_cclose(&cmatmul(&l, &u, m, n, n), &pa, 1e-12);
    }

    #[test]
    fn complex_qr_is_unitary() {
        for (m, n) in [(4, 3), (3, 4), (3, 3)] {
            let a = cmatrix(m, n, (m * 10 + n) as u64);
            for full in [false, true] {
                let (q, r) = qr(&a, 1, m, n, full);
                let kq = if full { m } else { m.min(n) };
                assert_cclose(&cmatmul(&q, &r, m, kq, n), &a, 1e-12);
                assert_cclose(
                    &cmatmul(&adjoint(&q, m, kq), &q, kq, m, kq),
                    &ceye(kq),
                    1e-12,
                );
                for i in 0..kq.min(n) {
                    // zlarfg's beta is real.
                    assert_eq!(r[i * n + i].im, 0.0);
                }
            }
        }
    }

    #[test]
    fn complex_eigh_diagonalizes() {
        let n = 4;
        let a = hpd(n, 3);
        for (lower, jacobi) in [(true, false), (false, false), (true, true), (false, true)] {
            let (v, w) = eigh(&a, 1, n, lower, jacobi);
            assert!(w.windows(2).all(|p| p[0] <= p[1]));
            let mut vw = v.clone();
            for r in 0..n {
                for c in 0..n {
                    vw[r * n + c] = vw[r * n + c].scale(w[c]);
                }
            }
            assert_cclose(&cmatmul(&vw, &adjoint(&v, n, n), n, n, n), &a, 1e-10);
            assert_cclose(&cmatmul(&adjoint(&v, n, n), &v, n, n, n), &ceye(n), 1e-12);
            // The largest component of each eigenvector is real and positive.
            for c in 0..n {
                let best = (0..n)
                    .max_by(|&i, &j| v[i * n + c].abs().total_cmp(&v[j * n + c].abs()))
                    .unwrap();
                assert_eq!(v[best * n + c].im, 0.0);
                assert!(v[best * n + c].re > 0.0);
            }
        }
    }

    #[test]
    fn complex_svd_reconstructs() {
        for (m, n) in [(4, 3), (3, 4), (3, 3)] {
            let a = cmatrix(m, n, (m * 7 + n) as u64);
            let k = m.min(n);
            for (full, jacobi) in [(false, false), (true, false), (false, true), (true, true)] {
                let (s, u, vt) = svd(&a, 1, m, n, full, true, jacobi);
                assert!(s.windows(2).all(|p| p[0] >= p[1]));
                let (uc, vr) = if full { (m, n) } else { (k, k) };
                let mut us = vec![Z::ZERO; m * vr];
                for i in 0..m {
                    for j in 0..k {
                        us[i * vr + j] = u[i * uc + j].scale(s[j]);
                    }
                }
                assert_cclose(&cmatmul(&us, &vt, m, vr, n), &a, 1e-12);
                assert_cclose(
                    &cmatmul(&adjoint(&u, m, uc), &u, uc, m, uc),
                    &ceye(uc),
                    1e-12,
                );
                assert_cclose(
                    &cmatmul(&vt, &adjoint(&vt, vr, n), vr, n, vr),
                    &ceye(vr),
                    1e-12,
                );
            }
        }
    }

    #[test]
    fn qr_pivoting_moves_large_columns_forward() {
        // The third column has the largest norm, then the first.
        let a = [1.0, 0.0, 5.0, 2.0, 0.1, 0.0, 0.0, 0.0, 1.0];
        let (q, r, p) = qr_pivoting(&a, 1, 3, 3, false);
        assert_eq!(p, [2, 0, 1]);
        let mut ap = vec![0.0; 9];
        for i in 0..3 {
            for j in 0..3 {
                ap[i * 3 + j] = a[i * 3 + p[j] as usize];
            }
        }
        assert_close(&matmul(&q, &r, 3, 3, 3), &ap, 1e-12);
        // |diag(R)| does not increase.
        assert!(r[0].abs() >= r[4].abs() && r[4].abs() >= r[8].abs());
        for (m, n) in [(4, 3), (3, 5), (5, 5)] {
            let mut a = matrix(m, n, (m * 13 + n) as u64);
            // A repeated column: rank deficient.
            for i in 0..m {
                a[i * n + n - 1] = a[i * n];
            }
            for full in [false, true] {
                let (q, r, p) = qr_pivoting(&a, 1, m, n, full);
                let kq = if full { m } else { m.min(n) };
                let mut ap = vec![0.0; m * n];
                for i in 0..m {
                    for j in 0..n {
                        ap[i * n + j] = a[i * n + p[j] as usize];
                    }
                }
                assert_close(&matmul(&q, &r, m, kq, n), &ap, 1e-12);
                let mut sorted = p.clone();
                sorted.sort_unstable();
                assert_eq!(sorted, (0..n as i32).collect::<Vec<_>>());
            }
        }
        let (_, _, p) = qr_pivoting::<f64>(&[], 2, 0, 3, true);
        assert_eq!(p, [0; 6]);
    }

    #[test]
    fn complex_qr_pivoting_reconstructs() {
        let (m, n) = (4, 3);
        let a = cmatrix(m, n, 21);
        let (q, r, p) = qr_pivoting(&a, 1, m, n, false);
        let mut ap = vec![Z::ZERO; m * n];
        for i in 0..m {
            for j in 0..n {
                ap[i * n + j] = a[i * n + p[j] as usize];
            }
        }
        assert_cclose(&cmatmul(&q, &r, m, n, n), &ap, 1e-12);
        assert_cclose(&cmatmul(&adjoint(&q, m, n), &q, n, m, n), &ceye(n), 1e-12);
    }

    #[test]
    fn householder_product_and_ormqr_agree_with_qr() {
        let (m, n) = (5, 3);
        let a = matrix(m, n, 44);
        let mut r = a.clone();
        let taus = geqrf_one(&mut r, m, n);
        let q = householder_product(&r, &taus, 1, m, n, n);
        let (q_ref, _) = qr(&a, 1, m, n, false);
        assert_close(&q, &q_ref, 1e-14);
        // `Q^T Q c = c`, and `(Q c)^T = c^T Q^T` from the right.
        let c = matrix(m, 2, 45);
        let qc = ormqr(&r, &taus, &c, 1, (m, n, n), (m, 2), true, false);
        let back = ormqr(&r, &taus, &qc, 1, (m, n, n), (m, 2), true, true);
        assert_close(&back, &c, 1e-12);
        let ct = transpose(&c, m, 2);
        let cq = ormqr(&r, &taus, &ct, 1, (m, n, n), (2, m), false, true);
        assert_close(&transpose(&cq, 2, m), &qc, 1e-12);
    }
}