colmat 0.34.0

Dense and sparse linear algebra for HPC applications with caller owned thread teams.
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
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
//! low level implementation of the generalized eigenvalue decomposition of a
//! square matrix pair.
//!
//! the generalized eigenvalue decomposition of a matrix pair $(A, B)$ of shape
//! $(n, n)$ is a decomposition into components $S$, $U$ such that:
//!
//! - $U$ has shape $(n, n)$ and is invertible
//! - $S$ has shape $(n, n)$ and is a diagonal matrix
//! - and finally:
//!
//! $$A = B U S U^{-1}$$
//!
//! if $A$ is self-adjoint and $B$ is positive definite, then $U$ can be made
//! $B$-orthonormal ($U^H B U = I$), and $S$ is real valued.
//!
//! the implementation can choose to compute the left and/or right generalized
//! eigenvectors separately, and the generalized eigenvalues (diagonal of $S$)
//! are represented as a ratio $\alpha / \beta$ to improve numerical stability.
//!
//! The real driver's protected small solves and propagation of their scales
//! follow the numerical contracts of Reference LAPACK v3.12.1, SRC/dlaln2.f and
//! SRC/dtgevc.f: <https://github.com/Reference-LAPACK/lapack/tree/v3.12.1/SRC>.
use crate::internal_prelude::*;
use complex::Complex;
use equator::assert;
pub use linalg::evd::ComputeEigenvectors;
mod reorder;
mod schur_eigenvalues;
pub use reorder::{
	SchurReorderError, reorder_schur_cplx, reorder_schur_real,
	reorder_schur_scratch,
};
pub use schur_eigenvalues::{SchurEigenvalueError,schur_eigenvalues_real};

/// eigendecomposition error
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum GevdError {
	/// reached max iterations, the input was not finite, or the requested
	/// eigenvectors came out non-finite (see [`gevd_real`] for the range of
	/// scales)
	NoConvergence,
}
/// eigendecomposition error
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SelfAdjointGevdError {
	/// reached max iterations
	NoConvergence,
	/// B matrix not positive definite
	NonPositiveDefinite,
}
/// generalized schur decomposition parameters
#[derive(Clone, Copy, Debug)]
pub struct GeneralizedSchurParams {
	/// An estimate of the relative cost of flops within the near-the-diagonal
	/// shift chase compared to flops within the matmul calls of a QZ sweep.
	pub relative_cost_estimate_of_shift_chase_to_matmul: extern "C" fn(
		matrix_dimension: usize,
		active_block_dimension: usize,
	)
		-> usize,
	/// Function that returns the number of shifts to use for a given matrix
	/// size
	pub recommended_shift_count: extern "C" fn(
		matrix_dimension: usize,
		active_block_dimension: usize,
	) -> usize,
	/// Function that returns the deflation window to use for a given matrix
	/// size
	pub recommended_deflation_window: extern "C" fn(
		matrix_dimension: usize,
		active_block_dimension: usize,
	) -> usize,
	/// Threshold to switch between blocked and unblocked code
	pub blocking_threshold: usize,
	/// Threshold of percent of aggressive-early-deflation window that must
	/// converge to skip a sweep
	pub nibble_threshold: usize,
	#[doc(hidden)]
	pub non_exhaustive: NonExhaustive,
}
/// schur to eigendecomposition conversion parameters
#[derive(Clone, Copy, Debug)]
pub struct GevdFromSchurParams {
	#[doc(hidden)]
	pub non_exhaustive: NonExhaustive,
}
/// eigendecomposition tuning parameters
#[derive(Clone, Copy, Debug)]
pub struct GevdParams {
	/// hessenberg parameters
	pub hessenberg: gen_hessenberg::GeneralizedHessenbergParams,
	/// schur from hessenberg conversion parameters
	pub schur: GeneralizedSchurParams,
	/// eigendecomposition from schur conversion parameters
	pub evd_from_schur: GevdFromSchurParams,
	#[doc(hidden)]
	pub non_exhaustive: NonExhaustive,
}
extern "C" fn default_relative_cost_estimate_of_shift_chase_to_matmul(
	n: usize,
	nh: usize,
) -> usize {
	_ = (n, nh);
	10
}
impl<T: ComplexField> Auto<T> for GeneralizedSchurParams {
	fn auto() -> Self {
		let schur: linalg::evd::SchurParams = auto!(T);
		Self {
			relative_cost_estimate_of_shift_chase_to_matmul:
				default_relative_cost_estimate_of_shift_chase_to_matmul,
			recommended_shift_count: schur.recommended_shift_count,
			recommended_deflation_window: schur.recommended_deflation_window,
			blocking_threshold: schur.blocking_threshold,
			nibble_threshold: schur.nibble_threshold,
			non_exhaustive: NonExhaustive(()),
		}
	}
}
impl<T: ComplexField> Auto<T> for GevdParams {
	fn auto() -> Self {
		Self {
			hessenberg: auto!(T),
			schur: auto!(T),
			evd_from_schur: auto!(T),
			non_exhaustive: NonExhaustive(()),
		}
	}
}
impl<T: ComplexField> Auto<T> for GevdFromSchurParams {
	fn auto() -> Self {
		Self {
			non_exhaustive: NonExhaustive(()),
		}
	}
}
/// hessenberg decomposition
pub mod gen_hessenberg;
/// $QZ$ decomposition for complex matrices
pub mod qz_cplx;
/// $QZ$ decomposition for real matrices
pub mod qz_real;
/// `2^32` and `2^-32`, the step of [`exponent_of`] and [`mul_pow2`]
fn pow2_32<T: RealField>() -> (T, T) {
	let mut p = one::<T>() + one::<T>();
	for _ in 0..5 {
		p = &p * &p;
	}
	let q = p.recip();
	(p, q)
}

/// `floor(log2(x))` for a finite `x > 0`, computed by exact power-of-two
/// steps (`T` has no `frexp`)
fn exponent_of<T: RealField>(x: &T) -> isize {
	let two = one::<T>() + one::<T>();
	let half = two.recip();
	let (p32, q32) = pow2_32::<T>();
	let mut m = x.copy();
	let mut e = 0isize;
	while m >= p32 {
		m = &m * &q32;
		e += 32;
	}
	while m >= two {
		m = &m * &half;
		e += 1;
	}
	while m < q32 {
		m = &m * &p32;
		e -= 32;
	}
	while m < one::<T>() {
		m = &m * &two;
		e -= 1;
	}
	e
}

/// `x * 2^e`, applied in steps that are each a representable power of two, so
/// no out-of-range factor is ever formed, and rounded once. upwards every step
/// is exact until the result overflows. downwards the steps are taken while
/// the value stays normal (exact), and what is left is one multiplication by
/// `2^e'`, a normal number, so a result in the subnormal range is rounded once
/// rather than once per step (repeated halving of a subnormal can round a
/// nonzero result to zero)
fn mul_pow2<T: ComplexField>(x: &T, e: isize) -> T {
	let two = one::<T::Real>() + one::<T::Real>();
	let half = two.recip();
	let (p32, q32) = pow2_32::<T::Real>();
	let safmin = min_positive::<T::Real>();
	let emin = exponent_of(&safmin);
	let mut x = x.copy();
	let mut e = e;
	while e >= 32 {
		x = x.mul_real(&p32);
		e -= 32;
	}
	while e > 0 {
		x = x.mul_real(&two);
		e -= 1;
	}
	if e == 0 {
		return x;
	}
	// `|re| + |im|`: a complex value's parts are moved together, so only its
	// larger part is guaranteed one rounding
	let m = |x: &T| x.abs1();
	if m(&x) == zero::<T::Real>() {
		return x;
	}
	while e <= -32 && m(&x) * &q32 >= safmin {
		x = x.mul_real(&q32);
		e += 32;
	}
	while e < 0 && m(&x) * &half >= safmin {
		x = x.mul_real(&half);
		e += 1;
	}
	if e == 0 {
		return x;
	}
	// `|x|` is now below `2 safmin`, so the rest takes it to the subnormal range
	// or to zero; `2^e` is normal for `e >= emin`, and below that the result is
	// zero whichever way it is formed
	let e = e.max(emin);
	let mut f = one::<T::Real>();
	for _ in 0..(-e) {
		f = &f * &half;
	}
	x.mul_real(&f)
}

#[track_caller]
fn compute_gevd_generic<T: ComplexField>(
	A: MatMut<'_, T>,
	B: MatMut<'_, T>,
	alpha_re: ColMut<'_, T>,
	alpha_im: ColMut<'_, T>,
	beta: ColMut<'_, T>,
	u_left: Option<MatMut<'_, T>>,
	u_right: Option<MatMut<'_, T>>,
	mut par: Par,
	stack: &mut MemStack,
	params: GevdParams,
	hessenberg_to_qz: fn(
		A: MatMut<'_, T>,
		B: MatMut<'_, T>,
		Q: Option<MatMut<'_, T>>,
		Z: Option<MatMut<'_, T>>,
		alphar: ColMut<'_, T>,
		alphai: ColMut<'_, T>,
		beta: ColMut<'_, T>,
		eigenvectors: ComputeEigenvectors,
		par: Par,
		params: GeneralizedSchurParams,
		stack: &mut MemStack,
	),
	qz_to_gevd: fn(
		A: MatRef<'_, T>,
		B: MatRef<'_, T>,
		Q: Option<MatMut<'_, T>>,
		Z: Option<MatMut<'_, T>>,
		par: Par,
		stack: &mut MemStack,
	),
) -> Result<(), GevdError> {
	let n = A.nrows();
	assert!(all(
		A.nrows() == n,
		A.ncols() == n,
		B.nrows() == n,
		B.ncols() == n,
		alpha_re.nrows() == n,
		if const { T::IS_REAL } {
			alpha_im.nrows()
		} else {
			n
		} == n,
		beta.nrows() == n,
	));
	if let Some(u_left) = u_left.rb() {
		assert!(all(u_left.nrows() == n, u_left.ncols() == n));
	}
	if let Some(u_right) = u_right.rb() {
		assert!(all(u_right.nrows() == n, u_right.ncols() == n));
	}
	if n == 0 {
		return Ok(());
	}
	#[cfg(feature = "perf-warn")]
	{
		for u in [u_left.rb(), u_right.rb()] {
			if let Some(matrix) = u.rb() {
				if matrix.row_stride().unsigned_abs() != 1
					&& crate::__perf_warn!(GEVD_WARN)
				{
					if matrix.col_stride().unsigned_abs() == 1 {
						log::warn!(
							target : "faer_perf",
							"GEVD prefers column-major eigenvector matrix. Found row-major matrix."
						);
					} else {
						log::warn!(
							target : "faer_perf",
							"GEVD prefers column-major eigenvector matrix. Found matrix with generic strides."
						);
					}
				}
			}
		}
		for M in [A.rb(), B.rb()] {
			if M.row_stride().unsigned_abs() != 1
				&& crate::__perf_warn!(GEVD_WARN)
			{
				if M.col_stride().unsigned_abs() == 1 {
					log::warn!(
						target : "faer_perf",
						"GEVD prefers column-major input matrix. Found row-major matrix."
					);
				} else {
					log::warn!(
						target : "faer_perf",
						"GEVD prefers column-major input matrix. Found matrix with generic strides."
					);
				}
			}
		}
	}
	if !(A.is_all_finite() && B.is_all_finite()) {
		{ alpha_re }.fill(nan());
		{ alpha_im }.fill(nan());
		{ beta }.fill(nan());
		for u in [u_left, u_right] {
			if let Some(mut u) = u {
				u.fill(nan());
			}
		}
		return Err(GevdError::NoConvergence);
	}
	let need_qz = u_left.is_some() || u_right.is_some();
	let mut A = A;
	let mut B = B;
	// tensor4all/faer#375: like LAPACK `dggev`, scale `A` and `B` separately
	// before the reduction and the QZ, which otherwise underflow for tiny pencils
	// and return `alpha = beta = 0`. a matrix whose largest entry is below
	// `smlnum = sqrt(safmin) / eps` is scaled to a largest entry in
	// `[smlnum, 2 smlnum)`, one above `bignum = 1 / smlnum` to `(bignum / 2,
	// bignum]`. unlike `dggev` (`dlascl` by `smlnum / norm`) the factor is a power
	// of two, so the scaling and the scaling back are exact (except where an
	// entry is or becomes subnormal) and `(2^k A, 2^k B)` gets exactly `2^k`
	// times the `alpha` and `beta` of `(A, B)` when both are scaled. in `f32`
	// and `f64` the factor and its inverse are normal numbers.
	//
	// `alpha` is scaled back by `A`'s factor and `beta` by `B`'s after the QZ.
	// The eigenvectors are not scaled back: `(a A, b B)` has the eigenvalues
	// `(a alpha, b beta)` and the same eigenvectors, the orthogonal `Q`, `Z` do
	// not depend on `a`, `b`, and the eigenvector stage normalizes its output.
	let smlnum = sqrt_min_positive::<T::Real>() / eps::<T::Real>();
	let bignum = smlnum.recip();
	// the inverse `2^e` of the factor `2^-e` applied to `M`, as `(2^e, e)`, if
	// `M` was scaled
	let prescale = |M: MatMut<'_, T>| -> Option<(T::Real, isize)> {
		let norm = M.rb().norm_max();
		let two = one::<T::Real>() + one::<T::Real>();
		let half = two.recip();
		let mut factor = one::<T::Real>();
		let mut e = 0isize;
		if norm > zero::<T::Real>() && norm < smlnum {
			while &norm * &factor < smlnum {
				factor = &factor * &two;
				e -= 1;
			}
		} else if norm > bignum {
			while &norm * &factor > bignum {
				factor = &factor * &half;
				e += 1;
			}
		} else {
			return None;
		}
		zip!(M).for_each(|unzip!(x)| *x = x.mul_real(&factor));
		Some((factor.recip(), e))
	};
	let a_unscale = prescale(A.rb_mut());
	let b_unscale = prescale(B.rb_mut());
	let mut u_left = u_left;
	let mut u_right = u_right;
	let mut alpha_re = alpha_re;
	let mut alpha_im = alpha_im;
	let mut beta = beta;
	for u in [u_left.rb_mut(), u_right.rb_mut()] {
		if let Some(mut u) = u {
			// the outputs may be reused buffers; initialize them as full identities,
			// which is what LAPACK's `dgges` does with `dlaset` before `dhgeqz`
			// accumulates the transformations
			u.fill(zero());
			u.diagonal_mut().column_vector_mut().fill(one());
		}
	}
	{
		let block_size =
			linalg::qr::no_pivoting::factor::recommended_block_size::<T>(n, n);
		let (mut householder, stack) =
			unsafe { linalg::temp_mat_uninit::<T, _, _>(block_size, n, stack) };
		let mut householder = householder.as_mat_mut();
		linalg::qr::no_pivoting::factor::qr_in_place(
			B.rb_mut(),
			householder.rb_mut(),
			par.reborrow(),
			stack,
			default(),
		);
		linalg::householder::apply_block_householder_sequence_transpose_on_the_left_in_place_with_conj(
			B.rb(),
			householder.rb(),
			Conj::Yes,
			A.rb_mut(),
			par.reborrow(),
			stack,
		);
		if let Some(u_left) = u_left.rb_mut() {
			linalg::householder::apply_block_householder_sequence_on_the_left_in_place_with_conj(
				B.rb(),
				householder.rb(),
				Conj::No,
				u_left,
				par.reborrow(),
				stack,
			);
		}
		zip!(B.rb_mut())
			.for_each_triangular_lower(linalg::zip::Diag::Skip, |unzip!(x)| {
				*x = zero()
			});
	}
	gen_hessenberg::generalized_hessenberg(
		A.rb_mut(),
		B.rb_mut(),
		u_left.rb_mut(),
		u_right.rb_mut(),
		par.reborrow(),
		stack,
		params.hessenberg,
	);
	hessenberg_to_qz(
		A.rb_mut(),
		B.rb_mut(),
		u_left.rb_mut(),
		u_right.rb_mut(),
		alpha_re.rb_mut(),
		alpha_im.rb_mut(),
		beta.rb_mut(),
		if need_qz {
			ComputeEigenvectors::Yes
		} else {
			ComputeEigenvectors::No
		},
		par.reborrow(),
		params.schur,
		stack,
	);
	// undo the prescaling of `A` and `B` on `alpha` and `beta`. the pair of an
	// eigenvalue is `(alpha 2^ea, beta 2^eb)`, `2^ea` and `2^eb` being `A`'s and
	// `B`'s inverse factors, and any common power of two `2^d` times it is the
	// same eigenvalue. `d = 0` (the input's scale) is kept when both components
	// come out finite and, if nonzero, normal. otherwise `d` is chosen from the
	// components' binary exponents, as integers, so no factor outside the range
	// (such as `2^(ea - eb)` for a pencil prescaled in opposite directions) is
	// formed (review of #378):
	// - `d` is at most `hi`, the largest `d` that keeps the larger component
	//   finite,
	// - within that, the `d` nearest zero that makes both normal,
	// - else the `d` nearest zero that keeps it nonzero (subnormal),
	// - else the largest `d`, where the smaller one is below the smallest
	//   subnormal even next to a larger one at the top of the range (the
	//   eigenvalue itself is beyond the range: `0` or infinite).
	// a pair the QZ returned as `0 / 0` is left so
	if a_unscale.is_some() || b_unscale.is_some() {
		let (fa, ea) = a_unscale.unwrap_or((one::<T::Real>(), 0));
		let (fb, eb) = b_unscale.unwrap_or((one::<T::Real>(), 0));
		let safmin = min_positive::<T::Real>();
		let emax = exponent_of(&max_positive::<T::Real>());
		let emin = exponent_of(&safmin);
		// `p - 1`, `p` the number of significand bits
		let digits = -exponent_of(&eps::<T::Real>());
		// `|x| * f` is finite, and zero or normal
		let representable = |m: &T::Real, f: &T::Real| {
			let x = m * f;
			x.is_finite() && (*m == zero::<T::Real>() || x >= safmin)
		};
		for j in 0..n {
			let amag = if const { T::IS_REAL } {
				alpha_re[j].abs1().fmax(alpha_im[j].abs1())
			} else {
				alpha_re[j].abs1()
			};
			let bmag = beta[j].abs1();
			if representable(&amag, &fa) && representable(&bmag, &fb) {
				alpha_re[j] = alpha_re[j].mul_real(&fa);
				if const { T::IS_REAL } {
					alpha_im[j] = alpha_im[j].mul_real(&fa);
				}
				beta[j] = beta[j].mul_real(&fb);
				continue;
			}
			// binary exponents of the nonzero components at the input's scale
			let mut exps = [None, None];
			if amag != zero::<T::Real>() {
				exps[0] = Some(exponent_of(&amag) + ea);
			}
			if bmag != zero::<T::Real>() {
				exps[1] = Some(exponent_of(&bmag) + eb);
			}
			let (large, small) = match exps {
				[Some(x), Some(y)] => (x.max(y), x.min(y)),
				[Some(x), None] | [None, Some(x)] => (x, x),
				// `0 / 0` from the QZ
				[None, None] => continue,
			};
			let hi = emax - large;
			let lo = emin - small;
			let lo_nonzero = lo - digits;
			let d = if lo <= hi {
				0isize.clamp(lo, hi)
			} else if lo_nonzero <= hi {
				0isize.clamp(lo_nonzero, hi)
			} else {
				hi
			};
			alpha_re[j] = mul_pow2(&alpha_re[j], ea + d);
			if const { T::IS_REAL } {
				alpha_im[j] = mul_pow2(&alpha_im[j], ea + d);
			}
			beta[j] = mul_pow2(&beta[j], eb + d);
		}
	}
	qz_to_gevd(
		A.rb(),
		B.rb(),
		u_left.rb_mut(),
		u_right.rb_mut(),
		par,
		stack,
	);
	// non-finite eigenvectors are reported rather than returned with `Ok`
	// (tensor4all/faer#370). before the prescaling of tensor4all/faer#375 this
	// is how a QZ that underflowed to `alpha = beta = 0` for a pencil below
	// about `1e-280` (f64) showed up; it is kept as a safety net
	for u in [u_left.rb(), u_right.rb()] {
		if let Some(u) = u {
			if !u.is_all_finite() {
				return Err(GevdError::NoConvergence);
			}
		}
	}
	Ok(())
}
fn solve_shifted_1x1<T: ComplexField>(
	smin: T::Real,
	ca: T::Real,
	A: T,
	d0: T,
	B: &mut T,
	w: T,
) {
	let ref safmin = min_positive::<T::Real>();
	let ref smlnum = safmin + safmin;
	let ref smin = smin.fmax(smlnum);
	let CR = A.mul_real(ca) - w * d0;
	let cmax = CR.abs();
	if cmax < *smin {
		// protected denominator: `d = max(|d|, smin)` instead of dividing by
		// the shift twice (LAPACK `dtgevc`: `IF( ABS( D ).LE.DMIN ) D = DMIN`)
		*B = B.mul_real(smin.recip());
		return;
	}
	*B *= CR.recip();
}
fn solve_complex_shifted_1x1<T: RealField>(
	smin: T,
	ca: T,
	A: MatRef<'_, T>,
	ref d0: T,
	mut B: MatMut<'_, T>,
	wr: T,
	wi: T,
) {
	let nw = B.ncols();
	let ref safmin = min_positive::<T>();
	let ref smlnum = safmin + safmin;
	let ref smin = smin.fmax(smlnum);
	let CR = ca * &A[(0, 0)] - wr * d0;
	let CI = -wi * d0;
	let cmax = CR.abs().fmax(CI.abs());
	if cmax < *smin {
		// protected denominator, as in `solve_shifted_1x1` (LAPACK `ztgevc`:
		// `IF( CABS1( D ).LE.DMIN ) D = CMPLX( DMIN )`); dividing by the
		// complex shift afterwards would scale it twice
		let ref smin_inv = smin.recip();
		zip!(B.rb_mut()).for_each(|unzip!(x)| *x *= smin_inv);
		return;
	}
	if nw == 1 {
		let ref C = CR.recip();
		zip!(B.rb_mut()).for_each(|unzip!(x)| *x *= C);
	} else {
		let (Br, Bi) = B.two_cols_mut(0, 1);
		let C = Complex { re: CR, im: CI }.recip();
		zip!(Br, Bi).for_each(|unzip!(re, im)| {
			(*re, *im) =
				(&*re * &C.re - &*im * &C.im, &*re * &C.im + &*im * &C.re);
		});
	}
}
// Reserve room for the two elimination/substitution steps, including complex
// products. The caller protects both pivots before using this bound.
//
// What it guarantees: with `limit = min(pivot_min, 1) / (16 * min_positive)`
// and the right hand side scaled to `|b|_max <= limit`, no intermediate of
// `solve_scaled_2x2` overflows. Complete pivoting gives `|L10| <= 1` and
// `|U01 / U00| <= 1`, so `|b1 - L10 b0| <= 2 |b|_max`, `|x1| <= 2 |b|_max /
// pivot_min` and `|x0| <= 3 |b|_max / pivot_min`, all below `3 / (16 *
// min_positive)`; the factor 16 covers this and the growth of complex
// products. `pivot_min` is capped at 1 because only a pivot below 1 can
// enlarge the solution (`dlaln2` likewise scales only when `|U11| < 1`).
//
// How it differs from `dlaln2`: Reference LAPACK bounds the eliminated
// right hand side, `BBND = max(|b0 U11 / U00|, |b1 - L10 b0|)`, against
// `BIGNUM * |U11|` with `BIGNUM = 1 / (2 * min_positive)`, after the `SMIN`
// clamp, and rescales a second time when `|x| > BIGNUM / max|C|` so that the
// caller's next update `C x` cannot overflow. Here the bound is taken on the
// unreduced `b` against the smaller pivot, which is sufficient but can scale
// where `dlaln2` would not; the second rescale is left to the caller, which
// normalizes the whole working vector after every block
// (`rescale_gevd_rhs`). A different scale only changes the working vector by
// a positive factor, which the final normalization removes; the vector is
// not bit-identical to `dtgevc`'s.
//
// Out of scope: this is an overflow guard for the 2x2 solve, nothing more.
// - Underflow: scaling down may flush small components to subnormals or zero
//   earlier than `dlaln2` would.
// - The complex divisions in `solve_scaled_2x2` (and the complex reciprocal
//   in `solve_complex_shifted_1x1`) form `|d|^2` without scaling, unlike
//   `dlaln2`'s `DLADIV`, so they lose the result for `|d|` outside about
//   `[sqrt(min_positive), sqrt(max_positive)]` (`1e-154 .. 1e154` in f64,
//   `1e-19 .. 1e19` in f32), whatever this scale is. A complex pair's
//   vectors are therefore only finite for pencils within that range: in f64,
//   `(s A, s B)` for the faer#220 pencils gives non-finite vectors for `s`
//   outside `[1e-146, 1e154]`, measured at powers of ten (faer#234). Reference LAPACK's `dggev` avoids this
//   range by scaling the pencil into `[sqrt(min_positive) / eps, eps /
//   sqrt(min_positive)]` before the QZ; `gevd_real` does not.
// - With `dtgevc`'s coefficient normalization the right hand side is about
//   `|coef| |(A, B)| xmax` and `smin >= eps |coef| |(A, B)|`, so `|b|_max /
//   pivot_min` stays below about `2 / eps`: this scale can only engage when
//   `pivot_min > 1` and `|b|_max > 1 / (16 min_positive)`, that is for
//   `|(A, B)|` near `max_positive`, beyond the range where the complex
//   divisions above already fail. No GEVD test, reference fixture or graded
//   random pencil (entries up to `1e+-300`) reaches it (faer#234).
fn shifted_2x2_scale<T: RealField>(bnorm: T, pivot_min: T) -> T {
	let limit = (min_positive::<T>() * from_f64::<T>(16.0)).recip()
		* pivot_min.fmin(one::<T>());
	if bnorm > limit { limit / bnorm } else { one() }
}

// `(a + i b) / (c + i d)` without forming `c^2 + d^2` (LAPACK `dladiv`,
// Baudin and Smith's robust complex division). The quotient by `num_complex`'s
// `Div` squares the denominator, which underflows to zero for `|c + i d|`
// below about `sqrt(min_positive)` and overflows above `sqrt(max_positive)`, so
// a finite quotient came out as `0/0 = NaN` or `inf` (tensor4all/faer#370).
fn ladiv<T: RealField>(a: &T, b: &T, c: &T, d: &T) -> (T, T) {
	fn ladiv2<T: RealField>(a: &T, b: &T, c: &T, d: &T, r: &T, t: &T) -> T {
		if *r != zero() {
			let br = b * r;
			if br != zero() {
				(a + br) * t
			} else {
				a * t + (b * t) * r
			}
		} else {
			(a + d * (b / c)) * t
		}
	}
	fn ladiv1<T: RealField>(a: &T, b: &T, c: &T, d: &T) -> (T, T) {
		let ref r = d / c;
		let ref t = (c + d * r).recip();
		let p = ladiv2(a, b, c, d, r, t);
		let q = ladiv2(b, &-a, c, d, r, t);
		(p, q)
	}
	let ref half = from_f64::<T>(0.5);
	let ref two = from_f64::<T>(2.0);
	let (mut a, mut b, mut c, mut d) = (a.copy(), b.copy(), c.copy(), d.copy());
	let ab = a.abs().fmax(b.abs());
	let cd = c.abs().fmax(d.abs());
	let mut s = one::<T>();
	let ov = max_positive::<T>();
	let un = min_positive::<T>();
	let eps = eps::<T>();
	let be = two / (&eps * &eps);
	let tiny = un * two / eps;
	if ab >= half * &ov {
		(a, b, s) = (half * a, half * b, two * s);
	}
	if cd >= half * &ov {
		(c, d, s) = (half * c, half * d, half * s);
	}
	if ab <= tiny {
		(a, b, s) = (&be * a, &be * b, s / &be);
	}
	if cd <= tiny {
		(c, d, s) = (&be * c, &be * d, s * &be);
	}
	let (p, q) = if d.abs() <= c.abs() {
		ladiv1(&a, &b, &c, &d)
	} else {
		let (p, q) = ladiv1(&b, &a, &d, &c);
		(p, -q)
	};
	(p * &s, q * &s)
}

fn ladiv_complex<T: RealField>(x: &Complex<T>, y: &Complex<T>) -> Complex<T> {
	let (re, im) = ladiv(&x.re, &x.im, &y.re, &y.im);
	Complex { re, im }
}

// Solve the pivoted 2x2 system with a scaled RHS. Form U01/U00 before
// multiplying by x1: U01*x1 itself can overflow even when x0 is finite. `div`
// is the scalar quotient: `/` for a real system, `ladiv_complex` for a complex
// one.
fn solve_scaled_2x2<T: ComplexField>(
	LU: MatRef<'_, T>,
	row_perm: crate::perm::PermRef<'_, usize>,
	col_perm: crate::perm::PermRef<'_, usize>,
	mut b: ColMut<'_, T>,
	div: impl Fn(&T, &T) -> T,
) -> T::Real {
	let bnorm = b[0]
		.real()
		.abs()
		.fmax(b[0].imag().abs())
		.fmax(b[1].real().abs())
		.fmax(b[1].imag().abs());
	let scale =
		shifted_2x2_scale(bnorm, LU[(0, 0)].abs().fmin(LU[(1, 1)].abs()));
	let rows = row_perm.arrays().0;
	let cols = col_perm.arrays().0;
	let b0 = b[rows[0]].mul_real(&scale);
	let b1 = b[rows[1]].mul_real(&scale) - &LU[(1, 0)] * &b0;
	let x1 = div(&b1, &LU[(1, 1)]);
	let x0 = div(&b0, &LU[(0, 0)]) - div(&LU[(0, 1)], &LU[(0, 0)]) * &x1;
	b[cols[0]] = x0;
	b[cols[1]] = x1;
	scale
}

fn solve_complex_shifted_2x2<T: RealField>(
	smin: T,
	ref ca: T,
	A: MatRef<'_, T>,
	ref d0: T,
	ref d1: T,
	mut B: MatMut<'_, T>,
	ref wr: T,
	ref wi: T,
	stack: &mut MemStack,
) -> T {
	let nw = B.ncols();
	let zero = zero::<T>;
	let ref safmin = min_positive::<T>();
	let ref smlnum = safmin + safmin;
	let ref smin = smin.fmax(smlnum);
	if nw == 1 {
		let (mut C, stack) =
			unsafe { linalg::temp_mat_uninit::<T, _, _>(2, 2, stack) };
		let mut C = C.as_mat_mut();
		let mut row_perm_fwd = [0usize; 2];
		let mut row_perm_inv = [0usize; 2];
		let mut col_perm_fwd = [0usize; 2];
		let mut col_perm_inv = [0usize; 2];
		C[(0, 0)] = ca * &A[(0, 0)] - wr * d0;
		C[(1, 0)] = ca * &A[(1, 0)];
		C[(0, 1)] = ca * &A[(0, 1)];
		C[(1, 1)] = ca * &A[(1, 1)] - wr * d1;
		let cmax = C.norm_max();
		if cmax < *smin {
			// `C` is replaced by `smin * I` (LAPACK `dlaln2`), so the solve is
			// this scaling alone
			let ref smin_inv = smin.recip();
			let scale = shifted_2x2_scale(B.norm_max(), smin.copy());
			zip!(B.rb_mut()).for_each(|unzip!(x)| {
				*x = (&*x * &scale) * smin_inv;
			});
			return scale;
		}
		let (_, row_perm, col_perm) =
			linalg::lu::full_pivoting::factor::lu_in_place(
				C.rb_mut(),
				&mut row_perm_fwd,
				&mut row_perm_inv,
				&mut col_perm_fwd,
				&mut col_perm_inv,
				Par::Seq,
				stack,
				Default::default(),
			);
		// a second pivot below `smin` is replaced by `smin` (LAPACK `dlaln2`).
		// `C` is exactly singular when the block holds a copy of the
		// eigenvalue being computed, and the zero pivot would divide the right
		// hand side into `inf`/`NaN` (faer#220)
		//
		// The clamp is applied to the factorized `U11`, after `lu_in_place`
		// has formed `L10 = C10 / U00`, and `L10` is not recomputed. For a 2x2
		// this is the same perturbation as `dlaln2`'s, not an approximation of
		// it: `dlaln2` also forms `LR21 = CR21 / UR11` and `UR22 = CR22 - UR12 *
		// LR21` first and then clamps `UR22` (v3.12.1, SRC/dlaln2.f, real 2x2
		// and complex 2x2 branches). The multiplier depends only on the first
		// pivot, which complete pivoting makes the largest entry, `>= cmax >=
		// smin`, so it never needs protection; the clamp replaces the solved
		// system by `L (U + (smin - U11) e1 e1^T)`, which perturbs only the
		// pivoted (1, 1) entry of `C`, by less than `2 smin`. What can differ
		// from `dlaln2` is the first pivot itself: faer's LU may rank complex
		// entries by another magnitude than `dlaln2`'s `|re| + |im|` and break
		// ties differently. Any largest entry gives `|L10| <= 1` and the same
		// argument.
		if C[(1, 1)].abs() < *smin {
			C[(1, 1)] = smin.copy();
		}
		solve_scaled_2x2(
			C.rb(),
			row_perm,
			col_perm,
			B.rb_mut().col_mut(0),
			|x: &T, y: &T| x / y,
		)
	} else {
		let (mut C, stack) =
			unsafe { linalg::temp_mat_uninit::<Complex<T>, _, _>(2, 2, stack) };
		let mut C = C.as_mat_mut();
		let mut row_perm_fwd = [0usize; 2];
		let mut row_perm_inv = [0usize; 2];
		let mut col_perm_fwd = [0usize; 2];
		let mut col_perm_inv = [0usize; 2];
		C[(0, 0)] = Complex {
			re: ca * &A[(0, 0)] - wr * d0,
			im: -wi * d0,
		};
		C[(1, 0)] = Complex {
			re: ca * &A[(1, 0)],
			im: zero(),
		};
		C[(0, 1)] = Complex {
			re: ca * &A[(0, 1)],
			im: zero(),
		};
		C[(1, 1)] = Complex {
			re: ca * &A[(1, 1)] - wr * d1,
			im: -wi * d1,
		};
		let cmax = C.norm_max();
		if cmax < *smin {
			// `C` is replaced by `smin * I`, as in the real branch
			let ref smin_inv = smin.recip();
			let scale = shifted_2x2_scale(B.norm_max(), smin.copy());
			zip!(B.rb_mut()).for_each(|unzip!(x)| {
				*x = (&*x * &scale) * smin_inv;
			});
			return scale;
		}
		let (_, row_perm, col_perm) =
			linalg::lu::full_pivoting::factor::lu_in_place(
				C.rb_mut(),
				&mut row_perm_fwd,
				&mut row_perm_inv,
				&mut col_perm_fwd,
				&mut col_perm_inv,
				Par::Seq,
				stack,
				Default::default(),
			);
		// the second pivot is protected as in the real branch, measured by
		// `|re| + |im|` (LAPACK `dlaln2`), and for the same reason it is
		// equivalent to `dlaln2`'s clamp after elimination (see the real
		// branch above)
		if C[(1, 1)].re.abs() + C[(1, 1)].im.abs() < *smin {
			C[(1, 1)] = Complex {
				re: smin.copy(),
				im: zero(),
			};
		}
		let n = B.nrows();
		let (Br, Bi) = B.two_cols_mut(0, 1);
		let (mut B, _) =
			unsafe { linalg::temp_mat_uninit::<Complex<T>, _, _>(n, 1, stack) };
		let mut B = B.as_mat_mut().col_mut(0);
		zip!(&mut B, &Br, &Bi).for_each(|unzip!(z, re, im)| {
			*z = Complex {
				re: re.copy(),
				im: im.copy(),
			}
		});
		let scale = solve_scaled_2x2(
			C.rb(),
			row_perm,
			col_perm,
			B.rb_mut(),
			ladiv_complex::<T>,
		);
		zip!(Br, Bi, &B).for_each(|unzip!(re, im, z)| {
			(*re, *im) = (z.re.copy(), z.im.copy())
		});
		scale
	}
}

// Apply the solve's scale to the remaining entries, then bound the whole
// working vector before the next matrix update or the back transformation.
fn rescale_gevd_rhs<T: RealField>(
	mut rhs: MatMut<'_, T>,
	j: usize,
	na: usize,
	ref scale: T,
) -> T {
	if *scale != one() {
		zip!(rhs.rb_mut().get_mut(..j, ..)).for_each(|unzip!(x)| *x *= scale);
		zip!(rhs.rb_mut().get_mut(j + na.., ..))
			.for_each(|unzip!(x)| *x *= scale);
	}
	let limit = if rhs.ncols() == 2 {
		from_f64::<T>(0.5)
	} else {
		one()
	};
	let xmax = rhs.norm_max();
	if xmax > limit {
		let ref scale = &limit / &xmax;
		zip!(rhs).for_each(|unzip!(x)| *x *= scale);
		one()
	} else {
		xmax / limit
	}
}
fn qz_to_gevd_real<T: RealField>(
	A: MatRef<'_, T>,
	B: MatRef<'_, T>,
	Q: Option<MatMut<'_, T>>,
	Z: Option<MatMut<'_, T>>,
	mut par: Par,
	stack: &mut MemStack,
) {
	let n = A.nrows();
	if n == 0 {
		return;
	}
	let one = one::<T>;
	let zero = zero::<T>;
	let ref ulp = eps::<T>();
	let ref safmin = min_positive::<T>();
	let ref smallnum = safmin * from_f64::<T::Real>(n as f64);
	let ref small = smallnum * ulp.recip();
	let ref bignum = smallnum.recip();
	let ref big = small.recip();
	let (mut acolnorm, stack) = linalg::temp_mat_zeroed::<T, _, _>(n, 1, stack);
	let acolnorm = acolnorm.as_mat_mut();
	let (mut bcolnorm, stack) = linalg::temp_mat_zeroed::<T, _, _>(n, 1, stack);
	let bcolnorm = bcolnorm.as_mat_mut();
	let mut acolnorm = acolnorm.col_mut(0);
	let mut bcolnorm = bcolnorm.col_mut(0);
	let mut anorm = zero();
	let mut bnorm = zero();
	let mut j = 0;
	while j < n {
		let cplx = j + 1 < n && A[(j + 1, j)] != zero();
		if !cplx {
			let a = A.rb().col(j).get(..j).norm_l1();
			acolnorm[j] = a.copy();
			anorm = anorm.fmax(a + A[(j, j)].abs());
			j += 1;
		} else {
			for jc in j..j + 2 {
				let a = A.rb().col(jc).get(..j).norm_l1();
				acolnorm[jc] = a.copy();
				anorm = anorm.fmax(a + A[(j, jc)].abs() + A[(j + 1, jc)].abs());
			}
			j += 2;
		}
	}
	for j in 0..n {
		let b = B.rb().col(j).get(..j).norm_l1();
		bcolnorm[j] = b.copy();
		bnorm = bnorm.fmax(b + B[(j, j)].abs());
	}
	let ref anorm = anorm;
	let ref bnorm = bnorm;
	let ref ascale = anorm.fmax(safmin).recip();
	let ref bscale = bnorm.fmax(safmin).recip();
	if let Some(mut u) = Q {
		let mut je = 0usize;
		while je < n {
			let cplx_eigval = je + 1 < n && A[(je + 1, je)] != zero();
			let nw = if cplx_eigval { 2 } else { 1 };
			if !cplx_eigval
				&& A[(je, je)].abs().fmax(&B[(je, je)].abs()) < *safmin
			{
				u.rb_mut().col_mut(je).fill(zero());
				u[(je, je)] = one();
				je += 1;
				continue;
			}
			let mut acoef;
			let mut acoefa;
			let mut bcoefa;
			let mut bcoefr;
			let mut bcoefi;
			let mut xmax;
			let (mut rhs, stack) =
				linalg::temp_mat_zeroed::<T, _, _>(n, nw, stack);
			let mut rhs = rhs.as_mat_mut();
			if !cplx_eigval {
				let ref temp = safmin.fmax(
					(A[(je, je)].abs() * ascale)
						.fmax(B[(je, je)].abs() * bscale),
				);
				let ref salfar = A[(je, je)].mul_real(temp).mul_real(ascale);
				let ref sbeta = B[(je, je)].real() * temp * bscale;
				acoef = sbeta * ascale;
				bcoefr = salfar * bscale;
				bcoefi = zero();
				let mut scale = one();
				let lsa = sbeta.abs() >= *safmin && acoef.abs() < *small;
				let lsb = salfar.abs() >= *safmin && bcoefr.abs() < *small;
				if lsa {
					scale = (small / sbeta.abs()) * anorm.fmin(big);
				}
				if lsb {
					scale =
						scale.fmax((small / salfar.abs()) * bnorm.fmin(big));
				}
				if lsa || lsb {
					scale = scale.fmin(
						one()
							/ (safmin
								* one().fmax(acoef.abs()).fmax(bcoefr.abs())),
					);
					if lsa {
						acoef = ascale * (&scale * sbeta)
					} else {
						acoef = &scale * acoef
					}
					if lsb {
						bcoefr = bscale * (&scale * salfar)
					} else {
						bcoefr = &scale * bcoefr
					}
				}
				acoefa = acoef.abs();
				bcoefa = bcoefr.abs();
				rhs[(je, 0)] = one();
				xmax = one();
			} else {
				let (ref scale, _, wr, _, wi) = qz_real::generalized_eigval_2x2(
					(
						A[(je, je)].copy(),
						A[(je, je + 1)].copy(),
						A[(je + 1, je)].copy(),
						A[(je + 1, je + 1)].copy(),
					),
					(
						B[(je, je)].copy(),
						B[(je, je + 1)].copy(),
						B[(je + 1, je)].copy(),
						B[(je + 1, je + 1)].copy(),
					),
				);
				acoef = scale.copy();
				bcoefr = wr;
				bcoefi = wi;
				acoefa = acoef.abs();
				bcoefa = bcoefr.abs() + bcoefi.abs();
				let mut scale = one();
				if &acoefa * ulp < *safmin && acoefa >= *safmin {
					scale = (safmin / ulp) / &acoefa;
				}
				if &bcoefa * ulp < *safmin && bcoefa >= *safmin {
					scale = scale.fmax((safmin / ulp) / &bcoefa);
				}
				if safmin * &acoefa > *ascale {
					scale = ascale / (safmin * &acoefa);
				}
				if safmin * &bcoefa > *bscale {
					scale = scale.fmin(bscale / (safmin * &bcoefa));
				}
				if scale != one() {
					acoef = &scale * &acoef;
					acoefa = acoef.abs();
					bcoefr = &scale * &bcoefr;
					bcoefi = &scale * &bcoefi;
					bcoefa = bcoefr.abs() + bcoefi.abs();
				}
				let ref temp = &acoef * &A[(je + 1, je)];
				let temp2r = &acoef * &A[(je, je)] - &bcoefr * &B[(je, je)];
				let temp2i = -&bcoefi * &B[(je, je)];
				if temp.abs() > temp2r.abs() + temp2i.abs() {
					rhs[(je, 0)] = one();
					rhs[(je, 1)] = zero();
					rhs[(je + 1, 0)] = -temp2r / temp;
					rhs[(je + 1, 1)] = -temp2i / temp;
				} else {
					rhs[(je + 1, 0)] = one();
					rhs[(je + 1, 1)] = zero();
					let ref temp = &acoef * &A[(je, je + 1)];
					rhs[(je, 0)] = (&bcoefr * &B[(je + 1, je + 1)]
						- &acoef * &A[(je + 1, je + 1)])
						/ temp;
					rhs[(je, 1)] = &bcoefi * &B[(je + 1, je + 1)] / temp;
				}
				xmax = (rhs[(je, 0)].abs() + rhs[(je, 1)].abs())
					.fmax(rhs[(je + 1, 0)].abs() + rhs[(je + 1, 1)].abs());
			}
			let dmin = safmin
				.fmax(ulp * &acoefa * anorm)
				.fmax(ulp * &bcoefa * bnorm);
			let mut j = je + nw;
			while j < n {
				let cplx = j + 1 < n && A[(j + 1, j)] != zero();
				let na = if cplx { 2 } else { 1 };
				// the guard below may only shrink the vector (LAPACK `dtgevc`:
				// `XSCALE = ONE / MAX( ONE, XMAX )`)
				let ref xscale = xmax.fmax(one()).recip();
				let mut temp = acolnorm[j]
					.fmax(&bcolnorm[j])
					.fmax(&acoefa * &acolnorm[j] + &bcoefa * &bcolnorm[j]);
				let b0 = B[(j, j)].copy();
				let b1;
				if cplx {
					temp = temp
						.fmax(
							&acoefa * &acolnorm[j + 1]
								+ &bcoefa * &bcolnorm[j + 1],
						)
						.fmax(&acolnorm[j + 1])
						.fmax(&bcolnorm[j + 1]);
					b1 = B[(j + 1, j + 1)].copy();
				} else {
					b1 = zero();
				}
				if temp > bignum * xscale {
					for jw in 0..nw {
						for jr in je..j {
							rhs[(jr, jw)] = xscale * &rhs[(jr, jw)];
						}
					}
				}
				let (mut sums, stack) = unsafe {
					linalg::temp_mat_uninit::<T, _, _>(na, nw, stack)
				};
				let mut sums = sums.as_mat_mut();
				let (mut sump, stack) = unsafe {
					linalg::temp_mat_uninit::<T, _, _>(na, nw, stack)
				};
				let mut sump = sump.as_mat_mut();
				for jw in 0..nw {
					for ja in 0..na {
						sums[(ja, jw)] = zero();
						sump[(ja, jw)] = zero();
						for jr in je..j {
							sums[(ja, jw)] = &sums[(ja, jw)]
								+ &A[(jr, j + ja)] * &rhs[(jr, jw)];
							sump[(ja, jw)] = &sump[(ja, jw)]
								+ &B[(jr, j + ja)] * &rhs[(jr, jw)];
						}
					}
				}
				for ja in 0..na {
					if cplx_eigval {
						rhs[(j + ja, 0)] = -&acoef * &sums[(ja, 0)]
							+ &bcoefr * &sump[(ja, 0)]
							- &bcoefi * &sump[(ja, 1)];
						rhs[(j + ja, 1)] = -&acoef * &sums[(ja, 1)]
							+ &bcoefr * &sump[(ja, 1)]
							+ &bcoefi * &sump[(ja, 0)];
					} else {
						rhs[(j + ja, 0)] =
							-&acoef * &sums[(ja, 0)] + &bcoefr * &sump[(ja, 0)];
					}
				}
				let scale = if cplx {
					solve_complex_shifted_2x2(
						dmin.copy(),
						acoef.copy(),
						A.submatrix(j, j, na, na).transpose(),
						b0,
						b1,
						rhs.rb_mut().subrows_mut(j, na),
						bcoefr.copy(),
						bcoefi.copy(),
						stack,
					)
				} else {
					solve_complex_shifted_1x1(
						dmin.copy(),
						acoef.copy(),
						A.submatrix(j, j, na, na).transpose(),
						b0,
						rhs.rb_mut().subrows_mut(j, na),
						bcoefr.copy(),
						bcoefi.copy(),
					);
					one()
				};
				// the left vector is zero above `je`, so this window (from `je`,
				// offset `j - je`) and the right vectors' form (from row 0, offset
				// `j`) give the same result; the offset only matters when the 2x2
				// solve returned `scale != 1`, which `shifted_2x2_scale` explains
				// is out of reach today.
				// `left_vectors_of_schur_pencil_*` pins this path
				xmax = rescale_gevd_rhs(
					rhs.rb_mut().get_mut(je..j + na, ..),
					j - je,
					na,
					scale,
				);
				j += na;
			}
			let (mut tmp, _) = linalg::temp_mat_zeroed::<T, _, _>(n, nw, stack);
			let mut tmp = tmp.as_mat_mut();
			linalg::matmul::matmul(
				tmp.rb_mut(),
				Accum::Replace,
				u.rb().get(.., je..),
				rhs.rb().get(je.., ..),
				one(),
				par.reborrow(),
			);
			let mut u = u.rb_mut().subcols_mut(je, nw);
			u.copy_from(&tmp);
			let ref scale = u.norm_l2().recip();
			zip!(u).for_each(|unzip!(u)| {
				*u *= scale;
			});
			je += nw;
		}
	}
	if let Some(mut u) = Z {
		let mut je = n;
		while je > 0 {
			je -= 1;
			let cplx_eigval = je > 0 && A[(je, je - 1)] != zero();
			let nw = if cplx_eigval { 2 } else { 1 };
			je -= nw - 1;
			if !cplx_eigval
				&& A[(je, je)].abs().fmax(&B[(je, je)].abs()) < *safmin
			{
				u.rb_mut().col_mut(je).fill(zero());
				u[(je, je)] = one();
				continue;
			}
			let mut acoef;
			let mut acoefa;
			let mut bcoefa;
			let mut bcoefr;
			let mut bcoefi;
			let (mut rhs, stack) =
				linalg::temp_mat_zeroed::<T, _, _>(n, nw, stack);
			let mut rhs = rhs.as_mat_mut();
			if !cplx_eigval {
				let ref temp = safmin.fmax(
					(A[(je, je)].abs() * ascale)
						.fmax(B[(je, je)].abs() * bscale),
				);
				let ref salfar = A[(je, je)].mul_real(temp).mul_real(ascale);
				let ref sbeta = B[(je, je)].real() * temp * bscale;
				acoef = sbeta * ascale;
				bcoefr = salfar * bscale;
				bcoefi = zero();
				let mut scale = one();
				let lsa = sbeta.abs() >= *safmin && acoef.abs() < *small;
				let lsb = salfar.abs() >= *safmin && bcoefr.abs() < *small;
				if lsa {
					scale = (small / sbeta.abs()) * anorm.fmin(big);
				}
				if lsb {
					scale =
						scale.fmax((small / salfar.abs()) * bnorm.fmin(big));
				}
				if lsa || lsb {
					scale = scale.fmin(
						one()
							/ (safmin
								* one().fmax(acoef.abs()).fmax(bcoefr.abs())),
					);
					if lsa {
						acoef = ascale * (&scale * sbeta)
					} else {
						acoef = &scale * &acoef
					}
					if lsb {
						bcoefr = bscale * (&scale * salfar)
					} else {
						bcoefr = &scale * &bcoefr
					}
				}
				acoefa = acoef.abs();
				bcoefa = bcoefr.abs();
				rhs[(je, 0)] = one();
				for jr in 0..je {
					rhs[(jr, 0)] =
						&bcoefr * &B[(jr, je)] - &acoef * &A[(jr, je)];
				}
			} else {
				let (scale, _, wr, _, wi) = qz_real::generalized_eigval_2x2(
					(
						A[(je, je)].copy(),
						A[(je, je + 1)].copy(),
						A[(je + 1, je)].copy(),
						A[(je + 1, je + 1)].copy(),
					),
					(
						B[(je, je)].copy(),
						B[(je, je + 1)].copy(),
						B[(je + 1, je)].copy(),
						B[(je + 1, je + 1)].copy(),
					),
				);
				acoef = scale;
				bcoefr = wr;
				bcoefi = wi;
				acoefa = acoef.abs();
				bcoefa = bcoefr.abs() + bcoefi.abs();
				let mut scale = one();
				if &acoefa * ulp < *safmin && acoefa >= *safmin {
					scale = (safmin / ulp) / &acoefa;
				}
				if &bcoefa * ulp < *safmin && bcoefa >= *safmin {
					scale = scale.fmax((safmin / ulp) / &bcoefa);
				}
				if safmin * &acoefa > *ascale {
					scale = ascale / (safmin * &acoefa);
				}
				if safmin * &bcoefa > *bscale {
					scale = scale.fmin(bscale / (safmin * &bcoefa));
				}
				if scale != one() {
					acoef = &scale * &acoef;
					acoefa = acoef.abs();
					bcoefr = &scale * &bcoefr;
					bcoefi = &scale * &bcoefi;
					bcoefa = bcoefr.abs() + bcoefi.abs();
				}
				let ref temp = &acoef * &A[(je + 1, je)];
				let ref temp2r = &acoef * &A[(je + 1, je + 1)]
					- &bcoefr * &B[(je + 1, je + 1)];
				let ref temp2i = -&bcoefi * &B[(je + 1, je + 1)];
				if temp.abs() > temp2r.abs() + temp2i.abs() {
					rhs[(je + 1, 0)] = one();
					rhs[(je + 1, 1)] = zero();
					rhs[(je, 0)] = -temp2r / temp;
					rhs[(je, 1)] = -temp2i / temp;
				} else {
					rhs[(je, 0)] = one();
					rhs[(je, 1)] = zero();
					let ref temp = &acoef * &A[(je, je + 1)];
					rhs[(je + 1, 0)] =
						(&bcoefr * &B[(je, je)] - &acoef * &A[(je, je)]) / temp;
					rhs[(je + 1, 1)] = &bcoefi * &B[(je, je)] / temp;
				}
				let ref creala = &acoef * &rhs[(je, 0)];
				let ref cimaga = &acoef * &rhs[(je, 1)];
				let ref crealb =
					&bcoefr * &rhs[(je, 0)] - &bcoefi * &rhs[(je, 1)];
				let ref cimagb =
					&bcoefi * &rhs[(je, 0)] + &bcoefr * &rhs[(je, 1)];
				let ref cre2a = &acoef * &rhs[(je + 1, 0)];
				let ref cim2a = &acoef * &rhs[(je + 1, 1)];
				let ref cre2b =
					&bcoefr * &rhs[(je + 1, 0)] - &bcoefi * &rhs[(je + 1, 1)];
				let ref cim2b =
					&bcoefi * &rhs[(je + 1, 0)] + &bcoefr * &rhs[(je + 1, 1)];
				for jr in 0..je {
					rhs[(jr, 0)] = -creala * &A[(jr, je)]
						+ crealb * &B[(jr, je)]
						- cre2a * &A[(jr, je + 1)]
						+ cre2b * &B[(jr, je + 1)];
					rhs[(jr, 1)] = -cimaga * &A[(jr, je)]
						+ cimagb * &B[(jr, je)]
						- cim2a * &A[(jr, je + 1)]
						+ cim2b * &B[(jr, je + 1)];
				}
			}
			let dmin = safmin
				.fmax(ulp * &acoefa * anorm)
				.fmax(ulp * &bcoefa * bnorm);
			let mut j = je;
			while j > 0 {
				j -= 1;
				let cplx = j > 0 && A[(j, j - 1)] != zero();
				let na = if cplx { 2 } else { 1 };
				j -= na - 1;
				let b0 = B[(j, j)].copy();
				let b1;
				if cplx {
					b1 = B[(j + 1, j + 1)].copy();
				} else {
					b1 = zero();
				}
				let scale = if cplx {
					solve_complex_shifted_2x2(
						dmin.copy(),
						acoef.copy(),
						A.submatrix(j, j, na, na),
						b0,
						b1,
						rhs.rb_mut().subrows_mut(j, na),
						bcoefr.copy(),
						bcoefi.copy(),
						stack,
					)
				} else {
					solve_complex_shifted_1x1(
						dmin.copy(),
						acoef.copy(),
						A.submatrix(j, j, na, na),
						b0,
						rhs.rb_mut().subrows_mut(j, na),
						bcoefr.copy(),
						bcoefi.copy(),
					);
					one()
				};
				rescale_gevd_rhs(
					rhs.rb_mut().get_mut(..je + nw, ..),
					j,
					na,
					scale,
				);
				for ja in 0..na {
					if cplx_eigval {
						let ref creala = &acoef * &rhs[(j + ja, 0)];
						let ref cimaga = &acoef * &rhs[(j + ja, 1)];
						let ref crealb = &bcoefr * &rhs[(j + ja, 0)]
							- &bcoefi * &rhs[(j + ja, 1)];
						let ref cimagb = &bcoefi * &rhs[(j + ja, 0)]
							+ &bcoefr * &rhs[(j + ja, 1)];
						for jr in 0..j {
							rhs[(jr, 0)] -= creala * &A[(jr, j + ja)]
								- crealb * &B[(jr, j + ja)];
							rhs[(jr, 1)] -= cimaga * &A[(jr, j + ja)]
								- cimagb * &B[(jr, j + ja)];
						}
					} else {
						let ref creala = &acoef * &rhs[(j + ja, 0)];
						let ref crealb = &bcoefr * &rhs[(j + ja, 0)];
						for jr in 0..j {
							rhs[(jr, 0)] -= creala * &A[(jr, j + ja)]
								- crealb * &B[(jr, j + ja)];
						}
					}
				}
			}
			let (mut tmp, _) = linalg::temp_mat_zeroed::<T, _, _>(n, nw, stack);
			let mut tmp = tmp.as_mat_mut();
			linalg::matmul::matmul(
				tmp.rb_mut(),
				Accum::Replace,
				u.rb().get(.., ..je + nw),
				rhs.rb().get(..je + nw, ..),
				one(),
				par.reborrow(),
			);
			let mut u = u.rb_mut().subcols_mut(je, nw);
			u.copy_from(&tmp);
			let ref scale = u.norm_l2().recip();
			zip!(u).for_each(|unzip!(u)| {
				*u *= scale;
			});
		}
	}
}
fn qz_to_gevd_cplx<T: ComplexField>(
	A: MatRef<'_, T>,
	B: MatRef<'_, T>,
	Q: Option<MatMut<'_, T>>,
	Z: Option<MatMut<'_, T>>,
	mut par: Par,
	stack: &mut MemStack,
) {
	let n = A.nrows();
	if n == 0 {
		return;
	}
	let one = one::<T::Real>;
	let ref ulp = eps::<T::Real>();
	let ref safmin = min_positive::<T::Real>();
	let ref smallnum = safmin * from_f64::<T::Real>(n as f64);
	let ref small = smallnum * ulp.recip();
	let ref bignum = smallnum.recip();
	let ref big = small.recip();
	let (mut acolnorm, stack) =
		linalg::temp_mat_zeroed::<T::Real, _, _>(n, 1, stack);
	let acolnorm = acolnorm.as_mat_mut();
	let (mut bcolnorm, stack) =
		linalg::temp_mat_zeroed::<T::Real, _, _>(n, 1, stack);
	let bcolnorm = bcolnorm.as_mat_mut();
	let mut acolnorm = acolnorm.col_mut(0);
	let mut bcolnorm = bcolnorm.col_mut(0);
	let mut anorm = zero::<T::Real>();
	let mut bnorm = zero::<T::Real>();
	let mut j = 0;
	while j < n {
		let a = A.rb().col(j).get(..j).norm_l1();
		acolnorm[j] = a.copy();
		anorm = anorm.fmax(a + A[(j, j)].abs());
		j += 1;
	}
	for j in 0..n {
		let ref b = B.rb().col(j).get(..j).norm_l1();
		bcolnorm[j] = b.copy();
		bnorm = bnorm.fmax(b + B[(j, j)].abs());
	}
	let ref anorm = anorm;
	let ref bnorm = bnorm;
	let ref ascale = anorm.fmax(safmin).recip();
	let ref bscale = bnorm.fmax(safmin).recip();
	if let Some(mut u) = Q {
		let mut je = 0usize;
		while je < n {
			if A[(je, je)].abs().fmax(&B[(je, je)].abs()) < *safmin {
				u.rb_mut().col_mut(je).fill(zero());
				u[(je, je)] = one().to_cplx();
				je += 1;
				continue;
			}
			let mut acoef;
			let acoefa;
			let bcoefa;
			let mut bcoef;
			let mut xmax;
			let (mut rhs, stack) =
				linalg::temp_mat_zeroed::<T, _, _>(n, 1, stack);
			let mut rhs = rhs.as_mat_mut().col_mut(0);
			{
				let ref temp = safmin.fmax(
					(A[(je, je)].abs() * ascale)
						.fmax(B[(je, je)].abs() * bscale),
				);
				let ref salfar = A[(je, je)].mul_real(temp).mul_real(ascale);
				let ref sbeta = B[(je, je)].real() * temp * bscale;
				acoef = sbeta * ascale;
				bcoef = salfar.mul_real(bscale);
				let mut scale = one();
				let lsa = sbeta.abs() >= *safmin && acoef.abs() < *small;
				let lsb = salfar.abs() >= *safmin && bcoef.abs() < *small;
				if lsa {
					scale = (small / sbeta.abs()) * anorm.fmin(big);
				}
				if lsb {
					scale =
						scale.fmax((small / salfar.abs()) * bnorm.fmin(big));
				}
				if lsa || lsb {
					scale = scale.fmin(
						one()
							/ (safmin
								* one().fmax(acoef.abs()).fmax(bcoef.abs())),
					);
					if lsa {
						acoef = sbeta * &scale * ascale
					} else {
						acoef = acoef * &scale
					}
					if lsb {
						bcoef = salfar.mul_real(&scale).mul_real(bscale)
					} else {
						bcoef = bcoef.mul_real(&scale)
					}
				}
				acoefa = acoef.abs();
				bcoefa = bcoef.abs();
				rhs[je] = one().to_cplx();
				xmax = one();
			}
			let dmin = safmin
				.fmax(ulp * &acoefa * anorm)
				.fmax(ulp * &bcoefa * bnorm);
			let mut j = je + 1;
			while j < n {
				let ref xscale = xmax.recip();
				let ref temp = acolnorm[j]
					.fmax(&bcolnorm[j])
					.fmax(&acoefa * &acolnorm[j] + &bcoefa * &bcolnorm[j]);
				let b0 = B[(j, j)].copy();
				if *temp > bignum * xscale {
					for jr in je..j {
						rhs[jr] = rhs[jr].mul_real(xscale);
					}
					xmax = xmax * xscale;
				}
				let mut sums = zero::<T>();
				let mut sump = zero::<T>();
				for jr in je..j {
					sums += A[(jr, j)].conj() * &rhs[jr];
					sump += B[(jr, j)].conj() * &rhs[jr];
				}
				rhs[j] = bcoef.conj() * &sump - sums.mul_real(&acoef);
				solve_shifted_1x1(
					dmin.copy(),
					acoef.copy(),
					A[(j, j)].conj(),
					b0.conj(),
					&mut rhs[j],
					bcoef.conj(),
				);
				j += 1;
			}
			let (mut tmp, _) = linalg::temp_mat_zeroed::<T, _, _>(n, 1, stack);
			let mut tmp = tmp.as_mat_mut().col_mut(0);
			linalg::matmul::matmul(
				tmp.rb_mut(),
				Accum::Replace,
				u.rb().get(.., je..),
				rhs.rb().get(je..),
				one().to_cplx(),
				par.reborrow(),
			);
			let mut u = u.rb_mut().col_mut(je);
			u.copy_from(&tmp);
			let ref scale = u.norm_l2().recip();
			zip!(u).for_each(|unzip!(u)| {
				*u = u.mul_real(scale);
			});
			je += 1;
		}
	}
	if let Some(mut u) = Z {
		let mut je = n;
		while je > 0 {
			je -= 1;
			if A[(je, je)].abs().fmax(&B[(je, je)].abs()) < *safmin {
				u.rb_mut().col_mut(je).fill(zero());
				u[(je, je)] = one().to_cplx();
				continue;
			}
			let mut acoef;
			let acoefa;
			let bcoefa;
			let mut bcoefr;
			let (mut rhs, stack) =
				linalg::temp_mat_zeroed::<T, _, _>(n, 1, stack);
			let mut rhs = rhs.as_mat_mut().col_mut(0);
			{
				let ref temp = safmin.fmax(
					(A[(je, je)].abs() * ascale)
						.fmax(B[(je, je)].abs() * bscale),
				);
				let ref salfar = A[(je, je)].mul_real(temp).mul_real(ascale);
				let ref sbeta = B[(je, je)].real() * temp * bscale;
				acoef = sbeta * ascale;
				bcoefr = salfar.mul_real(bscale);
				let mut scale = one();
				let lsa = sbeta.abs() >= *safmin && acoef.abs() < *small;
				let lsb = salfar.abs() >= *safmin && bcoefr.abs() < *small;
				if lsa {
					scale = (small / sbeta.abs()) * anorm.fmin(big);
				}
				if lsb {
					scale =
						scale.fmax((small / salfar.abs()) * bnorm.fmin(big));
				}
				if lsa || lsb {
					scale = scale.fmin(
						one()
							/ (safmin
								* one().fmax(acoef.abs()).fmax(bcoefr.abs())),
					);
					if lsa {
						acoef = sbeta * &scale * ascale
					} else {
						acoef = acoef * &scale
					}
					if lsb {
						bcoefr = salfar.mul_real(&scale).mul_real(bscale)
					} else {
						bcoefr = bcoefr.mul_real(&scale)
					}
				}
				acoefa = acoef.abs();
				bcoefa = bcoefr.abs();
				rhs[je] = one().to_cplx();
				for jr in 0..je {
					rhs[jr] =
						&bcoefr * &B[(jr, je)] - A[(jr, je)].mul_real(&acoef);
				}
			}
			let dmin = safmin
				.fmax(ulp * &acoefa * anorm)
				.fmax(ulp * &bcoefa * bnorm);
			let mut j = je;
			while j > 0 {
				j -= 1;
				let b0 = B[(j, j)].copy();
				solve_shifted_1x1(
					dmin.copy(),
					acoef.copy(),
					A[(j, j)].copy(),
					b0,
					&mut rhs[j],
					bcoefr.copy(),
				);
				let ref creala = rhs[j].mul_real(&acoef);
				let ref crealb = &bcoefr * &rhs[j];
				for jr in 0..j {
					rhs[jr] =
						&rhs[jr] - creala * &A[(jr, j)] + crealb * &B[(jr, j)];
				}
			}
			let (mut tmp, _) = linalg::temp_mat_zeroed::<T, _, _>(n, 1, stack);
			let mut tmp = tmp.as_mat_mut().col_mut(0);
			linalg::matmul::matmul(
				tmp.rb_mut(),
				Accum::Replace,
				u.rb().get(.., ..je + 1),
				rhs.rb().get(..je + 1),
				one().to_cplx(),
				par.reborrow(),
			);
			let mut u = u.rb_mut().col_mut(je);
			u.copy_from(&tmp);
			let ref scale = u.norm_l2().recip();
			zip!(u).for_each(|unzip!(u)| {
				*u = u.mul_real(scale);
			});
		}
	}
}

fn qz_to_gevd_real_scratch<T: RealField>(n: usize, _: ParShape) -> StackReq {
	StackReq::all_of(&[
		temp_mat_scratch::<T>(n, 1),
		temp_mat_scratch::<T>(n, 1),
		temp_mat_scratch::<T>(n, 2),
		temp_mat_scratch::<T>(2, 2),
		temp_mat_scratch::<T>(2, 2),
		StackReq::all_of(&[
			temp_mat_scratch::<T>(2, 2),
			temp_mat_scratch::<T>(n, 1),
			linalg::lu::full_pivoting::factor::lu_in_place_scratch::<
				usize,
				Complex<T>,
			>(2, 2, ParShape::Seq, Default::default()),
			linalg::lu::full_pivoting::solve::solve_in_place_scratch::<
				usize,
				Complex<T>,
			>(2, 1, ParShape::Seq),
		]),
		temp_mat_scratch::<T>(n, 2),
	])
}

fn qz_to_gevd_cplx_scratch<T: ComplexField>(n: usize, _: ParShape) -> StackReq {
	StackReq::all_of(&[temp_mat_scratch::<T>(n, 1); 4])
}

/// computes the layout of the workspace required to compute a matrix pair's
/// generalized eigendecomposition
pub fn gevd_scratch<T: ComplexField>(
	dim: usize,
	left: ComputeEigenvectors,
	right: ComputeEigenvectors,
	par: ParShape,
	params: Spec<GevdParams, T>,
) -> StackReq {
	let _ = (left, right);
	let n = dim;
	let block_size =
		linalg::qr::no_pivoting::factor::recommended_block_size::<T>(n, n);
	StackReq::any_of(&[
		linalg::temp_mat_scratch::<T>(block_size, n).and(
			linalg::qr::no_pivoting::factor::qr_in_place_scratch::<T>(n, n, block_size, par, default())
				.or(linalg::householder::apply_block_householder_sequence_transpose_on_the_left_in_place_scratch::<T>(n, block_size, n)),
		),
		gen_hessenberg::generalized_hessenberg_scratch::<T>(n, auto!(T)),
		if const { T::IS_REAL } {
			qz_real::hessenberg_to_qz_scratch::<T::Real>(n, par, params.schur)
		} else {
			qz_cplx::hessenberg_to_qz_scratch::<T>(n, par, params.schur)
		},
		if const { T::IS_REAL } {
			qz_to_gevd_real_scratch::<T::Real>(n, par)
		} else {
			qz_to_gevd_cplx_scratch::<T>(n, par)
		},
	])
}
/// computes the real matrix pair $(A, B)$'s eigendecomposition
///
/// the eigenvalues are stored in $S$, the left eigenvectors in $U_L$, and the
/// right eigenvectors in $U_R$
///
/// the values in $A$ and $B$ after this function is called are unspecified.
///
/// # range of scales
///
/// the eigenvalues $\alpha / \beta$ and the eigenvector directions of
/// $(sA, sB)$ are those of $(A, B)$. like LAPACK's `dggev`, $A$ and $B$ are
/// each scaled by a power of two before the reduction when their largest entry
/// is below $\sqrt{\text{safmin}} / \varepsilon$ or above its inverse, and
/// $\alpha$, $\beta$ are scaled back afterwards (tensor4all/faer#375; before
/// that the QZ underflowed and returned $\alpha = \beta = 0$ for every
/// eigenvalue of a tiny pencil). in `f64`, for the well-conditioned pencils of
/// `tests/gevd_scaled_pencil.rs`, the eigenvalues and eigenvectors were
/// measured within $3 \cdot 10^{-15}$ of $s = 1$ for every $s = 10^k$ at which
/// all entries of $(sA, sB)$ are normal and finite ($10^{-305}$ to $10^{307}$
/// for the widest-ranged pencil). when entries are subnormal, the input itself
/// has lost precision, and the results are correspondingly less accurate
/// (measured: within $10^{-13}$ of $s = 1$ down to $s \approx 2.0 \cdot
/// 10^{-311}$ to $2.4 \cdot 10^{-311}$, depending on the pencil).
///
/// $\alpha$ and $\beta$ are returned at the scale of the input where both are
/// finite and, if nonzero, normal there. otherwise (in `f64` this needs entries
/// near `f64::MAX` or subnormal ones) that eigenvalue's pair is multiplied by
/// a common power of two $2^d$, which leaves $\alpha / \beta$ unchanged: $d$
/// is the one nearest zero that keeps both finite and normal, else the one
/// nearest zero that keeps both finite and nonzero, and only when the
/// eigenvalue's magnitude is beyond what any pair can hold is the smaller one
/// zero (an eigenvalue $0$ or infinite). the factors are applied by exact
/// power-of-two steps, never formed as one out-of-range number. $\alpha =
/// \beta = 0$ is returned with `Ok` only when the QZ itself finds it, i.e. for
/// a pencil that is singular within the QZ's backward error. Whether such a
/// `0 / 0` depends on the input's scale is not established: on the three pencils
/// of `tests/gevd_scaled_pencil.rs` under a common scale $s$, the only ones
/// measured systematically, no $\alpha = \beta = 0$ was observed at any
/// sampled scale (every $s = 10^{k/10}$ over the range, and the transitions
/// bisected by `scan_zero_eigenvalue_boundary`); the samples do not prove
/// absence between them. the scaling back never turns a nonzero pair into one.
///
/// in short, for `f64`:
///
/// - **guaranteed range** (for a well-conditioned pencil): every entry of
///   $(sA, sB)$ normal and finite. for the pencils of `tests/gevd_scaled_pencil.rs` (entries of order $s$) that
///   is $10^{-305} \le s \le 10^{307}$; the ends are asserted
///   (`documented_range_ends_f64`, eigenvalues and eigenvectors within
///   $10^{-13}$ of $s = 1$), and a scan over every $s = 10^k$ in between
///   measured at most $3 \cdot 10^{-15}$.
///   this includes the scales of tensor4all/faer#370
///   ($10^{-150}, 10^{-146}, 10^{154}, 10^{160}$, asserted by
///   `issue_scales_f64`), where a complex pair's eigenvectors came out NaN
///   before tensor4all/faer#374.
/// - **subnormal entries**: `Ok` with finite results whose accuracy follows
///   the precision the input has lost (measured against $s = 1$: $3.7 \cdot
///   10^{-13}$ at $s = 10^{-311}$, $3.3 \cdot 10^{-7}$ at $10^{-317}$, and
///   eigenvalues off by up to $5 \cdot 10^{-4}$ relative at $10^{-320}$).
/// - **non-finite entries** (for example $s \ge 10^{308}$, where $sA$
///   overflows): [`GevdError::NoConvergence`]. NaN eigenvectors are never
///   returned with `Ok`: requested eigenvectors that come out non-finite also
///   give [`GevdError::NoConvergence`].
#[track_caller]
pub fn gevd_real<T: RealField>(
	A: MatMut<'_, T>,
	B: MatMut<'_, T>,
	S_re: DiagMut<'_, T>,
	S_im: DiagMut<'_, T>,
	beta: DiagMut<'_, T>,
	U_left: Option<MatMut<'_, T>>,
	U_right: Option<MatMut<'_, T>>,
	par: Par,
	stack: &mut MemStack,
	params: Spec<GevdParams, T>,
) -> Result<(), GevdError> {
	compute_gevd_generic(
		A,
		B,
		S_re.column_vector_mut(),
		S_im.column_vector_mut(),
		beta.column_vector_mut(),
		U_left,
		U_right,
		par,
		stack,
		params.config,
		qz_real::hessenberg_to_qz,
		qz_to_gevd_real,
	)
}
/// computes the complex matrix pair $(A, B)$'s eigendecomposition
///
/// the eigenvalues are stored in $S$, the left eigenvectors in $U_L$, and the
/// right eigenvectors in $U_R$
///
/// the values in $A$ and $B$ after this function is called are unspecified.
///
/// # range of scales
///
/// $A$ and $B$ are prescaled, and $\alpha$, $\beta$ scaled back, as in
/// [`gevd_real`], and the eigenvector back substitution divides with a scaled
/// complex reciprocal, so the range is that of [`gevd_real`]. for `c64`,
/// measured on the same three real pencils of `tests/gevd_scaled_pencil.rs`
/// taken as complex:
///
/// - **guaranteed range** (for a well-conditioned pencil): every entry of
///   $(sA, sB)$ normal and finite, which
///   for these pencils is $10^{-305} \le s \le 10^{307}$. the ends
///   (`documented_range_ends_c64`) and the tensor4all/faer#370 scales
///   $10^{-150}, 10^{-146}, 1, 10^{154}, 10^{160}$ (`issue_scales_c64`) are
///   asserted within $10^{-13}$ of $s = 1$; a scan over every $s = 10^k$ in
///   between measured at most $3 \cdot 10^{-15}$.
/// - **subnormal entries**: `Ok` with finite results whose accuracy follows
///   the precision the input has lost (measured: $3.7 \cdot 10^{-13}$ at
///   $s = 10^{-311}$, $3.3 \cdot 10^{-7}$ at $10^{-317}$).
/// - **non-finite entries** (for example $s \ge 10^{308}$):
///   [`GevdError::NoConvergence`]; requested eigenvectors that come out
///   non-finite also give [`GevdError::NoConvergence`] rather than `Ok`.
#[track_caller]
pub fn gevd_cplx<T: ComplexField>(
	A: MatMut<'_, T>,
	B: MatMut<'_, T>,
	S: DiagMut<'_, T>,
	beta: DiagMut<'_, T>,
	U_left: Option<MatMut<'_, T>>,
	U_right: Option<MatMut<'_, T>>,
	par: Par,
	stack: &mut MemStack,
	params: Spec<GevdParams, T>,
) -> Result<(), GevdError> {
	compute_gevd_generic(
		A,
		B,
		S.column_vector_mut(),
		ColMut::from_slice_mut(&mut []),
		beta.column_vector_mut(),
		U_left,
		U_right,
		par,
		stack,
		params.config,
		|A: MatMut<'_, T>,
		 B: MatMut<'_, T>,
		 Q: Option<MatMut<'_, T>>,
		 Z: Option<MatMut<'_, T>>,
		 alphar: ColMut<'_, T>,
		 _: ColMut<'_, T>,
		 beta: ColMut<'_, T>,
		 eigenvectors: ComputeEigenvectors,
		 par: Par,
		 params: GeneralizedSchurParams,
		 stack: &mut MemStack| {
			qz_cplx::hessenberg_to_qz(
				A,
				B,
				Q,
				Z,
				alphar,
				beta,
				eigenvectors,
				par,
				params,
				stack,
			)
		},
		qz_to_gevd_cplx,
	)
}
#[cfg(test)]
mod tests {
	use super::*;
	use crate::stats::prelude::*;
	use crate::utils;
	use dyn_stack::MemBuffer;
	use equator::assert;

	/// faer#217: a zero shift with a zero right hand side must not produce `0 *
	/// inf`. The protected branch replaces the denominator with `smin`, so the
	/// result is zero.
	#[test]
	fn shifted_1x1_zero_shift_zero_rhs_stays_finite() {
		let smin = 1e-30_f64;
		// ca*A - w*d0 == 0
		for (ca, a, w, d0) in [
			(1.0_f64, 1.0_f64, 1.0_f64, 1.0_f64),
			(1.0, 0.0, 3.0, 0.0),
			(2.0, 1.0, 1.0, 2.0),
		] {
			let mut b = 0.0_f64;
			solve_shifted_1x1(smin, ca, a, d0, &mut b, w);
			core::assert!(b.is_finite(), "ca={ca} a={a} w={w} d0={d0}: {b}");
			core::assert_eq!(b, 0.0);
		}
		// a nonzero right hand side in the same branch stays finite as well
		let mut b = 1.0_f64;
		solve_shifted_1x1(smin, 1.0, 1.0, 1.0, &mut b, 1.0);
		core::assert!(b.is_finite(), "{b}");
		core::assert!(b > 0.0, "{b}");
		// a tiny, representable denominator: dividing by it *and* by `smin` used to
		// overflow to infinity. `1.0 + 1e-16` was meant to be that denominator, but it
		// rounds to `1.0` in f64, so it exercised the exact-zero branch instead.
		let mut b = 1.0_f64;
		solve_shifted_1x1(smin, 1.0, 1e-300, 1.0, &mut b, 0.0);
		core::assert!(b.is_finite(), "{b}");
	}

	/// The complex helper has the same protected branch, for a real right hand
	/// side and for a complex one (two columns).
	#[test]
	fn complex_shifted_1x1_zero_shift_zero_rhs_stays_finite() {
		use crate::mat::Mat;
		let smin = 1e-30_f64;
		let a = Mat::<f64>::from_fn(1, 1, |_, _| 1.0);
		// real right hand side: ca*1 - wr*1 == 0, wi == 0
		let mut b = Mat::<f64>::zeros(2, 1);
		solve_complex_shifted_1x1(
			smin,
			1.0,
			a.as_ref(),
			1.0,
			b.as_mut(),
			1.0,
			0.0,
		);
		core::assert!(b.is_all_finite(), "{b:?}");
		core::assert_eq!(b[(0, 0)], 0.0);
		// two columns: the complex case, CR == CI == 0
		let mut b = Mat::<f64>::zeros(2, 2);
		solve_complex_shifted_1x1(
			smin,
			1.0,
			a.as_ref(),
			1.0,
			b.as_mut(),
			1.0,
			0.0,
		);
		core::assert!(b.is_all_finite(), "{b:?}");
		// nonzero right hand side in the same branch
		let mut b = Mat::<f64>::from_fn(2, 2, |i, j| (i + j + 1) as f64);
		solve_complex_shifted_1x1(
			smin,
			1.0,
			a.as_ref(),
			1.0,
			b.as_mut(),
			1.0,
			0.0,
		);
		core::assert!(b.is_all_finite(), "{b:?}");
	}

	/// faer#220: an exactly singular shifted 2x2 block, with a nonzero right
	/// hand side and the norm of `C` above `smin`. The second pivot is replaced
	/// by `smin`, so the solution is finite and nonzero.
	#[test]
	fn complex_shifted_2x2_singular_block_stays_finite() {
		use crate::mat::Mat;
		let smin = 1e-30_f64;
		let mut mem = MemBuffer::new(dyn_stack::StackReq::new::<f64>(256));
		let stack = MemStack::new(&mut mem);
		// real shift: `C = A` with `A` of rank one
		let a = Mat::<f64>::from_fn(2, 2, |_, _| 1.0);
		let mut b = Mat::<f64>::from_fn(2, 1, |i, _| (i + 1) as f64);
		solve_complex_shifted_2x2(
			smin,
			1.0,
			a.as_ref(),
			1.0,
			1.0,
			b.as_mut(),
			0.0,
			0.0,
			stack,
		);
		core::assert!(b.is_all_finite(), "{b:?}");
		core::assert!(b.norm_max() > 0.0, "{b:?}");
		// complex shift: `A = [[2, 1], [-1, 2]]` shifted by its own eigenvalue
		// `2 + i`, in both orientations the callers pass
		let a =
			Mat::<f64>::from_fn(2, 2, |i, j| [[2.0, 1.0], [-1.0, 2.0]][i][j]);
		for a in [a.as_ref(), a.transpose()] {
			let mut b =
				Mat::<f64>::from_fn(2, 2, |i, j| (i + 2 * j + 1) as f64);
			solve_complex_shifted_2x2(
				smin,
				1.0,
				a,
				1.0,
				1.0,
				b.as_mut(),
				2.0,
				1.0,
				stack,
			);
			core::assert!(b.is_all_finite(), "{b:?}");
			core::assert!(b.norm_max() > 0.0, "{b:?}");
		}
	}

	/// A shifted 2x2 block whose largest entry is below `smin` is replaced by
	/// `smin * I`: the solution is the right hand side divided by `smin`, not
	/// divided again by the block.
	#[test]
	fn complex_shifted_2x2_tiny_block_is_a_scaling() {
		use crate::mat::Mat;
		let smin = 1e-20_f64;
		let mut mem = MemBuffer::new(dyn_stack::StackReq::new::<f64>(256));
		let stack = MemStack::new(&mut mem);
		let a = Mat::<f64>::from_fn(2, 2, |i, j| {
			1e-30 * [[2.0, 1.0], [-1.0, 2.0]][i][j]
		});
		for nw in [1, 2] {
			let b0 = Mat::<f64>::from_fn(2, nw, |i, j| (i + 2 * j + 1) as f64);
			let mut b = b0.clone();
			solve_complex_shifted_2x2(
				smin,
				1.0,
				a.as_ref(),
				1.0,
				1.0,
				b.as_mut(),
				0.0,
				0.0,
				stack,
			);
			for j in 0..nw {
				for i in 0..2 {
					core::assert_eq!(b[(i, j)], b0[(i, j)] * smin.recip());
				}
			}
		}
	}

	fn check_complex_shifted_2x2_large_rhs<T: RealField>() {
		let eps = eps::<T>();
		let smin = &eps * &eps;
		let big = min_positive::<T>().recip() / from_f64::<T>(16.0);
		let mut mem = MemBuffer::new(dyn_stack::StackReq::new::<T>(256));
		for tiny in [false, true] {
			let c = if tiny { &smin * &eps } else { eps.copy() };
			let a = Mat::<T>::from_fn(2, 2, |i, j| {
				&c * from_f64::<T>([[1.0, 5.0], [2.0, 3.0]][i][j])
			});
			for a in [a.as_ref(), a.transpose()] {
				for nw in [1, 2] {
					for j in [0, 1] {
						let mut b = Mat::<T>::from_fn(3, nw, |_, _| big.copy());
						let scale = solve_complex_shifted_2x2(
							smin.copy(),
							one(),
							a,
							one(),
							one(),
							b.as_mut().subrows_mut(j, 2),
							zero(),
							if nw == 2 { c.copy() } else { zero() },
							MemStack::new(&mut mem),
						);
						core::assert!(
							b.is_all_finite(),
							"tiny={tiny}, nw={nw}: {b:?}"
						);
						core::assert!(
							scale > zero() && scale < one(),
							"{scale:?}"
						);
						rescale_gevd_rhs(b.as_mut(), j, 2, scale);
						// The untouched row represents the rest of the eigenvector.
						// C*x must equal that row after both scales are propagated.
						let anchor = if j == 0 { 2 } else { 0 };
						let unit = if tiny { &smin } else { &c };
						let target = &b[(anchor, 0)] / unit;
						core::assert!(target > zero(), "{b:?}");
						for i in 0..2 {
							let mut rr = -&target;
							let mut ri = if nw == 2 {
								-&b[(anchor, 1)] / unit
							} else {
								zero()
							};
							for k in 0..2 {
								let ar = if tiny {
									if i == k { one() } else { zero() }
								} else {
									&a[(i, k)] / &c
								};
								let xr = &b[(j + k, 0)];
								let xi = if nw == 2 {
									b[(j + k, 1)].copy()
								} else {
									zero()
								};
								rr += &ar * xr;
								ri += &ar * &xi;
								if !tiny && nw == 2 && i == k {
									rr += &xi;
									ri -= xr;
								}
							}
							let residual = rr.abs().fmax(ri.abs())
								/ target.fmax(one::<T>());
							core::assert!(
								residual < &eps * from_f64::<T>(128.0),
								"residual={residual:?}"
							);
						}
					}
				}
			}
		}
	}

	#[test]
	fn complex_shifted_2x2_large_rhs_f32() {
		check_complex_shifted_2x2_large_rhs::<f32>();
	}

	#[test]
	fn complex_shifted_2x2_large_rhs_f64() {
		check_complex_shifted_2x2_large_rhs::<f64>();
	}

	/// tensor4all/faer#370: quotients whose denominator squares out of range.
	/// `num_complex`'s `Div` returns NaN or `0` for each of these; `ladiv`
	/// matches the exact quotient to a few ulps.
	#[test]
	fn ladiv_does_not_square_the_denominator() {
		// (a, b, c, d, exact (a + ib) / (c + id))
		let cases: [(f64, f64, f64, f64, (f64, f64)); 5] = [
			// the clamped pivot of the faer#220 pencil at `s = 1e-200`
			(1e-200, 0.0, 4e-216, 0.0, (2.5e15, 0.0)),
			(1e-170, 1e-170, 1e-170, -1e-170, (0.0, 1.0)),
			(1e300, 1e300, 1e300, -1e300, (0.0, 1.0)),
			(3e-170, 4e-170, 1e-170, 0.0, (3.0, 4.0)),
			(1.0, 0.0, 1e200, 1e200, (5e-201, -5e-201)),
		];
		for (a, b, c, d, (re, im)) in cases {
			let naive = c64::new(a, b) / c64::new(c, d);
			let (p, q) = ladiv(&a, &b, &c, &d);
			let err = ((p - re).abs() + (q - im).abs())
				/ (re.abs() + im.abs());
			assert!(
				err <= 4.0 * f64::EPSILON,
				"({a:e} + {b:e}i) / ({c:e} + {d:e}i) = ({p:e}, {q:e}), exact \
				 ({re:e}, {im:e}), naive {naive}"
			);
			assert!(!(naive.re == re && naive.im == im));
		}
	}
	#[test]
	fn test_lishen_() {
		let approx_eq = utils::approx::CwiseMat(
			utils::approx::ApproxEq::<f64>::eps() * 128.0,
		);
		let A = &[
			[
				0.0000000067116330731078674,
				-0.0000000024189842394753674,
				0.00000000032505193899740187,
				0.0,
				0.0,
				0.0,
			],
			[
				-0.0000000024189842394753674,
				0.000000011866543705551487,
				-0.00000001582083742901503,
				0.0,
				0.0,
				0.0,
			],
			[
				0.00000000032505193899740187,
				-0.00000001582083742901503,
				0.00000002523087227632826,
				0.0,
				0.0,
				0.0,
			],
			[0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
			[0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
			[0.0, 0.0, 0.0, 0.0, 0.0, 1.0f64],
		];
		let B = &[
			[
				0.00016038376001067668,
				-0.00003674235041182116,
				-0.0000029397921270058582,
				-1.0,
				-0.0,
				-0.0,
			],
			[
				-0.00003674235041182116,
				0.0002038454538304322,
				-0.00021213416901900504,
				-0.0,
				-1.0,
				-0.0,
			],
			[
				-0.0000029397921270058582,
				-0.00021213416901900504,
				0.0003954706173886255,
				-0.0,
				-0.0,
				-1.0,
			],
			[1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
			[0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
			[0.0, 0.0, 1.0, 0.0, 0.0, 0.0f64],
		];
		let A = MatRef::from_row_major_array(A);
		let B = MatRef::from_row_major_array(B);
		let n = A.nrows();
		{
			let mut H = A.to_owned();
			let mut T = B.to_owned();
			let mut alpha_re = Diag::<f64>::zeros(n);
			let mut alpha_im = Diag::<f64>::zeros(n);
			let mut beta = Diag::<f64>::zeros(n);
			let mut UL = Mat::<f64>::identity(n, n);
			let mut UR = Mat::<f64>::identity(n, n);
			gevd_real(
				H.as_mut(),
				T.as_mut(),
				alpha_re.rb_mut(),
				alpha_im.rb_mut(),
				beta.rb_mut(),
				Some(UL.as_mut()),
				Some(UR.as_mut()),
				Par::Seq,
				MemStack::new(&mut MemBuffer::new(gevd_scratch::<f64>(
					n,
					ComputeEigenvectors::Yes,
					ComputeEigenvectors::Yes,
					ParShape::Seq,
					default(),
				))),
				default(),
			)
			.unwrap();
			{
				let mut i = 0;
				while i < n {
					if alpha_im[i] == 0.0 {
						let u = UR.col(i);
						let a = alpha_re[i];
						let b = beta[i];
						assert!((b / a) * & A * u ~ B * u);
						i += 1;
					} else {
						let ur = UR.col(i);
						let ui = UR.col(i + 1);
						let ar = alpha_re[i];
						let ai = alpha_im[i];
						let b = beta[i];
						assert!(b * & A * ur ~ B * (ar * ur - ai * ui));
						assert!(b * & A * ui ~ B * (ar * ui + ai * ur));
						i += 2;
					}
				}
			}
			{
				let mut i = 0;
				while i < n {
					if alpha_im[i] == 0.0 {
						let u = UL.col(i);
						let a = alpha_re[i];
						let b = beta[i];
						assert!(b / a * u.adjoint() * & A ~ u.adjoint() * B);
						i += 1;
					} else {
						let ur = UL.col(i);
						let ui = UL.col(i + 1);
						let ar = alpha_re[i];
						let ai = alpha_im[i];
						let b = beta[i];
						assert!(
							b * ur.adjoint() * & A ~ (ar * ur - ai * ui).adjoint() * B
						);
						assert!(
							b * ui.adjoint() * & A ~ (ar * ui + ai * ur).adjoint() * B
						);
						i += 2;
					}
				}
			}
		}
	}
	#[test]
	fn test_cplx() {
		let rng = &mut StdRng::seed_from_u64(1);
		let approx_eq = utils::approx::CwiseMat(
			utils::approx::ApproxEq::<f64>::eps() * 128.0,
		);
		let n = 20;
		let A = &CwiseMatDistribution {
			nrows: n,
			ncols: n,
			dist: ComplexDistribution::new(StandardNormal, StandardNormal),
		}
		.rand::<Mat<c64>>(rng);
		let B = &CwiseMatDistribution {
			nrows: n,
			ncols: n,
			dist: ComplexDistribution::new(StandardNormal, StandardNormal),
		}
		.rand::<Mat<c64>>(rng);
		{
			let mut H = A.to_owned();
			let mut T = B.to_owned();
			let mut alpha_re = Diag::<c64>::zeros(n);
			let mut beta = Diag::<c64>::zeros(n);
			let mut UL = Mat::<c64>::identity(n, n);
			let mut UR = Mat::<c64>::identity(n, n);
			gevd_cplx(
				H.as_mut(),
				T.as_mut(),
				alpha_re.rb_mut(),
				beta.rb_mut(),
				Some(UL.as_mut()),
				Some(UR.as_mut()),
				Par::Seq,
				MemStack::new(&mut MemBuffer::new(gevd_scratch::<c64>(
					n,
					ComputeEigenvectors::Yes,
					ComputeEigenvectors::Yes,
					ParShape::Seq,
					default(),
				))),
				default(),
			)
			.unwrap();
			{
				let mut i = 0;
				while i < n {
					let u = UR.col(i);
					let a = alpha_re[i];
					let b = beta[i];
					assert!(Scale(b / a) * A * u ~ B * u);
					i += 1;
				}
			}
			{
				let mut i = 0;
				while i < n {
					let u = UL.col(i);
					let a = alpha_re[i];
					let b = beta[i];
					assert!(Scale(b / a) * u.adjoint() * A ~ u.adjoint() * B);
					i += 1;
				}
			}
		}
	}
	/// faer#234: the left-vector substitution of `qz_to_gevd_real`, checked
	/// directly on a pencil already in generalized Schur form (so `Q = I` and
	/// no QZ runs) against a plain complex forward substitution, rather than
	/// through a residual. The pencil has a real eigenvalue first, so the
	/// complex pairs start at `je > 0` and their substitution runs on the
	/// `rhs` window that begins at `je` (offset `j - je`; the right vectors use
	/// a window from row 0, offset `j`). Its three pairs `2 + 0.05 k +- i` are
	/// coupled, so the working vector grows between blocks.
	///
	/// The window/offset pair itself is not observable here or anywhere else:
	/// it is read only when the 2x2 solve returns `scale != 1`, which
	/// `shifted_2x2_scale` explains is out of reach today.
	/// Replacing it by the right vectors' form, or changing only the offset or
	/// only the window, leaves every GEVD test green (faer#234). This test pins
	/// the values the path produces, so a refactor that changes them fails.
	///
	/// Each column pair must equal, up to one complex factor, the vector `y`
	/// with `y^T A = lambda y^T B` for the eigenvalue with positive imaginary
	/// part (the convention `gevd_real` documents).
	fn check_left_vectors_of_schur_pencil<T: RealField + Copy + Into<f64>>(
		tol: f64,
	) {
		use crate::mat::Mat;
		use num_complex::Complex as C;
		let n = 9;
		let delta = 0.05;
		// blocks: [0], [1, 2], [3, 4], [5, 6], [7], [8]
		let starts = [0usize, 1, 3, 5, 7, 8];
		let mut a = Mat::<f64>::zeros(n, n);
		let mut b = Mat::<f64>::zeros(n, n);
		a[(0, 0)] = 0.5;
		for (k, &o) in [1usize, 3, 5].iter().enumerate() {
			let x = 2.0 + k as f64 * delta;
			a[(o, o)] = x;
			a[(o, o + 1)] = 1.0;
			a[(o + 1, o)] = -1.0;
			a[(o + 1, o + 1)] = x;
			if o + 2 < 7 {
				a[(o + 1, o + 3)] = 0.75;
			}
		}
		a[(7, 7)] = 3.0;
		a[(8, 8)] = -1.0;
		// the 2x2 blocks of B are multiples of I (diagonal, as the Schur form
		// requires, and equal so that the block's eigenvalue is `(x +- i) / b`)
		for (bi, &i) in starts.iter().enumerate() {
			let ie = starts.get(bi + 1).copied().unwrap_or(n);
			for r in i..ie {
				b[(r, r)] = 1.0 + 0.125 * bi as f64;
			}
			for j in ie..n {
				for r in i..ie {
					if a[(r, j)] == 0.0 {
						a[(r, j)] = 0.1 * ((r + 2 * j) % 5) as f64 - 0.2;
					}
					b[(r, j)] = 0.05 * ((3 * r + j) % 7) as f64 - 0.15;
				}
			}
		}
		let a_t = Mat::<T>::from_fn(n, n, |i, j| from_f64::<T>(a[(i, j)]));
		let b_t = Mat::<T>::from_fn(n, n, |i, j| from_f64::<T>(b[(i, j)]));
		let mut u = Mat::<T>::identity(n, n);
		let mut mem =
			MemBuffer::new(qz_to_gevd_real_scratch::<T>(n, ParShape::Seq));
		qz_to_gevd_real(
			a_t.as_ref(),
			b_t.as_ref(),
			Some(u.as_mut()),
			None,
			Par::Seq,
			MemStack::new(&mut mem),
		);
		let u = Mat::<f64>::from_fn(n, n, |i, j| u[(i, j)].into());
		assert!(u.is_all_finite());

		let block = |i: usize| {
			let bi = starts.iter().rposition(|&s| s <= i).unwrap();
			let ie = starts.get(bi + 1).copied().unwrap_or(n);
			(starts[bi], ie - starts[bi])
		};
		let mut je = 0;
		while je < n {
			let (_, nw) = block(je);
			// the eigenvalue with positive imaginary part, from the block
			let lambda = if nw == 1 {
				C::new(a[(je, je)] / b[(je, je)], 0.0)
			} else {
				C::new(a[(je, je)], a[(je, je + 1)].abs()) / b[(je, je)]
			};
			let m = |i: usize, j: usize| {
				C::new(a[(i, j)], 0.0) - lambda * b[(i, j)]
			};
			// y^T M = 0, y zero above the block
			let mut y = vec![C::new(0.0, 0.0); n];
			if nw == 1 {
				y[je] = C::new(1.0, 0.0);
			} else {
				// left null vector of the singular 2x2 block
				y[je] = C::new(1.0, 0.0);
				y[je + 1] = -m(je, je) / m(je + 1, je);
			}
			let mut j = je + nw;
			while j < n {
				let (_, na) = block(j);
				// y_blk^T M_blk = -sum_{i < j} y_i M_{i, blk}
				let rhs: Vec<C<f64>> = (0..na)
					.map(|c| {
						-(0..j).map(|i| y[i] * m(i, j + c)).sum::<C<f64>>()
					})
					.collect();
				if na == 1 {
					y[j] = rhs[0] / m(j, j);
				} else {
					// solve [y0 y1] [[m00 m01] [m10 m11]] = [r0 r1]
					let (m00, m01, m10, m11) =
						(m(j, j), m(j, j + 1), m(j + 1, j), m(j + 1, j + 1));
					let det = m00 * m11 - m01 * m10;
					y[j] = (rhs[0] * m11 - rhs[1] * m10) / det;
					y[j + 1] = (rhs[1] * m00 - rhs[0] * m01) / det;
				}
				j += na;
			}
			let got: Vec<C<f64>> = (0..n)
				.map(|i| {
					C::new(
						u[(i, je)],
						if nw == 2 { u[(i, je + 1)] } else { 0.0 },
					)
				})
				.collect();
			// sine of the complex angle between `got` and `y`, from the part of
			// `got` orthogonal to `y` (not `1 - cos^2`, which cancels below
			// `sqrt(eps)`)
			let ny: f64 = y.iter().map(|z| z.norm_sqr()).sum::<f64>();
			let ng: f64 = got.iter().map(|z| z.norm_sqr()).sum::<f64>();
			let c = (0..n).map(|i| y[i].conj() * got[i]).sum::<C<f64>>() / ny;
			let sin =
				((0..n).map(|i| (got[i] - y[i] * c).norm_sqr()).sum::<f64>()
					/ ng)
					.sqrt();
			assert!(sin < tol, "left vector at {je}: sin = {sin:e}");
			// zero above the block
			for (i, z) in got.iter().enumerate().take(je) {
				assert!(*z == C::new(0.0, 0.0), "left vector at {je}: row {i}");
			}
			je += nw;
		}
	}

	#[test]
	fn left_vectors_of_schur_pencil_f32() {
		check_left_vectors_of_schur_pencil::<f32>(1e-5);
	}

	#[test]
	fn left_vectors_of_schur_pencil_f64() {
		check_left_vectors_of_schur_pencil::<f64>(1e-13);
	}
}

// tests by @sjoelund
#[cfg(test)]
mod t {
	use colmat::dyn_stack::{MemBuffer, MemStack};
	use colmat::linalg::evd::ComputeEigenvectors as CE;
	use colmat::prelude::*;
	use colmat::{Par, Spec, linalg};

	fn mk(n: usize, seed: u64) -> Mat<f64> {
		let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
		let mut next = move || {
			s = s
				.wrapping_mul(6364136223846793005)
				.wrapping_add(1442695040888963407);
			((s >> 33) as f64 / (1u64 << 31) as f64) - 1.0
		};
		Mat::from_fn(n, n, |i, j| next() + if i == j { n as f64 } else { 0.0 })
	}

	/// `gevd_real`, with the right-eigenvector flag as a parameter.
	fn gevd(a: &Mat<f64>, b: &Mat<f64>, vectors: bool) -> Vec<(f64, f64)> {
		let n = a.nrows();
		let (mut am, mut bm) = (a.clone(), b.clone());
		let mut sre = colmat::diag::Diag::<f64>::zeros(n);
		let mut sim = colmat::diag::Diag::<f64>::zeros(n);
		let mut bet = colmat::diag::Diag::<f64>::zeros(n);
		let mut u = Mat::<f64>::zeros(n, n);
		let ce = if vectors { CE::Yes } else { CE::No };
		let mut mem = MemBuffer::new(linalg::gevd::gevd_scratch::<f64>(
			n,
			CE::No,
			ce,
			ParShape::Seq,
			Spec::default(),
		));
		linalg::gevd::gevd_real(
			am.as_mut(),
			bm.as_mut(),
			sre.as_mut(),
			sim.as_mut(),
			bet.as_mut(),
			None,
			vectors.then(|| u.as_mut()),
			Par::Seq,
			MemStack::new(&mut mem),
			Spec::default(),
		)
		.unwrap();
		(0..n).map(|k| (sre[k] / bet[k], sim[k] / bet[k])).collect()
	}

	/// |det(A - lambda B)|, zero exactly at an eigenvalue.
	fn residual(a: &Mat<f64>, b: &Mat<f64>, lam: (f64, f64)) -> f64 {
		let n = a.nrows();
		let mut m: Vec<(f64, f64)> = (0..n * n)
			.map(|k| {
				let (i, j) = (k % n, k / n);
				(a[(i, j)] - lam.0 * b[(i, j)], -lam.1 * b[(i, j)])
			})
			.collect();
		let mut det = (1.0f64, 0.0f64);
		for col in 0..n {
			let p = (col..n)
				.max_by(|&x, &y| {
					let f = |r: usize| m[r + col * n].0.hypot(m[r + col * n].1);
					f(x).partial_cmp(&f(y)).unwrap()
				})
				.unwrap();
			if p != col {
				for j in 0..n {
					m.swap(col + j * n, p + j * n);
				}
				det = (-det.0, -det.1);
			}
			let d = m[col + col * n];
			det = (det.0 * d.0 - det.1 * d.1, det.0 * d.1 + det.1 * d.0);
			let dn = d.0 * d.0 + d.1 * d.1;
			if dn == 0.0 {
				continue;
			}
			for r in col + 1..n {
				let x = m[r + col * n];
				let f = (
					(x.0 * d.0 + x.1 * d.1) / dn,
					(x.1 * d.0 - x.0 * d.1) / dn,
				);
				for j in col..n {
					let y = m[col + j * n];
					m[r + j * n].0 -= f.0 * y.0 - f.1 * y.1;
					m[r + j * n].1 -= f.0 * y.1 + f.1 * y.0;
				}
			}
		}
		det.0.hypot(det.1)
	}

	/// ISSUE 1 (documentation): `gevd_real` writes a complex conjugate pair's
	/// eigenvalue into the FIRST slot only. The second slot holds the 2x2
	/// block's other diagonal entry, which is not an eigenvalue -- reading it
	/// gives a value whose `det(A - lambda B)` is O(1e-2) rather than O(1e-16).
	///
	/// faer's own `Solvers` layer never reads it: `solvers.rs::real_to_cplx`
	/// builds `S[j + 1]` from `S_re[j]`, not `S_re[j + 1]`. Nothing on
	/// `gevd_real` says so, and the same applies to
	/// `qz_real::hessenberg_to_qz`.
	#[test]
	fn eigenvalues_only_gives_wrong_complex_pairs() {
		let (mut bad_novec, mut bad_vec) = (0, 0);
		for n in [3usize, 4, 5, 6, 8, 10, 12] {
			for seed in 0..40u64 {
				let a = mk(n, seed * 7919 + n as u64);
				let b = mk(n, seed * 7919 + n as u64 + 5000);
				let scale = (0..n * n)
					.map(|k| a[(k % n, k / n)].abs())
					.fold(1.0f64, f64::max);
				let tol = 1e-9 * scale.powi(n as i32);
				for (lams, vectors) in
					[(gevd(&a, &b, false), false), (gevd(&a, &b, true), true)]
				{
					for &l in &lams {
						if l.1 == 0.0 {
							continue;
						}
						if residual(&a, &b, l) > tol {
							if vectors {
								bad_vec += 1
							} else {
								bad_novec += 1
							}
						}
					}
				}
			}
		}
		assert_eq!(bad_novec, 0, "eigenvalues-only path is wrong");
		assert_eq!(bad_vec, 0, "eigenvalues-only path is wrong");
	}

	/// BUG 2: `gevd_scratch` under-allocates, so `gevd_real` panics inside
	/// `temp_mat_zeroed`. n = 2 with eigenvectors requested.
	#[test]
	fn gevd_scratch_is_too_small_for_n2() {
		let mut panics = 0;
		for seed in 0..40u64 {
			let a = mk(2, seed * 7919 + 2);
			let b = mk(2, seed * 7919 + 2 + 5000);
			if std::panic::catch_unwind(|| gevd(&a, &b, true)).is_err() {
				panics += 1;
			}
		}
		assert_eq!(panics, 0, "gevd_scratch under-allocates");
	}
	/// `gevd_real` writes into caller-provided output buffers, so a reused buffer
	/// must not leak into the eigenvectors through the entries it leaves unwritten.
	#[test]
	fn reused_eigenvector_buffers() {
		fn check<T: colmat::traits::RealField>(
			a: Mat<T>,
			b: Mat<T>,
			prefills: [T; 2],
			tol: T,
		) {
			for prefill in prefills {
				for (want_left, want_right) in
					[(false, true), (true, false), (true, true)]
				{
					let mut am = a.clone();
					let mut bm = b.clone();
					let mut sre = colmat::diag::Diag::<T>::zeros(2);
					let mut sim = colmat::diag::Diag::<T>::zeros(2);
					let mut bet = colmat::diag::Diag::<T>::zeros(2);
					let mut ul = Mat::<T>::full(2, 2, prefill.clone());
					let mut ur = Mat::<T>::full(2, 2, prefill.clone());
					let ce = |v: bool| {
						if v { CE::Yes } else { CE::No }
					};
					linalg::gevd::gevd_real(
						am.as_mut(),
						bm.as_mut(),
						sre.as_mut(),
						sim.as_mut(),
						bet.as_mut(),
						want_left.then(|| ul.as_mut()),
						want_right.then(|| ur.as_mut()),
						Par::Seq,
						MemStack::new(&mut MemBuffer::new(
							linalg::gevd::gevd_scratch::<T>(
								2,
								ce(want_left),
								ce(want_right),
								ParShape::Seq,
								Spec::default(),
							),
						)),
						Spec::default(),
					)
					.unwrap();
					// the residual alone would also accept all-zero eigenvectors, and
					// `norm_max` skips NaN entries, so require real vectors and finite sums
					let nonzero = |v: &Mat<T>| {
						for j in 0..v.ncols() {
							assert!(v.col(j).norm_l2() > tol);
						}
					};
					if want_right {
						assert!(ur.is_all_finite());
						nonzero(&ur);
						let res =
							(&a * &ur) * bet.as_ref() - &ur * sre.as_ref();
						assert!(res.is_all_finite());
						assert!(res.norm_max() < tol);
					}
					if want_left {
						assert!(ul.is_all_finite());
						nonzero(&ul);
						let res = bet.as_ref() * (ul.adjoint() * &a)
							- sre.as_ref() * (ul.adjoint() * &b);
						assert!(res.is_all_finite());
						assert!(res.norm_max() < tol);
					}
				}
			}
		}
		check(
			Mat::<f32>::from_fn(2, 2, |i, j| [[2.0, 1.0], [0.0, 3.0]][i][j]),
			Mat::<f32>::identity(2, 2),
			[0.0, 2.0],
			1e-5,
		);
		check(
			Mat::<f64>::from_fn(2, 2, |i, j| [[2.0, 1.0], [0.0, 3.0]][i][j]),
			Mat::<f64>::identity(2, 2),
			[0.0, 2.0],
			1e-12,
		);
	}
}