phasesmith-workflows 0.4.1

Application-neutral native workflows for PhaseSmith
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
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
//! Native fixed-reflection Le Bail integrated-intensity extraction.

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{Display, Formatter};

use nalgebra::{DMatrix, DVector};
use phasesmith_core::{
    Accumulation, ConstantWavelengthInstrument, CwContributionsError, GridView,
    OwnedCwContributionArrays, OwnedCwContributions, ProfileError, SupportPolicy,
    accumulate_cw_contributions_batch_with_context,
};
use phasesmith_crystallography::UnitCell;
use phasesmith_execution::{ExecutionPolicy, ExecutionPolicyError};
use phasesmith_model::{DomainError, PatternRecord};

use crate::{
    BackgroundError, BackgroundModel, Constraint, ConstraintError, ConstraintTransform,
    DiagnosticValue, DifferentiableBackground, GeneratedLatticeDomain, LatticeError,
    LatticeReflectionDomain, ParameterBounds, ParameterError, ParameterKey, ParameterSet,
    ParameterSpec, RefinementEventKind, RefinementLimits, RefinementRuntime, ResidualError,
    ResidualEvaluation, ResidualOptions, RuntimeError, TerminationReason, cw_lattice_geometry,
    evaluate_residuals,
};

const INSTRUMENT_PARAMETER_NAMES: [&str; 5] = ["u_deg2", "v_deg2", "w_deg2", "x_deg", "y_deg"];
const LATTICE_PARAMETER_NAMES: [&str; 6] = [
    "a_angstrom",
    "b_angstrom",
    "c_angstrom",
    "alpha_deg",
    "beta_deg",
    "gamma_deg",
];

/// One fixed reflection phase whose integrated intensities are extracted.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailPhase {
    phase_id: String,
    name: String,
    reflection_ids: Vec<String>,
    hkl: Vec<[i32; 3]>,
    d_spacing_angstrom: Vec<f64>,
    two_theta_deg: Vec<f64>,
    integrated_intensity: Vec<f64>,
    scale: f64,
    preserve_unobserved: Vec<bool>,
    cell: Option<UnitCell>,
    reflection_domain: Option<LatticeReflectionDomain>,
}

impl LeBailPhase {
    /// Validate and own one ordered fixed-reflection phase.
    ///
    /// `preserve_unobserved` marks generated reflections outside the currently
    /// visible interval. Their checkpoint intensity is retained when their
    /// finite profile support has no included samples. Pass an empty vector for
    /// ordinary fixed reflection lists.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError::InvalidPhase`] for invalid identity, shape, or
    /// numerical state.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        phase_id: impl Into<String>,
        name: impl Into<String>,
        reflection_ids: Vec<String>,
        hkl: Vec<[i32; 3]>,
        d_spacing_angstrom: Vec<f64>,
        two_theta_deg: Vec<f64>,
        integrated_intensity: Vec<f64>,
        scale: f64,
        preserve_unobserved: Vec<bool>,
    ) -> Result<Self, LeBailError> {
        let phase = Self {
            phase_id: phase_id.into(),
            name: name.into(),
            reflection_ids,
            hkl,
            d_spacing_angstrom,
            two_theta_deg,
            integrated_intensity,
            scale,
            preserve_unobserved,
            cell: None,
            reflection_domain: None,
        };
        phase.validate()?;
        Ok(phase)
    }

    /// Generate and own a bounded dynamic-lattice phase.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] if the cell lies outside the domain, reflection
    /// generation fails, or the resulting phase state is invalid.
    pub fn from_lattice_domain(
        phase_id: impl Into<String>,
        name: impl Into<String>,
        cell: UnitCell,
        scale: f64,
        reflection_domain: LatticeReflectionDomain,
    ) -> Result<Self, LeBailError> {
        let generated = reflection_domain
            .generate(cell, None)
            .map_err(LeBailError::Lattice)?;
        let mut phase = Self::new(
            phase_id,
            name,
            generated.reflection_ids.clone(),
            generated.hkl.clone(),
            generated.d_spacing_angstrom.clone(),
            generated.two_theta_deg.clone(),
            generated.integrated_intensity.clone(),
            scale,
            generated.visible.iter().map(|visible| !visible).collect(),
        )?;
        phase.cell = Some(cell);
        phase.reflection_domain = Some(reflection_domain);
        phase.validate()?;
        Ok(phase)
    }

    fn validate(&self) -> Result<(), LeBailError> {
        validate_stable_label("phase_id", &self.phase_id)?;
        if self.name.trim().is_empty() {
            return Err(invalid_phase("phase name must be non-empty"));
        }
        let count = self.reflection_ids.len();
        if count == 0 {
            return Err(invalid_phase("at least one reflection is required"));
        }
        if self.hkl.len() != count
            || self.d_spacing_angstrom.len() != count
            || self.two_theta_deg.len() != count
            || self.integrated_intensity.len() != count
            || (!self.preserve_unobserved.is_empty() && self.preserve_unobserved.len() != count)
        {
            return Err(invalid_phase("reflection arrays must have equal lengths"));
        }
        let mut identities = std::collections::BTreeSet::new();
        for reflection_id in &self.reflection_ids {
            validate_stable_label("reflection_id", reflection_id)?;
            if !identities.insert(reflection_id) {
                return Err(invalid_phase(
                    "reflection IDs must be unique within a phase",
                ));
            }
        }
        if self
            .d_spacing_angstrom
            .iter()
            .any(|value| !value.is_finite() || *value <= 0.0)
        {
            return Err(invalid_phase("d-spacings must be positive and finite"));
        }
        if self
            .two_theta_deg
            .iter()
            .any(|value| !value.is_finite() || *value <= 0.0 || *value >= 180.0)
        {
            return Err(invalid_phase(
                "reflection positions must lie strictly inside (0, 180) degrees",
            ));
        }
        if self
            .integrated_intensity
            .iter()
            .any(|value| !value.is_finite() || *value < 0.0)
        {
            return Err(invalid_phase(
                "integrated intensities must be non-negative and finite",
            ));
        }
        if !self.scale.is_finite() || self.scale < 0.0 {
            return Err(invalid_phase("phase scale must be non-negative and finite"));
        }
        match (&self.cell, &self.reflection_domain) {
            (None, None) => {}
            (Some(cell), Some(domain)) => {
                domain.validate_cell(*cell).map_err(LeBailError::Lattice)?;
                if self.preserve_unobserved.len() != count {
                    return Err(invalid_phase(
                        "dynamic phases require one visibility marker per reflection",
                    ));
                }
            }
            _ => {
                return Err(invalid_phase(
                    "dynamic phases require both a cell and reflection domain",
                ));
            }
        }
        Ok(())
    }

    /// Borrow the stable phase ID.
    #[must_use]
    pub fn phase_id(&self) -> &str {
        &self.phase_id
    }

    /// Borrow the display name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Borrow reflection IDs in calculation order.
    #[must_use]
    pub fn reflection_ids(&self) -> &[String] {
        &self.reflection_ids
    }

    /// Borrow Miller indices in reflection order.
    #[must_use]
    pub fn hkl(&self) -> &[[i32; 3]] {
        &self.hkl
    }

    /// Borrow d-spacings in ångströms.
    #[must_use]
    pub fn d_spacing_angstrom(&self) -> &[f64] {
        &self.d_spacing_angstrom
    }

    /// Borrow fixed reflection positions in degrees `2theta`.
    #[must_use]
    pub fn two_theta_deg(&self) -> &[f64] {
        &self.two_theta_deg
    }

    /// Borrow current integrated intensities.
    #[must_use]
    pub fn integrated_intensity(&self) -> &[f64] {
        &self.integrated_intensity
    }

    /// Replace integrated intensities while preserving phase identity/geometry.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] for a shape mismatch, negative value, or
    /// non-finite value.
    pub fn with_integrated_intensities(&self, values: &[f64]) -> Result<Self, LeBailError> {
        self.replace_intensities(values)
    }

    /// Return the phase scale.
    #[must_use]
    pub const fn scale(&self) -> f64 {
        self.scale
    }

    /// Borrow the preserve-if-unobserved mask.
    #[must_use]
    pub fn preserve_unobserved(&self) -> &[bool] {
        &self.preserve_unobserved
    }

    /// Return the current cell for a dynamic-lattice phase.
    #[must_use]
    pub const fn cell(&self) -> Option<UnitCell> {
        self.cell
    }

    /// Borrow the guarded reflection domain for a dynamic-lattice phase.
    #[must_use]
    pub const fn reflection_domain(&self) -> Option<&LatticeReflectionDomain> {
        self.reflection_domain.as_ref()
    }

    /// Regenerate a dynamic phase at another accepted bounded cell.
    ///
    /// Intensities transfer by stable reflection ID and new families use the
    /// domain's declared initial intensity.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] for a fixed phase, out-of-bounds cell, or
    /// reflection-generation failure.
    pub fn regenerate_lattice_at_cell(&self, cell: UnitCell) -> Result<Self, LeBailError> {
        let domain = self
            .reflection_domain
            .as_ref()
            .ok_or_else(|| invalid_phase("only dynamic phases have a lattice reflection domain"))?;
        let previous = self
            .reflection_ids
            .iter()
            .cloned()
            .zip(self.integrated_intensity.iter().copied())
            .collect::<BTreeMap<_, _>>();
        let generated = domain
            .generate(cell, Some(&previous))
            .map_err(LeBailError::Lattice)?;
        self.replace_generated_domain(cell, generated)
    }

    fn replace_intensities(&self, values: &[f64]) -> Result<Self, LeBailError> {
        if values.len() != self.integrated_intensity.len()
            || values
                .iter()
                .any(|value| !value.is_finite() || *value < 0.0)
        {
            return Err(invalid_phase(
                "replacement intensities must match and remain non-negative",
            ));
        }
        let mut phase = self.clone();
        phase.integrated_intensity.copy_from_slice(values);
        Ok(phase)
    }

    fn replace_scale_and_positions(
        &self,
        scale: f64,
        positions: Vec<f64>,
    ) -> Result<Self, LeBailError> {
        let mut phase = self.clone();
        phase.scale = scale;
        phase.two_theta_deg = positions;
        phase.validate()?;
        Ok(phase)
    }

    fn replace_cell_geometry(
        &self,
        cell: UnitCell,
        wavelength_angstrom: f64,
    ) -> Result<Self, LeBailError> {
        let domain = self.reflection_domain.as_ref().ok_or_else(|| {
            invalid_phase("lattice parameters require a bounded reflection domain")
        })?;
        domain.validate_cell(cell).map_err(LeBailError::Lattice)?;
        let geometry = cw_lattice_geometry(
            domain.parameterization(),
            cell,
            &self.hkl,
            wavelength_angstrom,
        )
        .map_err(LeBailError::Lattice)?;
        let mut phase = self.clone();
        phase.cell = Some(cell);
        phase.d_spacing_angstrom = geometry.d_spacing_angstrom;
        phase.two_theta_deg = geometry.two_theta_deg;
        phase.validate()?;
        Ok(phase)
    }

    fn replace_generated_domain(
        &self,
        cell: UnitCell,
        generated: GeneratedLatticeDomain,
    ) -> Result<Self, LeBailError> {
        let mut phase = self.clone();
        phase.cell = Some(cell);
        phase.reflection_ids = generated.reflection_ids;
        phase.hkl = generated.hkl;
        phase.d_spacing_angstrom = generated.d_spacing_angstrom;
        phase.two_theta_deg = generated.two_theta_deg;
        phase.integrated_intensity = generated.integrated_intensity;
        phase.preserve_unobserved = generated
            .visible
            .into_iter()
            .map(|visible| !visible)
            .collect();
        phase.validate()?;
        Ok(phase)
    }
}

/// Return the stable key for one supported CW profile coefficient.
///
/// # Errors
///
/// Returns [`LeBailError`] for an unsupported name.
pub fn lebail_instrument_parameter_key(name: &str) -> Result<ParameterKey, LeBailError> {
    if !INSTRUMENT_PARAMETER_NAMES.contains(&name) {
        return Err(LeBailError::UnsupportedParameter {
            label: format!("instrument[cw].{name}"),
        });
    }
    ParameterKey::new("instrument", "cw", name).map_err(LeBailError::Parameter)
}

/// Return the stable key for a phase scale.
///
/// # Errors
///
/// Returns [`LeBailError`] for an invalid phase ID.
pub fn lebail_phase_scale_key(phase_id: &str) -> Result<ParameterKey, LeBailError> {
    ParameterKey::new("phase", phase_id, "scale").map_err(LeBailError::Parameter)
}

/// Return the stable key for one refinable residual-background coefficient.
///
/// # Errors
///
/// Returns [`LeBailError`] when an identity segment is invalid.
pub fn lebail_background_parameter_key(
    background_id: &str,
    name: &str,
) -> Result<ParameterKey, LeBailError> {
    ParameterKey::new("background", background_id, name).map_err(LeBailError::Parameter)
}

/// Return the stable key for one symmetry-independent lattice variable.
///
/// # Errors
///
/// Returns [`LeBailError`] for an unsupported name or invalid phase ID.
pub fn lebail_lattice_parameter_key(
    phase_id: &str,
    name: &str,
) -> Result<ParameterKey, LeBailError> {
    if !LATTICE_PARAMETER_NAMES.contains(&name) {
        return Err(LeBailError::UnsupportedParameter {
            label: format!("lattice[{phase_id}].{name}"),
        });
    }
    ParameterKey::new("lattice", phase_id, name).map_err(LeBailError::Parameter)
}

/// Return the stable key for one independent reflection position.
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid identity segments.
pub fn lebail_reflection_position_key(
    phase_id: &str,
    reflection_id: &str,
) -> Result<ParameterKey, LeBailError> {
    ParameterKey::new(
        "reflection",
        format!("{phase_id}/{reflection_id}"),
        "two_theta_deg",
    )
    .map_err(LeBailError::Parameter)
}

/// Build bounded typed specifications for selected fixed-geometry parameters.
///
/// # Errors
///
/// Returns [`LeBailError`] for unsupported names or invalid phase state.
pub fn build_lebail_parameter_set(
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    instrument_parameters: &[&str],
    phase_scales: bool,
    reflection_positions: bool,
) -> Result<ParameterSet, LeBailError> {
    build_lebail_parameter_set_with_lattice(
        instrument,
        phases,
        instrument_parameters,
        phase_scales,
        reflection_positions,
        false,
    )
}

/// Build bounded typed specifications including optional lattice variables.
///
/// # Errors
///
/// Returns [`LeBailError`] for unsupported selections or invalid phase state.
pub fn build_lebail_parameter_set_with_lattice(
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    instrument_parameters: &[&str],
    phase_scales: bool,
    reflection_positions: bool,
    lattice_parameters: bool,
) -> Result<ParameterSet, LeBailError> {
    if lattice_parameters && reflection_positions {
        return Err(invalid_phase(
            "lattice parameters and independent reflection positions are redundant",
        ));
    }
    let mut specs = Vec::new();
    for name in instrument_parameters {
        let key = lebail_instrument_parameter_key(name)?;
        let value = instrument_parameter(instrument, name)
            .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
        specs.push(
            ParameterSpec::new(
                key,
                value,
                if name.ends_with("deg2") {
                    "degree^2"
                } else {
                    "degree"
                },
                ParameterBounds::default(),
                value.abs().max(if name.ends_with("deg2") {
                    1.0e-5
                } else {
                    1.0e-4
                }),
                true,
            )
            .map_err(LeBailError::Parameter)?,
        );
    }
    for phase in phases {
        if lattice_parameters {
            append_lattice_parameter_specs(&mut specs, phase)?;
        }
        if phase_scales {
            specs.push(
                ParameterSpec::new(
                    lebail_phase_scale_key(phase.phase_id())?,
                    phase.scale(),
                    "dimensionless",
                    ParameterBounds::new(0.0, f64::INFINITY).map_err(LeBailError::Parameter)?,
                    phase.scale().max(1.0),
                    true,
                )
                .map_err(LeBailError::Parameter)?,
            );
        }
        if reflection_positions {
            if phase.reflection_domain.is_some() {
                return Err(invalid_phase(
                    "independent reflection positions require fixed-topology phases",
                ));
            }
            for (reflection_id, position) in phase.reflection_ids.iter().zip(&phase.two_theta_deg) {
                specs.push(
                    ParameterSpec::new(
                        lebail_reflection_position_key(phase.phase_id(), reflection_id)?,
                        *position,
                        "degree_2theta",
                        ParameterBounds::new(
                            f64::from_bits(1),
                            f64::from_bits(180.0_f64.to_bits() - 1),
                        )
                        .map_err(LeBailError::Parameter)?,
                        0.01,
                        true,
                    )
                    .map_err(LeBailError::Parameter)?,
                );
            }
        }
    }
    ParameterSet::new(specs).map_err(LeBailError::Parameter)
}

fn append_lattice_parameter_specs(
    specs: &mut Vec<ParameterSpec>,
    phase: &LeBailPhase,
) -> Result<(), LeBailError> {
    let cell = phase
        .cell
        .ok_or_else(|| invalid_phase("lattice parameters require bounded dynamic phases"))?;
    let domain = phase
        .reflection_domain
        .as_ref()
        .ok_or_else(|| invalid_phase("lattice parameters require bounded dynamic phases"))?;
    let values = domain
        .parameterization()
        .values_from_cell(cell)
        .map_err(LeBailError::Lattice)?;
    for (((name, value), lower), upper) in domain
        .parameterization()
        .parameter_names()
        .iter()
        .zip(values)
        .zip(domain.bounds().lower())
        .zip(domain.bounds().upper())
    {
        specs.push(
            ParameterSpec::new(
                lebail_lattice_parameter_key(phase.phase_id(), name)?,
                value,
                if name.ends_with("_angstrom") {
                    "angstrom"
                } else {
                    "degree"
                },
                ParameterBounds::new(*lower, *upper).map_err(LeBailError::Parameter)?,
                value.abs().max(1.0),
                true,
            )
            .map_err(LeBailError::Parameter)?,
        );
    }
    Ok(())
}

/// Observations, instrument, and ordered fixed-reflection phases.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailInput {
    /// Observed pattern and fixed supplied background.
    pub pattern: PatternRecord,
    /// Constant-wavelength U/V/W/X/Y profile.
    pub instrument: ConstantWavelengthInstrument,
    /// Ordered non-empty phase list.
    pub phases: Vec<LeBailPhase>,
    /// Optional refinable analytical correction added to the fixed background.
    pub background: Option<BackgroundModel>,
    /// Optional typed profile parameter set.
    pub parameters: Option<ParameterSet>,
    /// Ordered fixed/affine/linear parameter constraints.
    pub constraints: Vec<Constraint>,
}

impl LeBailInput {
    /// Validate a complete fixed-reflection Le Bail request.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] for invalid observations, instrument, phase
    /// state, or repeated phase IDs.
    pub fn new(
        pattern: PatternRecord,
        instrument: ConstantWavelengthInstrument,
        phases: Vec<LeBailPhase>,
    ) -> Result<Self, LeBailError> {
        pattern.validate().map_err(LeBailError::Pattern)?;
        if pattern.observed_y.is_none() {
            return Err(LeBailError::MissingObservations);
        }
        instrument
            .validate()
            .map_err(|error| LeBailError::Profile {
                message: error.to_string(),
            })?;
        if phases.is_empty() {
            return Err(invalid_phase("at least one phase is required"));
        }
        let mut phase_ids = std::collections::BTreeSet::new();
        for phase in &phases {
            phase.validate()?;
            if phase.reflection_domain.as_ref().is_some_and(|domain| {
                domain.wavelength_angstrom().to_bits() != instrument.wavelength_angstrom.to_bits()
            }) {
                return Err(invalid_phase(
                    "dynamic phase wavelength must match the Le Bail instrument",
                ));
            }
            if !phase_ids.insert(phase.phase_id()) {
                return Err(invalid_phase("phase IDs must be unique"));
            }
        }
        Ok(Self {
            pattern,
            instrument,
            phases,
            background: None,
            parameters: None,
            constraints: Vec::new(),
        })
    }

    /// Validate a request with optional analytical profile parameters.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] for unsupported keys, domain/value mismatch, or
    /// an invalid constraint graph.
    pub fn new_with_parameters(
        pattern: PatternRecord,
        instrument: ConstantWavelengthInstrument,
        phases: Vec<LeBailPhase>,
        parameters: ParameterSet,
        constraints: Vec<Constraint>,
    ) -> Result<Self, LeBailError> {
        let mut input = Self::new(pattern, instrument, phases)?;
        validate_parameter_selection(&input.phases, input.background.as_ref(), &parameters)?;
        domain_parameter_values(
            input.instrument,
            &input.phases,
            input.background.as_ref(),
            &parameters,
        )?;
        ConstraintTransform::new(parameters.clone(), constraints.clone())
            .map_err(LeBailError::Constraint)?;
        input.parameters = Some(parameters);
        input.constraints = constraints;
        Ok(input)
    }

    /// Attach a refinable analytical correction on top of the fixed supplied background.
    ///
    /// The model coefficients are appended to the existing parameter set in stable order.
    /// This makes a Smooth Bruckner array in [`PatternRecord`] the fixed broad baseline,
    /// while the analytical model captures low-order residual curvature.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] for an invalid model/grid or duplicate parameter identity.
    pub fn with_refinable_background(
        mut self,
        background: BackgroundModel,
    ) -> Result<Self, LeBailError> {
        background
            .basis(&self.pattern.x_deg)
            .map_err(LeBailError::Background)?;
        background
            .calculate(&self.pattern.x_deg)
            .map_err(LeBailError::Background)?;
        let names = background.parameter_names();
        let coefficients = background.coefficients();
        let bounds = background.parameter_bounds();
        let refine_in_nonlinear_step = !background.basis_is_invariant();
        let mut specs = self
            .parameters
            .as_ref()
            .map_or_else(Vec::new, |parameters| parameters.specs().to_vec());
        let background_scale = self
            .pattern
            .background_y
            .iter()
            .map(|value| value.abs())
            .fold(1.0_f64, f64::max);
        for ((name, value), bounds) in names.iter().zip(coefficients).zip(bounds) {
            specs.push(
                ParameterSpec::new(
                    lebail_background_parameter_key(background.background_id(), name)?,
                    value,
                    "intensity",
                    bounds,
                    value.abs().max(background_scale),
                    refine_in_nonlinear_step,
                )
                .map_err(LeBailError::Parameter)?,
            );
        }
        self.parameters = Some(ParameterSet::new(specs).map_err(LeBailError::Parameter)?);
        self.background = Some(background);
        validate_parameter_selection(
            &self.phases,
            self.background.as_ref(),
            self.parameters
                .as_ref()
                .ok_or(LeBailError::InternalInvariant)?,
        )?;
        ConstraintTransform::new(
            self.parameters
                .clone()
                .ok_or(LeBailError::InternalInvariant)?,
            self.constraints.clone(),
        )
        .map_err(LeBailError::Constraint)?;
        Ok(self)
    }
}

/// Deterministic controls for fixed-reflection extraction.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailOptions {
    /// Maximum accepted iterations.
    pub max_iterations: usize,
    /// Minimum accepted iterations before convergence.
    pub min_iterations: usize,
    /// Maximum relative integrated-intensity change for convergence.
    pub intensity_tolerance: f64,
    /// Absolute Rwp change for convergence.
    pub rwp_tolerance: f64,
    /// Multiplicative redistribution damping in `(0, 1]`.
    pub redistribution_damping: f64,
    /// Minimum calculated profile accepted in the observed/calculated ratio.
    pub minimum_calculated: f64,
    /// Positive starting and relative-change denominator floor.
    pub initial_intensity_floor: f64,
    /// Whether supplied one-sigma uncertainty is used.
    pub use_uncertainty: bool,
    /// Non-negative diagonal regularization for profile normal equations.
    pub profile_damping: f64,
    /// Maximum absolute free-parameter step in scaled coordinates.
    pub max_scaled_parameter_step: f64,
    /// Number of profile-step halvings after the initial candidate.
    pub max_profile_backtracks: usize,
    /// Correlation threshold used by optional unresolved-group diagnostics.
    pub unresolved_correlation: f64,
    /// Whether coincident reflection rank diagnostics are calculated.
    pub diagnose_rank_deficiency: bool,
    /// Finite profile support in FWHM units.
    pub support_fwhm: f64,
    /// Persistent bounded native worker policy.
    pub execution: ExecutionPolicy,
}

impl LeBailOptions {
    /// Validate all convergence and execution controls.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError::InvalidOptions`] for an invalid control.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        max_iterations: usize,
        min_iterations: usize,
        intensity_tolerance: f64,
        rwp_tolerance: f64,
        redistribution_damping: f64,
        minimum_calculated: f64,
        initial_intensity_floor: f64,
        use_uncertainty: bool,
        unresolved_correlation: f64,
        diagnose_rank_deficiency: bool,
        support_fwhm: f64,
        execution: ExecutionPolicy,
    ) -> Result<Self, LeBailError> {
        let options = Self {
            max_iterations,
            min_iterations,
            intensity_tolerance,
            rwp_tolerance,
            redistribution_damping,
            minimum_calculated,
            initial_intensity_floor,
            use_uncertainty,
            profile_damping: 1.0e-10,
            max_scaled_parameter_step: 0.25,
            max_profile_backtracks: 8,
            unresolved_correlation,
            diagnose_rank_deficiency,
            support_fwhm,
            execution,
        };
        options.validate()?;
        Ok(options)
    }

    fn validate(&self) -> Result<(), LeBailError> {
        if self.max_iterations == 0
            || self.min_iterations == 0
            || self.min_iterations > self.max_iterations
        {
            return Err(invalid_options(
                "iteration counts must be positive and minimum must not exceed maximum",
            ));
        }
        for (name, value) in [
            ("intensity_tolerance", self.intensity_tolerance),
            ("rwp_tolerance", self.rwp_tolerance),
            ("minimum_calculated", self.minimum_calculated),
            ("initial_intensity_floor", self.initial_intensity_floor),
            ("support_fwhm", self.support_fwhm),
        ] {
            if !value.is_finite() || value <= 0.0 {
                return Err(LeBailError::InvalidOptions {
                    message: format!("{name} must be positive and finite"),
                });
            }
        }
        if !self.redistribution_damping.is_finite()
            || self.redistribution_damping <= 0.0
            || self.redistribution_damping > 1.0
        {
            return Err(invalid_options("redistribution_damping must lie in (0, 1]"));
        }
        if !self.unresolved_correlation.is_finite()
            || !(0.0..=1.0).contains(&self.unresolved_correlation)
        {
            return Err(invalid_options("unresolved_correlation must lie in [0, 1]"));
        }
        if !self.profile_damping.is_finite() || self.profile_damping < 0.0 {
            return Err(invalid_options(
                "profile_damping must be non-negative and finite",
            ));
        }
        if !self.max_scaled_parameter_step.is_finite() || self.max_scaled_parameter_step <= 0.0 {
            return Err(invalid_options(
                "max_scaled_parameter_step must be positive and finite",
            ));
        }
        Ok(())
    }

    /// Replace the native profile-solver controls after validation.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] for invalid damping or step controls.
    pub fn with_profile_controls(
        mut self,
        profile_damping: f64,
        max_scaled_parameter_step: f64,
        max_profile_backtracks: usize,
    ) -> Result<Self, LeBailError> {
        self.profile_damping = profile_damping;
        self.max_scaled_parameter_step = max_scaled_parameter_step;
        self.max_profile_backtracks = max_profile_backtracks;
        self.validate()?;
        Ok(self)
    }

    /// Construct the scripting-compatible defaults with an explicit policy.
    ///
    /// # Errors
    ///
    /// Returns [`LeBailError`] if the controls cannot be constructed.
    pub fn scripting_defaults(execution: ExecutionPolicy) -> Result<Self, LeBailError> {
        Self::new(
            50,
            2,
            1.0e-6,
            1.0e-8,
            1.0,
            1.0e-15,
            1.0e-12,
            true,
            1.0 - 1.0e-10,
            false,
            20.0,
            execution,
        )
    }
}

/// One display-ready phase curve.
#[derive(Clone, Debug, PartialEq)]
pub struct PhasePatternComponent {
    /// Stable phase ID.
    pub phase_id: String,
    /// Sample-aligned phase contribution.
    pub y: Vec<f64>,
}

/// Native fixed-phase pattern result used by extraction and adapters.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailCalculation {
    /// Profile plus combined fixed and analytical background.
    pub y: Vec<f64>,
    /// Sum of all phase profiles.
    pub profile_y: Vec<f64>,
    /// Combined fixed supplied baseline and analytical residual background.
    pub background_y: Vec<f64>,
    /// Sparse local and dense global profile derivatives.
    pub accumulation: Accumulation,
    /// `(phase_id, reflection_id)` in local-Jacobian order.
    pub reflection_keys: Vec<(String, String)>,
    /// Prefix sum of phase reflection counts.
    pub phase_offsets: Vec<usize>,
    /// One diagnostic curve per phase.
    pub phase_components: Vec<PhasePatternComponent>,
}

/// One non-negative multiplicative redistribution result.
#[derive(Clone, Debug, PartialEq)]
pub struct IntensityExtractionResult {
    /// New integrated intensities in reflection order.
    pub intensities: Vec<f64>,
    /// Largest floored relative intensity change.
    pub maximum_relative_change: f64,
    /// Reflection keys without included finite support.
    pub unobserved_reflections: Vec<(String, String)>,
}

/// One accepted physical profile-parameter change.
#[derive(Clone, Debug, PartialEq)]
pub struct ParameterChange {
    /// Stable parameter identity.
    pub key: ParameterKey,
    /// Physical value before the step.
    pub before: f64,
    /// Physical value after the step.
    pub after: f64,
    /// Change divided by the parameter scale.
    pub scaled_change: f64,
}

/// One immutable accepted fixed-reflection iteration.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailIterationRecord {
    /// One-based attempted iteration.
    pub iteration: usize,
    /// Unweighted profile residual.
    pub rp: f64,
    /// Weighted profile residual.
    pub rwp: f64,
    /// Weighted residual sum of squares.
    pub chi_square: f64,
    /// Chi-square per positive residual degree of freedom.
    pub reduced_chi_square: f64,
    /// Largest relative integrated-intensity change.
    pub maximum_relative_intensity_change: f64,
    /// Euclidean norm of the accepted scaled profile step.
    pub scaled_profile_step_norm: f64,
    /// Accepted physical parameter changes.
    pub parameter_changes: Vec<ParameterChange>,
    /// Iteration warnings in deterministic order.
    pub warnings: Vec<String>,
}

/// Final stable reflection identity and intensity.
#[derive(Clone, Debug, PartialEq)]
pub struct ReflectionIntensity {
    /// Stable phase ID.
    pub phase_id: String,
    /// Stable reflection ID.
    pub reflection_id: String,
    /// Non-negative integrated intensity.
    pub integrated_intensity: f64,
}

/// Numerically coincident profile columns and their matrix rank.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CoincidentReflectionGroup {
    /// Stable reflection keys.
    pub reflection_keys: Vec<(String, String)>,
    /// Numerical rank of the joined support matrix.
    pub rank: usize,
}

/// Complete immutable continuation state for the fixed-reflection workflow.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailCheckpoint {
    /// Number of accepted iterations.
    pub completed_iterations: usize,
    /// Current phase records and integrated intensities.
    pub phases: Vec<LeBailPhase>,
    /// Current instrument, including accepted profile changes.
    pub instrument: ConstantWavelengthInstrument,
    /// Current refinable residual background.
    pub background: Option<BackgroundModel>,
    /// Flattened current integrated intensities.
    pub intensities: Vec<f64>,
    /// Current profile parameter set.
    pub parameters: Option<ParameterSet>,
    /// Rwp from the last non-converged accepted iteration.
    pub previous_rwp: f64,
    /// Complete accepted deterministic history.
    pub history: Vec<LeBailIterationRecord>,
}

impl LeBailCheckpoint {
    fn validate(&self) -> Result<(), LeBailError> {
        if self.completed_iterations != self.history.len() {
            return Err(LeBailError::InvalidCheckpoint {
                message: "checkpoint iteration count must equal its history length".to_owned(),
            });
        }
        if self.previous_rwp.is_nan() || self.previous_rwp == f64::NEG_INFINITY {
            return Err(LeBailError::InvalidCheckpoint {
                message: "checkpoint previous_rwp must be finite or positive infinity".to_owned(),
            });
        }
        for phase in &self.phases {
            phase.validate()?;
        }
        self.instrument
            .validate()
            .map_err(|error| LeBailError::Profile {
                message: error.to_string(),
            })?;
        if self.phases.iter().any(|phase| {
            phase.reflection_domain.as_ref().is_some_and(|domain| {
                domain.wavelength_angstrom().to_bits()
                    != self.instrument.wavelength_angstrom.to_bits()
            })
        }) {
            return Err(LeBailError::InvalidCheckpoint {
                message: "checkpoint dynamic phase wavelength must match its instrument".to_owned(),
            });
        }
        if let Some(parameters) = &self.parameters {
            validate_parameter_selection(&self.phases, self.background.as_ref(), parameters)?;
            let domain_values = domain_parameter_values(
                self.instrument,
                &self.phases,
                self.background.as_ref(),
                parameters,
            )?;
            if domain_values != parameters.values() {
                return Err(LeBailError::InvalidCheckpoint {
                    message: "checkpoint parameters disagree with its live domain".to_owned(),
                });
            }
        }
        let expected = self.phases.iter().map(reflection_count).sum::<usize>();
        if self.intensities.len() != expected
            || self
                .intensities
                .iter()
                .any(|value| !value.is_finite() || *value < 0.0)
        {
            return Err(LeBailError::InvalidCheckpoint {
                message: "checkpoint intensities must match its phases".to_owned(),
            });
        }
        if flatten_intensities(&self.phases) != self.intensities {
            return Err(LeBailError::InvalidCheckpoint {
                message: "checkpoint phase and flattened intensities disagree".to_owned(),
            });
        }
        if self
            .history
            .iter()
            .enumerate()
            .any(|(index, record)| record.iteration != index + 1)
        {
            return Err(LeBailError::InvalidCheckpoint {
                message: "checkpoint history iterations must be contiguous and one-based"
                    .to_owned(),
            });
        }
        Ok(())
    }
}

/// Complete native fixed-reflection Le Bail result.
#[derive(Clone, Debug, PartialEq)]
pub struct LeBailResult {
    /// Final calculated pattern and sparse derivative storage.
    pub calculation: LeBailCalculation,
    /// Final phases.
    pub phases: Vec<LeBailPhase>,
    /// Final constant-wavelength profile.
    pub instrument: ConstantWavelengthInstrument,
    /// Final refinable residual background added to the fixed pattern baseline.
    pub background: Option<BackgroundModel>,
    /// Final labeled integrated intensities.
    pub intensities: Vec<ReflectionIntensity>,
    /// Final residual arrays and metrics.
    pub metrics: ResidualEvaluation,
    /// Accepted deterministic iteration history.
    pub history: Vec<LeBailIterationRecord>,
    /// Stable termination category.
    pub termination_reason: TerminationReason,
    /// Optional unresolved reflection diagnostics.
    pub rank_deficient_groups: Vec<CoincidentReflectionGroup>,
    /// Final typed profile parameters.
    pub parameters: Option<ParameterSet>,
    /// Row-major free-parameter covariance, if identifiable.
    pub covariance: Option<CovarianceMatrix>,
    /// Complete restart state.
    pub checkpoint: LeBailCheckpoint,
}

/// Square row-major covariance over scaled free parameters.
///
/// The inverse weighted normal matrix is unscaled for supplied uncertainties;
/// unit-weight fits estimate their noise scale from the reduced chi-square.
#[derive(Clone, Debug, PartialEq)]
pub struct CovarianceMatrix {
    /// Matrix dimension.
    pub size: usize,
    /// Row-major values with length `size * size`.
    pub values: Vec<f64>,
}

/// Calculate all fixed phases through one native fused accumulation.
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid pattern/profile state or allocation.
pub fn calculate_lebail_pattern(
    pattern: &PatternRecord,
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    support_fwhm: f64,
    execution: &ExecutionPolicy,
) -> Result<LeBailCalculation, LeBailError> {
    calculate_lebail_pattern_with_background(
        pattern,
        instrument,
        phases,
        None,
        support_fwhm,
        execution,
    )
}

/// Calculate all fixed phases plus an optional analytical residual background.
///
/// The analytical values are added to, never substituted for, the fixed
/// background stored by [`PatternRecord`].
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid pattern, profile, or background state.
pub fn calculate_lebail_pattern_with_background(
    pattern: &PatternRecord,
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    background: Option<&BackgroundModel>,
    support_fwhm: f64,
    execution: &ExecutionPolicy,
) -> Result<LeBailCalculation, LeBailError> {
    pattern.validate().map_err(LeBailError::Pattern)?;
    if phases.is_empty() {
        return Err(invalid_phase("at least one phase is required"));
    }
    if !support_fwhm.is_finite() || support_fwhm <= 0.0 {
        return Err(invalid_options("support_fwhm must be positive and finite"));
    }
    let reflection_count = phases.iter().map(reflection_count).sum::<usize>();
    let mut positions = Vec::with_capacity(reflection_count);
    let mut intensities = Vec::with_capacity(reflection_count);
    let mut multipliers = Vec::with_capacity(reflection_count);
    let mut reflection_keys = Vec::with_capacity(reflection_count);
    let mut phase_offsets = Vec::with_capacity(phases.len() + 1);
    let phase_derivative_count = phases
        .len()
        .checked_mul(reflection_count)
        .ok_or(LeBailError::SizeOverflow)?;
    let mut derivative_multipliers = vec![0.0; phase_derivative_count];
    phase_offsets.push(0);
    for (phase_index, phase) in phases.iter().enumerate() {
        phase.validate()?;
        let begin = positions.len();
        positions.extend_from_slice(&phase.two_theta_deg);
        intensities.extend_from_slice(&phase.integrated_intensity);
        multipliers.extend(std::iter::repeat_n(phase.scale, reflection_count_of(phase)));
        reflection_keys.extend(
            phase
                .reflection_ids
                .iter()
                .map(|reflection_id| (phase.phase_id.clone(), reflection_id.clone())),
        );
        let end = positions.len();
        derivative_multipliers
            [phase_index * reflection_count + begin..phase_index * reflection_count + end]
            .fill(1.0);
        phase_offsets.push(end);
    }
    let contributions = OwnedCwContributions::new(
        reflection_count,
        phases.len(),
        OwnedCwContributionArrays {
            gaussian_variance_deg2: vec![0.0; reflection_count],
            lorentzian_fwhm_deg: vec![0.0; reflection_count],
            intensity_multiplier: multipliers,
            d_gaussian_variance_d_position: vec![0.0; reflection_count],
            d_lorentzian_fwhm_d_position: vec![0.0; reflection_count],
            d_intensity_multiplier_d_position: vec![0.0; reflection_count],
            d_gaussian_variance_d_parameters: vec![0.0; phase_derivative_count],
            d_lorentzian_fwhm_d_parameters: vec![0.0; phase_derivative_count],
            d_intensity_multiplier_d_parameters: derivative_multipliers,
        },
    )
    .map_err(LeBailError::Calculation)?;
    let grid = GridView::new(&pattern.x_deg).map_err(LeBailError::Grid)?;
    let accumulation = accumulate_cw_contributions_batch_with_context(
        grid,
        &positions,
        &intensities,
        instrument,
        contributions.as_view(),
        SupportPolicy::FwhmMultiple(support_fwhm),
        execution.context(),
    )
    .map_err(LeBailError::Calculation)?;
    let profile_y = accumulation.y.clone();
    let background_y = combined_background_values(pattern, background)?;
    let y = profile_y
        .iter()
        .zip(&background_y)
        .map(|(profile, background)| profile + background)
        .collect::<Vec<_>>();
    let phase_components = build_phase_components(
        phases,
        &phase_offsets,
        &intensities,
        &accumulation,
        pattern.sample_count(),
    );
    Ok(LeBailCalculation {
        y,
        profile_y,
        background_y,
        accumulation,
        reflection_keys,
        phase_offsets,
        phase_components,
    })
}

fn combined_background_values(
    pattern: &PatternRecord,
    background: Option<&BackgroundModel>,
) -> Result<Vec<f64>, LeBailError> {
    let mut values = pattern.background_y.clone();
    if let Some(background) = background {
        for (fixed, residual) in values.iter_mut().zip(
            background
                .calculate(&pattern.x_deg)
                .map_err(LeBailError::Background)?,
        ) {
            *fixed += residual;
        }
    }
    Ok(values)
}

fn build_phase_components(
    phases: &[LeBailPhase],
    phase_offsets: &[usize],
    intensities: &[f64],
    accumulation: &Accumulation,
    sample_count: usize,
) -> Vec<PhasePatternComponent> {
    phases
        .iter()
        .enumerate()
        .map(|(phase_index, phase)| {
            let mut phase_y = vec![0.0; sample_count];
            let first = phase_offsets[phase_index];
            let last = phase_offsets[phase_index + 1];
            for (reflection, intensity) in intensities.iter().enumerate().take(last).skip(first) {
                let begin = accumulation.derivatives.local.offsets[reflection];
                let end = accumulation.derivatives.local.offsets[reflection + 1];
                let start = accumulation.derivatives.local.starts[reflection];
                for active in begin..end {
                    let sample = start + active - begin;
                    phase_y[sample] += intensity
                        * accumulation.derivatives.local.values
                            [active * accumulation.derivatives.local.parameter_count];
                }
            }
            PhasePatternComponent {
                phase_id: phase.phase_id.clone(),
                y: phase_y,
            }
        })
        .collect()
}

/// Return deterministic positive starting intensities in phase order.
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid input or option state.
pub fn initialize_lebail_intensities(
    input: &LeBailInput,
    options: &LeBailOptions,
) -> Result<Vec<f64>, LeBailError> {
    options.validate()?;
    let values = flatten_intensities(&input.phases);
    if values
        .iter()
        .any(|value| !value.is_finite() || *value < 0.0)
    {
        return Err(invalid_phase(
            "starting intensities must be non-negative and finite",
        ));
    }
    if values.iter().any(|value| *value > 0.0) {
        return Ok(values
            .into_iter()
            .map(|value| value.max(options.initial_intensity_floor))
            .collect());
    }
    let observed = input
        .pattern
        .observed_y
        .as_deref()
        .ok_or(LeBailError::MissingObservations)?;
    let weights = bin_integration_weights(&input.pattern.x_deg);
    let mut background_y = input.pattern.background_y.clone();
    if let Some(background) = &input.background {
        for (fixed, residual) in background_y.iter_mut().zip(
            background
                .calculate(&input.pattern.x_deg)
                .map_err(LeBailError::Background)?,
        ) {
            *fixed += residual;
        }
    }
    let area = observed
        .iter()
        .zip(&background_y)
        .zip(weights)
        .map(|((observed, background), width)| (observed - background).max(0.0) * width)
        .sum::<f64>();
    let starting = (area / count_as_f64(values.len().max(1))).max(options.initial_intensity_floor);
    Ok(vec![starting; values.len()])
}

/// Perform one non-negative multiplicative redistribution step.
///
/// # Errors
///
/// Returns [`LeBailError`] for shape, observation, or finite-state failures.
pub fn extract_lebail_intensities(
    pattern: &PatternRecord,
    calculation: &LeBailCalculation,
    current: &[f64],
    options: &LeBailOptions,
    preserve_unobserved: &[bool],
) -> Result<IntensityExtractionResult, LeBailError> {
    options.validate()?;
    let observed = pattern
        .observed_y
        .as_deref()
        .ok_or(LeBailError::MissingObservations)?;
    let reflection_count = calculation.accumulation.derivatives.local.peak_count();
    if current.len() != reflection_count
        || current
            .iter()
            .any(|value| !value.is_finite() || *value < 0.0)
    {
        return Err(LeBailError::IntensityShapeMismatch);
    }
    if preserve_unobserved.len() != reflection_count {
        return Err(LeBailError::PreserveMaskLengthMismatch);
    }
    let included = pattern
        .mask
        .clone()
        .unwrap_or_else(|| vec![true; pattern.sample_count()]);
    let ratio = observed
        .iter()
        .zip(&calculation.background_y)
        .zip(&calculation.profile_y)
        .zip(&included)
        .map(|(((observed, background), calculated), included)| {
            if *included && *calculated > options.minimum_calculated {
                (observed - background).max(0.0) / calculated
            } else {
                0.0
            }
        })
        .collect::<Vec<_>>();
    let mut weights = bin_integration_weights(&pattern.x_deg);
    if options.use_uncertainty
        && let Some(uncertainty) = &pattern.uncertainty
    {
        for (weight, uncertainty) in weights.iter_mut().zip(uncertainty) {
            *weight /= uncertainty * uncertainty;
        }
    }
    for (weight, included) in weights.iter_mut().zip(&included) {
        if !included {
            *weight = 0.0;
        }
    }
    let local = &calculation.accumulation.derivatives.local;
    let mut updated = vec![0.0; reflection_count];
    let mut unobserved_reflections = Vec::new();
    for reflection in 0..reflection_count {
        let begin = local.offsets[reflection];
        let end = local.offsets[reflection + 1];
        let start = local.starts[reflection];
        let mut denominator = 0.0;
        let mut numerator = 0.0;
        for active in begin..end {
            let sample = start + active - begin;
            let profile = local.values[active * local.parameter_count];
            let weighted_profile = weights[sample] * profile;
            denominator += weighted_profile;
            numerator += weighted_profile * ratio[sample];
        }
        if denominator <= 0.0 {
            unobserved_reflections.push(calculation.reflection_keys[reflection].clone());
            if preserve_unobserved[reflection] {
                updated[reflection] = current[reflection];
            }
            continue;
        }
        let raw = (current[reflection] * numerator / denominator).max(0.0);
        updated[reflection] =
            current[reflection] + options.redistribution_damping * (raw - current[reflection]);
    }
    let maximum_relative_change = updated
        .iter()
        .zip(current)
        .map(|(updated, current)| {
            (updated - current).abs() / current.abs().max(options.initial_intensity_floor)
        })
        .fold(0.0_f64, f64::max);
    Ok(IntensityExtractionResult {
        intensities: updated,
        maximum_relative_change,
        unobserved_reflections,
    })
}

/// Run fixed-reflection Le Bail extraction with a workflow-owned runtime.
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid state, runtime construction, profile
/// evaluation, metrics, or checkpoint delivery.
pub fn refine_lebail(
    input: &LeBailInput,
    options: &LeBailOptions,
    checkpoint: Option<&LeBailCheckpoint>,
) -> Result<LeBailResult, LeBailError> {
    let evaluations_per_iteration = options
        .max_profile_backtracks
        .checked_add(2)
        .ok_or(LeBailError::SizeOverflow)?;
    let max_evaluations = options
        .max_iterations
        .checked_mul(evaluations_per_iteration)
        .and_then(|value| value.checked_add(1))
        .ok_or(LeBailError::SizeOverflow)?;
    let limits = RefinementLimits::new(options.max_iterations, max_evaluations, None, 1)
        .map_err(LeBailError::Runtime)?;
    let mut runtime = RefinementRuntime::new(limits, None).map_err(LeBailError::Runtime)?;
    refine_lebail_with_runtime(input, options, checkpoint, &mut runtime)
}

/// Advance exactly one accepted Le Bail iteration for custom orchestration.
///
/// Pass the returned checkpoint to the next call. A cancellation-aware host
/// that needs to stop before the iteration should use
/// [`refine_lebail_with_runtime`] with a one-iteration runtime budget.
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid input, options, checkpoint, or numerical
/// evaluation state.
pub fn iterate_lebail_once(
    input: &LeBailInput,
    options: &LeBailOptions,
    checkpoint: Option<&LeBailCheckpoint>,
) -> Result<LeBailResult, LeBailError> {
    let completed = checkpoint.map_or(0, |value| value.completed_iterations);
    let iteration = completed.checked_add(1).ok_or(LeBailError::SizeOverflow)?;
    let mut selected = options.clone();
    selected.min_iterations = iteration;
    selected.max_iterations = iteration;
    selected.validate()?;
    refine_lebail(input, &selected, checkpoint)
}

/// Run fixed-reflection extraction with host-owned cancellation/events/checkpoints.
///
/// The runtime should be fresh for a new run. A continuation restores its
/// accepted counter from the supplied checkpoint before numerical work begins.
///
/// # Errors
///
/// Returns [`LeBailError`] for invalid input/checkpoint state, non-normal
/// runtime failures, or numerical evaluation failures.
pub fn refine_lebail_with_runtime(
    input: &LeBailInput,
    options: &LeBailOptions,
    checkpoint: Option<&LeBailCheckpoint>,
    runtime: &mut RefinementRuntime<LeBailCheckpoint>,
) -> Result<LeBailResult, LeBailError> {
    options.validate()?;
    let mut state = restore_state(input, options, checkpoint)?;
    if let Some(checkpoint) = checkpoint {
        runtime
            .resume_accepted(checkpoint.completed_iterations)
            .map_err(LeBailError::Runtime)?;
    }
    runtime
        .emit(
            RefinementEventKind::Start,
            "lebail",
            "Le Bail extraction started",
            Vec::new(),
        )
        .map_err(LeBailError::Runtime)?;
    state.calculation = Some(calculate_lebail_pattern_with_background(
        &input.pattern,
        state.instrument,
        &state.phases,
        state.background.as_ref(),
        options.support_fwhm,
        &options.execution,
    )?);
    let termination = run_lebail_iterations(input, options, &mut state, runtime)?;
    finish_result(
        input,
        options,
        state.phases,
        state.instrument,
        state.background,
        &state.intensities,
        state.parameters,
        state.history,
        state.previous_rwp,
        state.calculation.ok_or(LeBailError::InternalInvariant)?,
        termination,
        runtime,
    )
}

fn run_lebail_iterations(
    input: &LeBailInput,
    options: &LeBailOptions,
    state: &mut RestoredLeBailState,
    runtime: &mut RefinementRuntime<LeBailCheckpoint>,
) -> Result<TerminationReason, LeBailError> {
    if let Err(error) = runtime.begin_evaluation() {
        return stop_reason_or_error(error);
    }
    for iteration in state.first_iteration..=options.max_iterations {
        if let Err(error) = runtime.begin_iteration(iteration) {
            return stop_reason_or_error(error);
        }
        if let Err(error) = runtime.begin_evaluation() {
            return stop_reason_or_error(error);
        }
        let candidate = match evaluate_lebail_iteration(input, options, state, runtime) {
            Ok(candidate) => candidate,
            Err(LeBailError::Runtime(error)) if normal_stop_reason(&error).is_some() => {
                return stop_reason_or_error(error);
            }
            Err(error) => return Err(error),
        };
        state.history.push(LeBailIterationRecord {
            iteration,
            rp: candidate.metrics.rp,
            rwp: candidate.metrics.rwp,
            chi_square: candidate.metrics.chi_square,
            reduced_chi_square: candidate.metrics.reduced_chi_square,
            maximum_relative_intensity_change: candidate.extraction.maximum_relative_change,
            scaled_profile_step_norm: candidate.profile_step_norm,
            parameter_changes: candidate.parameter_changes,
            warnings: candidate.warnings,
        });
        state.instrument = candidate.instrument;
        state.background = candidate.background;
        state.phases = candidate.phases;
        state.parameters = candidate.parameters;
        state.intensities = candidate.extraction.intensities;
        state.calculation = Some(candidate.calculation);
        accept_lebail_iteration(runtime, state, &candidate.metrics)?;
        if iteration >= options.min_iterations
            && candidate.extraction.maximum_relative_change < options.intensity_tolerance
            && (state.previous_rwp - candidate.metrics.rwp).abs() < options.rwp_tolerance
        {
            return Ok(TerminationReason::Converged);
        }
        state.previous_rwp = candidate.metrics.rwp;
    }
    Ok(TerminationReason::MaxIterations)
}

struct EvaluatedLeBailIteration {
    extraction: IntensityExtractionResult,
    phases: Vec<LeBailPhase>,
    calculation: LeBailCalculation,
    metrics: ResidualEvaluation,
    warnings: Vec<String>,
    instrument: ConstantWavelengthInstrument,
    background: Option<BackgroundModel>,
    parameters: Option<ParameterSet>,
    profile_step_norm: f64,
    parameter_changes: Vec<ParameterChange>,
}

fn evaluate_lebail_iteration(
    input: &LeBailInput,
    options: &LeBailOptions,
    state: &RestoredLeBailState,
    runtime: &mut RefinementRuntime<LeBailCheckpoint>,
) -> Result<EvaluatedLeBailIteration, LeBailError> {
    let mut extraction = extract_lebail_intensities(
        &input.pattern,
        state.calculation()?,
        &state.intensities,
        options,
        &flatten_preserve_mask(&state.phases),
    )?;
    let phases = replace_flat_intensities(&state.phases, &extraction.intensities)?;
    let calculation = calculate_lebail_pattern_with_background(
        &input.pattern,
        state.instrument,
        &phases,
        state.background.as_ref(),
        options.support_fwhm,
        &options.execution,
    )?;
    let (background, parameters) = fit_linear_background(
        &input.pattern,
        &calculation.profile_y,
        state.background.as_ref(),
        state.parameters.as_ref(),
        options.use_uncertainty,
    )?;
    let calculation = calculate_lebail_pattern_with_background(
        &input.pattern,
        state.instrument,
        &phases,
        background.as_ref(),
        options.support_fwhm,
        &options.execution,
    )?;
    let profile = profile_update(
        &input.pattern,
        state.instrument,
        phases,
        calculation,
        parameters.as_ref(),
        background,
        &input.constraints,
        options,
        runtime,
    )?;
    extraction.intensities = flatten_intensities(&profile.phases);
    let parameter_count = free_parameter_count(profile.parameters.as_ref(), &input.constraints)?;
    let metrics = evaluate_residuals(
        &input.pattern,
        &profile.calculation.y,
        ResidualOptions {
            use_uncertainty: options.use_uncertainty,
            parameter_count,
        },
    )
    .map_err(LeBailError::Residual)?;
    let warnings = if extraction.unobserved_reflections.is_empty() {
        Vec::new()
    } else {
        vec![format!(
            "{} reflections have no included support",
            extraction.unobserved_reflections.len()
        )]
    };
    Ok(EvaluatedLeBailIteration {
        extraction,
        phases: profile.phases,
        calculation: profile.calculation,
        metrics,
        warnings: [warnings, profile.warnings].concat(),
        instrument: profile.instrument,
        background: profile.background,
        parameters: profile.parameters,
        profile_step_norm: profile.step_norm,
        parameter_changes: profile.parameter_changes,
    })
}

fn accept_lebail_iteration(
    runtime: &mut RefinementRuntime<LeBailCheckpoint>,
    state: &RestoredLeBailState,
    metrics: &ResidualEvaluation,
) -> Result<(), LeBailError> {
    let checkpoint = LeBailCheckpoint {
        completed_iterations: state.history.len(),
        phases: state.phases.clone(),
        instrument: state.instrument,
        background: state.background.clone(),
        intensities: state.intensities.clone(),
        parameters: state.parameters.clone(),
        previous_rwp: metrics.rwp,
        history: state.history.clone(),
    };
    runtime
        .accept_step(Some(&checkpoint))
        .map_err(LeBailError::Runtime)?;
    runtime
        .emit(
            RefinementEventKind::Iteration,
            "lebail_iteration",
            "Le Bail iteration accepted",
            vec![
                ("rwp".to_owned(), DiagnosticValue::Float(metrics.rwp)),
                (
                    "maximum_relative_intensity_change".to_owned(),
                    DiagnosticValue::Float(
                        state
                            .history
                            .last()
                            .ok_or(LeBailError::InternalInvariant)?
                            .maximum_relative_intensity_change,
                    ),
                ),
            ],
        )
        .map_err(LeBailError::Runtime)?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn finish_result(
    input: &LeBailInput,
    options: &LeBailOptions,
    phases: Vec<LeBailPhase>,
    instrument: ConstantWavelengthInstrument,
    background: Option<BackgroundModel>,
    intensities: &[f64],
    parameters: Option<ParameterSet>,
    history: Vec<LeBailIterationRecord>,
    previous_rwp: f64,
    calculation: LeBailCalculation,
    termination: TerminationReason,
    runtime: &mut RefinementRuntime<LeBailCheckpoint>,
) -> Result<LeBailResult, LeBailError> {
    let metrics = evaluate_residuals(
        &input.pattern,
        &calculation.y,
        ResidualOptions {
            use_uncertainty: options.use_uncertainty,
            parameter_count: free_parameter_count(parameters.as_ref(), &input.constraints)?,
        },
    )
    .map_err(LeBailError::Residual)?;
    let checkpoint = LeBailCheckpoint {
        completed_iterations: history.len(),
        phases: phases.clone(),
        instrument,
        background: background.clone(),
        intensities: intensities.to_owned(),
        parameters: parameters.clone(),
        previous_rwp: if termination == TerminationReason::Cancelled {
            previous_rwp
        } else {
            metrics.rwp
        },
        history: history.clone(),
    };
    checkpoint.validate()?;
    let labeled = calculation
        .reflection_keys
        .iter()
        .zip(intensities)
        .map(
            |((phase_id, reflection_id), intensity)| ReflectionIntensity {
                phase_id: phase_id.clone(),
                reflection_id: reflection_id.clone(),
                integrated_intensity: *intensity,
            },
        )
        .collect();
    let rank_deficient_groups = if options.diagnose_rank_deficiency {
        rank_deficient_groups(&calculation, options.unresolved_correlation)
    } else {
        Vec::new()
    };
    let covariance = covariance(
        &input.pattern,
        &calculation,
        instrument,
        background.as_ref(),
        &phases,
        parameters.as_ref(),
        &input.constraints,
        options.use_uncertainty,
        metrics.reduced_chi_square,
    )?;
    runtime
        .emit(
            RefinementEventKind::Termination,
            "lebail",
            "Le Bail extraction terminated",
            vec![(
                "termination_reason".to_owned(),
                DiagnosticValue::String(termination.as_str().to_owned()),
            )],
        )
        .map_err(LeBailError::Runtime)?;
    Ok(LeBailResult {
        calculation,
        phases,
        instrument,
        background,
        intensities: labeled,
        metrics,
        history,
        termination_reason: termination,
        rank_deficient_groups,
        parameters,
        covariance,
        checkpoint,
    })
}

struct RestoredLeBailState {
    phases: Vec<LeBailPhase>,
    instrument: ConstantWavelengthInstrument,
    background: Option<BackgroundModel>,
    intensities: Vec<f64>,
    history: Vec<LeBailIterationRecord>,
    parameters: Option<ParameterSet>,
    previous_rwp: f64,
    first_iteration: usize,
    calculation: Option<LeBailCalculation>,
}

impl RestoredLeBailState {
    fn calculation(&self) -> Result<&LeBailCalculation, LeBailError> {
        self.calculation
            .as_ref()
            .ok_or(LeBailError::InternalInvariant)
    }
}

fn restore_state(
    input: &LeBailInput,
    options: &LeBailOptions,
    checkpoint: Option<&LeBailCheckpoint>,
) -> Result<RestoredLeBailState, LeBailError> {
    let Some(checkpoint) = checkpoint else {
        let intensities = initialize_lebail_intensities(input, options)?;
        let phases = replace_flat_intensities(&input.phases, &intensities)?;
        return Ok(RestoredLeBailState {
            phases,
            instrument: input.instrument,
            background: input.background.clone(),
            intensities,
            history: Vec::new(),
            parameters: input.parameters.clone(),
            previous_rwp: f64::INFINITY,
            first_iteration: 1,
            calculation: None,
        });
    };
    checkpoint.validate()?;
    if checkpoint.completed_iterations >= options.max_iterations {
        return Err(LeBailError::InvalidCheckpoint {
            message: "checkpoint already reached the configured maximum iteration".to_owned(),
        });
    }
    if !phases_restart_compatible(&input.phases, &checkpoint.phases) {
        return Err(LeBailError::InvalidCheckpoint {
            message: "checkpoint phase/reflection domain does not match the input".to_owned(),
        });
    }
    if !backgrounds_restart_compatible(input.background.as_ref(), checkpoint.background.as_ref()) {
        return Err(LeBailError::InvalidCheckpoint {
            message: "checkpoint background does not match the input".to_owned(),
        });
    }
    let input_parameter_keys = input.parameters.as_ref().map(parameter_keys);
    let checkpoint_parameter_keys = checkpoint.parameters.as_ref().map(parameter_keys);
    if input_parameter_keys != checkpoint_parameter_keys {
        return Err(LeBailError::InvalidCheckpoint {
            message: "checkpoint parameter identities do not match the input".to_owned(),
        });
    }
    Ok(RestoredLeBailState {
        phases: checkpoint.phases.clone(),
        instrument: checkpoint.instrument,
        background: checkpoint.background.clone(),
        intensities: checkpoint.intensities.clone(),
        history: checkpoint.history.clone(),
        parameters: checkpoint.parameters.clone(),
        previous_rwp: checkpoint.previous_rwp,
        first_iteration: checkpoint.completed_iterations + 1,
        calculation: None,
    })
}

struct ProfileUpdate {
    instrument: ConstantWavelengthInstrument,
    phases: Vec<LeBailPhase>,
    background: Option<BackgroundModel>,
    calculation: LeBailCalculation,
    parameters: Option<ParameterSet>,
    step_norm: f64,
    parameter_changes: Vec<ParameterChange>,
    warnings: Vec<String>,
}

fn fit_linear_background(
    pattern: &PatternRecord,
    profile_y: &[f64],
    background: Option<&BackgroundModel>,
    parameters: Option<&ParameterSet>,
    use_uncertainty: bool,
) -> Result<(Option<BackgroundModel>, Option<ParameterSet>), LeBailError> {
    let Some(background) = background else {
        return Ok((None, parameters.cloned()));
    };
    if !background.basis_is_invariant() {
        return Ok((Some(background.clone()), parameters.cloned()));
    }
    let observed = pattern
        .observed_y
        .as_deref()
        .ok_or(LeBailError::MissingObservations)?;
    let basis = background
        .basis(&pattern.x_deg)
        .map_err(LeBailError::Background)?;
    let included = pattern
        .mask
        .clone()
        .unwrap_or_else(|| vec![true; pattern.sample_count()]);
    let row_count = included.iter().filter(|value| **value).count();
    if row_count < basis.columns || profile_y.len() != pattern.sample_count() {
        return Err(LeBailError::LinearSolve);
    }
    let mut design = Vec::with_capacity(row_count * basis.columns);
    let mut target = Vec::with_capacity(row_count);
    for sample in 0..pattern.sample_count() {
        if !included[sample] {
            continue;
        }
        let sigma = if use_uncertainty {
            pattern
                .uncertainty
                .as_ref()
                .map_or(1.0, |values| values[sample])
        } else {
            1.0
        };
        let row = basis.row(sample).ok_or(LeBailError::InternalInvariant)?;
        design.extend(row.iter().map(|value| value / sigma));
        target.push((observed[sample] - pattern.background_y[sample] - profile_y[sample]) / sigma);
    }
    let matrix = DMatrix::from_row_slice(row_count, basis.columns, &design);
    let target = DVector::from_vec(target);
    let coefficients = matrix
        .svd(true, true)
        .solve(&target, 1.0e-12)
        .map_err(|_| LeBailError::LinearSolve)?;
    if coefficients.iter().any(|value| !value.is_finite()) {
        return Err(LeBailError::LinearSolve);
    }
    let updated = background
        .replace_coefficients(coefficients.as_slice())
        .map_err(LeBailError::Background)?;
    let updated_parameters = if let Some(parameters) = parameters {
        let values = updated
            .parameter_names()
            .iter()
            .zip(updated.coefficients())
            .map(|(name, value)| {
                Ok((
                    lebail_background_parameter_key(updated.background_id(), name)?,
                    value,
                ))
            })
            .collect::<Result<BTreeMap<_, _>, LeBailError>>()?;
        Some(
            parameters
                .replace_values(&values)
                .map_err(LeBailError::Parameter)?,
        )
    } else {
        None
    };
    Ok((Some(updated), updated_parameters))
}

#[allow(clippy::too_many_arguments)]
// The linearization, bounded solve, and backtracking order intentionally stay
// adjacent so this numerical state transition remains auditable against the
// independent Python oracle.
#[allow(clippy::too_many_lines)]
fn profile_update(
    pattern: &PatternRecord,
    instrument: ConstantWavelengthInstrument,
    phases: Vec<LeBailPhase>,
    calculation: LeBailCalculation,
    parameters: Option<&ParameterSet>,
    background: Option<BackgroundModel>,
    constraints: &[Constraint],
    options: &LeBailOptions,
    runtime: &mut RefinementRuntime<LeBailCheckpoint>,
) -> Result<ProfileUpdate, LeBailError> {
    let Some(parameters) = parameters else {
        return Ok(ProfileUpdate {
            instrument,
            phases,
            background,
            calculation,
            parameters: None,
            step_norm: 0.0,
            parameter_changes: Vec::new(),
            warnings: Vec::new(),
        });
    };
    let domain_values =
        domain_parameter_values(instrument, &phases, background.as_ref(), parameters)?;
    let current = parameters
        .replace_values(&domain_values)
        .map_err(LeBailError::Parameter)?;
    let transform = ConstraintTransform::new(current.clone(), constraints.to_vec())
        .map_err(LeBailError::Constraint)?;
    if transform.free_keys().is_empty() {
        return Ok(ProfileUpdate {
            instrument,
            phases,
            background,
            calculation,
            parameters: Some(current),
            step_norm: 0.0,
            parameter_changes: Vec::new(),
            warnings: Vec::new(),
        });
    }
    let physical = parameter_columns(
        &calculation,
        &current,
        instrument,
        &phases,
        background.as_ref(),
        &pattern.x_deg,
    )?;
    let derivative = transform
        .derivative_matrix()
        .map_err(LeBailError::Constraint)?;
    let chain = DMatrix::from_row_slice(derivative.rows, derivative.columns, &derivative.values);
    let jacobian = physical * chain;
    let observed = pattern
        .observed_y
        .as_deref()
        .ok_or(LeBailError::MissingObservations)?;
    let included = pattern
        .mask
        .clone()
        .unwrap_or_else(|| vec![true; pattern.sample_count()]);
    let selected_count = included.iter().filter(|value| **value).count();
    let free_count = transform.free_keys().len();
    let mut selected_jacobian = DMatrix::zeros(selected_count, free_count);
    let mut selected_residual = DVector::zeros(selected_count);
    let mut selected_row = 0;
    for sample in 0..pattern.sample_count() {
        if !included[sample] {
            continue;
        }
        let weight = if options.use_uncertainty {
            pattern
                .uncertainty
                .as_ref()
                .map_or(1.0, |values| values[sample].recip())
        } else {
            1.0
        };
        selected_residual[selected_row] = (observed[sample] - calculation.y[sample]) * weight;
        for column in 0..free_count {
            selected_jacobian[(selected_row, column)] = jacobian[(sample, column)] * weight;
        }
        selected_row += 1;
    }
    let normal = selected_jacobian.transpose() * &selected_jacobian;
    let mut warnings = Vec::new();
    if matrix_rank(&normal) != free_count {
        warnings.push("profile Jacobian is rank deficient".to_owned());
    }
    if current
        .specs()
        .iter()
        .any(|spec| spec.key().module() == "phase" && spec.key().name() == "scale")
    {
        warnings.push(
            "phase scale is not identifiable independently of extracted Le Bail intensities"
                .to_owned(),
        );
    }
    let base = transform.pack().map_err(LeBailError::Constraint)?;
    let mut lower = vec![-options.max_scaled_parameter_step; free_count];
    let mut upper = vec![options.max_scaled_parameter_step; free_count];
    for (index, key) in transform.free_keys().iter().enumerate() {
        let spec = current.spec(key).ok_or(LeBailError::InternalInvariant)?;
        lower[index] = lower[index].max(spec.bounds().lower() / spec.scale() - base[index]);
        upper[index] = upper[index].min(spec.bounds().upper() / spec.scale() - base[index]);
    }
    let rhs = selected_jacobian.transpose() * &selected_residual;
    let mut regularized = normal;
    for index in 0..free_count {
        regularized[(index, index)] += options.profile_damping;
    }
    let mut step = if let Some(solution) = regularized.lu().solve(&rhs) {
        solution
    } else {
        warnings.push("profile normal equations used least-squares fallback".to_owned());
        selected_jacobian
            .clone()
            .svd(true, true)
            .solve(&selected_residual, f64::EPSILON)
            .map_err(|_| LeBailError::LinearSolve)?
    };
    for index in 0..free_count {
        step[index] = step[index].clamp(lower[index], upper[index]);
    }
    let baseline = evaluate_residuals(
        pattern,
        &calculation.y,
        ResidualOptions {
            use_uncertainty: options.use_uncertainty,
            parameter_count: free_count,
        },
    )
    .map_err(LeBailError::Residual)?;
    let mut factor = 1.0;
    for _ in 0..=options.max_profile_backtracks {
        let trial = base
            .iter()
            .zip(step.iter())
            .map(|(base, step)| base + factor * step)
            .collect::<Vec<_>>();
        let Ok(values) = transform.unpack(&trial, true) else {
            factor *= 0.5;
            continue;
        };
        let Ok((candidate_instrument, candidate_phases, candidate_background)) =
            apply_parameter_values(instrument, &phases, background.as_ref(), &values)
        else {
            factor *= 0.5;
            continue;
        };
        runtime.begin_evaluation().map_err(LeBailError::Runtime)?;
        let Ok(candidate_calculation) = calculate_lebail_pattern_with_background(
            pattern,
            candidate_instrument,
            &candidate_phases,
            candidate_background.as_ref(),
            options.support_fwhm,
            &options.execution,
        ) else {
            factor *= 0.5;
            continue;
        };
        let candidate_metrics = evaluate_residuals(
            pattern,
            &candidate_calculation.y,
            ResidualOptions {
                use_uncertainty: options.use_uncertainty,
                parameter_count: free_count,
            },
        )
        .map_err(LeBailError::Residual)?;
        if candidate_metrics.chi_square < baseline.chi_square {
            let candidate_parameters = current
                .replace_values(&values)
                .map_err(LeBailError::Parameter)?;
            let (candidate_phases, domain_warnings, topology_changed) =
                regenerate_accepted_domains(candidate_phases)?;
            let candidate_calculation = if topology_changed {
                runtime.begin_evaluation().map_err(LeBailError::Runtime)?;
                calculate_lebail_pattern_with_background(
                    pattern,
                    candidate_instrument,
                    &candidate_phases,
                    candidate_background.as_ref(),
                    options.support_fwhm,
                    &options.execution,
                )?
            } else {
                candidate_calculation
            };
            let parameter_changes = current
                .specs()
                .iter()
                .filter_map(|spec| {
                    let after = candidate_parameters.spec(spec.key())?.value();
                    (after.to_bits() != spec.value().to_bits()).then(|| ParameterChange {
                        key: spec.key().clone(),
                        before: spec.value(),
                        after,
                        scaled_change: (after - spec.value()) / spec.scale(),
                    })
                })
                .collect();
            return Ok(ProfileUpdate {
                instrument: candidate_instrument,
                phases: candidate_phases,
                background: candidate_background,
                calculation: candidate_calculation,
                parameters: Some(candidate_parameters),
                step_norm: factor * step.norm(),
                parameter_changes,
                warnings: [warnings, domain_warnings].concat(),
            });
        }
        factor *= 0.5;
    }
    warnings.push("profile step rejected by backtracking".to_owned());
    Ok(ProfileUpdate {
        instrument,
        phases,
        background,
        calculation,
        parameters: Some(current),
        step_norm: 0.0,
        parameter_changes: Vec::new(),
        warnings,
    })
}

fn domain_parameter_values(
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    background: Option<&BackgroundModel>,
    parameters: &ParameterSet,
) -> Result<BTreeMap<ParameterKey, f64>, LeBailError> {
    let mut values = BTreeMap::new();
    for spec in parameters.specs() {
        let key = spec.key();
        let value = if key.module() == "instrument" && key.owner_id() == "cw" {
            instrument_parameter(instrument, key.name())
        } else if key.module() == "phase" && key.name() == "scale" {
            phases
                .iter()
                .find(|phase| phase.phase_id() == key.owner_id())
                .map(LeBailPhase::scale)
        } else if key.module() == "background" {
            background.and_then(|background| {
                if background.background_id() != key.owner_id() {
                    return None;
                }
                background
                    .parameter_names()
                    .iter()
                    .position(|name| name == key.name())
                    .and_then(|index| background.coefficients().get(index).copied())
            })
        } else if key.module() == "lattice" {
            phases
                .iter()
                .find(|phase| phase.phase_id() == key.owner_id())
                .and_then(|phase| {
                    let cell = phase.cell?;
                    let parameterization = phase.reflection_domain.as_ref()?.parameterization();
                    let index = parameterization
                        .parameter_names()
                        .iter()
                        .position(|name| name == key.name())?;
                    parameterization
                        .values_from_cell(cell)
                        .ok()?
                        .get(index)
                        .copied()
                })
        } else if key.module() == "reflection" && key.name() == "two_theta_deg" {
            phases.iter().find_map(|phase| {
                phase
                    .reflection_ids
                    .iter()
                    .position(|reflection_id| {
                        format!("{}/{}", phase.phase_id(), reflection_id) == key.owner_id()
                    })
                    .map(|index| phase.two_theta_deg[index])
            })
        } else {
            None
        }
        .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
        if !spec.bounds().contains(value) {
            return Err(LeBailError::ParameterDomainOutsideBounds { label: key.label() });
        }
        values.insert(key.clone(), value);
    }
    Ok(values)
}

fn parameter_columns(
    calculation: &LeBailCalculation,
    parameters: &ParameterSet,
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    background: Option<&BackgroundModel>,
    x_deg: &[f64],
) -> Result<DMatrix<f64>, LeBailError> {
    let samples = calculation.y.len();
    let mut matrix = DMatrix::zeros(samples, parameters.specs().len());
    let global = calculation
        .accumulation
        .derivatives
        .global
        .as_ref()
        .ok_or(LeBailError::InternalInvariant)?;
    for (column, spec) in parameters.specs().iter().enumerate() {
        let key = spec.key();
        if key.module() == "instrument" {
            let row = INSTRUMENT_PARAMETER_NAMES
                .iter()
                .position(|name| *name == key.name())
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            for sample in 0..samples {
                matrix[(sample, column)] = global.values[row * samples + sample];
            }
        } else if key.module() == "phase" {
            let phase = phases
                .iter()
                .position(|phase| phase.phase_id() == key.owner_id())
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let row = 5 + phase;
            for sample in 0..samples {
                matrix[(sample, column)] = global.values[row * samples + sample];
            }
        } else if key.module() == "reflection" {
            let reflection = calculation
                .reflection_keys
                .iter()
                .position(|(phase_id, reflection_id)| {
                    format!("{phase_id}/{reflection_id}") == key.owner_id()
                })
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let local = &calculation.accumulation.derivatives.local;
            let begin = local.offsets[reflection];
            let end = local.offsets[reflection + 1];
            let start = local.starts[reflection];
            for active in begin..end {
                matrix[(start + active - begin, column)] =
                    local.values[active * local.parameter_count + 1];
            }
        } else if key.module() == "lattice" {
            let phase = phases
                .iter()
                .find(|phase| phase.phase_id() == key.owner_id())
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let cell = phase
                .cell
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let domain = phase
                .reflection_domain
                .as_ref()
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let geometry = cw_lattice_geometry(
                domain.parameterization(),
                cell,
                &phase.hkl,
                instrument.wavelength_angstrom,
            )
            .map_err(LeBailError::Lattice)?;
            let parameter = geometry
                .parameter_names
                .iter()
                .position(|name| name == key.name())
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let local = &calculation.accumulation.derivatives.local;
            for (phase_reflection, reflection_id) in phase.reflection_ids.iter().enumerate() {
                let reflection = calculation
                    .reflection_keys
                    .iter()
                    .position(|(phase_id, candidate_id)| {
                        phase_id == phase.phase_id() && candidate_id == reflection_id
                    })
                    .ok_or(LeBailError::InternalInvariant)?;
                let derivative = geometry.d_two_theta_d_parameters
                    [phase_reflection * geometry.parameter_names.len() + parameter];
                let begin = local.offsets[reflection];
                let end = local.offsets[reflection + 1];
                let start = local.starts[reflection];
                for active in begin..end {
                    matrix[(start + active - begin, column)] +=
                        local.values[active * local.parameter_count + 1] * derivative;
                }
            }
        } else if key.module() == "background" {
            fill_background_parameter_column(&mut matrix, column, key, background, x_deg)?;
        } else {
            return Err(LeBailError::UnsupportedParameter { label: key.label() });
        }
    }
    Ok(matrix)
}

fn fill_background_parameter_column(
    matrix: &mut DMatrix<f64>,
    column: usize,
    key: &ParameterKey,
    background: Option<&BackgroundModel>,
    x_deg: &[f64],
) -> Result<(), LeBailError> {
    let background = background
        .filter(|background| background.background_id() == key.owner_id())
        .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
    let parameter = background
        .parameter_names()
        .iter()
        .position(|name| name == key.name())
        .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
    let basis = background.basis(x_deg).map_err(LeBailError::Background)?;
    let values = basis
        .column(parameter)
        .ok_or(LeBailError::InternalInvariant)?;
    for sample in 0..matrix.nrows() {
        matrix[(sample, column)] = values[sample];
    }
    Ok(())
}

fn apply_parameter_values(
    instrument: ConstantWavelengthInstrument,
    phases: &[LeBailPhase],
    background: Option<&BackgroundModel>,
    values: &BTreeMap<ParameterKey, f64>,
) -> Result<
    (
        ConstantWavelengthInstrument,
        Vec<LeBailPhase>,
        Option<BackgroundModel>,
    ),
    LeBailError,
> {
    let mut updated_instrument = instrument;
    for (key, value) in values {
        if key.module() == "instrument" {
            set_instrument_parameter(&mut updated_instrument, key.name(), *value)?;
        }
    }
    updated_instrument
        .validate()
        .map_err(|error| LeBailError::Profile {
            message: error.to_string(),
        })?;
    let mut updated_phases = Vec::with_capacity(phases.len());
    for phase in phases {
        let scale = values
            .get(&lebail_phase_scale_key(phase.phase_id())?)
            .copied()
            .unwrap_or(phase.scale());
        let mut positions = phase.two_theta_deg.clone();
        for (index, reflection_id) in phase.reflection_ids.iter().enumerate() {
            if let Some(value) = values.get(&lebail_reflection_position_key(
                phase.phase_id(),
                reflection_id,
            )?) {
                positions[index] = *value;
            }
        }
        let mut updated = phase.replace_scale_and_positions(scale, positions)?;
        let lattice_values = values
            .iter()
            .filter(|(key, _)| key.module() == "lattice" && key.owner_id() == phase.phase_id())
            .collect::<Vec<_>>();
        if !lattice_values.is_empty() {
            let cell = phase.cell.ok_or_else(|| {
                invalid_phase("lattice parameters require a bounded reflection domain")
            })?;
            let domain = phase.reflection_domain.as_ref().ok_or_else(|| {
                invalid_phase("lattice parameters require a bounded reflection domain")
            })?;
            let mut independent = domain
                .parameterization()
                .values_from_cell(cell)
                .map_err(LeBailError::Lattice)?;
            for (key, value) in lattice_values {
                let index = domain
                    .parameterization()
                    .parameter_names()
                    .iter()
                    .position(|name| name == key.name())
                    .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
                independent[index] = *value;
            }
            let cell = domain
                .parameterization()
                .to_cell(&independent)
                .map_err(LeBailError::Lattice)?;
            updated =
                updated.replace_cell_geometry(cell, updated_instrument.wavelength_angstrom)?;
        }
        updated_phases.push(updated);
    }
    let updated_background = if let Some(background) = background {
        let names = background.parameter_names();
        let coefficients = names
            .iter()
            .zip(background.coefficients())
            .map(|(name, current)| {
                values
                    .get(&lebail_background_parameter_key(
                        background.background_id(),
                        name,
                    )?)
                    .copied()
                    .map_or(Ok(current), Ok)
            })
            .collect::<Result<Vec<_>, LeBailError>>()?;
        Some(
            background
                .replace_coefficients(&coefficients)
                .map_err(LeBailError::Background)?,
        )
    } else {
        None
    };
    Ok((updated_instrument, updated_phases, updated_background))
}

fn regenerate_accepted_domains(
    phases: Vec<LeBailPhase>,
) -> Result<(Vec<LeBailPhase>, Vec<String>, bool), LeBailError> {
    let mut updated = Vec::with_capacity(phases.len());
    let mut warnings = Vec::new();
    let mut topology_changed = false;
    for phase in phases {
        let Some(domain) = phase.reflection_domain.as_ref() else {
            updated.push(phase);
            continue;
        };
        let cell = phase.cell.ok_or(LeBailError::InternalInvariant)?;
        let previous = phase
            .reflection_ids
            .iter()
            .cloned()
            .zip(phase.integrated_intensity.iter().copied())
            .collect::<BTreeMap<_, _>>();
        let generated = domain
            .generate(cell, Some(&previous))
            .map_err(LeBailError::Lattice)?;
        let changed = generated.reflection_ids != phase.reflection_ids;
        topology_changed |= changed;
        if !generated.added_reflection_ids.is_empty()
            || !generated.removed_reflection_ids.is_empty()
        {
            warnings.push(format!(
                "phase {} reflection domain regenerated: {} added, {} removed",
                phase.phase_id(),
                generated.added_reflection_ids.len(),
                generated.removed_reflection_ids.len()
            ));
        }
        updated.push(phase.replace_generated_domain(cell, generated)?);
    }
    Ok((updated, warnings, topology_changed))
}

#[allow(clippy::too_many_arguments)]
fn covariance(
    pattern: &PatternRecord,
    calculation: &LeBailCalculation,
    instrument: ConstantWavelengthInstrument,
    background: Option<&BackgroundModel>,
    phases: &[LeBailPhase],
    parameters: Option<&ParameterSet>,
    constraints: &[Constraint],
    use_uncertainty: bool,
    reduced_chi_square: f64,
) -> Result<Option<CovarianceMatrix>, LeBailError> {
    let Some(parameters) = parameters else {
        return Ok(None);
    };
    let transform = ConstraintTransform::new(parameters.clone(), constraints.to_vec())
        .map_err(LeBailError::Constraint)?;
    let free_count = transform.free_keys().len();
    if free_count == 0 {
        return Ok(Some(CovarianceMatrix {
            size: 0,
            values: Vec::new(),
        }));
    }
    let derivative = transform
        .derivative_matrix()
        .map_err(LeBailError::Constraint)?;
    for (row, spec) in parameters.specs().iter().enumerate() {
        if spec.key().module() == "phase"
            && spec.key().name() == "scale"
            && derivative
                .row(row)
                .is_some_and(|values| values.iter().any(|value| *value != 0.0))
        {
            return Ok(None);
        }
    }
    let physical = parameter_columns(
        calculation,
        parameters,
        instrument,
        phases,
        background,
        &pattern.x_deg,
    )?;
    let chain = DMatrix::from_row_slice(derivative.rows, derivative.columns, &derivative.values);
    let jacobian = physical * chain;
    let included = pattern
        .mask
        .clone()
        .unwrap_or_else(|| vec![true; pattern.sample_count()]);
    let row_count = included.iter().filter(|value| **value).count();
    let mut selected = DMatrix::zeros(row_count, free_count);
    let mut row = 0;
    for sample in 0..pattern.sample_count() {
        if !included[sample] {
            continue;
        }
        let weight = if use_uncertainty {
            pattern
                .uncertainty
                .as_ref()
                .map_or(1.0, |values| values[sample].recip())
        } else {
            1.0
        };
        for column in 0..free_count {
            selected[(row, column)] = jacobian[(sample, column)] * weight;
        }
        row += 1;
    }
    let normal = selected.transpose() * selected;
    if matrix_rank(&normal) != free_count {
        return Ok(None);
    }
    let Some(mut inverse) = normal.try_inverse() else {
        return Ok(None);
    };
    let known_uncertainties = use_uncertainty && pattern.uncertainty.is_some();
    if !known_uncertainties && reduced_chi_square.is_finite() {
        inverse *= reduced_chi_square;
    }
    let mut values = Vec::with_capacity(free_count * free_count);
    for row in 0..free_count {
        for column in 0..free_count {
            values.push(inverse[(row, column)]);
        }
    }
    Ok(Some(CovarianceMatrix {
        size: free_count,
        values,
    }))
}

fn free_parameter_count(
    parameters: Option<&ParameterSet>,
    constraints: &[Constraint],
) -> Result<usize, LeBailError> {
    parameters.map_or(Ok(0), |parameters| {
        ConstraintTransform::new(parameters.clone(), constraints.to_vec())
            .map(|transform| transform.free_keys().len())
            .map_err(LeBailError::Constraint)
    })
}

fn matrix_rank(matrix: &DMatrix<f64>) -> usize {
    let singular = matrix.clone().svd(false, false).singular_values;
    let maximum = singular.iter().copied().fold(0.0_f64, f64::max);
    let tolerance = count_as_f64(matrix.nrows().max(matrix.ncols())) * f64::EPSILON * maximum;
    singular.iter().filter(|value| **value > tolerance).count()
}

fn instrument_parameter(instrument: ConstantWavelengthInstrument, name: &str) -> Option<f64> {
    match name {
        "u_deg2" => Some(instrument.u_deg2),
        "v_deg2" => Some(instrument.v_deg2),
        "w_deg2" => Some(instrument.w_deg2),
        "x_deg" => Some(instrument.x_deg),
        "y_deg" => Some(instrument.y_deg),
        _ => None,
    }
}

fn set_instrument_parameter(
    instrument: &mut ConstantWavelengthInstrument,
    name: &str,
    value: f64,
) -> Result<(), LeBailError> {
    match name {
        "u_deg2" => instrument.u_deg2 = value,
        "v_deg2" => instrument.v_deg2 = value,
        "w_deg2" => instrument.w_deg2 = value,
        "x_deg" => instrument.x_deg = value,
        "y_deg" => instrument.y_deg = value,
        _ => {
            return Err(LeBailError::UnsupportedParameter {
                label: format!("instrument[cw].{name}"),
            });
        }
    }
    Ok(())
}

fn rank_deficient_groups(
    calculation: &LeBailCalculation,
    threshold: f64,
) -> Vec<CoincidentReflectionGroup> {
    let local = &calculation.accumulation.derivatives.local;
    let count = local.peak_count();
    let mut parents = (0..count).collect::<Vec<_>>();
    let norms = (0..count)
        .map(|reflection| {
            let begin = local.offsets[reflection];
            let end = local.offsets[reflection + 1];
            (begin..end)
                .map(|active| {
                    let value = local.values[active * local.parameter_count];
                    value * value
                })
                .sum::<f64>()
                .sqrt()
        })
        .collect::<Vec<_>>();
    for left in 0..count {
        let left_begin = local.offsets[left];
        let left_end = local.offsets[left + 1];
        let left_start = local.starts[left];
        let left_stop = left_start + left_end - left_begin;
        for right in left + 1..count {
            let right_begin = local.offsets[right];
            let right_end = local.offsets[right + 1];
            let right_start = local.starts[right];
            let right_stop = right_start + right_end - right_begin;
            let start = left_start.max(right_start);
            let stop = left_stop.min(right_stop);
            if start >= stop || norms[left] == 0.0 || norms[right] == 0.0 {
                continue;
            }
            let correlation = (start..stop)
                .map(|sample| {
                    let left_active = left_begin + sample - left_start;
                    let right_active = right_begin + sample - right_start;
                    local.values[left_active * local.parameter_count]
                        * local.values[right_active * local.parameter_count]
                })
                .sum::<f64>()
                / (norms[left] * norms[right]);
            if correlation >= threshold {
                union(&mut parents, left, right);
            }
        }
    }
    let mut grouped = std::collections::BTreeMap::<usize, Vec<usize>>::new();
    for reflection in 0..count {
        let root = root(&mut parents, reflection);
        grouped.entry(root).or_default().push(reflection);
    }
    grouped
        .into_values()
        .filter(|indices| indices.len() > 1)
        .map(|indices| {
            let first = indices
                .iter()
                .map(|index| local.starts[*index])
                .min()
                .unwrap_or(0);
            let last = indices
                .iter()
                .map(|index| {
                    local.starts[*index] + local.offsets[*index + 1] - local.offsets[*index]
                })
                .max()
                .unwrap_or(first);
            let mut matrix = DMatrix::zeros(last - first, indices.len());
            for (column, reflection) in indices.iter().enumerate() {
                let begin = local.offsets[*reflection];
                let end = local.offsets[*reflection + 1];
                let start = local.starts[*reflection] - first;
                for active in begin..end {
                    matrix[(start + active - begin, column)] =
                        local.values[active * local.parameter_count];
                }
            }
            let singular_values = matrix.svd(false, false).singular_values;
            let maximum = singular_values.iter().copied().fold(0.0_f64, f64::max);
            let tolerance =
                count_as_f64((last - first).max(indices.len())) * f64::EPSILON * maximum;
            let rank = singular_values
                .iter()
                .filter(|value| **value > tolerance)
                .count();
            CoincidentReflectionGroup {
                reflection_keys: indices
                    .iter()
                    .map(|index| calculation.reflection_keys[*index].clone())
                    .collect(),
                rank,
            }
        })
        .collect()
}

fn root(parents: &mut [usize], mut index: usize) -> usize {
    while parents[index] != index {
        parents[index] = parents[parents[index]];
        index = parents[index];
    }
    index
}

fn union(parents: &mut [usize], left: usize, right: usize) {
    let left_root = root(parents, left);
    let right_root = root(parents, right);
    if left_root != right_root {
        parents[right_root] = left_root;
    }
}

fn bin_integration_weights(x: &[f64]) -> Vec<f64> {
    match x.len() {
        0 => Vec::new(),
        1 => vec![1.0],
        count => {
            let mut widths = vec![0.0; count];
            widths[0] = 0.5 * (x[1] - x[0]);
            widths[count - 1] = 0.5 * (x[count - 1] - x[count - 2]);
            for index in 1..count - 1 {
                widths[index] = 0.5 * (x[index + 1] - x[index - 1]);
            }
            widths
        }
    }
}

fn replace_flat_intensities(
    phases: &[LeBailPhase],
    intensities: &[f64],
) -> Result<Vec<LeBailPhase>, LeBailError> {
    let expected = phases.iter().map(reflection_count).sum::<usize>();
    if intensities.len() != expected {
        return Err(LeBailError::IntensityShapeMismatch);
    }
    let mut offset = 0;
    phases
        .iter()
        .map(|phase| {
            let end = offset + reflection_count(phase);
            let updated = phase.replace_intensities(&intensities[offset..end]);
            offset = end;
            updated
        })
        .collect()
}

fn flatten_intensities(phases: &[LeBailPhase]) -> Vec<f64> {
    phases
        .iter()
        .flat_map(|phase| phase.integrated_intensity.iter().copied())
        .collect()
}

fn flatten_preserve_mask(phases: &[LeBailPhase]) -> Vec<bool> {
    phases
        .iter()
        .flat_map(|phase| {
            if phase.preserve_unobserved.is_empty() {
                vec![false; reflection_count(phase)]
            } else {
                phase.preserve_unobserved.clone()
            }
        })
        .collect()
}

fn parameter_keys(parameters: &ParameterSet) -> Vec<&ParameterKey> {
    parameters.specs().iter().map(ParameterSpec::key).collect()
}

fn validate_parameter_selection(
    phases: &[LeBailPhase],
    background: Option<&BackgroundModel>,
    parameters: &ParameterSet,
) -> Result<(), LeBailError> {
    for spec in parameters.specs() {
        let key = spec.key();
        if key.module() == "background" {
            let supported = background.is_some_and(|background| {
                background.background_id() == key.owner_id()
                    && background
                        .parameter_names()
                        .iter()
                        .any(|name| name == key.name())
            });
            if !supported {
                return Err(LeBailError::UnsupportedParameter { label: key.label() });
            }
        } else if key.module() == "lattice" {
            let phase = phases
                .iter()
                .find(|phase| phase.phase_id() == key.owner_id())
                .ok_or_else(|| LeBailError::UnsupportedParameter { label: key.label() })?;
            let Some(domain) = phase.reflection_domain.as_ref() else {
                return Err(invalid_phase(
                    "lattice parameters require bounded dynamic phases",
                ));
            };
            if !domain
                .parameterization()
                .parameter_names()
                .iter()
                .any(|name| name == key.name())
            {
                return Err(LeBailError::UnsupportedParameter { label: key.label() });
            }
        } else if key.module() == "reflection" {
            let dynamic = phases.iter().any(|phase| {
                phase.reflection_domain.is_some()
                    && key
                        .owner_id()
                        .strip_prefix(phase.phase_id())
                        .is_some_and(|suffix| suffix.starts_with('/'))
            });
            if dynamic {
                return Err(invalid_phase(
                    "independent reflection positions require fixed-topology phases",
                ));
            }
        }
    }
    Ok(())
}

fn phases_restart_compatible(input: &[LeBailPhase], checkpoint: &[LeBailPhase]) -> bool {
    input.len() == checkpoint.len()
        && input.iter().zip(checkpoint).all(|(left, right)| {
            if left.phase_id() != right.phase_id() {
                return false;
            }
            match (&left.reflection_domain, &right.reflection_domain) {
                (None, None) => left.reflection_ids == right.reflection_ids,
                (Some(left_domain), Some(right_domain)) => left_domain == right_domain,
                _ => false,
            }
        })
}

fn backgrounds_restart_compatible(
    input: Option<&BackgroundModel>,
    checkpoint: Option<&BackgroundModel>,
) -> bool {
    match (input, checkpoint) {
        (None, None) => true,
        (Some(input), Some(checkpoint)) => checkpoint.restart_compatible(input),
        _ => false,
    }
}

fn reflection_count(phase: &LeBailPhase) -> usize {
    phase.reflection_ids.len()
}

fn reflection_count_of(phase: &LeBailPhase) -> usize {
    reflection_count(phase)
}

fn validate_stable_label(name: &'static str, value: &str) -> Result<(), LeBailError> {
    if value.is_empty()
        || value.trim() != value
        || value.chars().any(char::is_control)
        || value.contains('/')
    {
        return Err(LeBailError::InvalidPhase {
            message: format!(
                "{name} must be non-empty, trimmed, and contain neither '/' nor control characters"
            ),
        });
    }
    Ok(())
}

fn normal_stop_reason(error: &RuntimeError) -> Option<TerminationReason> {
    match error {
        RuntimeError::Stopped(stop) => Some(stop.reason),
        _ => None,
    }
}

fn stop_reason_or_error(error: RuntimeError) -> Result<TerminationReason, LeBailError> {
    normal_stop_reason(&error).ok_or(LeBailError::Runtime(error))
}

#[allow(clippy::cast_precision_loss)]
fn count_as_f64(value: usize) -> f64 {
    value as f64
}

fn invalid_phase(message: &str) -> LeBailError {
    LeBailError::InvalidPhase {
        message: message.to_owned(),
    }
}

fn invalid_options(message: &str) -> LeBailError {
    LeBailError::InvalidOptions {
        message: message.to_owned(),
    }
}

/// Invalid native fixed-reflection Le Bail state or operation.
#[derive(Debug)]
pub enum LeBailError {
    /// Pattern domain state is invalid.
    Pattern(DomainError),
    /// Observations are required.
    MissingObservations,
    /// Typed parameter construction or replacement failed.
    Parameter(ParameterError),
    /// Constraint graph or transform failed.
    Constraint(ConstraintError),
    /// Lattice parameterization, geometry, bounds, or generation failed.
    Lattice(LatticeError),
    /// Analytical residual-background evaluation failed.
    Background(BackgroundError),
    /// A parameter key is not supported by fixed-geometry Le Bail.
    UnsupportedParameter {
        /// Stable parameter label.
        label: String,
    },
    /// A live domain value violates its declared parameter bounds.
    ParameterDomainOutsideBounds {
        /// Stable parameter label.
        label: String,
    },
    /// Native least-squares solution failed.
    LinearSolve,
    /// One phase or reflection record is invalid.
    InvalidPhase {
        /// Stable diagnostic message.
        message: String,
    },
    /// One option is invalid.
    InvalidOptions {
        /// Stable diagnostic message.
        message: String,
    },
    /// A checkpoint cannot continue this request.
    InvalidCheckpoint {
        /// Stable diagnostic message.
        message: String,
    },
    /// Current intensities do not match the calculated reflection order.
    IntensityShapeMismatch,
    /// Preserve-if-unobserved mask does not match the reflection count.
    PreserveMaskLengthMismatch,
    /// Pattern grid validation failed.
    Grid(ProfileError),
    /// Native CW accumulation failed.
    Calculation(CwContributionsError),
    /// Residual evaluation failed.
    Residual(ResidualError),
    /// Bounded runtime or host callback failed.
    Runtime(RuntimeError),
    /// Execution policy construction failed.
    Execution(ExecutionPolicyError),
    /// A workflow-owned allocation/budget count overflowed.
    SizeOverflow,
    /// A lower-level profile/instrument validation failed.
    Profile {
        /// Stable diagnostic message.
        message: String,
    },
    /// Private workflow state became inconsistent.
    InternalInvariant,
}

impl Display for LeBailError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pattern(error) => Display::fmt(error, formatter),
            Self::MissingObservations => {
                formatter.write_str("observed_y is required for Le Bail extraction")
            }
            Self::Parameter(error) => Display::fmt(error, formatter),
            Self::Constraint(error) => Display::fmt(error, formatter),
            Self::Lattice(error) => Display::fmt(error, formatter),
            Self::Background(error) => Display::fmt(error, formatter),
            Self::UnsupportedParameter { label } => {
                write!(formatter, "unsupported Le Bail parameter {label}")
            }
            Self::ParameterDomainOutsideBounds { label } => {
                write!(
                    formatter,
                    "domain value for {label} lies outside its bounds"
                )
            }
            Self::LinearSolve => formatter.write_str("profile least-squares solve failed"),
            Self::InvalidPhase { message }
            | Self::InvalidOptions { message }
            | Self::InvalidCheckpoint { message }
            | Self::Profile { message } => formatter.write_str(message),
            Self::IntensityShapeMismatch => {
                formatter.write_str("current intensities must match the reflection count")
            }
            Self::PreserveMaskLengthMismatch => {
                formatter.write_str("preserve_unobserved must match the reflection count")
            }
            Self::Grid(error) => Display::fmt(error, formatter),
            Self::Calculation(error) => Display::fmt(error, formatter),
            Self::Residual(error) => Display::fmt(error, formatter),
            Self::Runtime(error) => Display::fmt(error, formatter),
            Self::Execution(error) => Display::fmt(error, formatter),
            Self::SizeOverflow => formatter.write_str("Le Bail workflow size or budget overflowed"),
            Self::InternalInvariant => {
                formatter.write_str("internal Le Bail workflow state is inconsistent")
            }
        }
    }
}

impl Error for LeBailError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Pattern(error) => Some(error),
            Self::Parameter(error) => Some(error),
            Self::Constraint(error) => Some(error),
            Self::Lattice(error) => Some(error),
            Self::Background(error) => Some(error),
            Self::Grid(error) => Some(error),
            Self::Calculation(error) => Some(error),
            Self::Residual(error) => Some(error),
            Self::Runtime(error) => Some(error),
            Self::Execution(error) => Some(error),
            Self::MissingObservations
            | Self::UnsupportedParameter { .. }
            | Self::ParameterDomainOutsideBounds { .. }
            | Self::LinearSolve
            | Self::InvalidPhase { .. }
            | Self::InvalidOptions { .. }
            | Self::InvalidCheckpoint { .. }
            | Self::IntensityShapeMismatch
            | Self::PreserveMaskLengthMismatch
            | Self::SizeOverflow
            | Self::Profile { .. }
            | Self::InternalInvariant => None,
        }
    }
}