layered_map

nrxrdct.laue.LayeredMap

Per-pixel orientation and strain map for a :class:~nrxrdct.laue.layers.LayeredCrystal.

Unlike :class:~nrxrdct.laue.map.GrainMap, all layers are predefined in the stack template — no grain selection or merging step is needed. A single fit per pixel drives all layers simultaneously through a shared global rotation and optional per-layer strain tensor.

Per-pixel arrays

Scalar (shape (ny, nx)): rms_px, mean_px, match_rate, cost, n_sim, score, score0 (image-based). n_matched uses -1 for unfitted pixels.

Orientation (shape (n_layers, ny, nx, 3, 3) or (ny, nx, 3[, 3])) : U, U_eff, R_global, rotvec.

Strain (shape (n_layers, ny, nx, 3, 3) or (n_layers, ny, nx, 6)): strain_tensor, strain_voigt, strain_tensor_deviatoric.

Source code in src/nrxrdct/laue/layered_map.py
 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
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
class LayeredMap:
    """
    Per-pixel orientation and strain map for a :class:`~nrxrdct.laue.layers.LayeredCrystal`.

    Unlike :class:`~nrxrdct.laue.map.GrainMap`, all layers are predefined in
    the stack template — no grain selection or merging step is needed.  A single
    fit per pixel drives all layers simultaneously through a shared global
    rotation and optional per-layer strain tensor.

    Per-pixel arrays
    ----------------

    Scalar (shape ``(ny, nx)``):
        ``rms_px``, ``mean_px``, ``match_rate``, ``cost``, ``n_sim``,
        ``score``, ``score0`` (image-based).
        ``n_matched`` uses ``-1`` for unfitted pixels.

    Orientation (shape ``(n_layers, ny, nx, 3, 3)`` or ``(ny, nx, 3[, 3])``) :
        ``U``, ``U_eff``, ``R_global``, ``rotvec``.

    Strain (shape ``(n_layers, ny, nx, 3, 3)`` or ``(n_layers, ny, nx, 6)``):
        ``strain_tensor``, ``strain_voigt``, ``strain_tensor_deviatoric``.
    """

    def __init__(
        self,
        ny: int,
        nx: int,
        stack,
        *,
        h5_path: str | None = None,
        entry: str = "1.1",
        motor_x: str | None = None,
        motor_y: str | None = None,
        save_path: str | None = None,
        monitor: str | None = None,
    ) -> None:
        self.ny        = ny
        self.nx        = nx
        self.stack     = stack
        self.h5_path   = h5_path
        self.entry     = entry
        self.save_path = save_path
        self.monitor   = monitor

        n_layers = len(stack.all_layers)
        self.n_layers    = n_layers
        self.layer_labels = [
            getattr(l, "label", f"layer_{i}")
            for i, l in enumerate(stack.all_layers)
        ]

        # ── scalar per-pixel arrays ────────────────────────────────────────────
        self.rms_px     = np.full((ny, nx), np.nan)
        self.mean_px    = np.full((ny, nx), np.nan)
        self.n_matched  = np.full((ny, nx), -1, dtype=int)
        self.match_rate = np.full((ny, nx), np.nan)
        self.cost       = np.full((ny, nx), np.nan)
        self.n_sim      = np.full((ny, nx), -1, dtype=int)
        self.score      = np.full((ny, nx), np.nan)
        self.score0     = np.full((ny, nx), np.nan)

        # ── orientation arrays ─────────────────────────────────────────────────
        self.R_global = np.full((ny, nx, 3, 3), np.nan)
        self.rotvec   = np.full((ny, nx, 3), np.nan)
        self.U        = np.full((n_layers, ny, nx, 3, 3), np.nan)
        self.U_eff    = np.full((n_layers, ny, nx, 3, 3), np.nan)

        # ── per-layer strain arrays ────────────────────────────────────────────
        self.strain_tensor            = np.full((n_layers, ny, nx, 3, 3), np.nan)
        self.strain_voigt             = np.full((n_layers, ny, nx, 6), np.nan)
        self.strain_tensor_deviatoric = np.full((n_layers, ny, nx, 3, 3), np.nan)

        # ── motor positions ────────────────────────────────────────────────────
        self.motors: dict[str, np.ndarray] = {}
        if h5_path is not None:
            self._load_motors(motor_x, motor_y)

        # ── raw result cache (optional) ────────────────────────────────────────
        self._results: list[list] = [[None] * nx for _ in range(ny)]

    # ── Index helpers ──────────────────────────────────────────────────────────

    def frame_index(self, iy: int, ix: int) -> int:
        """Flat frame index for pixel ``(iy, ix)``."""
        return iy * self.nx + ix

    def map_index(self, frame_idx: int) -> tuple[int, int]:
        """Map pixel ``(iy, ix)`` for a flat frame index."""
        return divmod(frame_idx, self.nx)

    # ── Motor loading ──────────────────────────────────────────────────────────

    def _load_motors(self, motor_x: str | None, motor_y: str | None) -> None:
        n_frames = self.ny * self.nx
        with h5py.File(self.h5_path, "r") as hf:
            for name in (motor_x, motor_y):
                if name is None:
                    continue
                arr = _read_motor_array(hf, self.entry, name, n_frames)
                if arr is not None:
                    self.motors[name] = arr.reshape(self.ny, self.nx)

    # ── Result storage ─────────────────────────────────────────────────────────

    def set_result(self, iy: int, ix: int, result) -> None:
        """
        Store a stack fitting result for pixel ``(iy, ix)``.

        Accepts :class:`~nrxrdct.laue.fitting.StackFitResult`,
        :class:`~nrxrdct.laue.fitting.StackStrainFitResult`,
        :class:`~nrxrdct.laue.fitting.StackImageRefinementResult`, and
        :class:`~nrxrdct.laue.fitting.StackStrainImageRefinementResult`.
        """
        from .fitting import (
            StackFitResult, StackStrainFitResult,
            StackImageRefinementResult, StackStrainImageRefinementResult,
        )

        self._results[iy][ix] = result

        self.R_global[iy, ix] = result.R_global
        self.rotvec[iy, ix]   = result.rotvec
        for li, U in enumerate(result.U_layers):
            self.U[li, iy, ix] = U

        if isinstance(result, (StackFitResult, StackStrainFitResult)):
            self.rms_px[iy, ix]     = result.rms_px
            self.mean_px[iy, ix]    = result.mean_px
            self.n_matched[iy, ix]  = result.n_matched
            self.match_rate[iy, ix] = result.match_rate
            self.cost[iy, ix]       = result.cost
            self.n_sim[iy, ix]      = result.n_sim

        if isinstance(result, (StackImageRefinementResult, StackStrainImageRefinementResult)):
            self.score[iy, ix]  = result.score
            self.score0[iy, ix] = result.score0
            self.n_sim[iy, ix]  = result.n_sim

        if isinstance(result, (StackStrainFitResult, StackStrainImageRefinementResult)):
            for li, (U_eff, eps, voigt) in enumerate(zip(
                result.U_eff_layers, result.strain_tensors, result.strain_voigts
            )):
                self.U_eff[li, iy, ix]           = U_eff
                self.strain_tensor[li, iy, ix]   = eps
                self.strain_voigt[li, iy, ix]    = voigt
                self.strain_tensor_deviatoric[li, iy, ix] = (
                    eps - np.trace(eps) / 3.0 * np.eye(3)
                )

    def get_result(self, iy: int, ix: int):
        """Return the cached result object for pixel ``(iy, ix)``, or ``None``."""
        return self._results[iy][ix]

    # ── Collect from .npz files ────────────────────────────────────────────────

    def collect(self, out_dir: str) -> int:
        """
        Load all ``frame_?????.npz`` files written by the ``run_*_local``
        methods into the map arrays.

        Returns the number of frames successfully loaded.
        """
        files = sorted(glob.glob(os.path.join(out_dir, "frame_?????.npz")))
        n_ok  = 0
        for path in files:
            frame_idx = int(os.path.basename(path)[6:11])
            iy, ix = self.map_index(frame_idx)
            if iy >= self.ny or ix >= self.nx:
                continue
            try:
                d = np.load(path, allow_pickle=False)
            except Exception as exc:
                print(f"  ✗  {path}: {exc}", flush=True)
                continue

            self.R_global[iy, ix]  = d["R_global"]
            self.rotvec[iy, ix]    = d["rotvec"]
            self.U[:, iy, ix]      = d["U_layers"]

            if "rms_px" in d:
                self.rms_px[iy, ix]     = float(d["rms_px"])
                self.mean_px[iy, ix]    = float(d["mean_px"])
                self.n_matched[iy, ix]  = int(d["n_matched"])
                self.match_rate[iy, ix] = float(d["match_rate"])
                self.cost[iy, ix]       = float(d["cost"])
            if "score" in d:
                self.score[iy, ix]  = float(d["score"])
                self.score0[iy, ix] = float(d["score0"])
            if "n_sim" in d:
                self.n_sim[iy, ix] = int(d["n_sim"])

            if "strain_tensors" in d:
                eps_arr = d["strain_tensors"]   # (n_layers, 3, 3)
                self.U_eff[:, iy, ix]           = d["U_eff_layers"]
                self.strain_tensor[:, iy, ix]   = eps_arr
                self.strain_voigt[:, iy, ix]    = d["strain_voigts"]
                for li in range(self.n_layers):
                    eps = eps_arr[li]
                    self.strain_tensor_deviatoric[li, iy, ix] = (
                        eps - np.trace(eps) / 3.0 * np.eye(3)
                    )

            n_ok += 1

        print(f"collect: {n_ok}/{len(files)} frames loaded from {out_dir!r}",
              flush=True)
        return n_ok

    # ── Internal pool helpers ──────────────────────────────────────────────────

    def _serialize_stack(self) -> str:
        with tempfile.NamedTemporaryFile(suffix=".pkl", delete=False) as tf:
            path = tf.name
        with open(path, "wb") as fh:
            _dill.dump(self.stack, fh)
        return path

    def _load_peaklists(
        self,
        seg_dir: str,
        frame_indices: list[int],
        r_squared_min: float,
        include_unfitted: bool,
        min_matched: int,
    ) -> dict:
        from .segmentation import convert_spotsfile2peaklist

        peaklists: dict[int, np.ndarray] = {}
        for fi in frame_indices:
            path = os.path.join(seg_dir, f"frame_{fi:05d}.h5")
            if not os.path.exists(path):
                continue
            try:
                pl = convert_spotsfile2peaklist(
                    path,
                    r_squared_min=r_squared_min,
                    include_unfitted=include_unfitted,
                )
                if len(pl) >= min_matched:
                    peaklists[fi] = pl[:, :2]
            except Exception as exc:
                print(f"  ✗  frame {fi}: peaklist load: {exc}", flush=True)
        return peaklists

    def _load_frames(
        self, h5_path: str, h5_dataset: str, frame_indices: list[int]
    ) -> dict:
        frames: dict[int, np.ndarray] = {}
        with h5py.File(h5_path, "r") as hf:
            ds = hf[h5_dataset]
            for fi in frame_indices:
                try:
                    frames[fi] = ds[fi].astype(np.float32)
                except Exception as exc:
                    print(f"  ✗  frame {fi}: image read: {exc}", flush=True)
        return frames

    def _run_pool(
        self,
        worker_fn,
        frame_indices: list[int],
        task_args: dict,
        common_kwargs: dict,
        stack_pkl: str,
        camera,
        allowed_hkl,
        n_workers: int,
    ) -> int:
        n_total = len(frame_indices)
        tick    = max(1, n_total // 20)
        t0      = time.time()
        n_ok    = 0
        done    = 0

        with concurrent.futures.ProcessPoolExecutor(
            max_workers = n_workers,
            initializer = _lm_pool_init,
            initargs    = (stack_pkl, camera, allowed_hkl),
        ) as pool:
            futs = {
                pool.submit(worker_fn, fi, task_args.get(fi), **common_kwargs): fi
                for fi in frame_indices
            }
            for fut in concurrent.futures.as_completed(futs):
                done += 1
                try:
                    _, ok = fut.result()
                    if ok:
                        n_ok += 1
                except Exception as exc:
                    print(f"  ✗  frame {futs[fut]}: {exc}", flush=True)

                if done % tick == 0 or done == n_total:
                    elapsed = time.time() - t0
                    rate    = done / elapsed if elapsed > 0 else float("inf")
                    eta     = (n_total - done) / rate if rate > 0 else float("inf")
                    print(
                        f"  {done}/{n_total}  {n_ok} ok  "
                        f"{elapsed:.0f}s  ETA {eta:.0f}s",
                        flush=True,
                    )
        return n_ok

    def _precompute_allowed(
        self, E_max_eV: float, f2_thresh: float
    ) -> "dict | None":
        from .simulation import precompute_allowed_hkl

        _enum_pool = (
            self.stack.buffer_layers + self.stack.layers[:1]
            if (self.stack.buffer_layers or self.stack.layers)
            else self.stack.all_layers
        )
        return {
            id(l.crystal): precompute_allowed_hkl(
                l.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
            )
            for l in _enum_pool
        }

    # ── Local parallel fitting ─────────────────────────────────────────────────

    def run_orientation_local(
        self,
        camera,
        seg_dir: str,
        out_dir: str,
        *,
        r_squared_min: float = 0.0,
        include_unfitted: bool = False,
        max_match_px=(30, 10, 3),
        min_matched: int = 5,
        min_match_rate: float = 0.2,
        max_rms_px: "float | None" = None,
        geometry_only: bool = True,
        correct_depth: bool = False,
        engine: str = "stack",
        f2_thresh: float = 1e-4,
        n_workers: "int | None" = None,
        overwrite: bool = False,
        frame_indices: "list[int] | None" = None,
        **fit_kwargs,
    ) -> int:
        """
        Fit stack orientation for every frame in *seg_dir* using local CPU cores.

        Results are written as ``frame_?????.npz`` in *out_dir*.
        Call :meth:`collect` afterwards to load them into the map arrays.

        Args:
            camera: Detector geometry.
            seg_dir: Directory with ``frame_?????.h5`` peaklist files.
            out_dir: Output directory for ``frame_?????.npz`` result files.
            max_match_px: Pixel match radius; a decreasing list enables staged
                refinement (e.g. ``[30, 10, 3]``).
            correct_depth: Project each layer's spots from its centre depth.
                Default ``False``.
            engine: Simulation engine — ``'stack'`` (default, kinematical) or
                ``'darwin'`` (Darwin primary extinction).  The Darwin engine
                uses physically correct intensities for thick layers
                but is somewhat slower per frame.
            fit_kwargs: Forwarded to :func:`~nrxrdct.laue.fitting.fit_orientation_stack`.

        Returns:
            Number of frames successfully fitted.
        """
        os.makedirs(out_dir, exist_ok=True)

        if frame_indices is None:
            h5s = sorted(glob.glob(os.path.join(seg_dir, "frame_?????.h5")))
            frame_indices = [int(os.path.basename(p)[6:11]) for p in h5s]

        allowed_hkl = None
        if geometry_only:
            _E_max = fit_kwargs.get("E_max_eV", 27_000)
            allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

        peaklists = self._load_peaklists(
            seg_dir, frame_indices, r_squared_min, include_unfitted, min_matched
        )
        print(
            f"run_orientation_local: {len(frame_indices)} frames | "
            f"{len(peaklists)} with ≥{min_matched} spots | "
            f"{self.n_layers} layers",
            flush=True,
        )

        common = dict(
            out_dir        = out_dir,
            max_match_px   = max_match_px,
            min_matched    = min_matched,
            min_match_rate = min_match_rate,
            max_rms_px     = max_rms_px,
            fit_kwargs     = {**fit_kwargs, "geometry_only": geometry_only,
                               "correct_depth": correct_depth, "engine": engine},
            overwrite      = overwrite,
        )
        stack_pkl = self._serialize_stack()
        try:
            n_ok = self._run_pool(
                _lm_orient_frame, frame_indices, peaklists, common,
                stack_pkl, camera, allowed_hkl,
                n_workers or os.cpu_count() or 1,
            )
        finally:
            os.unlink(stack_pkl)

        print(f"  → {n_ok}/{len(frame_indices)} frames fitted", flush=True)
        return n_ok

    def run_strain_local(
        self,
        camera,
        seg_dir: str,
        out_dir: str,
        *,
        fit_strain: "tuple | None" = None,
        orient_dir: "str | None" = None,
        r_squared_min: float = 0.0,
        include_unfitted: bool = False,
        max_match_px=(10, 3),
        min_matched: int = 5,
        min_match_rate: float = 0.2,
        max_rms_px: "float | None" = None,
        geometry_only: bool = True,
        correct_depth: bool = False,
        engine: str = "stack",
        f2_thresh: float = 1e-4,
        n_workers: "int | None" = None,
        overwrite: bool = False,
        frame_indices: "list[int] | None" = None,
        **fit_kwargs,
    ) -> int:
        """
        Fit stack orientation + per-layer strain for every frame using local cores.

        Mirrors :meth:`run_orientation_local` but calls
        :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack` instead.
        Start from a good orientation (run :meth:`run_orientation_local` first
        and :meth:`collect` the result into the stack's layer U matrices).

        Args:
            fit_strain: Strain components to refine, e.g.
                ``('e_xx', 'e_yy', 'e_zz')``.  ``None`` refines all six.
            correct_depth: Project each layer's spots from its centre depth.
                Default ``False``.
            engine: Simulation engine — ``'stack'`` (default) or
                ``'darwin'``.  See :meth:`run_orientation_local`.
        """
        from .fitting import _STRAIN_ALL
        _fit_strain = tuple(fit_strain) if fit_strain is not None else _STRAIN_ALL
        os.makedirs(out_dir, exist_ok=True)

        if frame_indices is None:
            h5s = sorted(glob.glob(os.path.join(seg_dir, "frame_?????.h5")))
            frame_indices = [int(os.path.basename(p)[6:11]) for p in h5s]

        allowed_hkl = None
        if geometry_only:
            _E_max = fit_kwargs.get("E_max_eV", 27_000)
            allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

        peaklists = self._load_peaklists(
            seg_dir, frame_indices, r_squared_min, include_unfitted, min_matched
        )
        print(
            f"run_strain_local: {len(frame_indices)} frames | "
            f"{len(peaklists)} with ≥{min_matched} spots | "
            f"fit_strain={list(_fit_strain)}",
            flush=True,
        )

        # Load per-frame orientation warm-starts if an orient_dir was given.
        orient_data: dict = {}
        if orient_dir is not None:
            for fi in frame_indices:
                path = os.path.join(orient_dir, f"frame_{fi:05d}.npz")
                if os.path.exists(path):
                    try:
                        d = np.load(path, allow_pickle=False)
                        if "U_layers" in d:
                            orient_data[fi] = d["U_layers"]   # (n_layers, 3, 3)
                    except Exception as exc:
                        print(f"  ✗  frame {fi}: orient load: {exc}", flush=True)
            print(
                f"  orient warm-start: {len(orient_data)}/{len(frame_indices)} "
                f"frames from {orient_dir!r}",
                flush=True,
            )

        common = dict(
            out_dir        = out_dir,
            fit_strain     = _fit_strain,
            max_match_px   = max_match_px,
            min_matched    = min_matched,
            min_match_rate = min_match_rate,
            max_rms_px     = max_rms_px,
            fit_kwargs     = {**fit_kwargs, "geometry_only": geometry_only,
                               "correct_depth": correct_depth, "engine": engine},
            overwrite      = overwrite,
            orient_data    = orient_data or None,
        )
        stack_pkl = self._serialize_stack()
        try:
            n_ok = self._run_pool(
                _lm_strain_frame, frame_indices, peaklists, common,
                stack_pkl, camera, allowed_hkl,
                n_workers or os.cpu_count() or 1,
            )
        finally:
            os.unlink(stack_pkl)

        print(f"  → {n_ok}/{len(frame_indices)} frames fitted", flush=True)
        return n_ok

    def run_image_orientation_local(
        self,
        camera,
        h5_path: str,
        h5_dataset: str,
        out_dir: str,
        *,
        geometry_only: bool = True,
        correct_depth: bool = False,
        f2_thresh: float = 1e-4,
        n_workers: "int | None" = None,
        overwrite: bool = False,
        frame_indices: "list[int] | None" = None,
        **fit_kwargs,
    ) -> int:
        """
        Image-based orientation refinement for every frame using local cores.

        Calls :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack`.
        The stack's layer U matrices must already be set to a good starting
        orientation (e.g. via a prior :meth:`run_orientation_local` + stack
        update).

        Args:
            h5_path: Path to the HDF5 scan file.
            h5_dataset: Dataset path inside *h5_path*, e.g.
                ``"1.1/measurement/eiger4m"``.
            out_dir: Output directory for result ``.npz`` files.
        """
        os.makedirs(out_dir, exist_ok=True)

        if frame_indices is None:
            frame_indices = list(range(self.ny * self.nx))

        allowed_hkl = None
        if geometry_only:
            _E_max = fit_kwargs.get("E_max", 27_000)
            allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

        frames = self._load_frames(h5_path, h5_dataset, frame_indices)
        print(
            f"run_image_orientation_local: {len(frame_indices)} frames loaded",
            flush=True,
        )

        common = dict(out_dir=out_dir,
                      fit_kwargs={**fit_kwargs, "correct_depth": correct_depth},
                      overwrite=overwrite)
        stack_pkl = self._serialize_stack()
        try:
            n_ok = self._run_pool(
                _lm_img_orient_frame, frame_indices, frames, common,
                stack_pkl, camera, allowed_hkl,
                n_workers or os.cpu_count() or 1,
            )
        finally:
            os.unlink(stack_pkl)

        return n_ok

    def run_strain_image_local(
        self,
        camera,
        h5_path: str,
        h5_dataset: str,
        out_dir: str,
        *,
        fit_strain: "tuple | None" = None,
        geometry_only: bool = True,
        correct_depth: bool = False,
        f2_thresh: float = 1e-4,
        n_workers: "int | None" = None,
        overwrite: bool = False,
        frame_indices: "list[int] | None" = None,
        **fit_kwargs,
    ) -> int:
        """
        Image-based orientation + per-layer strain refinement using local cores.

        Calls :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`.
        Pass ``strain0_list`` via *fit_kwargs* to warm-start from a prior
        strain fit.

        Args:
            fit_strain: Strain components to refine.  ``None`` refines all six.
        """
        from .fitting import _STRAIN_ALL
        _fit_strain = tuple(fit_strain) if fit_strain is not None else _STRAIN_ALL
        os.makedirs(out_dir, exist_ok=True)

        if frame_indices is None:
            frame_indices = list(range(self.ny * self.nx))

        allowed_hkl = None
        if geometry_only:
            _E_max = fit_kwargs.get("E_max", 27_000)
            allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

        frames = self._load_frames(h5_path, h5_dataset, frame_indices)
        print(
            f"run_strain_image_local: {len(frame_indices)} frames | "
            f"fit_strain={list(_fit_strain)}",
            flush=True,
        )

        common = dict(
            out_dir=out_dir, fit_strain=_fit_strain,
            fit_kwargs={**fit_kwargs, "correct_depth": correct_depth},
            overwrite=overwrite,
        )
        stack_pkl = self._serialize_stack()
        try:
            n_ok = self._run_pool(
                _lm_img_strain_frame, frame_indices, frames, common,
                stack_pkl, camera, allowed_hkl,
                n_workers or os.cpu_count() or 1,
            )
        finally:
            os.unlink(stack_pkl)

        return n_ok

    # ── Plotting ───────────────────────────────────────────────────────────────

    def _motor_extent(
        self, motor_x: "str | None", motor_y: "str | None"
    ) -> tuple:
        """Return (extent, xlabel, ylabel) for imshow, or (None, 'col', 'row')."""
        mx = self.motors.get(motor_x) if motor_x else None
        my = self.motors.get(motor_y) if motor_y else None
        if mx is not None and my is not None:
            return ([mx.min(), mx.max(), my.max(), my.min()],
                    motor_x, motor_y)
        return None, "column", "row"

    # ── Segmentation helpers ───────────────────────────────────────────────────

    def load_n_obs_map(self, seg_dir: str) -> np.ndarray:
        """Return a ``(ny, nx)`` map of segmented spot counts (-1 = no file)."""
        import re as _re
        n_obs = np.full((self.ny, self.nx), -1, dtype=int)
        pat = _re.compile(r'^frame_(\d+)\.h5$', _re.IGNORECASE)
        for fname in os.listdir(seg_dir):
            m = pat.match(fname)
            if not m:
                continue
            frame_idx = int(m.group(1))
            iy, ix = self.map_index(frame_idx)
            if iy >= self.ny or ix >= self.nx:
                continue
            fpath = os.path.join(seg_dir, fname)
            try:
                with h5py.File(fpath, "r") as fh:
                    if "n_spots" in fh.attrs:
                        n_obs[iy, ix] = int(fh.attrs["n_spots"])
                    else:
                        n_obs[iy, ix] = sum(
                            1 for k in fh if k.startswith("spot_")
                        )
            except Exception:
                pass
        return n_obs

    def segment_frame(
        self,
        base_dir: str,
        detector_mask: "np.ndarray | None" = None,
        *,
        h5_dataset: "str | None" = None,
        tiff_dir: "str | None" = None,
        map_quantity: str = "n_obs",
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        motor_units: "dict | None" = None,
        figsize: tuple = (14, 7),
    ) -> None:
        """
        Interactive single-frame segmentation tuner.

        Click a pixel on the left map panel to load the frame, adjust
        segmentation parameters, press **⚙ Segment** to preview, then
        **💾 Save** to write ``<base_dir>/seg/frame_NNNNN.h5``.

        Args:
            base_dir: Processing root; seg files go to ``<base_dir>/seg/``.
            detector_mask: Valid-pixel mask (``True`` = active).
            h5_dataset: Dataset path inside ``self.h5_path``.
                Mutually exclusive with *tiff_dir*.
            tiff_dir: Folder of ``img_*.tif`` files.
                Mutually exclusive with *h5_dataset*.
            map_quantity: Left-panel overview — ``'n_obs'`` (default),
                ``'match_rate'``, ``'rms_px'``, ``'score'``, ``'cost'``.
            motor_x, motor_y: Motor names in ``self.motors`` for physical axes.
            motor_units: Unit labels, e.g. ``{'sy': 'mm', 'sz': 'mm'}``.
            figsize: Figure size in inches.
        """
        import ipywidgets as ipw
        from IPython.display import display as _ipy_display
        from .segmentation import (
            LoG_segmentation, WTH_segmentation, hybrid_segmentation,
            clean_segmentation, label_segmented_image, measure_peaks,
            filter_and_rescale_images, gaussian_background, write_h5_spotsfile,
        )

        seg_dir = os.path.join(base_dir, "seg")
        os.makedirs(seg_dir, exist_ok=True)

        mu = motor_units or {}
        mx = self.motors.get(motor_x) if motor_x else None
        my = self.motors.get(motor_y) if motor_y else None

        if mx is not None and my is not None:
            extent_map = [mx[0, 0], mx[0, -1], my[-1, 0], my[0, 0]]
            xu_ = mu.get(motor_x, "")
            yu_ = mu.get(motor_y, "")
            xlabel_map = f"{motor_x} ({xu_})" if xu_ else motor_x
            ylabel_map = f"{motor_y} ({yu_})" if yu_ else motor_y
        else:
            extent_map = [0, self.nx, self.ny, 0]
            xlabel_map = "column (ix)"
            ylabel_map = "row (iy)"

        def _click_to_iy_ix(xdata: float, ydata: float):
            if mx is not None and my is not None:
                dist = (mx - xdata) ** 2 + (my - ydata) ** 2
                iy, ix = np.unravel_index(int(np.argmin(dist)), dist.shape)
            else:
                ix = int(np.clip(int(xdata), 0, self.nx - 1))
                iy = int(np.clip(int(ydata), 0, self.ny - 1))
            return int(iy), int(ix)

        _tiff_index: list = []

        def _load_image(frame_idx: int) -> "np.ndarray | None":
            if tiff_dir is not None:
                if not _tiff_index:
                    import re as _re
                    pat = _re.compile(r'(\d+)\.tiff?$', _re.IGNORECASE)
                    files = []
                    for fname in os.listdir(tiff_dir):
                        m = pat.search(fname)
                        if m:
                            files.append((int(m.group(1)), os.path.join(tiff_dir, fname)))
                    files.sort(key=lambda t: t[0])
                    _tiff_index.extend(p for _, p in files)
                    if not _tiff_index:
                        print(f"  ✗ No .tif/.tiff files found in {tiff_dir!r}", flush=True)
                        return None
                if frame_idx >= len(_tiff_index):
                    print(f"  ✗ frame {frame_idx} out of range", flush=True)
                    return None
                try:
                    import skimage.io
                    return skimage.io.imread(_tiff_index[frame_idx]).astype(np.float32)
                except Exception as exc:
                    print(f"  ✗ TIFF read error frame {frame_idx}: {exc}", flush=True)
                    return None
            elif h5_dataset is not None:
                _h5 = self.h5_path
                if _h5 is None:
                    print("  ✗ h5_path not set on this LayeredMap.", flush=True)
                    return None
                try:
                    with h5py.File(_h5, "r") as fh:
                        if h5_dataset not in fh:
                            print(f"  ✗ dataset {h5_dataset!r} not in {_h5!r}", flush=True)
                            return None
                        img = fh[h5_dataset][frame_idx].astype(np.float32)
                        if self.monitor and self.monitor in fh:
                            mon_val = float(fh[self.monitor][frame_idx])
                            if mon_val > 0:
                                img /= mon_val
                        return img
                except Exception as exc:
                    print(f"  ✗ HDF5 read error frame {frame_idx}: {exc}", flush=True)
                    return None
            return None

        def _build_n_obs_data() -> np.ndarray:
            raw = self.load_n_obs_map(seg_dir)
            return np.where(raw >= 0, raw.astype(float), np.nan)

        _map_opts = {
            "n_obs":       (_build_n_obs_data,                 "N spots (seg)",  "YlOrRd"),
            "match_rate":  (lambda: self.match_rate,           "Match rate",     "viridis"),
            "rms_px":      (lambda: self.rms_px,               "RMS (px)",       "plasma_r"),
            "mean_px":     (lambda: self.mean_px,              "Mean dev (px)",  "plasma_r"),
            "score":       (lambda: self.score,                "Image score",    "viridis"),
            "cost":        (lambda: self.cost,                 "Cost",           "plasma_r"),
        }
        _data_fn, map_label, map_cmap = _map_opts.get(
            map_quantity, _map_opts["n_obs"]
        )
        map_data = _data_fn()

        # ── figure ────────────────────────────────────────────────────────────
        with plt.ioff():
            fig = plt.figure(figsize=figsize)
        try:
            fig.canvas.manager.set_window_title("Laue — segment frame")
        except Exception:
            pass

        gs = fig.add_gridspec(
            1, 2, width_ratios=[1, 1.8], wspace=0.08,
            left=0.07, right=0.97, bottom=0.09, top=0.91,
        )
        ax_map = fig.add_subplot(gs[0])
        ax_det = fig.add_subplot(gs[1])

        im_map = ax_map.imshow(
            map_data, origin="upper", extent=extent_map,
            cmap=map_cmap, interpolation="nearest", aspect="auto",
        )
        cbar_map = fig.colorbar(im_map, ax=ax_map, fraction=0.04, pad=0.03,
                                 shrink=0.8, label=map_label)
        ax_map.set_xlabel(xlabel_map, fontsize=9)
        ax_map.set_ylabel(ylabel_map, fontsize=9)

        def _map_title(label: str) -> str:
            return f"Click to select — {label}"

        ax_map.set_title(_map_title(map_label), fontsize=9)
        sel_dot, = ax_map.plot([], [], "w+", ms=11, mew=2.0, zorder=10)

        ax_det.set_facecolor("k")
        ax_det.set_aspect("equal")
        ax_det.set_xlabel("x (px)", fontsize=9)
        ax_det.set_ylabel("y (px)", fontsize=9)
        ax_det.set_title("← click map to select a frame", fontsize=9, color="#888")
        fig.suptitle(
            "Segment frame  —  click map → adjust params → Segment → Save",
            fontsize=9, color="#555",
        )

        _state: dict = {
            "frame_idx": None, "iy": None, "ix": None,
            "image": None, "proc_image": None, "props": None, "drawn": False,
            "saved_xy": None,   # (N,2) xy from existing seg file, or None
        }

        def _parse(s: str):
            parts = [x.strip() for x in s.split(",") if x.strip()]
            if not parts:
                raise ValueError(f"Empty field: {s!r}")
            nums = [float(p) if "." in p else int(p) for p in parts]
            return nums[0] if len(nums) == 1 else nums

        def _draw_det(props=None) -> None:
            disp = _state["proc_image"] if _state["proc_image"] is not None else _state["image"]
            saved_xlim = ax_det.get_xlim()
            saved_ylim = ax_det.get_ylim()
            ax_det.cla()
            ax_det.set_facecolor("k")
            if disp is None:
                ax_det.set_title("← click map to select a frame", fontsize=9, color="#888")
                fig.canvas.draw_idle()
                return
            nv, nh = disp.shape
            clip_min, clip_max = w_vrange.value
            clip_min, clip_max = float(clip_min), float(clip_max)
            if clip_max <= clip_min:
                clip_max = clip_min + 1.0
            disp_clipped = np.clip(disp, clip_min, clip_max)
            disp_norm    = (disp_clipped - clip_min) / (clip_max - clip_min)
            disp_show = np.log1p(disp_norm * 1000) if w_log_scale.value else disp_norm
            ax_det.imshow(disp_show, origin="upper", extent=[0, nh, nv, 0],
                          cmap=w_cmap.value, aspect="equal", zorder=0)
            _has_legend = False
            saved_xy = _state.get("saved_xy")
            if saved_xy is not None and len(saved_xy) > 0:
                ax_det.scatter(saved_xy[:, 0], saved_xy[:, 1], s=35,
                               c="none", edgecolors="#ffcc00",
                               linewidths=0.9, zorder=3,
                               label=f"saved ({len(saved_xy)})")
                _has_legend = True
            if props is not None and len(props) > 0:
                ys = np.array([p.centroid_weighted[0] for p in props])
                xs = np.array([p.centroid_weighted[1] for p in props])
                ax_det.scatter(xs, ys, s=35, c="none", edgecolors="#44aaff",
                               linewidths=0.9, zorder=4, label=f"new ({len(props)})")
                _has_legend = True
            if _has_legend:
                ax_det.legend(fontsize=7, loc="upper right",
                              facecolor="#111", edgecolor="#444", labelcolor="white",
                              framealpha=0.85)
            ax_det.set_aspect("equal")
            ax_det.set_xlabel("x (px)", fontsize=9)
            ax_det.set_ylabel("y (px)", fontsize=9)
            iy, ix = _state["iy"], _state["ix"]
            n_new   = len(props) if props is not None else None
            n_saved = len(saved_xy) if saved_xy is not None else None
            if n_new is not None and n_saved is not None:
                suffix = f"  — {n_new} new  |  {n_saved} saved"
            elif n_new is not None:
                suffix = f"  — {n_new} spots"
            elif n_saved is not None:
                suffix = f"  — {n_saved} saved spots"
            else:
                suffix = ""
            ax_det.set_title(f"Frame {_state['frame_idx']}  (iy={iy}, ix={ix}){suffix}", fontsize=9)
            if _state["drawn"]:
                ax_det.set_xlim(saved_xlim)
                ax_det.set_ylim(saved_ylim)
            _state["drawn"] = True
            fig.canvas.draw_idle()

        def _on_click(event) -> None:
            if event.inaxes is not ax_map:
                return
            if event.xdata is None or event.ydata is None:
                return
            try:
                if fig.canvas.toolbar.mode != "":
                    return
            except Exception:
                pass
            iy, ix    = _click_to_iy_ix(event.xdata, event.ydata)
            frame_idx = self.frame_index(iy, ix)
            if mx is not None and my is not None:
                sel_dot.set_data([mx[iy, ix]], [my[iy, ix]])
            else:
                sel_dot.set_data([ix + 0.5], [iy + 0.5])
            image = _load_image(frame_idx)
            # Load existing segmentation if present
            saved_xy = None
            seg_path = os.path.join(seg_dir, f"frame_{frame_idx:05d}.h5")
            if os.path.exists(seg_path):
                try:
                    from .segmentation import convert_spotsfile2peaklist
                    pl = convert_spotsfile2peaklist(
                        seg_path, include_unfitted=True, r_squared_min=0.0
                    )
                    if len(pl) > 0:
                        saved_xy = pl[:, :2]   # (N, 2) x, y
                except Exception:
                    pass
            _state.update(frame_idx=frame_idx, iy=iy, ix=ix,
                          image=image, proc_image=None, props=None,
                          saved_xy=saved_xy)
            _update_vrange(image)
            btn_segment.disabled = image is None
            btn_save.disabled    = True
            n_saved = len(saved_xy) if saved_xy is not None else 0
            _info.value = (
                f"<span style='color:#aaa'>Frame {frame_idx} loaded"
                + (f" — {n_saved} existing spots" if n_saved else "")
                + (" — no image data" if image is None else "") + "</span>"
            )
            _draw_det(props=None)

        fig.canvas.mpl_connect("button_press_event", _on_click)

        # ── widgets ───────────────────────────────────────────────────────────
        _sk  = dict(continuous_update=False, style={"description_width": "110px"},
                    layout=ipw.Layout(width="320px"))
        _isk = dict(style={"description_width": "90px"}, layout=ipw.Layout(width="160px"))

        w_method = ipw.Dropdown(
            options=["LoG", "WTH", "Hybrid"], value="LoG",
            description="Method:", layout=ipw.Layout(width="220px"),
            style={"description_width": "70px"},
        )
        w_log_sigmas = ipw.Text(value="2, 4, 8", description="Sigmas:", **_sk,
                                placeholder="e.g. 2, 4, 8  or  4")
        w_wth_radius = ipw.Text(value="5, 7",    description="Disk radii:", **_sk,
                                placeholder="e.g. 5, 7  or  7")
        w_hyb_log    = ipw.Text(value="2, 4, 8", description="LoG sigmas:", **_sk,
                                placeholder="e.g. 2, 4, 8")
        w_hyb_wth    = ipw.Text(value="5, 7",    description="WTH radii:", **_sk,
                                placeholder="e.g. 5, 7")
        w_thresh     = ipw.FloatText(value=99.9, description="Threshold %:", **_sk)
        w_bg_sigma   = ipw.FloatText(value=5.0,  description="BG sigma:", **_sk)
        w_min_size   = ipw.IntText(value=3,   description="min_size:",    **_isk)
        w_max_size   = ipw.IntText(value=500, description="max_size:",    **_isk)
        w_gap_excl   = ipw.IntText(value=3,   description="gap_exclude:", **_isk)
        w_gap_clos   = ipw.IntText(value=3,   description="gap_closing:", **_isk)
        w_d          = ipw.IntText(value=10,  description="Crop d (px):", **_isk)
        w_r2         = ipw.FloatText(value=0.9, description="R² min:",    **_isk)
        w_fit_spots  = ipw.Checkbox(value=True, description="Fit spots (Gaussian)",
                                    layout=ipw.Layout(width="200px"),
                                    style={"description_width": "initial"})
        w_overwrite  = ipw.Checkbox(value=True, description="Overwrite existing",
                                    layout=ipw.Layout(width="200px"))

        box_log    = ipw.VBox([w_log_sigmas])
        box_wth    = ipw.VBox([w_wth_radius])
        box_hybrid = ipw.VBox([w_hyb_log, w_hyb_wth])
        box_wth.layout.display    = "none"
        box_hybrid.layout.display = "none"

        def _on_method(change) -> None:
            m = change["new"]
            box_log.layout.display    = "" if m == "LoG"    else "none"
            box_wth.layout.display    = "" if m == "WTH"    else "none"
            box_hybrid.layout.display = "" if m == "Hybrid" else "none"

        w_method.observe(_on_method, names="value")

        _bkw = dict(layout=ipw.Layout(width="130px", height="32px"))
        btn_segment = ipw.Button(description="⚙ Segment", button_style="primary", **_bkw)
        btn_save    = ipw.Button(description="💾 Save",   button_style="success", **_bkw)
        btn_segment.disabled = True
        btn_save.disabled    = True

        _info = ipw.HTML(
            "<span style='color:#666;font-style:italic'>click a map pixel to load a frame</span>",
            layout=ipw.Layout(margin="4px 0 0 6px"),
        )

        def _cb_segment(_) -> None:
            import asyncio
            import queue as _qmod
            import threading

            image = _state["image"]
            if image is None:
                return
            if getattr(_cb_segment, "_running", False):
                return
            _cb_segment._running    = True
            btn_segment.disabled    = True
            btn_segment.description = "Running…"

            method = w_method.value
            try:
                if method == "LoG":
                    method_kwargs = {"sigmas": _parse(w_log_sigmas.value),
                                     "threshold_percentile": w_thresh.value}
                elif method == "WTH":
                    method_kwargs = {"disk_radius": _parse(w_wth_radius.value),
                                     "threshold_percentile": w_thresh.value}
                else:
                    method_kwargs = {"log_sigmas": _parse(w_hyb_log.value),
                                     "wth_disk_radius": _parse(w_hyb_wth.value),
                                     "threshold_percentile": w_thresh.value}
            except ValueError as exc:
                _info.value = f"<b style='color:#f44'>Parameter error: {exc}</b>"
                btn_segment.description = "⚙ Segment"
                btn_segment.disabled    = False
                _cb_segment._running    = False
                return

            clean_kw = dict(min_size=w_min_size.value, max_size=w_max_size.value,
                            gap_exclude=w_gap_excl.value, gap_closing=w_gap_clos.value)
            bg_sigma = w_bg_sigma.value
            _det_mask = (detector_mask.astype(bool) if detector_mask is not None
                         else np.ones(image.shape, dtype=bool))

            q: _qmod.Queue = _qmod.Queue()

            def _run() -> None:
                try:
                    valid = _det_mask
                    frame = image.copy().astype(np.float32)
                    if bg_sigma > 0:
                        bg    = gaussian_background(frame, valid, sigma=bg_sigma)
                        frame = frame - bg
                    frame -= frame[valid].min()
                    frame[~valid] = 0.0
                    if method == "WTH":
                        seg = WTH_segmentation(frame, valid, **method_kwargs)
                    elif method == "Hybrid":
                        seg = hybrid_segmentation(frame, valid, **method_kwargs)
                    else:
                        seg = LoG_segmentation(frame, valid, **method_kwargs)
                    final_mask, _ = clean_segmentation(seg, valid, frame, **clean_kw)
                    filt = filter_and_rescale_images(frame, cutoff_freq=0.001)
                    labels, _, _ = label_segmented_image(final_mask, filt)
                    props = measure_peaks(labels, filt)
                    q.put(("ok", props, filt))
                except Exception as exc:
                    q.put(("err", exc))

            async def _wait() -> None:
                threading.Thread(target=_run, daemon=True).start()
                while q.empty():
                    await asyncio.sleep(0.15)
                tag, *payload = q.get_nowait()
                if tag == "err":
                    _info.value = f"<b style='color:#f44'>Error: {payload[0]}</b>"
                else:
                    props, filt = payload
                    _state["props"] = props
                    _state["proc_image"] = filt
                    n = len(props)
                    col = "#44dd66" if n > 0 else "#ffaa33"
                    _info.value = f"<b style='color:{col}'>{n} spots detected</b>"
                    btn_save.disabled = n == 0
                    _draw_det(props=props)
                    if n > 0:
                        _cb_save(None)
                btn_segment.description = "⚙ Segment"
                btn_segment.disabled    = False
                _cb_segment._running    = False

            try:
                asyncio.get_event_loop().create_task(_wait())
            except RuntimeError:
                asyncio.ensure_future(_wait())

        def _cb_save(_) -> None:
            props = _state["props"]
            if not props:
                return
            frame_idx = _state["frame_idx"]
            out_path  = os.path.join(seg_dir, f"frame_{frame_idx:05d}.h5")
            try:
                write_h5_spotsfile(
                    _state["image"], props, outpath=out_path,
                    d=w_d.value, r_squared_min=w_r2.value,
                    overwrite=w_overwrite.value, fit_spots=w_fit_spots.value,
                )
                _info.value = f"<b style='color:#44dd66'>Saved → {out_path}</b>"
                print(f"  💾 Saved → {os.path.abspath(out_path)}")
                _state["saved_xy"] = None   # new result replaces old overlay
                if w_map_quantity.value == "n_obs":
                    new_data = _build_n_obs_data()
                    im_map.set_data(new_data)
                    valid = new_data[np.isfinite(new_data)]
                    if valid.size:
                        im_map.set_clim(valid.min(), valid.max())
                    fig.canvas.draw_idle()
            except Exception as exc:
                _info.value = f"<b style='color:#f44'>Save error: {exc}</b>"

        w_map_quantity = ipw.Dropdown(
            options=[(label, key) for key, (_, label, _) in _map_opts.items()],
            value=map_quantity if map_quantity in _map_opts else "n_obs",
            layout=ipw.Layout(width="150px", height="32px"),
        )

        def _cb_map_quantity(change) -> None:
            data_fn, label, cmap = _map_opts[change["new"]]
            im_map.set_data(data_fn())
            im_map.set_cmap(cmap)
            im_map.autoscale()
            cbar_map.set_label(label)
            ax_map.set_title(_map_title(label), fontsize=9)
            fig.canvas.draw_idle()

        w_map_quantity.observe(_cb_map_quantity, names="value")

        w_log_scale = ipw.Checkbox(value=True, description="Log scale",
                                   layout=ipw.Layout(width="110px"),
                                   style={"description_width": "initial"})
        w_vrange = ipw.FloatRangeSlider(
            value=[0.0, 1.0], min=0.0, max=1.0, step=0.01,
            description="Range:", continuous_update=False,
            readout_format=".3g",
            layout=ipw.Layout(width="320px"),
            style={"description_width": "50px"},
        )
        w_cmap = ipw.Dropdown(
            options=sorted(plt.colormaps()), value="gray",
            description="Colormap:",
            layout=ipw.Layout(width="200px"),
            style={"description_width": "70px"},
        )

        def _update_vrange(img: "np.ndarray | None") -> None:
            if img is None:
                return
            pos = img[img > 0]
            lo_default = float(np.percentile(pos, 1)) if pos.size else 0.0
            hi_default = float(np.percentile(pos, 99.9)) if pos.size else 1.0
            if hi_default <= lo_default:
                hi_default = lo_default + 1.0
            # Cap the track at a high percentile rather than the raw pixel max —
            # a single saturated/hot pixel would otherwise stretch the slider so
            # far that the vmin/vmax handles bunch up in a sliver near the low end.
            slider_max = hi_default * 1.2
            w_vrange.max = max(slider_max, w_vrange.max)  # avoid a transient value > max
            w_vrange.value = [lo_default, hi_default]
            w_vrange.max = slider_max
            w_vrange.step = max(slider_max / 200.0, 1e-6)

        def _redraw(_=None) -> None:
            if _state["image"] is not None:
                _draw_det(props=_state["props"])

        def _on_fit_toggle(change) -> None:
            w_r2.disabled = not change["new"]

        w_log_scale.observe(_redraw, names="value")
        w_vrange.observe(_redraw, names="value")
        w_cmap.observe(_redraw, names="value")
        w_fit_spots.observe(_on_fit_toggle, names="value")
        btn_segment.on_click(_cb_segment)
        btn_save.on_click(_cb_save)

        _controls = ipw.VBox([
            ipw.HBox([w_method], layout=ipw.Layout(margin="4px 0 2px 0")),
            ipw.HBox([
                ipw.VBox([box_log, box_wth, box_hybrid, w_thresh, w_bg_sigma],
                         layout=ipw.Layout(padding="0 16px 0 0")),
                ipw.VBox([
                    ipw.HTML("<b>Clean:</b>"),
                    ipw.HBox([w_min_size, w_max_size]),
                    ipw.HBox([w_gap_excl, w_gap_clos]),
                    ipw.HTML("<b>Save:</b>"),
                    ipw.HBox([w_d, w_r2]),
                    w_fit_spots, w_overwrite,
                ]),
            ]),
            ipw.HBox([btn_segment, btn_save,
                      ipw.HTML("<span style='color:#aaa;align-self:center'>map:</span>",
                               layout=ipw.Layout(margin="0 2px 0 10px")),
                      w_map_quantity],
                     layout=ipw.Layout(gap="8px", margin="6px 0 0 0", align_items="center")),
            ipw.HBox(
                [ipw.HTML("<b style='line-height:26px;margin-right:6px'>Display:</b>"),
                 w_log_scale, w_vrange, w_cmap],
                layout=ipw.Layout(gap="6px", margin="4px 0 0 0", align_items="center"),
            ),
            _info,
        ], layout=ipw.Layout(padding="6px 8px"))

        _ipy_display(ipw.VBox([fig.canvas, _controls]))

    def plot_map(
        self,
        quantity: str,
        *,
        layer: "int | None" = None,
        strain_component: "str | None" = None,
        frame: str = "crystal",
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        cmap: str = "viridis",
        vmin=None,
        vmax=None,
        title: "str | None" = None,
        ax=None,
    ):
        """
        Plot a scalar quantity map.

        Args:
            quantity: One of ``'rms_px'``, ``'mean_px'``, ``'match_rate'``,
                ``'n_matched'``, ``'cost'``, ``'score'``, ``'score0'``,
                ``'n_sim'``, ``'rotation_deg'`` (magnitude of global rotation),
                or ``'strain'`` (requires *layer* and *strain_component*).
            layer: Layer index (required for ``'strain'``).
            strain_component: One of ``'e_xx'``, ``'e_yy'``, ``'e_zz'``,
                ``'e_xy'``, ``'e_xz'``, ``'e_yz'``.
            frame: ``'crystal'`` (default), ``'deviatoric'`` (strain only).
        """
        if quantity == "strain":
            if layer is None or strain_component is None:
                raise ValueError(
                    "plot_map('strain') requires layer= and strain_component="
                )
            ti, tj = _VOIGT_TENSOR[strain_component]
            if frame == "deviatoric":
                data = self.strain_tensor_deviatoric[layer, :, :, ti, tj]
            else:
                data = self.strain_tensor[layer, :, :, ti, tj]
            label = f"ε {strain_component}"
            if layer is not None:
                label += f" [{self.layer_labels[layer]}]"

        elif quantity == "rotation_deg":
            norms = np.linalg.norm(self.rotvec, axis=-1)
            data  = np.where(np.isnan(self.rotvec[:, :, 0]), np.nan,
                             np.degrees(norms))
            label = "|δω| (°)"

        else:
            arr = getattr(self, quantity, None)
            if arr is None:
                raise ValueError(f"Unknown quantity {quantity!r}")
            data  = np.where(arr == -1, np.nan, arr).astype(float)
            label = quantity.replace("_", " ")

        extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
        if ax is None:
            _, ax = plt.subplots(figsize=(7, 6))

        kw = dict(origin="upper", cmap=cmap, vmin=vmin, vmax=vmax)
        if extent is not None:
            kw.update(extent=extent, aspect="auto")

        im = ax.imshow(data, **kw)
        plt.colorbar(im, ax=ax, label=label)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_title(title or label)
        return ax

    def plot_strain_component(
        self,
        component: str,
        layer: int,
        *,
        frame: str = "crystal",
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        cmap: str = "RdBu_r",
        vmin=None,
        vmax=None,
        ax=None,
    ):
        """
        Plot one strain component for *layer*.

        Shortcut for ``plot_map('strain', layer=layer, strain_component=component)``.
        """
        return self.plot_map(
            "strain",
            layer=layer,
            strain_component=component,
            frame=frame,
            motor_x=motor_x,
            motor_y=motor_y,
            cmap=cmap,
            vmin=vmin,
            vmax=vmax,
            ax=ax,
            title=f"ε {component} — {self.layer_labels[layer]}",
        )

    def plot_overview(
        self,
        layer: int = 0,
        *,
        strain_components: tuple = ("e_xx", "e_yy", "e_zz"),
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        cmap_scalar: str = "viridis",
        cmap_strain: str = "RdBu_r",
        figsize: "tuple | None" = None,
    ):
        """
        Multi-panel overview: match quality + strain components for *layer*.

        Panels: ``match_rate``, ``rms_px``, ``rotation_deg``, then one panel
        per entry in *strain_components*.
        """
        n_panels = 3 + len(strain_components)
        if figsize is None:
            figsize = (5 * n_panels, 4)
        fig, axes = plt.subplots(1, n_panels, figsize=figsize)

        scalar_kw = dict(motor_x=motor_x, motor_y=motor_y, cmap=cmap_scalar)
        self.plot_map("match_rate",   ax=axes[0], **scalar_kw)
        self.plot_map("rms_px",       ax=axes[1], **scalar_kw)
        self.plot_map("rotation_deg", ax=axes[2], **scalar_kw)

        for ii, comp in enumerate(strain_components):
            self.plot_strain_component(
                comp, layer,
                motor_x=motor_x, motor_y=motor_y,
                cmap=cmap_strain, ax=axes[3 + ii],
            )

        fig.suptitle(
            f"LayeredMap — layer {self.layer_labels[layer]}", fontsize=13
        )
        fig.tight_layout()
        return fig, axes

    def plot_ipf_map(
        self,
        layer: int,
        *,
        direction=None,
        symmetry: str = "cubic",
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        ax=None,
    ):
        """
        Inverse pole figure colour map for *layer*.

        Args:
            layer: Layer index.
            direction: Reference direction in the sample frame as a length-3
                sequence (default: ``[0, 0, 1]``, the beam/z axis).
            symmetry: Crystal point-group symmetry for reducing orientations to
                the fundamental zone.  One of ``'cubic'``, ``'hexagonal'``,
                ``'tetragonal'``, ``'orthorhombic'``.  Used by orix when
                available; the fallback coloring always uses cubic reduction.
        """
        _dir = np.asarray(direction if direction is not None else [0, 0, 1],
                          dtype=float)
        _dir = _dir / np.linalg.norm(_dir)

        U_map = self.U[layer]                     # (ny, nx, 3, 3)
        valid = ~np.any(np.isnan(U_map), axis=(-2, -1))

        idx = np.argwhere(valid)
        if len(idx) == 0:
            print("No valid orientations to plot.")
            return ax

        U_valid = U_map[idx[:, 0], idx[:, 1]]    # (M, 3, 3)

        # ── Try modern orix API (>= 0.11) ────────────────────────────────────
        rgb = None
        try:
            from orix.quaternion import Rotation as ORotation
            from orix.vector import Vector3d as OVector3d
            from orix.plot import IPFColorKeyTSL
            from orix.crystal_map import Phase

            _sym_map = {
                "cubic":        "m-3m",
                "hexagonal":    "6/mmm",
                "tetragonal":   "4/mmm",
                "orthorhombic": "mmm",
            }
            pg_str = _sym_map.get(symmetry, "m-3m")
            phase  = Phase(point_group=pg_str)

            # scipy [x,y,z,w] → orix [w,x,y,z]
            q_arr  = Rotation.from_matrix(U_valid).as_quat()          # (M,4)
            orot   = ORotation(q_arr[:, [3, 0, 1, 2]])
            ipf_key = IPFColorKeyTSL(phase.point_group,
                                     direction=OVector3d(_dir))
            rgb = np.clip(ipf_key.orientation2color(orot), 0, 1)     # (M,3)
        except Exception:
            pass

        # ── Fallback: pure-scipy coloring (no orix needed) ───────────────────
        if rgb is None:
            rgb = _ipf_color_fallback(U_valid, _dir)

        img = np.ones((self.ny, self.nx, 3))
        img[idx[:, 0], idx[:, 1]] = rgb

        extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
        if ax is None:
            _, ax = plt.subplots(figsize=(6, 5))

        imkw = dict(origin="upper")
        if extent is not None:
            imkw.update(extent=extent, aspect="auto")
        ax.imshow(img, **imkw)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_title(f"IPF map — {self.layer_labels[layer]}  [{symmetry}]")
        return ax

    def inspect_frame(
        self,
        camera,
        frame_idx: int,
        *,
        h5_path: "str | None" = None,
        h5_dataset: str = "1.1/measurement/eiger4m",
        tiff_dir: "str | None" = None,
        seg_dir: "str | None" = None,
        r_squared_min: float = 0.0,
        include_unfitted: bool = True,
        E_min_eV: float = 5_000,
        E_max_eV: float = 27_000,
        f2_thresh: float = 1e-4,
        top_n_sim: "int | None" = None,
        max_match_dist: float = 5.0,
        use_eff: bool = True,
        figsize: tuple = (14, 6),
    ):
        """
        Display the diffraction image for *frame_idx* overlaid with simulated
        spots from all stack layers and (optionally) the measured segmented spots.

        The fitted orientations stored in ``U_eff`` (or ``U`` when strain is
        unavailable) are temporarily applied to the stack before simulating.

        Args:
            camera: Detector geometry.
            frame_idx: Flat frame index.
            h5_path: Path to the HDF5 scan file (mutually exclusive with
                *tiff_dir*).
            h5_dataset: Dataset path inside *h5_path*.
            tiff_dir: Directory of TIFF frames (mutually exclusive with
                *h5_path*).
            seg_dir: Directory containing ``frame_?????.h5`` segmentation files.
                When provided, the measured peaklist is loaded and overlaid.
            r_squared_min: Minimum Gaussian fit R² to accept a spot from the
                seg file (default ``0.0`` — accept all).
            include_unfitted: Include spots whose Gaussian fit failed
                (default ``True``).
            use_eff: If ``True`` (default), use ``U_eff`` (strained) when
                available; otherwise use ``U``.
        """
        from .simulation import simulate_laue_stack, precompute_allowed_hkl
        from .laue_plotting import plot_measured_vs_simulated

        iy, ix = self.map_index(frame_idx)

        # Load detector image
        image = None
        if h5_path is not None:
            with h5py.File(h5_path, "r") as hf:
                image = hf[h5_dataset][frame_idx].astype(np.float32)
        elif tiff_dir is not None:
            import skimage.io
            path  = os.path.join(tiff_dir, f"frame_{frame_idx:05d}.tif")
            image = skimage.io.imread(path).astype(np.float32)

        # Load measured peaklist from seg file if available
        peaklist = np.empty((0, 9), dtype=np.float32)
        if seg_dir is not None:
            seg_path = os.path.join(seg_dir, f"frame_{frame_idx:05d}.h5")
            if os.path.exists(seg_path):
                try:
                    from .segmentation import convert_spotsfile2peaklist
                    peaklist = convert_spotsfile2peaklist(
                        seg_path,
                        r_squared_min=r_squared_min,
                        include_unfitted=include_unfitted,
                    )
                except Exception as exc:
                    print(f"  ✗ could not load seg file: {exc}", flush=True)
            else:
                print(f"  no seg file for frame {frame_idx}", flush=True)

        # Precompute allowed HKL per unique crystal using the unit-cell |F|²
        # threshold.  This is the same filter used by the fitting functions and
        # correctly removes weak reflections before the simulation.
        allowed_hkl: dict = {}
        for _layer in self.stack.all_layers:
            _cid = id(_layer.crystal)
            if _cid not in allowed_hkl:
                allowed_hkl[_cid] = precompute_allowed_hkl(
                    _layer.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
                )

        # Choose U or U_eff
        U_src = self.U_eff if (use_eff and not np.all(np.isnan(self.U_eff[:, iy, ix]))) \
                else self.U

        # Apply fitted orientations to the stack (restore after)
        saved_U = [l.U.copy() for l in self.stack.all_layers]
        try:
            for li, layer in enumerate(self.stack.all_layers):
                if not np.any(np.isnan(U_src[li, iy, ix])):
                    layer.U = U_src[li, iy, ix].copy()

            spots = simulate_laue_stack(
                self.stack, camera,
                E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                geometry_only=True,
                allowed_hkl=allowed_hkl,
                verbose=False,
            )
            if top_n_sim is not None:
                spots = spots[:top_n_sim]
        finally:
            for layer, U0 in zip(self.stack.all_layers, saved_U):
                layer.U = U0

        fig = plot_measured_vs_simulated(
            peaklist,
            spots,
            image=image,
            camera=camera,
            max_match_dist=max_match_dist,
            figsize=figsize,
        )
        axes = fig.axes
        fig.suptitle(
            f"Frame {frame_idx}  [{iy}, {ix}]  —  LayeredMap",
            fontsize=11,
        )
        return fig, axes

    def plot_hkl_mosaic(
        self,
        camera,
        hkl: tuple,
        *,
        layer: "int | str | None" = None,
        use_eff: bool = True,
        half_window_x: int = 20,
        half_window_y: int = 20,
        h5_dataset: "str | None" = None,
        tiff_dir: "str | None" = None,
        E_min_eV: float = 5_000.0,
        E_max_eV: float = 27_000.0,
        f2_thresh: float = 1e-4,
        gap_px: int = 2,
        cmap: str = "gray",
        log_scale: bool = True,
        figsize: "tuple | None" = None,
        out_path: "str | None" = None,
    ) -> tuple:
        """
        Mosaic of one (h, k, l) reflection across the raster scan.

        For every map pixel, the stack's fitted orientations (`U_eff`, or `U`
        where strain is unavailable) are temporarily applied to `self.stack`
        and the detector position of *hkl* is simulated. A window of the raw
        detector image centred on that position is extracted and the windows
        are tiled on the same `(iy, ix)` grid as the scan, so spot shape,
        intensity, and position can be compared across the map at a glance.

        Because several layers can diffract the same nominal `hkl` at
        slightly different positions (main peak vs. pseudomorphic /
        relaxed satellites), pass *layer* to disambiguate — otherwise the
        brightest matching spot at each pixel is used, which can silently
        jump between layers across the map.

        Args:
            camera (Camera): Detector geometry.
            hkl (tuple of int): Miller indices `(h, k, l)` of the reflection to extract.
            layer (int, str, or None): Which layer's version of *hkl* to track — an index
                into `self.stack.all_layers` / `self.layer_labels`, or a
                layer label directly. `None` (default) takes the brightest
                matching spot regardless of originating layer.
            use_eff (bool): Use `U_eff` (strained) when available, falling back to `U`.
                Default `True`.
            half_window_x, half_window_y (int): Half-width / half-height, in pixels, of the
                window extracted around the simulated spot position. Each
                extracted tile is `(2*half_window_y + 1, 2*half_window_x + 1)`.
            h5_dataset (str or None): HDF5 dataset path inside `self.h5_path` for the image
                stack. Mutually exclusive with *tiff_dir*; supply exactly one.
            tiff_dir (str or None): Path to a folder of `img_<number>.tif` files, sorted by
                embedded number and mapped to 0-based frame indices. Mutually
                exclusive with *h5_dataset*.
            E_min_eV, E_max_eV (float): Energy range used to simulate the reflection's
                position. Defaults `5000` / `27000` eV.
            f2_thresh (float): Structure-factor threshold forwarded to
                `precompute_allowed_hkl`. Default `1e-4`.
            gap_px (int): NaN-filled gap, in pixels, inserted between neighbouring tiles
                so the grid stays visible. Default `2`.
            cmap (str): Colormap for the mosaic. Default `"gray"`.
            log_scale (bool): Display `log1p` of the extracted intensity. Default `True`.
            figsize (tuple or None): Figure size. `None` (default) scales with the mosaic
                size.
            out_path (str or None): If given, save the figure to this path.

        Returns:
            fig (Figure):
            ax (Axes):
            mosaic ((ny*(th+gap)-gap, nx*(tw+gap)-gap) ndarray): The assembled tile grid
                (`th = 2*half_window_y+1`, `tw = 2*half_window_x+1`), `NaN`
                wherever a tile — or part of it — could not be extracted
                (unfitted pixel, reflection off-detector / not excited for
                the requested layer, or image unavailable).
"""
        import re
        from .simulation import simulate_laue_stack, precompute_allowed_hkl

        if (h5_dataset is None) == (tiff_dir is None):
            raise ValueError(
                "plot_hkl_mosaic: supply exactly one of h5_dataset or tiff_dir"
            )

        hkl = tuple(int(v) for v in hkl)
        half_window_x = int(half_window_x)
        half_window_y = int(half_window_y)
        tile_h = 2 * half_window_y + 1
        tile_w = 2 * half_window_x + 1

        layer_label: "str | None" = None
        if layer is not None:
            if isinstance(layer, str):
                layer_label = layer
            else:
                li = int(layer)
                if not (0 <= li < self.n_layers):
                    raise ValueError(
                        f"layer index {li} out of range (0 - {self.n_layers - 1})"
                    )
                layer_label = self.layer_labels[li]

        # Precompute allowed HKL per unique crystal (same as inspect_frame / reindex_frame).
        allowed_hkl: dict = {}
        for _layer in self.stack.all_layers:
            _cid = id(_layer.crystal)
            if _cid not in allowed_hkl:
                allowed_hkl[_cid] = precompute_allowed_hkl(
                    _layer.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
                )

        U_src = self.U_eff if (use_eff and not np.all(np.isnan(self.U_eff))) else self.U

        # ── image loader (same convention as reindex_frame) ────────────────────
        _tiff_index: "list | None" = None

        def _load_image(frame_idx: int) -> "np.ndarray | None":
            nonlocal _tiff_index
            if tiff_dir is not None:
                if _tiff_index is None:
                    pat   = re.compile(r'(\d+)\.tiff?$', re.IGNORECASE)
                    files = []
                    for fname in os.listdir(tiff_dir):
                        m = pat.search(fname)
                        if m:
                            files.append((int(m.group(1)), os.path.join(tiff_dir, fname)))
                    files.sort(key=lambda x: x[0])
                    _tiff_index = [p for _, p in files]
                if frame_idx >= len(_tiff_index):
                    return None
                try:
                    import skimage.io
                    return skimage.io.imread(_tiff_index[frame_idx]).astype(np.float32)
                except Exception:
                    return None
            else:
                if self.h5_path is None:
                    return None
                try:
                    with h5py.File(self.h5_path, "r") as f:
                        if h5_dataset not in f:
                            return None
                        ds = f[h5_dataset]
                        if frame_idx >= ds.shape[0]:
                            return None
                        return ds[frame_idx].astype(np.float32)
                except Exception:
                    return None

        # ── assemble mosaic ──────────────────────────────────────────────────
        mosaic = np.full(
            (self.ny * (tile_h + gap_px) - gap_px, self.nx * (tile_w + gap_px) - gap_px),
            np.nan,
        )
        n_found = 0
        saved_U = [l.U.copy() for l in self.stack.all_layers]
        try:
            for iy in range(self.ny):
                for ix in range(self.nx):
                    u_here = U_src[:, iy, ix]
                    if np.all(np.isnan(u_here)):
                        continue

                    for li, lyr in enumerate(self.stack.all_layers):
                        lyr.U = (
                            saved_U[li].copy() if np.any(np.isnan(u_here[li]))
                            else u_here[li].copy()
                        )

                    try:
                        spots = simulate_laue_stack(
                            self.stack, camera,
                            E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                            geometry_only=True,
                            allowed_hkl=allowed_hkl,
                            verbose=False,
                        )
                    except Exception:
                        continue

                    spot = next(
                        (s for s in spots
                         if tuple(s["hkl"]) == hkl and s.get("pix") is not None
                         and (layer_label is None or s.get("phase_label") == layer_label)),
                        None,
                    )
                    if spot is None:
                        continue

                    image = _load_image(self.frame_index(iy, ix))
                    if image is None:
                        continue

                    xc, yc = spot["pix"]
                    xc, yc = int(round(xc)), int(round(yc))
                    nv_im, nh_im = image.shape

                    y0, y1 = yc - half_window_y, yc + half_window_y + 1
                    x0, x1 = xc - half_window_x, xc + half_window_x + 1
                    sy0, sy1 = max(y0, 0), min(y1, nv_im)
                    sx0, sx1 = max(x0, 0), min(x1, nh_im)
                    if sy0 >= sy1 or sx0 >= sx1:
                        continue

                    tile = np.full((tile_h, tile_w), np.nan)
                    tile[sy0 - y0: sy1 - y0, sx0 - x0: sx1 - x0] = image[sy0:sy1, sx0:sx1]

                    ry0 = iy * (tile_h + gap_px)
                    rx0 = ix * (tile_w + gap_px)
                    mosaic[ry0:ry0 + tile_h, rx0:rx0 + tile_w] = tile
                    n_found += 1
        finally:
            for lyr, U0 in zip(self.stack.all_layers, saved_U):
                lyr.U = U0

        # ── figure ────────────────────────────────────────────────────────────
        if figsize is None:
            figsize = (
                float(np.clip(2 + self.nx * tile_w / 40, 4, 20)),
                float(np.clip(2 + self.ny * tile_h / 40, 4, 20)),
            )

        fig, ax = plt.subplots(figsize=figsize)
        disp = np.log1p(np.clip(mosaic, 0, None)) if log_scale else mosaic
        im = ax.imshow(disp, cmap=cmap, interpolation="nearest", origin="upper")
        ax.set_xticks([])
        ax.set_yticks([])
        layer_txt = f"  —  layer {layer_label!r}" if layer_label is not None else ""
        ax.set_title(
            f"hkl = {hkl}{layer_txt}  —  "
            f"{n_found}/{self.ny * self.nx} tiles found  "
            f"(±{half_window_x} × ±{half_window_y} px)",
            fontsize=10,
        )
        fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02,
                     label="log(1 + I)" if log_scale else "I")
        fig.tight_layout()

        if out_path is not None:
            fig.savefig(out_path, dpi=150)

        return fig, ax, mosaic

    def reindex_frame(
        self,
        camera,
        base_dir: str,
        *,
        h5_dataset: "str | None" = None,
        tiff_dir: "str | None" = None,
        seg_dir: "str | None" = None,
        map_quantity: str = "match_rate",
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        motor_units: "dict | None" = None,
        E_min_eV: float = 5_000.0,
        E_max_eV: float = 27_000.0,
        f2_thresh: float = 1e-4,
        max_match_px: float = 5.0,
        fit_max_match_px: "float | list[float]" = (30.0, 10.0, 3.0),
        fit_strain: "tuple | None" = None,
        r_squared_min: float = 0.0,
        include_unfitted: bool = True,
        kernel_sigma: float = 0.3,
        bg_sigma: float = 251.0,
        max_angle_deg: float = 0.2,
        max_shift_px: "float | list[float] | None" = None,
        correct_depth: bool = False,
        figsize: tuple = (14, 7),
    ) -> None:
        """
        Interactive single-frame fitter and inspector for a
        :class:`~nrxrdct.laue.layers.LayeredCrystal` stack.

        Click a pixel on the left map panel to load the frame, then use the
        buttons to refit and store the result:

        1. **⚡ Fit** — runs :func:`~nrxrdct.laue.fitting.fit_orientation_stack`
           starting from the current map orientation (or the template stack U
           matrices if no result exists for that pixel).  Per-layer simulated
           spots are drawn in distinct colors; green lines connect matched pairs.
        2. **🔩 Fit strain** — runs
           :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack` from the
           best available orientation.  Enabled after a successful spot-based
           orientation fit.
        3. **🖼 Img orient** — runs
           :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack` on the
           raw pixel image.  Enabled whenever a starting orientation is
           available (existing map result or fit result).
        4. **🖼 Img strain** — runs
           :func:`~nrxrdct.laue.fitting.refine_strain_image_stack` jointly
           refining orientation and strain against the raw image.  The
           ``max_shift_px`` constraint (if set) is forwarded to the optimizer.
        5. **⬆ Store** — writes the best available result back into the map at
           the selected pixel via :meth:`set_result`.  If ``self.save_path`` is
           set the map is also persisted to disk.
        6. **💾 Save UBs** — saves the per-layer U matrices to auto-numbered
           ``.npy`` files in the current directory.

        Args:
            camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
            base_dir: Processing root directory.  The seg sub-folder defaults to
                ``<base_dir>/seg`` unless *seg_dir* is given explicitly.
            h5_dataset: HDF5 dataset path for the image stack (e.g.
                ``"1.1/measurement/eiger4m"``).  Mutually exclusive with
                *tiff_dir*.
            tiff_dir: Directory of ``img_*.tif`` files.  Mutually exclusive with
                *h5_dataset*.
            seg_dir: Directory containing ``frame_?????.h5`` segmentation files.
                Defaults to ``<base_dir>/seg``.
            map_quantity: Scalar quantity displayed on the left panel.  One of
                ``'match_rate'``, ``'rms_px'``, ``'n_matched'``, ``'score'``,
                ``'cost'``.
            motor_x, motor_y: Motor names for physical axis labels and
                click-to-pixel conversion.
            motor_units: Unit labels per motor, e.g. ``{'sy': 'mm', 'sz': 'mm'}``.
            E_min_eV, E_max_eV: Energy range for spot simulation.
            f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
            max_match_px: Pixel radius used when drawing match lines between
                observed and simulated spots.
            fit_max_match_px: Match-radius schedule passed to
                :func:`~nrxrdct.laue.fitting.fit_orientation_stack`.  A list
                enables staged refinement.
            fit_strain: Strain components to refine (e.g. ``('e_xx', 'e_yy',
                'e_zz')``).  ``None`` refines all six.
            r_squared_min: Minimum Gaussian-fit R² when loading the seg file.
            include_unfitted: Include raw centroids from the seg file.
            kernel_sigma: Gaussian kernel width (px) for image-based refinement.
            bg_sigma: Background subtraction kernel width (px).
            max_angle_deg: Local-search radius (°) for image-based orientation.
            max_shift_px: Per-layer pixel-displacement budget forwarded to
                :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`.
            figsize: Figure size in inches.
        """
        import re as _re
        import ipywidgets as ipw
        from IPython.display import display as _ipy_display
        from .simulation import simulate_laue, precompute_allowed_hkl
        from .segmentation import convert_spotsfile2peaklist
        from .fitting import (
            fit_orientation_stack,
            fit_strain_orientation_stack,
            refine_orientation_image_stack,
            refine_strain_image_stack,
            _match_spots,
            _STRAIN_ALL,
        )

        _seg_dir    = seg_dir or os.path.join(base_dir, "seg")
        _fit_strain = tuple(fit_strain) if fit_strain is not None else _STRAIN_ALL

        # Precompute allowed HKL for each unique crystal in the stack.
        _allowed_by_crystal: dict = {}
        for _layer in self.stack.all_layers:
            _cid = id(_layer.crystal)
            if _cid not in _allowed_by_crystal:
                _allowed_by_crystal[_cid] = precompute_allowed_hkl(
                    _layer.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
                )

        _LAYER_COLORS = [
            "#ff6b35", "#44aaff", "#44dd66", "#ffcc44", "#ff44aa", "#aa44ff",
        ]

        mu = motor_units or {}
        mx = self.motors.get(motor_x) if motor_x else None
        my = self.motors.get(motor_y) if motor_y else None

        if mx is not None and my is not None:
            extent_map = [mx[0, 0], mx[0, -1], my[-1, 0], my[0, 0]]
            xu_ = mu.get(motor_x, "")
            yu_ = mu.get(motor_y, "")
            xlabel_map = f"{motor_x} ({xu_})" if xu_ else motor_x
            ylabel_map = f"{motor_y} ({yu_})" if yu_ else motor_y
        else:
            extent_map = [0, self.nx, self.ny, 0]
            xlabel_map = "column (ix)"
            ylabel_map = "row (iy)"

        def _click_to_iy_ix(xdata: float, ydata: float):
            if mx is not None and my is not None:
                dist = (mx - xdata) ** 2 + (my - ydata) ** 2
                iy, ix = np.unravel_index(int(np.argmin(dist)), dist.shape)
            else:
                ix = int(np.clip(int(xdata), 0, self.nx - 1))
                iy = int(np.clip(int(ydata), 0, self.ny - 1))
            return int(iy), int(ix)

        _tiff_index: list = []

        def _load_image(frame_idx: int) -> "np.ndarray | None":
            if tiff_dir is not None:
                if not _tiff_index:
                    pat = _re.compile(r'(\d+)\.tiff?$', _re.IGNORECASE)
                    files = []
                    for fname in os.listdir(tiff_dir):
                        m = pat.search(fname)
                        if m:
                            files.append((int(m.group(1)), os.path.join(tiff_dir, fname)))
                    files.sort(key=lambda t: t[0])
                    _tiff_index.extend(p for _, p in files)
                if not _tiff_index or frame_idx >= len(_tiff_index):
                    return None
                try:
                    import skimage.io
                    return skimage.io.imread(_tiff_index[frame_idx]).astype(np.float32)
                except Exception as exc:
                    print(f"  ✗ TIFF read error frame {frame_idx}: {exc}", flush=True)
                    return None
            elif h5_dataset is not None:
                _h5 = self.h5_path
                if _h5 is None:
                    print("  ✗ h5_path not set on this LayeredMap.", flush=True)
                    return None
                try:
                    with h5py.File(_h5, "r") as fh:
                        if h5_dataset not in fh:
                            print(f"  ✗ dataset {h5_dataset!r} not in {_h5!r}", flush=True)
                            return None
                        return fh[h5_dataset][frame_idx].astype(np.float32)
                except Exception as exc:
                    print(f"  ✗ HDF5 read error frame {frame_idx}: {exc}", flush=True)
                    return None
            return None

        _map_opts = {
            "match_rate": (self.match_rate,                                      "Match rate", "viridis"),
            "rms_px":     (self.rms_px,                                          "RMS (px)",   "plasma_r"),
            "n_matched":  (np.where(self.n_matched == -1, np.nan,
                                    self.n_matched.astype(float)),               "N matched",  "YlOrRd"),
            "score":      (self.score,                                           "Img score",  "viridis"),
            "cost":       (self.cost,                                            "Cost",       "plasma_r"),
        }
        map_data, map_label, map_cmap = _map_opts.get(
            map_quantity, _map_opts["match_rate"]
        )

        with plt.ioff():
            fig = plt.figure(figsize=figsize)
        try:
            fig.canvas.manager.set_window_title("Laue — LayeredMap re-index")
        except Exception:
            pass

        gs = fig.add_gridspec(
            1, 2, width_ratios=[1, 1.8], wspace=0.08,
            left=0.07, right=0.97, bottom=0.09, top=0.91,
        )
        ax_map = fig.add_subplot(gs[0])
        ax_det = fig.add_subplot(gs[1])

        im_map = ax_map.imshow(
            map_data, origin="upper", extent=extent_map,
            cmap=map_cmap, interpolation="nearest", aspect="auto",
        )
        cbar_map = fig.colorbar(im_map, ax=ax_map, fraction=0.04, pad=0.03,
                                 shrink=0.8, label=map_label)
        ax_map.set_xlabel(xlabel_map, fontsize=9)
        ax_map.set_ylabel(ylabel_map, fontsize=9)

        def _map_title(label: str) -> str:
            return f"Click to select — {label}"

        ax_map.set_title(_map_title(map_label), fontsize=9)
        sel_dot, = ax_map.plot([], [], "w+", ms=11, mew=2.0, zorder=10)

        ax_det.set_facecolor("k")
        ax_det.set_xlim(0, camera.Nh)
        ax_det.set_ylim(camera.Nv, 0)
        ax_det.set_aspect("equal")
        ax_det.set_xlabel("x (px)", fontsize=9)
        ax_det.set_ylabel("y (px)", fontsize=9)
        ax_det.set_title("← click map to select a frame", fontsize=9, color="#888")
        fig.suptitle(
            "LayeredMap re-index  —  click map → Fit → Store",
            fontsize=9, color="#555",
        )

        _state: dict = {
            "frame_idx": None, "iy": None, "ix": None,
            "obs_xy": np.empty((0, 2)),
            "fit_result": None,
            "drawn": False,
        }

        def _best_U_layers() -> "list | None":
            """Return U_layers from the current fit result or map arrays."""
            r = _state["fit_result"]
            iy, ix = _state["iy"], _state["ix"]
            if r is not None:
                return (r.U_eff_layers if hasattr(r, "U_eff_layers") else r.U_layers)
            if iy is not None:
                U_src = (
                    self.U_eff if not np.all(np.isnan(self.U_eff[:, iy, ix]))
                    else self.U
                )
                if not np.all(np.isnan(U_src[:, iy, ix])):
                    return [U_src[li, iy, ix].copy() for li in range(self.n_layers)]
            return None

        def _overlay_sim(U_layers_list: list, obs_xy: np.ndarray) -> None:
            """Draw per-layer simulated spots (colored) with match lines."""
            for li, (layer, U) in enumerate(
                zip(self.stack.all_layers, U_layers_list)
            ):
                if np.any(np.isnan(U)):
                    continue
                color = _LAYER_COLORS[li % len(_LAYER_COLORS)]
                label = getattr(layer, "label", f"layer {li}")
                try:
                    spots = simulate_laue(
                        layer.crystal, U, camera,
                        E_min=E_min_eV, E_max=E_max_eV,
                        geometry_only=True,
                        allowed_hkl=_allowed_by_crystal.get(id(layer.crystal)),
                    )
                    sim_xy = np.array(
                        [s["pix"] for s in spots if s.get("pix") is not None],
                        dtype=float,
                    ) if spots else np.empty((0, 2))
                    if not len(sim_xy):
                        continue
                    ax_det.scatter(
                        sim_xy[:, 0], sim_xy[:, 1],
                        s=24, c=color, marker="D", linewidths=0,
                        zorder=5, alpha=0.85,
                        label=f"{label} ({len(sim_xy)})",
                    )
                    if len(obs_xy) and len(sim_xy):
                        row_ind, col_ind, dist_px = _match_spots(
                            obs_xy, sim_xy, max_match_px
                        )
                        for r, c, d in zip(row_ind, col_ind, dist_px):
                            if d < max_match_px:
                                ax_det.plot(
                                    [obs_xy[r, 0], sim_xy[c, 0]],
                                    [obs_xy[r, 1], sim_xy[c, 1]],
                                    color="#44dd66", lw=0.7, alpha=0.55, zorder=3,
                                )
                except Exception as exc:
                    print(f"  layer {li} sim error: {exc}", flush=True)

        def _draw_det() -> None:
            frame_idx  = _state["frame_idx"]
            obs_xy     = _state["obs_xy"]
            fit_result = _state["fit_result"]
            iy, ix     = _state["iy"], _state["ix"]

            saved_xlim = ax_det.get_xlim()
            saved_ylim = ax_det.get_ylim()
            ax_det.cla()
            ax_det.set_facecolor("k")

            image = _load_image(frame_idx)
            if image is not None:
                pos  = image[image > 0]
                vmin = float(np.percentile(pos, 1)) if pos.size else 0.0
                vmax = float(np.percentile(pos, 99.9)) if pos.size else 1.0
                if vmax <= vmin:
                    vmax = vmin + 1.0
                nv_im, nh_im = image.shape
                disp_norm = np.clip((image - vmin) / (vmax - vmin), 0, None)
                ax_det.imshow(
                    np.log1p(disp_norm * 1000),
                    origin="upper", extent=[0, nh_im, nv_im, 0],
                    cmap="gray", aspect="equal", zorder=0,
                )
            else:
                ax_det.set_xlim(0, camera.Nh)
                ax_det.set_ylim(camera.Nv, 0)
            ax_det.set_aspect("equal")

            if len(obs_xy):
                ax_det.scatter(
                    obs_xy[:, 0], obs_xy[:, 1],
                    s=40, c="none", edgecolors="white", linewidths=0.8,
                    zorder=4, label=f"observed ({len(obs_xy)})",
                )

            U_layers_draw = _best_U_layers()
            if U_layers_draw is not None:
                _overlay_sim(U_layers_draw, obs_xy)

            if len(obs_xy) or U_layers_draw is not None:
                ax_det.legend(
                    fontsize=7, loc="upper right",
                    facecolor="#111", edgecolor="#444", labelcolor="white",
                    framealpha=0.85,
                )

            ax_det.set_xlabel("x (px)", fontsize=9)
            ax_det.set_ylabel("y (px)", fontsize=9)
            suffix = f"  — {fit_result}" if fit_result is not None else ""
            ax_det.set_title(
                f"Frame {frame_idx}  (iy={iy}, ix={ix}){suffix}",
                fontsize=8,
            )
            if _state["drawn"]:
                ax_det.set_xlim(saved_xlim)
                ax_det.set_ylim(saved_ylim)
            _state["drawn"] = True
            fig.canvas.draw_idle()

        def _on_click(event) -> None:
            if event.inaxes is not ax_map:
                return
            if event.xdata is None or event.ydata is None:
                return
            try:
                if fig.canvas.toolbar.mode != "":
                    return
            except Exception:
                pass

            iy, ix    = _click_to_iy_ix(event.xdata, event.ydata)
            frame_idx = self.frame_index(iy, ix)

            if mx is not None and my is not None:
                sel_dot.set_data([mx[iy, ix]], [my[iy, ix]])
            else:
                sel_dot.set_data([ix + 0.5], [iy + 0.5])

            seg_path = os.path.join(_seg_dir, f"frame_{frame_idx:05d}.h5")
            if os.path.exists(seg_path):
                try:
                    obs_xy = convert_spotsfile2peaklist(
                        seg_path,
                        r_squared_min=r_squared_min,
                        include_unfitted=include_unfitted,
                    )[:, :2]
                except Exception:
                    obs_xy = np.empty((0, 2))
            else:
                obs_xy = np.empty((0, 2))

            has_map_result = not np.all(np.isnan(self.U[:, iy, ix, 0, 0]))
            has_image      = (h5_dataset is not None or tiff_dir is not None)
            enough_obs     = len(obs_xy) >= 3

            _state.update(
                frame_idx=frame_idx, iy=iy, ix=ix,
                obs_xy=obs_xy, fit_result=None,
            )

            _info.value = (
                f"<span style='color:#aaa'>Frame {frame_idx} — "
                f"{len(obs_xy)} observed spots"
                + (" — existing map result" if has_map_result else "")
                + "</span>"
            )
            btn_fit_ori.disabled = not (enough_obs and (has_map_result or True))
            btn_fit_str.disabled = True
            btn_img_ori.disabled = not (has_image and (has_map_result or enough_obs))
            btn_img_str.disabled = not (has_image and (has_map_result or enough_obs))
            btn_store.disabled   = True
            btn_save.disabled    = True
            btn_reload.disabled  = False
            _draw_det()

        fig.canvas.mpl_connect("button_press_event", _on_click)

        # ── widgets ────────────────────────────────────────────────────────────
        _bkw  = dict(layout=ipw.Layout(width="130px", height="32px"))
        _bkw2 = dict(layout=ipw.Layout(width="140px", height="32px"))

        btn_fit_ori = ipw.Button(description="⚡ Fit",       button_style="primary", **_bkw)
        btn_fit_str = ipw.Button(description="🔩 Fit strain", button_style="warning", **_bkw2)
        btn_img_ori = ipw.Button(description="🖼 Img orient", button_style="info",    **_bkw2)
        btn_img_str = ipw.Button(description="🖼 Img strain", button_style="warning", **_bkw2)
        btn_store   = ipw.Button(description="⬆ Store",      button_style="success", **_bkw)
        btn_save    = ipw.Button(description="💾 Save UBs",  button_style="",        **_bkw)
        btn_reload  = ipw.Button(description="↺ Reload",     button_style="danger",  **_bkw)

        for _b in (btn_fit_ori, btn_fit_str, btn_img_ori, btn_img_str,
                   btn_store, btn_save, btn_reload):
            _b.disabled = True

        _info = ipw.HTML(
            "<span style='color:#666;font-style:italic'>"
            "click a map pixel to select a frame"
            "</span>",
            layout=ipw.Layout(margin="4px 0 0 6px"),
        )

        w_map_quantity = ipw.Dropdown(
            options=[(label, key) for key, (_, label, _) in _map_opts.items()],
            value=map_quantity if map_quantity in _map_opts else "match_rate",
            layout=ipw.Layout(width="150px", height="32px"),
        )

        def _cb_map_quantity(change) -> None:
            data, label, cmap = _map_opts[change["new"]]
            im_map.set_data(data)
            im_map.set_cmap(cmap)
            im_map.autoscale()
            cbar_map.set_label(label)
            ax_map.set_title(_map_title(label), fontsize=9)
            fig.canvas.draw_idle()

        w_map_quantity.observe(_cb_map_quantity, names="value")

        # ── async-threaded button callbacks ───────────────────────────────────

        def _async_run(worker_fn, btn, label_running, label_done, on_success):
            import asyncio
            import queue as _qmod
            import threading

            if getattr(btn, "_running", False):
                return
            btn._running    = True
            btn.disabled    = True
            btn.description = label_running

            q: _qmod.Queue = _qmod.Queue()

            def _run():
                try:
                    q.put(("ok", worker_fn()))
                except Exception as exc:
                    q.put(("err", exc))

            async def _wait():
                threading.Thread(target=_run, daemon=True).start()
                while q.empty():
                    await asyncio.sleep(0.15)
                tag, payload = q.get_nowait()
                if tag == "err":
                    _info.value = (
                        f"<b style='color:#f44'>{label_done} error: {payload}</b>"
                    )
                else:
                    on_success(payload)
                btn.description = label_done
                btn.disabled    = False
                btn._running    = False

            try:
                asyncio.get_event_loop().create_task(_wait())
            except RuntimeError:
                asyncio.ensure_future(_wait())

        def _cb_fit_ori(_) -> None:
            obs_xy = _state["obs_xy"]
            if len(obs_xy) < 3:
                return

            start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
            saved_U = [l.U.copy() for l in self.stack.all_layers]
            for l, U in zip(self.stack.all_layers, start_U):
                l.U = U.copy()

            def _work():
                try:
                    return fit_orientation_stack(
                        self.stack, camera, obs_xy,
                        E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                        max_match_px=list(fit_max_match_px)
                        if hasattr(fit_max_match_px, "__iter__")
                        else fit_max_match_px,
                        allowed_hkl=_allowed_by_crystal,
                        geometry_only=True,
                        correct_depth=correct_depth,
                        update_stack=False,
                        verbose=True,
                    )
                finally:
                    for l, U in zip(self.stack.all_layers, saved_U):
                        l.U = U

            def _on_ok(res):
                _state["fit_result"] = res
                col = "#44aaff" if res.success else "#ffaa33"
                _info.value = f"<b style='color:{col}'>{res}</b>"
                btn_fit_str.disabled = len(_state["obs_xy"]) < 3
                btn_img_str.disabled = False
                btn_store.disabled   = False
                btn_save.disabled    = False
                _draw_det()

            _async_run(_work, btn_fit_ori, "Fitting…", "⚡ Fit", _on_ok)

        def _cb_fit_str(_) -> None:
            obs_xy = _state["obs_xy"]
            if len(obs_xy) < 3:
                return

            start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
            saved_U = [l.U.copy() for l in self.stack.all_layers]
            for l, U in zip(self.stack.all_layers, start_U):
                l.U = U.copy()

            def _work():
                try:
                    return fit_strain_orientation_stack(
                        self.stack, camera, obs_xy,
                        fit_strain=_fit_strain,
                        E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                        max_match_px=[3.0],
                        allowed_hkl=_allowed_by_crystal,
                        geometry_only=True,
                        correct_depth=correct_depth,
                        update_stack=False,
                        verbose=True,
                    )
                finally:
                    for l, U in zip(self.stack.all_layers, saved_U):
                        l.U = U

            def _on_ok(res):
                _state["fit_result"] = res
                col = "#ffcc44" if res.success else "#ffaa33"
                _info.value = f"<b style='color:{col}'>{res}</b>"
                btn_img_str.disabled = False
                btn_store.disabled   = False
                btn_save.disabled    = False
                _draw_det()

            _async_run(_work, btn_fit_str, "Fitting…", "🔩 Fit strain", _on_ok)

        def _cb_img_ori(_) -> None:
            frame_idx = _state["frame_idx"]
            if frame_idx is None:
                return

            start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
            if any(np.any(np.isnan(U)) for U in start_U):
                _info.value = "<b style='color:#f44'>No starting orientation available</b>"
                return

            saved_U = [l.U.copy() for l in self.stack.all_layers]
            for l, U in zip(self.stack.all_layers, start_U):
                l.U = U.copy()

            image = _load_image(frame_idx)
            if image is None:
                _info.value = "<b style='color:#f44'>Could not load image</b>"
                return

            def _work():
                try:
                    return refine_orientation_image_stack(
                        self.stack, camera, image.astype(np.float64),
                        allowed_hkl=_allowed_by_crystal,
                        kernel_sigma=kernel_sigma,
                        bg_sigma=bg_sigma,
                        max_angle_deg=max_angle_deg,
                        E_min=E_min_eV, E_max=E_max_eV,
                        correct_depth=correct_depth,
                        verbose=True,
                    )
                finally:
                    for l, U in zip(self.stack.all_layers, saved_U):
                        l.U = U

            def _on_ok(res):
                _state["fit_result"] = res
                _info.value = f"<b style='color:#44aaff'>{res}</b>"
                btn_img_str.disabled = False
                btn_store.disabled   = False
                btn_save.disabled    = False
                _draw_det()

            _async_run(_work, btn_img_ori, "Refining…", "🖼 Img orient", _on_ok)

        def _cb_img_str(_) -> None:
            frame_idx = _state["frame_idx"]
            if frame_idx is None:
                return

            start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
            if any(np.any(np.isnan(U)) for U in start_U):
                _info.value = "<b style='color:#f44'>No starting orientation available</b>"
                return

            r = _state["fit_result"]
            strain0_list = (
                r.strain_tensors if hasattr(r, "strain_tensors") else None
            )

            saved_U = [l.U.copy() for l in self.stack.all_layers]
            for l, U in zip(self.stack.all_layers, start_U):
                l.U = U.copy()

            image = _load_image(frame_idx)
            if image is None:
                _info.value = "<b style='color:#f44'>Could not load image</b>"
                return

            def _work():
                try:
                    kw: dict = dict(
                        allowed_hkl   = _allowed_by_crystal,
                        fit_strain    = _fit_strain,
                        kernel_sigma  = kernel_sigma,
                        bg_sigma      = bg_sigma,
                        max_angle_deg = max_angle_deg,
                        E_min         = E_min_eV,
                        E_max         = E_max_eV,
                        correct_depth = correct_depth,
                        verbose       = True,
                    )
                    if strain0_list is not None:
                        kw["strain0_list"] = strain0_list
                    if max_shift_px is not None:
                        kw["max_shift_px"] = max_shift_px
                    return refine_strain_image_stack(
                        self.stack, camera, image.astype(np.float64), **kw
                    )
                finally:
                    for l, U in zip(self.stack.all_layers, saved_U):
                        l.U = U

            def _on_ok(res):
                _state["fit_result"] = res
                _info.value = f"<b style='color:#ffcc44'>{res}</b>"
                btn_store.disabled = False
                btn_save.disabled  = False
                _draw_det()

            _async_run(_work, btn_img_str, "Refining…", "🖼 Img strain", _on_ok)

        def _cb_store(_) -> None:
            r = _state["fit_result"]
            if r is None:
                return
            iy, ix = _state["iy"], _state["ix"]
            self.set_result(iy, ix, r)
            # Refresh the map image so the stored pixel is visible immediately
            im_map.set_data(_map_opts[w_map_quantity.value][0])
            im_map.autoscale()
            fig.canvas.draw_idle()
            save_note = ""
            if self.save_path:
                self.save(self.save_path)
                save_note = f" — saved to {os.path.basename(self.save_path)}"
            else:
                save_note = " — <b style='color:#ffaa33'>no save_path, result in memory only</b>"
            _info.value = (
                f"<b style='color:#44dd66'>Stored → (iy={iy}, ix={ix})</b>"
                f"&emsp;{r}"
                f"<span style='color:#aaa'>{save_note}</span>"
            )
            print(
                f"  ⬆ Stored result at (iy={iy}, ix={ix})"
                + (f"  → {self.save_path}" if self.save_path else " (in memory only)"),
                flush=True,
            )

        def _cb_save(_) -> None:
            r = _state["fit_result"]
            if r is None:
                return
            U_layers = (
                r.U_eff_layers if hasattr(r, "U_eff_layers") else r.U_layers
            )
            saved = []
            for li, U in enumerate(U_layers):
                existing = glob.glob(os.path.join(os.getcwd(), f"UB_layer{li}_*.npy"))
                max_n = -1
                for fpath in existing:
                    m = _re.search(r"UB_layer\d+_(\d+)\.npy$", os.path.basename(fpath))
                    if m:
                        max_n = max(max_n, int(m.group(1)))
                fname = f"UB_layer{li}_{max_n + 1:02d}.npy"
                np.save(fname, U)
                saved.append(fname)
                print(f"  💾 Saved U layer {li} → {os.path.abspath(fname)}")
            _info.value = (
                f"<b style='color:#44dd66'>Saved {len(saved)} UB files: "
                + ", ".join(saved) + "</b>"
            )

        def _cb_reload(_) -> None:
            if _state["frame_idx"] is None:
                return
            _state["fit_result"] = None
            btn_fit_str.disabled = True
            btn_store.disabled   = True
            btn_save.disabled    = True
            iy, ix = _state["iy"], _state["ix"]
            has_map = not np.all(np.isnan(self.U[:, iy, ix, 0, 0]))
            _info.value = (
                "<span style='color:#aaa'>Reloaded — showing "
                + ("existing map orientation" if has_map else "template stack orientation")
                + "</span>"
            )
            _draw_det()

        btn_fit_ori.on_click(_cb_fit_ori)
        btn_fit_str.on_click(_cb_fit_str)
        btn_img_ori.on_click(_cb_img_ori)
        btn_img_str.on_click(_cb_img_str)
        btn_store.on_click(_cb_store)
        btn_save.on_click(_cb_save)
        btn_reload.on_click(_cb_reload)

        _row_kw = dict(layout=ipw.Layout(gap="6px", margin="2px 0 0 0", align_items="center"))
        _controls = ipw.VBox([
            ipw.HBox([btn_fit_ori, btn_fit_str, btn_img_ori, btn_img_str], **_row_kw),
            ipw.HBox([btn_store,   btn_save,    btn_reload,
                      ipw.HTML("<span style='color:#aaa;align-self:center'>map:</span>",
                               layout=ipw.Layout(margin="0 2px 0 10px")),
                      w_map_quantity],                                     **_row_kw),
            _info,
        ], layout=ipw.Layout(padding="6px 8px"))

        _ipy_display(ipw.VBox([fig.canvas, _controls]))

    # ── Serialization ──────────────────────────────────────────────────────────

    def save(self, path: str, compress: bool = True) -> None:
        """
        Save the map to an HDF5 file.

        All per-pixel arrays are stored under their attribute names.
        Motor positions land in ``motors/<name>``.
        """
        kw = {"compression": "gzip", "compression_opts": 4} if compress else {}

        with h5py.File(path, "w") as hf:
            meta = hf.create_group("meta")
            meta.attrs["ny"]       = self.ny
            meta.attrs["nx"]       = self.nx
            meta.attrs["n_layers"] = self.n_layers
            meta.attrs["h5_path"]  = self.h5_path or ""
            meta.attrs["entry"]    = self.entry
            meta.attrs["labels"]   = json.dumps(self.layer_labels)

            for name in (
                "R_global", "rotvec",
                "U", "U_eff",
                "rms_px", "mean_px", "n_matched", "match_rate",
                "cost", "n_sim", "score", "score0",
                "strain_tensor", "strain_voigt", "strain_tensor_deviatoric",
            ):
                hf.create_dataset(name, data=getattr(self, name), **kw)

            for name, arr in self.motors.items():
                hf.create_dataset(f"motors/{name}", data=arr, **kw)

        print(f"LayeredMap saved → {path!r}", flush=True)

    @classmethod
    def load(cls, path: str, stack) -> "LayeredMap":
        """
        Load a :class:`LayeredMap` from *path*.

        *stack* must be the same
        :class:`~nrxrdct.laue.layers.LayeredCrystal` used during fitting
        (supplies the layer crystal objects).

        Returns:
            LayeredMap with all per-pixel arrays restored.
        """
        with h5py.File(path, "r") as hf:
            meta     = hf["meta"]
            ny       = int(meta.attrs["ny"])
            nx       = int(meta.attrs["nx"])
            h5_path  = str(meta.attrs.get("h5_path", "")) or None
            entry    = str(meta.attrs.get("entry", "1.1"))

            obj = cls(ny=ny, nx=nx, stack=stack, h5_path=h5_path, entry=entry)

            for name in (
                "R_global", "rotvec",
                "U", "U_eff",
                "rms_px", "mean_px", "n_matched", "match_rate",
                "cost", "n_sim", "score", "score0",
                "strain_tensor", "strain_voigt", "strain_tensor_deviatoric",
            ):
                if name in hf:
                    setattr(obj, name, hf[name][()])

            if "motors" in hf:
                for name in hf["motors"]:
                    obj.motors[name] = hf[f"motors/{name}"][()]

        return obj

    # ── Disorientation ────────────────────────────────────────────────────────

    def disorientation_map(
        self,
        layer_a: int,
        layer_b: int,
        *,
        symmetry: str = "cubic",
        symmetry_b: "str | None" = None,
        use_eff: bool = False,
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        cmap: str = "inferno",
        vmin: float = 0.0,
        vmax: "float | None" = None,
        plot: bool = True,
        ax=None,
    ) -> np.ndarray:
        """
        Compute the per-pixel disorientation angle between two stack layers.

        The misorientation between the two layers is minimised over all pairs
        of point-group symmetry operators (the same algorithm as
        :func:`~nrxrdct.laue.simulation.disorientation`) and the result is
        the **fundamental zone disorientation angle** — the smallest rotation
        that maps one layer's orientation to the other's, accounting for
        crystal symmetry.

        Both orientation matrices are first projected onto SO(3) (via SVD),
        so ``U_eff`` matrices (which carry a small strain factor) are handled
        correctly.

        Args:
            layer_a: Index of the first layer (e.g. the substrate/buffer).
            layer_b: Index of the second layer (e.g. the film).
            symmetry: Point-group symmetry for *layer_a* (and *layer_b* if
                *symmetry_b* is ``None``).  One of ``'cubic'``, ``'hexagonal'``,
                ``'tetragonal'``, ``'orthorhombic'``.
            symmetry_b: Point-group symmetry for *layer_b*.  If ``None``
                (default), *symmetry* is used for both layers.  Set a
                different value for heterostructures with different crystal
                systems (e.g. cubic substrate + hexagonal film).
            use_eff: If ``True``, use ``U_eff`` (strained orientation) instead
                of the pure-rotation ``U``.  ``U_eff`` is only available after
                a strain fit; falls back silently to ``U`` if not set.
            motor_x, motor_y: Motor names for physical axis labels on the plot.
            cmap: Matplotlib colormap for the angle map.  Default ``'inferno'``.
            vmin: Minimum value for the colorscale (degrees).  Default ``0``.
            vmax: Maximum value for the colorscale.  ``None`` uses the 99th
                percentile of the valid pixel values.
            plot: If ``True`` (default), draw the map.  Set ``False`` to only
                compute and return the array.
            ax: Existing matplotlib ``Axes`` to draw into.  A new figure is
                created if ``None``.

        Returns:
            angle_map ((ny, nx) float64 ndarray): Disorientation angle in
                degrees at each pixel.  Pixels where either layer has no valid
                orientation are ``NaN``.
        """
        from .simulation import _symmetry_ops_np

        _sym_b = symmetry_b if symmetry_b is not None else symmetry

        # Choose U or U_eff
        if use_eff and not np.all(np.isnan(self.U_eff)):
            U_src = self.U_eff
        else:
            U_src = self.U

        Ua = U_src[layer_a]   # (ny, nx, 3, 3)
        Ub = U_src[layer_b]   # (ny, nx, 3, 3)

        # Valid mask: both layers must have a fitted orientation
        valid = (
            ~np.any(np.isnan(Ua), axis=(-2, -1)) &
            ~np.any(np.isnan(Ub), axis=(-2, -1))
        )

        ny, nx = self.ny, self.nx
        angle_map = np.full((ny, nx), np.nan)

        if not valid.any():
            if plot:
                if ax is None:
                    _, ax = plt.subplots(figsize=(7, 6))
                ax.set_title(
                    f"Disorientation — layers {self.layer_labels[layer_a]} / "
                    f"{self.layer_labels[layer_b]} (no data)"
                )
            return angle_map

        # Flatten to (M, 3, 3) for valid pixels only
        idx   = np.argwhere(valid)           # (M, 2)
        iy_v  = idx[:, 0]
        ix_v  = idx[:, 1]
        Ua_v  = Ua[iy_v, ix_v]              # (M, 3, 3)
        Ub_v  = Ub[iy_v, ix_v]              # (M, 3, 3)

        # Project to SO(3) — handles strained U_eff correctly
        Ra = Rotation.from_matrix(Ua_v).as_matrix()   # (M, 3, 3)
        Rb = Rotation.from_matrix(Ub_v).as_matrix()   # (M, 3, 3)

        # Raw misorientation per pixel: R_mis = Rb @ Ra.T
        R_mis = Rb @ Ra.transpose(0, 2, 1)            # (M, 3, 3)

        # Symmetry operators for both layers
        ops_a = _symmetry_ops_np(symmetry)             # (Na, 3, 3)
        ops_b = _symmetry_ops_np(_sym_b)               # (Nb, 3, 3)

        # Apply operators: S_a @ R_mis @ S_b.T for all (S_a, S_b) pairs.
        #   ops_a_R[s, m] = ops_a[s] @ R_mis[m]  →  (Na, M, 3, 3)
        ops_a_R = np.einsum("sij,mjk->smik", ops_a, R_mis)

        #   candidates[sa, sb, m] = ops_a_R[sa, m] @ ops_b[sb].T
        #   broadcast: ops_a_R[:, None]  (Na, 1,  M, 3, 3)
        #            @ ops_b.T[None, :, None]  (1, Nb, 1, 3, 3)
        ops_b_T = ops_b.transpose(0, 2, 1)            # (Nb, 3, 3)
        candidates = (
            ops_a_R[:, None] @ ops_b_T[None, :, None]
        )                                              # (Na, Nb, M, 3, 3)

        # Trace → angle for every candidate
        traces = (
            candidates[:, :, :, 0, 0] +
            candidates[:, :, :, 1, 1] +
            candidates[:, :, :, 2, 2]
        )                                              # (Na, Nb, M)

        # Flatten symmetry pairs → (Na*Nb, M), find minimum angle per pixel
        traces_flat  = traces.reshape(-1, len(iy_v))   # (Na*Nb, M)
        cos_half_ang = np.clip((traces_flat - 1.0) / 2.0, -1.0, 1.0)
        angles       = np.degrees(np.arccos(cos_half_ang))   # (Na*Nb, M)
        min_angles   = angles.min(axis=0)              # (M,)

        angle_map[iy_v, ix_v] = min_angles

        if not plot:
            return angle_map

        # ── Plot ──────────────────────────────────────────────────────────────
        if vmax is None:
            valid_vals = min_angles[np.isfinite(min_angles)]
            vmax = float(np.percentile(valid_vals, 99)) if len(valid_vals) else 1.0

        extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
        if ax is None:
            _, ax = plt.subplots(figsize=(7, 6))

        imkw = dict(origin="upper", cmap=cmap, vmin=vmin, vmax=vmax)
        if extent is not None:
            imkw.update(extent=extent, aspect="auto")

        im = ax.imshow(angle_map, **imkw)
        plt.colorbar(im, ax=ax, label="Disorientation (°)")
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_title(
            f"Disorientation — {self.layer_labels[layer_a]}"
            f" / {self.layer_labels[layer_b]}"
        )
        return angle_map

    def plot_kam(
        self,
        layer: int,
        *,
        order: int = 1,
        symmetry: str = "cubic",
        use_eff: bool = False,
        motor_x: "str | None" = None,
        motor_y: "str | None" = None,
        cmap: str = "inferno",
        vmin: float = 0.0,
        vmax: "float | None" = None,
        plot: bool = True,
        ax=None,
    ) -> np.ndarray:
        """
        Kernel Average Misorientation (KAM) map for *layer*.

        For each valid pixel the mean disorientation angle to all valid
        neighbors within Chebyshev distance *order* is computed after
        minimisation over crystal symmetry operators.  The result is the
        standard KAM metric used in EBSD analysis to highlight orientation
        gradients caused by geometrically necessary dislocations or grain
        sub-structure.

        Args:
            layer: Index into ``stack.all_layers`` selecting which layer's
                orientation to analyse.  Each layer has its own independent
                ``U`` / ``U_eff`` array, so the substrate and film will
                produce separate KAM maps reflecting gradients in their
                respective materials.
            order: Chebyshev shell radius in pixels.  ``1`` (default)
                uses the 8 immediate neighbors; ``2`` adds the next ring
                for 24 neighbors total; and so on.  Larger values smooth
                the map and capture longer-range gradients but blur sharp
                boundaries.  Standard EBSD convention is ``order=1``.
            symmetry: Point-group symmetry applied when minimising the
                misorientation angle between neighbors.  Must match the
                crystal structure of *layer*: ``'cubic'``,
                ``'hexagonal'``, ``'tetragonal'``, or
                ``'orthorhombic'``.  Using the wrong symmetry
                (e.g. ``'orthorhombic'`` for a cubic crystal) causes
                symmetry-equivalent orientations to be reported as real
                gradients, inflating KAM everywhere.
            use_eff: If ``True``, use ``U_eff`` (which carries the strain
                factor ``I + ε``) instead of the pure rotation ``U``.
                Before computing misorientations the matrices are projected
                onto SO(3), so large inter-pixel strain differences can
                still bleed into the KAM value.  Keep ``False`` (default)
                to isolate orientation gradients from strain.
            motor_x, motor_y: Names of motor position arrays stored in
                ``self.motors``.  When supplied the axes are labeled in
                physical units and the map extent is set from the motor
                ranges; without them row/column pixel indices are used.
            cmap: Matplotlib colormap.  ``'inferno'`` (default) is the
                standard choice for KAM because near-zero values appear
                black and gradient regions become progressively brighter.
            vmin: Lower colorscale bound in degrees.  Almost always left
                at ``0.0`` since KAM is non-negative by construction.
            vmax: Upper colorscale bound in degrees.  Set an explicit
                value when comparing maps across different scans so all
                images share the same scale.  ``None`` (default)
                auto-scales to the 99th percentile of valid pixels,
                which avoids isolated outlier pixels blowing out the
                colour range.
            plot: Render the map when ``True`` (default).  Set ``False``
                to compute and return the array without any drawing, e.g.
                for batch processing or when embedding in a custom figure.
            ax: Existing ``Axes`` to draw into.  A new figure is created
                when ``None``.

        Returns:
            ``(ny, nx)`` float64 array of KAM angles in degrees.  Pixels
            with no valid orientation or no valid neighbors are ``NaN``.
        """
        from .simulation import _symmetry_ops_np

        # Choose U source
        if use_eff and not np.all(np.isnan(self.U_eff[layer])):
            U_src = self.U_eff[layer]   # (ny, nx, 3, 3)
        else:
            U_src = self.U[layer]

        valid = ~np.any(np.isnan(U_src), axis=(-2, -1))   # (ny, nx) bool

        ny, nx = self.ny, self.nx
        kam_map = np.full((ny, nx), np.nan)

        if not valid.any():
            if plot:
                if ax is None:
                    _, ax = plt.subplots(figsize=(7, 6))
                ax.set_title(f"KAM — {self.layer_labels[layer]} (no data)")
            return kam_map

        # Project all valid orientations to SO(3) once (handles U_eff correctly).
        U_rot = np.full((ny, nx, 3, 3), np.nan)
        U_rot[valid] = Rotation.from_matrix(U_src[valid]).as_matrix()

        ops   = _symmetry_ops_np(symmetry)   # (N_sym, 3, 3)

        # Accumulate per-pixel misorientation sums and neighbor counts.
        angle_sum = np.zeros((ny, nx), dtype=np.float64)
        count     = np.zeros((ny, nx), dtype=np.int32)

        # All neighbor offsets with 1 ≤ Chebyshev distance ≤ order.
        offsets = [
            (diy, dix)
            for diy in range(-order, order + 1)
            for dix in range(-order, order + 1)
            if 1 <= max(abs(diy), abs(dix)) <= order
        ]

        for diy, dix in offsets:
            # Source pixel range: rows/cols that have a valid neighbor at (diy, dix).
            iy0_s = max(0, -diy);  iy1_s = min(ny, ny - diy)
            ix0_s = max(0, -dix);  ix1_s = min(nx, nx - dix)

            IY_s, IX_s = np.meshgrid(
                np.arange(iy0_s, iy1_s),
                np.arange(ix0_s, ix1_s),
                indexing="ij",
            )
            IY_n = IY_s + diy
            IX_n = IX_s + dix

            mask = valid[IY_s, IX_s] & valid[IY_n, IX_n]
            if not mask.any():
                continue

            iy_s = IY_s[mask]; ix_s = IX_s[mask]
            iy_n = IY_n[mask]; ix_n = IX_n[mask]

            Ra = U_rot[iy_s, ix_s]                        # (M, 3, 3)
            Rb = U_rot[iy_n, ix_n]                        # (M, 3, 3)

            # Misorientation: R_mis[m] = Rb[m] @ Ra[m].T
            R_mis = Rb @ Ra.transpose(0, 2, 1)            # (M, 3, 3)

            # ops[s] @ R_mis[m] → (N_sym, M, 3, 3)
            ops_R = np.einsum("sij,mjk->smik", ops, R_mis)

            # trace(ops_R[s,m] @ ops[t].T) for all (s, t, m)
            # = einsum smij, tji -> stm
            traces = np.einsum("smij,tji->stm", ops_R, ops)   # (N_sym, N_sym, M)

            # Minimum angle over all symmetry-equivalent pairs
            cos_ang    = np.clip((traces - 1.0) / 2.0, -1.0, 1.0)
            angles_sym = np.degrees(np.arccos(cos_ang))        # (N_sym, N_sym, M)
            min_ang    = angles_sym.reshape(-1, len(iy_s)).min(axis=0)  # (M,)

            np.add.at(angle_sum, (iy_s, ix_s), min_ang)
            np.add.at(count,     (iy_s, ix_s), 1)

        has_nbrs = count > 0
        kam_map[has_nbrs] = angle_sum[has_nbrs] / count[has_nbrs]

        if not plot:
            return kam_map

        # ── Plot ──────────────────────────────────────────────────────────────
        valid_vals = kam_map[np.isfinite(kam_map)]
        if vmax is None:
            vmax = float(np.percentile(valid_vals, 99)) if len(valid_vals) else 1.0
        vmax = max(float(vmax), float(vmin) + 1e-6)   # prevent blank image when all angles ≈ 0

        extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
        if ax is None:
            _, ax = plt.subplots(figsize=(7, 6))

        imkw = dict(origin="upper", cmap=cmap, vmin=vmin, vmax=vmax)
        if extent is not None:
            imkw.update(extent=extent, aspect="auto")

        im = ax.imshow(kam_map, **imkw)
        plt.colorbar(im, ax=ax, label="KAM (°)")
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_title(
            f"KAM — {self.layer_labels[layer]}  "
            f"(order={order}, {symmetry})"
        )
        return kam_map

    # ── SLURM submission ───────────────────────────────────────────────────────

    @staticmethod
    def _camera_to_dict(camera) -> dict:
        return {
            "dd":           float(camera.dd),
            "xcen":         float(camera.xcen),
            "ycen":         float(camera.ycen),
            "xbet":         float(camera.xbet),
            "xgam":         float(camera.xgam),
            "pixelsize":    float(camera.pixel_mm),
            "n_pix_h":      int(camera.Nh),
            "n_pix_v":      int(camera.Nv),
            "kf_direction": str(camera.kf_direction),
        }

    def _setup_slurm_dirs(self, base_dir: str, sub: str) -> dict:
        dirs = {
            "out":       os.path.join(base_dir, sub),
            "job_meta":  os.path.join(base_dir, "job_meta"),
            "slurm_logs": os.path.join(base_dir, "slurm_logs"),
        }
        for d in dirs.values():
            os.makedirs(d, exist_ok=True)
        return dirs

    def _write_stack_pkl(self, base_dir: str) -> str:
        path = os.path.join(base_dir, "job_meta", "stack.pkl")
        with open(path, "wb") as fh:
            _dill.dump(self.stack, fh)
        return path

    def _submit_jobs(
        self,
        job_name: str,
        worker_module: str,
        meta_json_path: str,
        chunks: list,
        slurm_logs_dir: str,
        *,
        partition: str = "all",
        time: str = "01:00:00",
        mem: str = "4G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        extra_sbatch: "dict | None" = None,
    ) -> list:
        job_ids = []
        for i, chunk in enumerate(chunks):
            indices_str = ",".join(str(fi) for fi in chunk)
            wrap_cmd = (
                f"{python_bin} -m {worker_module} "
                f"--meta-json {meta_json_path} "
                f"--frame-indices {indices_str}"
            )
            sbatch_args = [
                "sbatch",
                f"--job-name={job_name}_{i:04d}",
                f"--partition={partition}",
                f"--time={time}",
                f"--mem={mem}",
                f"--cpus-per-task={cpus_per_task}",
                f"--output={os.path.join(slurm_logs_dir, f'{job_name}_{i:04d}_%j.out')}",
                f"--error={os.path.join(slurm_logs_dir, f'{job_name}_{i:04d}_%j.err')}",
            ]
            if extra_sbatch:
                for k, v in extra_sbatch.items():
                    sbatch_args.append(f"--{k}={v}")
            sbatch_args += ["--wrap", wrap_cmd]

            result = subprocess.run(sbatch_args, capture_output=True, text=True)
            if result.returncode != 0:
                raise RuntimeError(
                    f"sbatch failed for chunk {i}: {result.stderr.strip()}"
                )
            job_id = result.stdout.strip().split()[-1]
            job_ids.append(job_id)
            print(f"  submitted {job_name}_{i:04d} → job {job_id}", flush=True)

        return job_ids

    # ── Simulation-guided segmentation ────────────────────────────────────────

    def submit_guided_segmentation(
        self,
        base_dir: str,
        camera,
        h5_dataset: str,
        mask_path: str,
        *,
        n_jobs: int = 10,
        partition: str = "all",
        time: str = "02:00:00",
        mem: str = "8G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        f2_thresh: float = 1e-4,
        correct_depth: bool = False,
        overwrite: bool = False,
        extra_sbatch: "dict | None" = None,
        **seg_kwargs,
    ) -> list:
        """
        Submit simulation-guided segmentation jobs to SLURM.

        The stack's **current U matrices** (set interactively or from a
        previous fit) are serialised to a pickle and shipped to each job.
        Every worker simulates Laue spots **once** with that fixed orientation
        and uses the predicted positions to drive
        :func:`~nrxrdct.laue.segmentation.simulation_guided_segmentation`
        on its assigned frames.

        This is the right strategy when one orientation estimate is a good
        approximation for the whole map — typically true for well-ordered
        substrate materials.  Results are written to
        ``<base_dir>/seg/frame_?????.h5`` in the same HDF5 format produced by
        :func:`~nrxrdct.laue.segmentation.write_h5_spotsfile`, so the output
        is directly compatible with
        :meth:`run_orientation_local` and :meth:`run_strain_local`.

        Workflow::

            lmap.stack.all_layers[0].U = my_U    # set orientation estimate
            lmap.submit_guided_segmentation(
                "proc/", camera, "1.1/measurement/eiger4m", "mask.npy",
                search_radius=8, min_snr=2.0,
            )
            # Wait for jobs, then:
            lmap.run_orientation_local(camera, seg_dir="proc/seg/", out_dir="proc/ubs/")

        Args:
            base_dir: Processing root directory.  Sub-directories
                ``seg/``, ``slurm_logs/``, and ``job_meta/`` are created
                inside it automatically.
            camera: Detector geometry (``Camera`` object).
            h5_dataset: Dataset path inside ``self.h5_path``, e.g.
                ``'1.1/measurement/eiger4m'``.
            mask_path: Path to a ``.npy`` file containing the boolean
                detector validity mask (``True`` = active pixel).
            n_jobs: Number of SLURM array jobs.  Frames are split evenly.
            partition: SLURM partition name.
            time: SLURM wall-clock limit (``'HH:MM:SS'``).
            mem: Memory per job (e.g. ``'8G'``).
            cpus_per_task: CPU threads per SLURM task.
            python_bin: Python interpreter path on the compute nodes.
            f2_thresh: Structure-factor threshold for
                :func:`~nrxrdct.laue.simulate_laue_stack` (spot
                pre-filter).  Default ``1e-4``.
            correct_depth: Pass ``True`` to depth-correct predicted spot
                positions before guiding the search.
            overwrite: If ``True``, re-segment frames that already have an
                output file.
            extra_sbatch: Additional ``--key=value`` sbatch arguments.
            **seg_kwargs: Forwarded to
                :func:`~nrxrdct.laue.segmentation.simulation_guided_segmentation`:
                ``psf_sigma``, ``search_radius``, ``min_distance``,
                ``min_snr``, ``bg_sigma``, ``d``, ``r_squared_min``,
                ``include_unfitted``, ``fit_spots``.

        Returns:
            List of SLURM job ID strings.
        """
        if self.h5_path is None:
            raise ValueError("h5_path not set on this LayeredMap.")

        dirs      = self._setup_slurm_dirs(base_dir, "seg")
        stack_pkl = self._write_stack_pkl(base_dir)

        all_frames = list(range(self.ny * self.nx))
        chunks = [
            list(map(int, c))
            for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
            if len(c) > 0
        ]

        meta = {
            "stack_pkl":     stack_pkl,
            "camera":        self._camera_to_dict(camera),
            "h5_path":       self.h5_path,
            "h5_dataset":    h5_dataset,
            "mask_path":     mask_path,
            "monitor":       self.monitor,
            "seg_dir":       dirs["out"],
            "f2_thresh":     f2_thresh,
            "correct_depth": correct_depth,
            "overwrite":     overwrite,
            **seg_kwargs,
        }
        meta_path = os.path.join(dirs["job_meta"], "guided_seg_meta.json")
        with open(meta_path, "w") as fh:
            json.dump(meta, fh, indent=2)

        job_ids = self._submit_jobs(
            "lm_gseg", "nrxrdct.laue.workers.slurm_guided_seg_worker",
            meta_path, chunks, dirs["slurm_logs"],
            partition=partition, time=time, mem=mem,
            cpus_per_task=cpus_per_task, python_bin=python_bin,
            extra_sbatch=extra_sbatch,
        )
        print(f"Guided segmentation: {len(job_ids)} jobs → {dirs['out']}")
        return job_ids

    def submit_segmentation(
        self,
        base_dir: str,
        h5_path: "str | None" = None,
        h5_dataset: "str | None" = None,
        n_jobs: int = 10,
        *,
        tiff_dir: "str | None" = None,
        partition: str = "all",
        time: str = "01:00:00",
        mem: str = "4G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        mask_path: "str | None" = None,
        method: str = "LoG",
        method_kwargs: "dict | None" = None,
        min_size: int = 3,
        max_size: int = 500,
        gap_exclude: int = 3,
        gap_closing: int = 3,
        bg_sigma: float = 251,
        max_components: int = 1,
        d: int = 10,
        r_squared_min: float = 0.0,
        include_unfitted: bool = False,
        fit_spots: bool = True,
        extra_sbatch: "dict | None" = None,
    ) -> list:
        """
        Submit segmentation jobs to SLURM.

        Peak-list files are written to ``<base_dir>/seg/frame_?????.h5``.
        Pass *seg_dir* to the ``submit_orientation`` / ``submit_strain`` calls
        (defaults to the same path automatically).

        Args:
            base_dir: Root processing directory.
            h5_path: Path to the HDF5 scan file (must be accessible from
                compute nodes).
            h5_dataset: Dataset path inside *h5_path*, e.g.
                ``'1.1/measurement/eiger4m'``.  Mutually exclusive with
                *tiff_dir*; exactly one must be supplied.
            tiff_dir: Path to a directory of ``img_*.tif`` files.
                Mutually exclusive with *h5_dataset*.
            n_jobs: Number of SLURM array jobs.
            method: ``'LoG'``, ``'WTH'``, or ``'HYBRID'``.
            bg_sigma: Gaussian sigma for background estimation (pixels).
            r_squared_min: Minimum Gaussian-fit R² to accept a spot.

        Returns:
            List of SLURM job IDs.
        """
        h5_path = h5_path or self.h5_path
        if h5_path is None and h5_dataset is not None:
            raise ValueError("h5_path not set on the object and not passed as argument.")
        if h5_dataset is None and tiff_dir is None:
            raise ValueError("Provide either h5_dataset or tiff_dir.")
        if h5_dataset is not None and tiff_dir is not None:
            raise ValueError("Provide h5_dataset or tiff_dir, not both.")

        dirs = self._setup_slurm_dirs(base_dir, "seg")
        all_frames = list(range(self.ny * self.nx))
        chunks = [
            list(map(int, c))
            for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
            if len(c) > 0
        ]
        meta = {
            "h5_path":        h5_path,
            "h5_dataset":     h5_dataset,
            "tiff_dir":       tiff_dir,
            "seg_dir":        dirs["out"],
            "mask_path":      mask_path,
            "monitor":        self.monitor,
            "method":         method,
            "method_kwargs":  method_kwargs or {},
            "min_size":       min_size,
            "max_size":       max_size,
            "gap_exclude":    gap_exclude,
            "gap_closing":    gap_closing,
            "bg_sigma":       bg_sigma,
            "max_components": max_components,
            "d":              d,
            "r_squared_min":  r_squared_min,
            "include_unfitted": include_unfitted,
            "fit_spots":      fit_spots,
        }
        meta_path = os.path.join(dirs["job_meta"], "seg_meta.json")
        with open(meta_path, "w") as fh:
            json.dump(meta, fh, indent=2)

        job_ids = self._submit_jobs(
            "lm_seg", "nrxrdct.laue.workers.slurm_seg_worker",
            meta_path, chunks, dirs["slurm_logs"],
            partition=partition, time=time, mem=mem,
            cpus_per_task=cpus_per_task, python_bin=python_bin,
            extra_sbatch=extra_sbatch,
        )
        print(f"Segmentation: {len(job_ids)} jobs → {dirs['out']}")
        return job_ids

    def submit_orientation(
        self,
        base_dir: str,
        camera,
        *,
        seg_dir: "str | None" = None,
        n_jobs: int = 10,
        partition: str = "all",
        time: str = "02:00:00",
        mem: str = "4G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        max_match_px=(30, 10, 3),
        min_matched: int = 5,
        min_match_rate: float = 0.2,
        max_rms_px: "float | None" = None,
        r_squared_min: float = 0.0,
        include_unfitted: bool = False,
        geometry_only: bool = True,
        f2_thresh: float = 1e-6,
        correct_depth: bool = False,
        overwrite: bool = False,
        extra_sbatch: "dict | None" = None,
        **fit_kwargs,
    ) -> list:
        """
        Submit peak-list-based orientation fitting for the full LayeredCrystal
        stack to SLURM.

        Each frame is fitted with :func:`~nrxrdct.laue.fitting.fit_orientation_stack`,
        which finds a single global rotation shared by all layers simultaneously.
        Fitting is staged: ``max_match_px`` is applied as a sequence of decreasing
        matching radii so the optimizer coarsely locks onto the orientation before
        tightening.

        **Workflow**::

            job_ids = lmap.submit_orientation(base_dir, camera, seg_dir="path/to/seg")
            # wait for SLURM jobs to finish
            lmap.collect("path/to/base_dir/layered_ori/")

        Output files are written to ``<base_dir>/layered_ori/frame_?????.npz``.

        Args:
            base_dir: Root directory for all job artefacts.  Sub-directories
                ``layered_ori/``, ``slurm_logs/`` and ``job_meta/`` are created
                automatically.
            camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
            seg_dir: Directory containing ``frame_?????.h5`` segmentation files
                produced by :meth:`segment_frame` or the segmentation workers.
                Defaults to ``<base_dir>/seg``.
            n_jobs: Number of SLURM array jobs.  Frames are split evenly across
                jobs; each job runs all its frames in a ``ProcessPoolExecutor``
                with up to ``cpus_per_task`` workers.
            partition: SLURM partition name.
            time: Wall-clock time limit per job (``HH:MM:SS``).
            mem: Memory limit per job (e.g. ``"4G"``).
            cpus_per_task: CPU cores per job, also the ``ProcessPoolExecutor``
                worker count.  Set to ``> 1`` to parallelise frames within a job.
            python_bin: Python interpreter to invoke on the cluster (e.g.
                ``"python"`` or ``"/path/to/env/bin/python"``).
            max_match_px: Staged matching threshold(s) in pixels.  A sequence
                ``(30, 10, 3)`` runs three successive refinement stages.  Each
                stage uses the previous stage's solution as the starting point.
            min_matched: Minimum number of matched spots required to accept and
                save a result.
            min_match_rate: Minimum fraction of simulated spots that must be
                matched (``n_matched / n_sim``).
            max_rms_px: If set, frames with RMS pixel residual above this value
                are rejected even if ``min_matched`` is satisfied.
            r_squared_min: Minimum Gaussian-fit R² for peaks loaded from the
                segmentation file.  ``0.0`` (default) keeps all peaks including
                those with poor fits.
            include_unfitted: If ``True``, also use peaks that failed Gaussian
                fitting (stored with ``fitted=False`` in the segmentation file).
            geometry_only: If ``True`` (default), precompute the allowed-HKL
                set from structure factors at rest and skip per-spot F² evaluation
                during the fit.  Much faster; disable only if you need exact
                intensity weighting.
            f2_thresh: Structure-factor threshold used when precomputing the
                allowed-HKL set (``geometry_only=True``) or filtering spots
                (``geometry_only=False``).
            correct_depth: Apply depth correction to the pixel projection to
                account for the displacement of the diffracting volume below
                the sample surface.
            overwrite: Re-process frames that already have a result file.
            extra_sbatch: Additional ``#SBATCH`` directives passed verbatim,
                e.g. ``{"account": "myproject", "constraint": "gpu"}``.
            **fit_kwargs: Extra keyword arguments forwarded to
                :func:`~nrxrdct.laue.fitting.fit_orientation_stack`
                (e.g. ``E_min_eV``, ``E_max_eV``, ``source``, ``ftol``).

        Returns:
            List of SLURM job IDs (strings).
        """
        dirs = self._setup_slurm_dirs(base_dir, "layered_ori")
        stack_pkl = self._write_stack_pkl(base_dir)

        meta = {
            "stack_pkl":       stack_pkl,
            "camera":          self._camera_to_dict(camera),
            "seg_dir":         seg_dir or os.path.join(base_dir, "seg"),
            "out_dir":         dirs["out"],
            "max_match_px":    list(max_match_px) if hasattr(max_match_px, "__iter__") else [float(max_match_px)],
            "min_matched":     min_matched,
            "min_match_rate":  min_match_rate,
            "max_rms_px":      max_rms_px,
            "r_squared_min":   r_squared_min,
            "include_unfitted": include_unfitted,
            "geometry_only":   geometry_only,
            "f2_thresh":       f2_thresh,
            "correct_depth":   correct_depth,
            "overwrite":       overwrite,
            **fit_kwargs,
        }
        meta_path = os.path.join(dirs["job_meta"], "layered_orient_meta.json")
        with open(meta_path, "w") as fh:
            json.dump(meta, fh, indent=2)

        all_frames = list(range(self.ny * self.nx))
        chunks = [
            list(map(int, c))
            for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
            if len(c) > 0
        ]

        return self._submit_jobs(
            "lm_ori",
            "nrxrdct.laue.workers.slurm_layered_orient_worker",
            meta_path, chunks, dirs["slurm_logs"],
            partition=partition, time=time, mem=mem,
            cpus_per_task=cpus_per_task, python_bin=python_bin,
            extra_sbatch=extra_sbatch,
        )

    def submit_strain(
        self,
        base_dir: str,
        camera,
        *,
        seg_dir: "str | None" = None,
        orient_dir: "str | None" = None,
        fit_strain: "tuple | None" = None,
        n_jobs: int = 10,
        partition: str = "all",
        time: str = "04:00:00",
        mem: str = "4G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        max_match_px=(10, 3),
        min_matched: int = 5,
        min_match_rate: float = 0.2,
        max_rms_px: "float | None" = None,
        r_squared_min: float = 0.0,
        include_unfitted: bool = False,
        geometry_only: bool = True,
        f2_thresh: float = 1e-6,
        correct_depth: bool = False,
        overwrite: bool = False,
        extra_sbatch: "dict | None" = None,
        **fit_kwargs,
    ) -> list:
        """
        Submit simultaneous orientation + per-layer strain fitting to SLURM.

        Each frame is fitted with
        :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack`, which
        refines a single shared global rotation (3 parameters) and an
        independent strain tensor for every layer (``N_layers × len(fit_strain)``
        parameters).  Because the parameter count grows with the number of
        layers, this is inherently slower than single-crystal strain fitting;
        reducing ``fit_strain`` to only the physically expected components is
        the main lever to control cost.

        **Workflow**::

            job_ids = lmap.submit_strain(base_dir, camera, seg_dir="path/to/seg",
                                         fit_strain=("e_xx", "e_yy", "e_zz"))
            # wait for SLURM jobs to finish
            lmap.collect("path/to/base_dir/layered_strain/")

        Output files are written to ``<base_dir>/layered_strain/frame_?????.npz``.
        Each file contains ``R_global``, ``rotvec``, ``U_layers``,
        ``U_eff_layers``, ``strain_tensors``, ``strain_voigts``, ``rms_px``,
        ``n_matched``, ``match_rate``, and ``n_sim``.

        Args:
            base_dir: Root directory for all job artefacts.
            camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
            seg_dir: Directory containing ``frame_?????.h5`` segmentation files.
                Defaults to ``<base_dir>/seg``.
            fit_strain: Strain tensor components to refine, e.g.
                ``("e_xx", "e_yy", "e_zz")`` for diagonal/biaxial strain only.
                ``None`` (default) refines all six independent components
                ``(e_xx, e_yy, e_zz, e_xy, e_xz, e_yz)``.  Reducing this set
                is the most effective way to speed up the fit for systems with
                known symmetry constraints.
            n_jobs: Number of SLURM array jobs.
            partition: SLURM partition name.
            time: Wall-clock time limit per job (``HH:MM:SS``).  Strain fitting
                is significantly slower than orientation-only; increase if jobs
                time out.
            mem: Memory limit per job.
            cpus_per_task: CPU cores per job / ``ProcessPoolExecutor`` workers.
            python_bin: Python interpreter on the cluster.
            max_match_px: Staged matching threshold(s) in pixels.  A sequence
                ``(10, 3)`` runs two stages.
            min_matched: Minimum matched spots to save a result.
            min_match_rate: Minimum fraction of simulated spots matched.
            max_rms_px: Maximum RMS pixel residual to accept.
            r_squared_min: Minimum peak R² for loading from segmentation files.
                ``0.0`` (default) keeps all peaks.
            include_unfitted: Include peaks that failed Gaussian fitting.
            geometry_only: Skip per-spot F² evaluation during fitting by using
                a precomputed allowed-HKL set.  Recommended (default ``True``).
            f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
            correct_depth: Apply depth correction to pixel projections.
            overwrite: Re-process frames that already have a result file.
            extra_sbatch: Additional ``#SBATCH`` directives.
            **fit_kwargs: Extra keyword arguments forwarded to
                :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack`
                (e.g. ``E_min_eV``, ``E_max_eV``, ``strain_scale``, ``ftol``).

        Returns:
            List of SLURM job IDs (strings).
        """
        from .fitting import _STRAIN_ALL
        _fit_strain = list(fit_strain) if fit_strain is not None else list(_STRAIN_ALL)

        dirs = self._setup_slurm_dirs(base_dir, "layered_strain")
        stack_pkl = self._write_stack_pkl(base_dir)

        meta = {
            "stack_pkl":       stack_pkl,
            "camera":          self._camera_to_dict(camera),
            "seg_dir":         seg_dir or os.path.join(base_dir, "seg"),
            "orient_dir":      orient_dir,
            "out_dir":         dirs["out"],
            "fit_strain":      _fit_strain,
            "max_match_px":    list(max_match_px) if hasattr(max_match_px, "__iter__") else [float(max_match_px)],
            "min_matched":     min_matched,
            "min_match_rate":  min_match_rate,
            "max_rms_px":      max_rms_px,
            "r_squared_min":   r_squared_min,
            "include_unfitted": include_unfitted,
            "geometry_only":   geometry_only,
            "f2_thresh":       f2_thresh,
            "correct_depth":   correct_depth,
            "overwrite":       overwrite,
            **fit_kwargs,
        }
        meta_path = os.path.join(dirs["job_meta"], "layered_strain_meta.json")
        with open(meta_path, "w") as fh:
            json.dump(meta, fh, indent=2)

        all_frames = list(range(self.ny * self.nx))
        chunks = [
            list(map(int, c))
            for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
            if len(c) > 0
        ]

        return self._submit_jobs(
            "lm_strain",
            "nrxrdct.laue.workers.slurm_layered_strain_worker",
            meta_path, chunks, dirs["slurm_logs"],
            partition=partition, time=time, mem=mem,
            cpus_per_task=cpus_per_task, python_bin=python_bin,
            extra_sbatch=extra_sbatch,
        )

    def submit_image_orientation(
        self,
        base_dir: str,
        camera,
        h5_path: "str | None" = None,
        h5_dataset: "str | None" = None,
        *,
        n_jobs: int = 10,
        partition: str = "all",
        time: str = "02:00:00",
        mem: str = "8G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        geometry_only: bool = True,
        f2_thresh: float = 1e-6,
        correct_depth: bool = False,
        overwrite: bool = False,
        extra_sbatch: "dict | None" = None,
        **fit_kwargs,
    ) -> list:
        """
        Submit image-based orientation refinement to SLURM.

        Unlike :meth:`submit_orientation`, which works from a pre-extracted
        peak list, this method refines the orientation directly from the raw
        detector image using
        :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack`.
        The fit correlates a simulated spot pattern against the measured
        intensity image, which is useful when segmentation is difficult or
        unreliable.

        Requires ``self.h5_path`` to be set on the object, or an explicit
        ``h5_path`` argument.

        **Workflow**::

            lmap.h5_path = "/data/scan.h5"
            job_ids = lmap.submit_image_orientation(
                base_dir, camera, h5_dataset="1.1/measurement/eiger4m"
            )
            # wait for SLURM jobs to finish
            lmap.collect("path/to/base_dir/layered_img_ori/")

        Output files are written to ``<base_dir>/layered_img_ori/frame_?????.npz``.
        Each file contains ``R_global``, ``rotvec``, ``U_layers``, ``score``,
        ``score0``, and ``n_sim``.

        Args:
            base_dir: Root directory for all job artefacts.
            camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
            h5_path: Path to the HDF5 scan file.  Defaults to ``self.h5_path``.
            h5_dataset: Dataset path within the HDF5 file, e.g.
                ``"1.1/measurement/eiger4m"``.  Required.
            n_jobs: Number of SLURM array jobs.
            partition: SLURM partition name.
            time: Wall-clock time limit per job (``HH:MM:SS``).
            mem: Memory limit per job.  Image-based fitting loads full detector
                frames; increase if jobs are killed for OOM.
            cpus_per_task: CPU cores per job / ``ProcessPoolExecutor`` workers.
            python_bin: Python interpreter on the cluster.
            geometry_only: Use precomputed allowed-HKL set instead of computing
                structure factors per spot.  Strongly recommended (default ``True``).
            f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
            correct_depth: Apply depth correction to pixel projections.
            overwrite: Re-process frames that already have a result file.
            extra_sbatch: Additional ``#SBATCH`` directives.
            **fit_kwargs: Extra keyword arguments forwarded to
                :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack`
                (e.g. ``E_min_eV``, ``E_max_eV``, ``kernel_sigma``,
                ``bg_sigma``, ``max_angle_deg``).

        Returns:
            List of SLURM job IDs (strings).
        """
        h5_path = h5_path or self.h5_path
        if h5_path is None:
            raise ValueError("h5_path not set on the object and not passed as argument.")
        if h5_dataset is None:
            raise ValueError("h5_dataset is required.")
        dirs = self._setup_slurm_dirs(base_dir, "layered_img_ori")
        stack_pkl = self._write_stack_pkl(base_dir)

        meta = {
            "stack_pkl":    stack_pkl,
            "camera":       self._camera_to_dict(camera),
            "h5_path":      h5_path,
            "h5_dataset":   h5_dataset,
            "out_dir":      dirs["out"],
            "geometry_only":  geometry_only,
            "f2_thresh":      f2_thresh,
            "correct_depth":  correct_depth,
            "overwrite":      overwrite,
            **fit_kwargs,
        }
        meta_path = os.path.join(dirs["job_meta"], "layered_img_orient_meta.json")
        with open(meta_path, "w") as fh:
            json.dump(meta, fh, indent=2)

        all_frames = list(range(self.ny * self.nx))
        chunks = [
            list(map(int, c))
            for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
            if len(c) > 0
        ]

        return self._submit_jobs(
            "lm_img_ori",
            "nrxrdct.laue.workers.slurm_layered_img_orient_worker",
            meta_path, chunks, dirs["slurm_logs"],
            partition=partition, time=time, mem=mem,
            cpus_per_task=cpus_per_task, python_bin=python_bin,
            extra_sbatch=extra_sbatch,
        )

    def submit_strain_image(
        self,
        base_dir: str,
        camera,
        h5_path: "str | None" = None,
        h5_dataset: "str | None" = None,
        *,
        fit_strain: "tuple | None" = None,
        n_jobs: int = 10,
        partition: str = "all",
        time: str = "04:00:00",
        mem: str = "8G",
        cpus_per_task: int = 1,
        python_bin: str = "python",
        geometry_only: bool = True,
        f2_thresh: float = 1e-6,
        correct_depth: bool = False,
        overwrite: bool = False,
        extra_sbatch: "dict | None" = None,
        **fit_kwargs,
    ) -> list:
        """
        Submit image-based orientation + per-layer strain refinement to SLURM.

        Combines image-based fitting with full per-layer strain refinement using
        :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`.  This is the
        most computationally intensive submit method: it fits a shared global
        rotation plus an independent strain tensor per layer directly against
        the raw detector image.

        Use this method when you want strain maps without a prior segmentation
        step, or as a refinement stage after :meth:`submit_image_orientation`.

        **Workflow**::

            lmap.h5_path = "/data/scan.h5"
            job_ids = lmap.submit_strain_image(
                base_dir, camera,
                h5_dataset="1.1/measurement/eiger4m",
                fit_strain=("e_xx", "e_yy", "e_zz"),
            )
            # wait for SLURM jobs to finish
            lmap.collect("path/to/base_dir/layered_img_strain/")

        Output files are written to ``<base_dir>/layered_img_strain/frame_?????.npz``.
        Each file contains ``R_global``, ``rotvec``, ``U_layers``,
        ``U_eff_layers``, ``strain_tensors``, ``strain_voigts``, ``score``,
        ``score0``, and ``n_sim``.

        Args:
            base_dir: Root directory for all job artefacts.
            camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
            h5_path: Path to the HDF5 scan file.  Defaults to ``self.h5_path``.
            h5_dataset: Dataset path within the HDF5 file.  Required.
            fit_strain: Strain tensor components to refine, e.g.
                ``("e_xx", "e_yy", "e_zz")``.  ``None`` refines all six.
                Reducing this set is the most effective way to lower compute cost.
            n_jobs: Number of SLURM array jobs.
            partition: SLURM partition name.
            time: Wall-clock time limit per job.  This method is the slowest of
                the four; budget generously.
            mem: Memory limit per job.
            cpus_per_task: CPU cores per job / ``ProcessPoolExecutor`` workers.
            python_bin: Python interpreter on the cluster.
            geometry_only: Use precomputed allowed-HKL set.  Strongly recommended
                (default ``True``).
            f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
            correct_depth: Apply depth correction to pixel projections.
            overwrite: Re-process frames that already have a result file.
            extra_sbatch: Additional ``#SBATCH`` directives.
            **fit_kwargs: Extra keyword arguments forwarded to
                :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`
                (e.g. ``E_min_eV``, ``E_max_eV``, ``kernel_sigma``,
                ``strain_scale``, ``max_angle_deg``).

        Returns:
            List of SLURM job IDs (strings).
        """
        h5_path = h5_path or self.h5_path
        if h5_path is None:
            raise ValueError("h5_path not set on the object and not passed as argument.")
        if h5_dataset is None:
            raise ValueError("h5_dataset is required.")
        from .fitting import _STRAIN_ALL
        _fit_strain = list(fit_strain) if fit_strain is not None else list(_STRAIN_ALL)

        dirs = self._setup_slurm_dirs(base_dir, "layered_img_strain")
        stack_pkl = self._write_stack_pkl(base_dir)

        meta = {
            "stack_pkl":    stack_pkl,
            "camera":       self._camera_to_dict(camera),
            "h5_path":      h5_path,
            "h5_dataset":   h5_dataset,
            "out_dir":      dirs["out"],
            "fit_strain":   _fit_strain,
            "geometry_only":  geometry_only,
            "f2_thresh":      f2_thresh,
            "correct_depth":  correct_depth,
            "overwrite":      overwrite,
            **fit_kwargs,
        }
        meta_path = os.path.join(dirs["job_meta"], "layered_img_strain_meta.json")
        with open(meta_path, "w") as fh:
            json.dump(meta, fh, indent=2)

        all_frames = list(range(self.ny * self.nx))
        chunks = [
            list(map(int, c))
            for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
            if len(c) > 0
        ]

        return self._submit_jobs(
            "lm_img_strain",
            "nrxrdct.laue.workers.slurm_layered_img_strain_worker",
            meta_path, chunks, dirs["slurm_logs"],
            partition=partition, time=time, mem=mem,
            cpus_per_task=cpus_per_task, python_bin=python_bin,
            extra_sbatch=extra_sbatch,
        )

    # ── Repr ──────────────────────────────────────────────────────────────────

    def __repr__(self) -> str:
        n_fitted = int(np.sum(self.n_matched >= 0))
        return (
            f"LayeredMap(ny={self.ny}, nx={self.nx}, "
            f"n_layers={self.n_layers}, "
            f"fitted={n_fitted}/{self.ny * self.nx})"
        )

collect

collect(out_dir: str) -> int

Load all frame_?????.npz files written by the run_*_local methods into the map arrays.

Returns the number of frames successfully loaded.

Source code in src/nrxrdct/laue/layered_map.py
def collect(self, out_dir: str) -> int:
    """
    Load all ``frame_?????.npz`` files written by the ``run_*_local``
    methods into the map arrays.

    Returns the number of frames successfully loaded.
    """
    files = sorted(glob.glob(os.path.join(out_dir, "frame_?????.npz")))
    n_ok  = 0
    for path in files:
        frame_idx = int(os.path.basename(path)[6:11])
        iy, ix = self.map_index(frame_idx)
        if iy >= self.ny or ix >= self.nx:
            continue
        try:
            d = np.load(path, allow_pickle=False)
        except Exception as exc:
            print(f"  ✗  {path}: {exc}", flush=True)
            continue

        self.R_global[iy, ix]  = d["R_global"]
        self.rotvec[iy, ix]    = d["rotvec"]
        self.U[:, iy, ix]      = d["U_layers"]

        if "rms_px" in d:
            self.rms_px[iy, ix]     = float(d["rms_px"])
            self.mean_px[iy, ix]    = float(d["mean_px"])
            self.n_matched[iy, ix]  = int(d["n_matched"])
            self.match_rate[iy, ix] = float(d["match_rate"])
            self.cost[iy, ix]       = float(d["cost"])
        if "score" in d:
            self.score[iy, ix]  = float(d["score"])
            self.score0[iy, ix] = float(d["score0"])
        if "n_sim" in d:
            self.n_sim[iy, ix] = int(d["n_sim"])

        if "strain_tensors" in d:
            eps_arr = d["strain_tensors"]   # (n_layers, 3, 3)
            self.U_eff[:, iy, ix]           = d["U_eff_layers"]
            self.strain_tensor[:, iy, ix]   = eps_arr
            self.strain_voigt[:, iy, ix]    = d["strain_voigts"]
            for li in range(self.n_layers):
                eps = eps_arr[li]
                self.strain_tensor_deviatoric[li, iy, ix] = (
                    eps - np.trace(eps) / 3.0 * np.eye(3)
                )

        n_ok += 1

    print(f"collect: {n_ok}/{len(files)} frames loaded from {out_dir!r}",
          flush=True)
    return n_ok

disorientation_map

disorientation_map(layer_a: int, layer_b: int, *, symmetry: str = 'cubic', symmetry_b: 'str | None' = None, use_eff: bool = False, motor_x: 'str | None' = None, motor_y: 'str | None' = None, cmap: str = 'inferno', vmin: float = 0.0, vmax: 'float | None' = None, plot: bool = True, ax=None) -> np.ndarray

Compute the per-pixel disorientation angle between two stack layers.

The misorientation between the two layers is minimised over all pairs of point-group symmetry operators (the same algorithm as :func:~nrxrdct.laue.simulation.disorientation) and the result is the fundamental zone disorientation angle — the smallest rotation that maps one layer's orientation to the other's, accounting for crystal symmetry.

Both orientation matrices are first projected onto SO(3) (via SVD), so U_eff matrices (which carry a small strain factor) are handled correctly.

Parameters:
  • layer_a (int) –

    Index of the first layer (e.g. the substrate/buffer).

  • layer_b (int) –

    Index of the second layer (e.g. the film).

  • symmetry (str, default: 'cubic' ) –

    Point-group symmetry for layer_a (and layer_b if symmetry_b is None). One of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic'.

  • symmetry_b ('str | None', default: None ) –

    Point-group symmetry for layer_b. If None (default), symmetry is used for both layers. Set a different value for heterostructures with different crystal systems (e.g. cubic substrate + hexagonal film).

  • use_eff (bool, default: False ) –

    If True, use U_eff (strained orientation) instead of the pure-rotation U. U_eff is only available after a strain fit; falls back silently to U if not set.

  • motor_x, motor_y –

    Motor names for physical axis labels on the plot.

  • cmap (str, default: 'inferno' ) –

    Matplotlib colormap for the angle map. Default 'inferno'.

  • vmin (float, default: 0.0 ) –

    Minimum value for the colorscale (degrees). Default 0.

  • vmax ('float | None', default: None ) –

    Maximum value for the colorscale. None uses the 99th percentile of the valid pixel values.

  • plot (bool, default: True ) –

    If True (default), draw the map. Set False to only compute and return the array.

  • ax –

    Existing matplotlib Axes to draw into. A new figure is created if None.

Returns:
  • angle_map( (ny, nx) float64 ndarray ) –

    Disorientation angle in degrees at each pixel. Pixels where either layer has no valid orientation are NaN.

Source code in src/nrxrdct/laue/layered_map.py
def disorientation_map(
    self,
    layer_a: int,
    layer_b: int,
    *,
    symmetry: str = "cubic",
    symmetry_b: "str | None" = None,
    use_eff: bool = False,
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    cmap: str = "inferno",
    vmin: float = 0.0,
    vmax: "float | None" = None,
    plot: bool = True,
    ax=None,
) -> np.ndarray:
    """
    Compute the per-pixel disorientation angle between two stack layers.

    The misorientation between the two layers is minimised over all pairs
    of point-group symmetry operators (the same algorithm as
    :func:`~nrxrdct.laue.simulation.disorientation`) and the result is
    the **fundamental zone disorientation angle** — the smallest rotation
    that maps one layer's orientation to the other's, accounting for
    crystal symmetry.

    Both orientation matrices are first projected onto SO(3) (via SVD),
    so ``U_eff`` matrices (which carry a small strain factor) are handled
    correctly.

    Args:
        layer_a: Index of the first layer (e.g. the substrate/buffer).
        layer_b: Index of the second layer (e.g. the film).
        symmetry: Point-group symmetry for *layer_a* (and *layer_b* if
            *symmetry_b* is ``None``).  One of ``'cubic'``, ``'hexagonal'``,
            ``'tetragonal'``, ``'orthorhombic'``.
        symmetry_b: Point-group symmetry for *layer_b*.  If ``None``
            (default), *symmetry* is used for both layers.  Set a
            different value for heterostructures with different crystal
            systems (e.g. cubic substrate + hexagonal film).
        use_eff: If ``True``, use ``U_eff`` (strained orientation) instead
            of the pure-rotation ``U``.  ``U_eff`` is only available after
            a strain fit; falls back silently to ``U`` if not set.
        motor_x, motor_y: Motor names for physical axis labels on the plot.
        cmap: Matplotlib colormap for the angle map.  Default ``'inferno'``.
        vmin: Minimum value for the colorscale (degrees).  Default ``0``.
        vmax: Maximum value for the colorscale.  ``None`` uses the 99th
            percentile of the valid pixel values.
        plot: If ``True`` (default), draw the map.  Set ``False`` to only
            compute and return the array.
        ax: Existing matplotlib ``Axes`` to draw into.  A new figure is
            created if ``None``.

    Returns:
        angle_map ((ny, nx) float64 ndarray): Disorientation angle in
            degrees at each pixel.  Pixels where either layer has no valid
            orientation are ``NaN``.
    """
    from .simulation import _symmetry_ops_np

    _sym_b = symmetry_b if symmetry_b is not None else symmetry

    # Choose U or U_eff
    if use_eff and not np.all(np.isnan(self.U_eff)):
        U_src = self.U_eff
    else:
        U_src = self.U

    Ua = U_src[layer_a]   # (ny, nx, 3, 3)
    Ub = U_src[layer_b]   # (ny, nx, 3, 3)

    # Valid mask: both layers must have a fitted orientation
    valid = (
        ~np.any(np.isnan(Ua), axis=(-2, -1)) &
        ~np.any(np.isnan(Ub), axis=(-2, -1))
    )

    ny, nx = self.ny, self.nx
    angle_map = np.full((ny, nx), np.nan)

    if not valid.any():
        if plot:
            if ax is None:
                _, ax = plt.subplots(figsize=(7, 6))
            ax.set_title(
                f"Disorientation — layers {self.layer_labels[layer_a]} / "
                f"{self.layer_labels[layer_b]} (no data)"
            )
        return angle_map

    # Flatten to (M, 3, 3) for valid pixels only
    idx   = np.argwhere(valid)           # (M, 2)
    iy_v  = idx[:, 0]
    ix_v  = idx[:, 1]
    Ua_v  = Ua[iy_v, ix_v]              # (M, 3, 3)
    Ub_v  = Ub[iy_v, ix_v]              # (M, 3, 3)

    # Project to SO(3) — handles strained U_eff correctly
    Ra = Rotation.from_matrix(Ua_v).as_matrix()   # (M, 3, 3)
    Rb = Rotation.from_matrix(Ub_v).as_matrix()   # (M, 3, 3)

    # Raw misorientation per pixel: R_mis = Rb @ Ra.T
    R_mis = Rb @ Ra.transpose(0, 2, 1)            # (M, 3, 3)

    # Symmetry operators for both layers
    ops_a = _symmetry_ops_np(symmetry)             # (Na, 3, 3)
    ops_b = _symmetry_ops_np(_sym_b)               # (Nb, 3, 3)

    # Apply operators: S_a @ R_mis @ S_b.T for all (S_a, S_b) pairs.
    #   ops_a_R[s, m] = ops_a[s] @ R_mis[m]  →  (Na, M, 3, 3)
    ops_a_R = np.einsum("sij,mjk->smik", ops_a, R_mis)

    #   candidates[sa, sb, m] = ops_a_R[sa, m] @ ops_b[sb].T
    #   broadcast: ops_a_R[:, None]  (Na, 1,  M, 3, 3)
    #            @ ops_b.T[None, :, None]  (1, Nb, 1, 3, 3)
    ops_b_T = ops_b.transpose(0, 2, 1)            # (Nb, 3, 3)
    candidates = (
        ops_a_R[:, None] @ ops_b_T[None, :, None]
    )                                              # (Na, Nb, M, 3, 3)

    # Trace → angle for every candidate
    traces = (
        candidates[:, :, :, 0, 0] +
        candidates[:, :, :, 1, 1] +
        candidates[:, :, :, 2, 2]
    )                                              # (Na, Nb, M)

    # Flatten symmetry pairs → (Na*Nb, M), find minimum angle per pixel
    traces_flat  = traces.reshape(-1, len(iy_v))   # (Na*Nb, M)
    cos_half_ang = np.clip((traces_flat - 1.0) / 2.0, -1.0, 1.0)
    angles       = np.degrees(np.arccos(cos_half_ang))   # (Na*Nb, M)
    min_angles   = angles.min(axis=0)              # (M,)

    angle_map[iy_v, ix_v] = min_angles

    if not plot:
        return angle_map

    # ── Plot ──────────────────────────────────────────────────────────────
    if vmax is None:
        valid_vals = min_angles[np.isfinite(min_angles)]
        vmax = float(np.percentile(valid_vals, 99)) if len(valid_vals) else 1.0

    extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
    if ax is None:
        _, ax = plt.subplots(figsize=(7, 6))

    imkw = dict(origin="upper", cmap=cmap, vmin=vmin, vmax=vmax)
    if extent is not None:
        imkw.update(extent=extent, aspect="auto")

    im = ax.imshow(angle_map, **imkw)
    plt.colorbar(im, ax=ax, label="Disorientation (°)")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(
        f"Disorientation — {self.layer_labels[layer_a]}"
        f" / {self.layer_labels[layer_b]}"
    )
    return angle_map

frame_index

frame_index(iy: int, ix: int) -> int

Flat frame index for pixel (iy, ix).

Source code in src/nrxrdct/laue/layered_map.py
def frame_index(self, iy: int, ix: int) -> int:
    """Flat frame index for pixel ``(iy, ix)``."""
    return iy * self.nx + ix

get_result

get_result(iy: int, ix: int)

Return the cached result object for pixel (iy, ix), or None.

Source code in src/nrxrdct/laue/layered_map.py
def get_result(self, iy: int, ix: int):
    """Return the cached result object for pixel ``(iy, ix)``, or ``None``."""
    return self._results[iy][ix]

inspect_frame

inspect_frame(camera, frame_idx: int, *, h5_path: 'str | None' = None, h5_dataset: str = '1.1/measurement/eiger4m', tiff_dir: 'str | None' = None, seg_dir: 'str | None' = None, r_squared_min: float = 0.0, include_unfitted: bool = True, E_min_eV: float = 5000, E_max_eV: float = 27000, f2_thresh: float = 0.0001, top_n_sim: 'int | None' = None, max_match_dist: float = 5.0, use_eff: bool = True, figsize: tuple = (14, 6))

Display the diffraction image for frame_idx overlaid with simulated spots from all stack layers and (optionally) the measured segmented spots.

The fitted orientations stored in U_eff (or U when strain is unavailable) are temporarily applied to the stack before simulating.

Parameters:
  • camera –

    Detector geometry.

  • frame_idx (int) –

    Flat frame index.

  • h5_path ('str | None', default: None ) –

    Path to the HDF5 scan file (mutually exclusive with tiff_dir).

  • h5_dataset (str, default: '1.1/measurement/eiger4m' ) –

    Dataset path inside h5_path.

  • tiff_dir ('str | None', default: None ) –

    Directory of TIFF frames (mutually exclusive with h5_path).

  • seg_dir ('str | None', default: None ) –

    Directory containing frame_?????.h5 segmentation files. When provided, the measured peaklist is loaded and overlaid.

  • r_squared_min (float, default: 0.0 ) –

    Minimum Gaussian fit R² to accept a spot from the seg file (default 0.0 — accept all).

  • include_unfitted (bool, default: True ) –

    Include spots whose Gaussian fit failed (default True).

  • use_eff (bool, default: True ) –

    If True (default), use U_eff (strained) when available; otherwise use U.

Source code in src/nrxrdct/laue/layered_map.py
def inspect_frame(
    self,
    camera,
    frame_idx: int,
    *,
    h5_path: "str | None" = None,
    h5_dataset: str = "1.1/measurement/eiger4m",
    tiff_dir: "str | None" = None,
    seg_dir: "str | None" = None,
    r_squared_min: float = 0.0,
    include_unfitted: bool = True,
    E_min_eV: float = 5_000,
    E_max_eV: float = 27_000,
    f2_thresh: float = 1e-4,
    top_n_sim: "int | None" = None,
    max_match_dist: float = 5.0,
    use_eff: bool = True,
    figsize: tuple = (14, 6),
):
    """
    Display the diffraction image for *frame_idx* overlaid with simulated
    spots from all stack layers and (optionally) the measured segmented spots.

    The fitted orientations stored in ``U_eff`` (or ``U`` when strain is
    unavailable) are temporarily applied to the stack before simulating.

    Args:
        camera: Detector geometry.
        frame_idx: Flat frame index.
        h5_path: Path to the HDF5 scan file (mutually exclusive with
            *tiff_dir*).
        h5_dataset: Dataset path inside *h5_path*.
        tiff_dir: Directory of TIFF frames (mutually exclusive with
            *h5_path*).
        seg_dir: Directory containing ``frame_?????.h5`` segmentation files.
            When provided, the measured peaklist is loaded and overlaid.
        r_squared_min: Minimum Gaussian fit R² to accept a spot from the
            seg file (default ``0.0`` — accept all).
        include_unfitted: Include spots whose Gaussian fit failed
            (default ``True``).
        use_eff: If ``True`` (default), use ``U_eff`` (strained) when
            available; otherwise use ``U``.
    """
    from .simulation import simulate_laue_stack, precompute_allowed_hkl
    from .laue_plotting import plot_measured_vs_simulated

    iy, ix = self.map_index(frame_idx)

    # Load detector image
    image = None
    if h5_path is not None:
        with h5py.File(h5_path, "r") as hf:
            image = hf[h5_dataset][frame_idx].astype(np.float32)
    elif tiff_dir is not None:
        import skimage.io
        path  = os.path.join(tiff_dir, f"frame_{frame_idx:05d}.tif")
        image = skimage.io.imread(path).astype(np.float32)

    # Load measured peaklist from seg file if available
    peaklist = np.empty((0, 9), dtype=np.float32)
    if seg_dir is not None:
        seg_path = os.path.join(seg_dir, f"frame_{frame_idx:05d}.h5")
        if os.path.exists(seg_path):
            try:
                from .segmentation import convert_spotsfile2peaklist
                peaklist = convert_spotsfile2peaklist(
                    seg_path,
                    r_squared_min=r_squared_min,
                    include_unfitted=include_unfitted,
                )
            except Exception as exc:
                print(f"  ✗ could not load seg file: {exc}", flush=True)
        else:
            print(f"  no seg file for frame {frame_idx}", flush=True)

    # Precompute allowed HKL per unique crystal using the unit-cell |F|²
    # threshold.  This is the same filter used by the fitting functions and
    # correctly removes weak reflections before the simulation.
    allowed_hkl: dict = {}
    for _layer in self.stack.all_layers:
        _cid = id(_layer.crystal)
        if _cid not in allowed_hkl:
            allowed_hkl[_cid] = precompute_allowed_hkl(
                _layer.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
            )

    # Choose U or U_eff
    U_src = self.U_eff if (use_eff and not np.all(np.isnan(self.U_eff[:, iy, ix]))) \
            else self.U

    # Apply fitted orientations to the stack (restore after)
    saved_U = [l.U.copy() for l in self.stack.all_layers]
    try:
        for li, layer in enumerate(self.stack.all_layers):
            if not np.any(np.isnan(U_src[li, iy, ix])):
                layer.U = U_src[li, iy, ix].copy()

        spots = simulate_laue_stack(
            self.stack, camera,
            E_min_eV=E_min_eV, E_max_eV=E_max_eV,
            geometry_only=True,
            allowed_hkl=allowed_hkl,
            verbose=False,
        )
        if top_n_sim is not None:
            spots = spots[:top_n_sim]
    finally:
        for layer, U0 in zip(self.stack.all_layers, saved_U):
            layer.U = U0

    fig = plot_measured_vs_simulated(
        peaklist,
        spots,
        image=image,
        camera=camera,
        max_match_dist=max_match_dist,
        figsize=figsize,
    )
    axes = fig.axes
    fig.suptitle(
        f"Frame {frame_idx}  [{iy}, {ix}]  —  LayeredMap",
        fontsize=11,
    )
    return fig, axes

load classmethod

load(path: str, stack) -> 'LayeredMap'

Load a :class:LayeredMap from path.

stack must be the same :class:~nrxrdct.laue.layers.LayeredCrystal used during fitting (supplies the layer crystal objects).

Returns:
  • 'LayeredMap' –

    LayeredMap with all per-pixel arrays restored.

Source code in src/nrxrdct/laue/layered_map.py
@classmethod
def load(cls, path: str, stack) -> "LayeredMap":
    """
    Load a :class:`LayeredMap` from *path*.

    *stack* must be the same
    :class:`~nrxrdct.laue.layers.LayeredCrystal` used during fitting
    (supplies the layer crystal objects).

    Returns:
        LayeredMap with all per-pixel arrays restored.
    """
    with h5py.File(path, "r") as hf:
        meta     = hf["meta"]
        ny       = int(meta.attrs["ny"])
        nx       = int(meta.attrs["nx"])
        h5_path  = str(meta.attrs.get("h5_path", "")) or None
        entry    = str(meta.attrs.get("entry", "1.1"))

        obj = cls(ny=ny, nx=nx, stack=stack, h5_path=h5_path, entry=entry)

        for name in (
            "R_global", "rotvec",
            "U", "U_eff",
            "rms_px", "mean_px", "n_matched", "match_rate",
            "cost", "n_sim", "score", "score0",
            "strain_tensor", "strain_voigt", "strain_tensor_deviatoric",
        ):
            if name in hf:
                setattr(obj, name, hf[name][()])

        if "motors" in hf:
            for name in hf["motors"]:
                obj.motors[name] = hf[f"motors/{name}"][()]

    return obj

load_n_obs_map

load_n_obs_map(seg_dir: str) -> np.ndarray

Return a (ny, nx) map of segmented spot counts (-1 = no file).

Source code in src/nrxrdct/laue/layered_map.py
def load_n_obs_map(self, seg_dir: str) -> np.ndarray:
    """Return a ``(ny, nx)`` map of segmented spot counts (-1 = no file)."""
    import re as _re
    n_obs = np.full((self.ny, self.nx), -1, dtype=int)
    pat = _re.compile(r'^frame_(\d+)\.h5$', _re.IGNORECASE)
    for fname in os.listdir(seg_dir):
        m = pat.match(fname)
        if not m:
            continue
        frame_idx = int(m.group(1))
        iy, ix = self.map_index(frame_idx)
        if iy >= self.ny or ix >= self.nx:
            continue
        fpath = os.path.join(seg_dir, fname)
        try:
            with h5py.File(fpath, "r") as fh:
                if "n_spots" in fh.attrs:
                    n_obs[iy, ix] = int(fh.attrs["n_spots"])
                else:
                    n_obs[iy, ix] = sum(
                        1 for k in fh if k.startswith("spot_")
                    )
        except Exception:
            pass
    return n_obs

map_index

map_index(frame_idx: int) -> tuple[int, int]

Map pixel (iy, ix) for a flat frame index.

Source code in src/nrxrdct/laue/layered_map.py
def map_index(self, frame_idx: int) -> tuple[int, int]:
    """Map pixel ``(iy, ix)`` for a flat frame index."""
    return divmod(frame_idx, self.nx)

plot_hkl_mosaic

plot_hkl_mosaic(camera, hkl: tuple, *, layer: 'int | str | None' = None, use_eff: bool = True, half_window_x: int = 20, half_window_y: int = 20, h5_dataset: 'str | None' = None, tiff_dir: 'str | None' = None, E_min_eV: float = 5000.0, E_max_eV: float = 27000.0, f2_thresh: float = 0.0001, gap_px: int = 2, cmap: str = 'gray', log_scale: bool = True, figsize: 'tuple | None' = None, out_path: 'str | None' = None) -> tuple

Mosaic of one (h, k, l) reflection across the raster scan.

For every map pixel, the stack's fitted orientations (U_eff, or U where strain is unavailable) are temporarily applied to self.stack and the detector position of hkl is simulated. A window of the raw detector image centred on that position is extracted and the windows are tiled on the same (iy, ix) grid as the scan, so spot shape, intensity, and position can be compared across the map at a glance.

Because several layers can diffract the same nominal hkl at slightly different positions (main peak vs. pseudomorphic / relaxed satellites), pass layer to disambiguate — otherwise the brightest matching spot at each pixel is used, which can silently jump between layers across the map.

Parameters:
  • camera (Camera) –

    Detector geometry.

  • hkl (tuple of int) –

    Miller indices (h, k, l) of the reflection to extract.

  • layer (int, str, or None, default: None ) –

    Which layer's version of hkl to track — an index into self.stack.all_layers / self.layer_labels, or a layer label directly. None (default) takes the brightest matching spot regardless of originating layer.

  • use_eff (bool, default: True ) –

    Use U_eff (strained) when available, falling back to U. Default True.

  • half_window_x, half_window_y (int) –

    Half-width / half-height, in pixels, of the window extracted around the simulated spot position. Each extracted tile is (2*half_window_y + 1, 2*half_window_x + 1).

  • h5_dataset (str or None, default: None ) –

    HDF5 dataset path inside self.h5_path for the image stack. Mutually exclusive with tiff_dir; supply exactly one.

  • tiff_dir (str or None, default: None ) –

    Path to a folder of img_<number>.tif files, sorted by embedded number and mapped to 0-based frame indices. Mutually exclusive with h5_dataset.

  • E_min_eV, E_max_eV (float) –

    Energy range used to simulate the reflection's position. Defaults 5000 / 27000 eV.

  • f2_thresh (float, default: 0.0001 ) –

    Structure-factor threshold forwarded to precompute_allowed_hkl. Default 1e-4.

  • gap_px (int, default: 2 ) –

    NaN-filled gap, in pixels, inserted between neighbouring tiles so the grid stays visible. Default 2.

  • cmap (str, default: 'gray' ) –

    Colormap for the mosaic. Default "gray".

  • log_scale (bool, default: True ) –

    Display log1p of the extracted intensity. Default True.

  • figsize (tuple or None, default: None ) –

    Figure size. None (default) scales with the mosaic size.

  • out_path (str or None, default: None ) –

    If given, save the figure to this path.

Returns:
  • fig( Figure ) –
  • ax( Axes ) –
  • mosaic( (ny*(th+gap)-gap, nx*(tw+gap)-gap) ndarray ) –

    The assembled tile grid (th = 2*half_window_y+1, tw = 2*half_window_x+1), NaN wherever a tile — or part of it — could not be extracted (unfitted pixel, reflection off-detector / not excited for the requested layer, or image unavailable).

Source code in src/nrxrdct/laue/layered_map.py
    def plot_hkl_mosaic(
        self,
        camera,
        hkl: tuple,
        *,
        layer: "int | str | None" = None,
        use_eff: bool = True,
        half_window_x: int = 20,
        half_window_y: int = 20,
        h5_dataset: "str | None" = None,
        tiff_dir: "str | None" = None,
        E_min_eV: float = 5_000.0,
        E_max_eV: float = 27_000.0,
        f2_thresh: float = 1e-4,
        gap_px: int = 2,
        cmap: str = "gray",
        log_scale: bool = True,
        figsize: "tuple | None" = None,
        out_path: "str | None" = None,
    ) -> tuple:
        """
        Mosaic of one (h, k, l) reflection across the raster scan.

        For every map pixel, the stack's fitted orientations (`U_eff`, or `U`
        where strain is unavailable) are temporarily applied to `self.stack`
        and the detector position of *hkl* is simulated. A window of the raw
        detector image centred on that position is extracted and the windows
        are tiled on the same `(iy, ix)` grid as the scan, so spot shape,
        intensity, and position can be compared across the map at a glance.

        Because several layers can diffract the same nominal `hkl` at
        slightly different positions (main peak vs. pseudomorphic /
        relaxed satellites), pass *layer* to disambiguate — otherwise the
        brightest matching spot at each pixel is used, which can silently
        jump between layers across the map.

        Args:
            camera (Camera): Detector geometry.
            hkl (tuple of int): Miller indices `(h, k, l)` of the reflection to extract.
            layer (int, str, or None): Which layer's version of *hkl* to track — an index
                into `self.stack.all_layers` / `self.layer_labels`, or a
                layer label directly. `None` (default) takes the brightest
                matching spot regardless of originating layer.
            use_eff (bool): Use `U_eff` (strained) when available, falling back to `U`.
                Default `True`.
            half_window_x, half_window_y (int): Half-width / half-height, in pixels, of the
                window extracted around the simulated spot position. Each
                extracted tile is `(2*half_window_y + 1, 2*half_window_x + 1)`.
            h5_dataset (str or None): HDF5 dataset path inside `self.h5_path` for the image
                stack. Mutually exclusive with *tiff_dir*; supply exactly one.
            tiff_dir (str or None): Path to a folder of `img_<number>.tif` files, sorted by
                embedded number and mapped to 0-based frame indices. Mutually
                exclusive with *h5_dataset*.
            E_min_eV, E_max_eV (float): Energy range used to simulate the reflection's
                position. Defaults `5000` / `27000` eV.
            f2_thresh (float): Structure-factor threshold forwarded to
                `precompute_allowed_hkl`. Default `1e-4`.
            gap_px (int): NaN-filled gap, in pixels, inserted between neighbouring tiles
                so the grid stays visible. Default `2`.
            cmap (str): Colormap for the mosaic. Default `"gray"`.
            log_scale (bool): Display `log1p` of the extracted intensity. Default `True`.
            figsize (tuple or None): Figure size. `None` (default) scales with the mosaic
                size.
            out_path (str or None): If given, save the figure to this path.

        Returns:
            fig (Figure):
            ax (Axes):
            mosaic ((ny*(th+gap)-gap, nx*(tw+gap)-gap) ndarray): The assembled tile grid
                (`th = 2*half_window_y+1`, `tw = 2*half_window_x+1`), `NaN`
                wherever a tile — or part of it — could not be extracted
                (unfitted pixel, reflection off-detector / not excited for
                the requested layer, or image unavailable).
"""
        import re
        from .simulation import simulate_laue_stack, precompute_allowed_hkl

        if (h5_dataset is None) == (tiff_dir is None):
            raise ValueError(
                "plot_hkl_mosaic: supply exactly one of h5_dataset or tiff_dir"
            )

        hkl = tuple(int(v) for v in hkl)
        half_window_x = int(half_window_x)
        half_window_y = int(half_window_y)
        tile_h = 2 * half_window_y + 1
        tile_w = 2 * half_window_x + 1

        layer_label: "str | None" = None
        if layer is not None:
            if isinstance(layer, str):
                layer_label = layer
            else:
                li = int(layer)
                if not (0 <= li < self.n_layers):
                    raise ValueError(
                        f"layer index {li} out of range (0 - {self.n_layers - 1})"
                    )
                layer_label = self.layer_labels[li]

        # Precompute allowed HKL per unique crystal (same as inspect_frame / reindex_frame).
        allowed_hkl: dict = {}
        for _layer in self.stack.all_layers:
            _cid = id(_layer.crystal)
            if _cid not in allowed_hkl:
                allowed_hkl[_cid] = precompute_allowed_hkl(
                    _layer.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
                )

        U_src = self.U_eff if (use_eff and not np.all(np.isnan(self.U_eff))) else self.U

        # ── image loader (same convention as reindex_frame) ────────────────────
        _tiff_index: "list | None" = None

        def _load_image(frame_idx: int) -> "np.ndarray | None":
            nonlocal _tiff_index
            if tiff_dir is not None:
                if _tiff_index is None:
                    pat   = re.compile(r'(\d+)\.tiff?$', re.IGNORECASE)
                    files = []
                    for fname in os.listdir(tiff_dir):
                        m = pat.search(fname)
                        if m:
                            files.append((int(m.group(1)), os.path.join(tiff_dir, fname)))
                    files.sort(key=lambda x: x[0])
                    _tiff_index = [p for _, p in files]
                if frame_idx >= len(_tiff_index):
                    return None
                try:
                    import skimage.io
                    return skimage.io.imread(_tiff_index[frame_idx]).astype(np.float32)
                except Exception:
                    return None
            else:
                if self.h5_path is None:
                    return None
                try:
                    with h5py.File(self.h5_path, "r") as f:
                        if h5_dataset not in f:
                            return None
                        ds = f[h5_dataset]
                        if frame_idx >= ds.shape[0]:
                            return None
                        return ds[frame_idx].astype(np.float32)
                except Exception:
                    return None

        # ── assemble mosaic ──────────────────────────────────────────────────
        mosaic = np.full(
            (self.ny * (tile_h + gap_px) - gap_px, self.nx * (tile_w + gap_px) - gap_px),
            np.nan,
        )
        n_found = 0
        saved_U = [l.U.copy() for l in self.stack.all_layers]
        try:
            for iy in range(self.ny):
                for ix in range(self.nx):
                    u_here = U_src[:, iy, ix]
                    if np.all(np.isnan(u_here)):
                        continue

                    for li, lyr in enumerate(self.stack.all_layers):
                        lyr.U = (
                            saved_U[li].copy() if np.any(np.isnan(u_here[li]))
                            else u_here[li].copy()
                        )

                    try:
                        spots = simulate_laue_stack(
                            self.stack, camera,
                            E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                            geometry_only=True,
                            allowed_hkl=allowed_hkl,
                            verbose=False,
                        )
                    except Exception:
                        continue

                    spot = next(
                        (s for s in spots
                         if tuple(s["hkl"]) == hkl and s.get("pix") is not None
                         and (layer_label is None or s.get("phase_label") == layer_label)),
                        None,
                    )
                    if spot is None:
                        continue

                    image = _load_image(self.frame_index(iy, ix))
                    if image is None:
                        continue

                    xc, yc = spot["pix"]
                    xc, yc = int(round(xc)), int(round(yc))
                    nv_im, nh_im = image.shape

                    y0, y1 = yc - half_window_y, yc + half_window_y + 1
                    x0, x1 = xc - half_window_x, xc + half_window_x + 1
                    sy0, sy1 = max(y0, 0), min(y1, nv_im)
                    sx0, sx1 = max(x0, 0), min(x1, nh_im)
                    if sy0 >= sy1 or sx0 >= sx1:
                        continue

                    tile = np.full((tile_h, tile_w), np.nan)
                    tile[sy0 - y0: sy1 - y0, sx0 - x0: sx1 - x0] = image[sy0:sy1, sx0:sx1]

                    ry0 = iy * (tile_h + gap_px)
                    rx0 = ix * (tile_w + gap_px)
                    mosaic[ry0:ry0 + tile_h, rx0:rx0 + tile_w] = tile
                    n_found += 1
        finally:
            for lyr, U0 in zip(self.stack.all_layers, saved_U):
                lyr.U = U0

        # ── figure ────────────────────────────────────────────────────────────
        if figsize is None:
            figsize = (
                float(np.clip(2 + self.nx * tile_w / 40, 4, 20)),
                float(np.clip(2 + self.ny * tile_h / 40, 4, 20)),
            )

        fig, ax = plt.subplots(figsize=figsize)
        disp = np.log1p(np.clip(mosaic, 0, None)) if log_scale else mosaic
        im = ax.imshow(disp, cmap=cmap, interpolation="nearest", origin="upper")
        ax.set_xticks([])
        ax.set_yticks([])
        layer_txt = f"  —  layer {layer_label!r}" if layer_label is not None else ""
        ax.set_title(
            f"hkl = {hkl}{layer_txt}  —  "
            f"{n_found}/{self.ny * self.nx} tiles found  "
            f"(±{half_window_x} × ±{half_window_y} px)",
            fontsize=10,
        )
        fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02,
                     label="log(1 + I)" if log_scale else "I")
        fig.tight_layout()

        if out_path is not None:
            fig.savefig(out_path, dpi=150)

        return fig, ax, mosaic

plot_ipf_map

plot_ipf_map(layer: int, *, direction=None, symmetry: str = 'cubic', motor_x: 'str | None' = None, motor_y: 'str | None' = None, ax=None)

Inverse pole figure colour map for layer.

Parameters:
  • layer (int) –

    Layer index.

  • direction –

    Reference direction in the sample frame as a length-3 sequence (default: [0, 0, 1], the beam/z axis).

  • symmetry (str, default: 'cubic' ) –

    Crystal point-group symmetry for reducing orientations to the fundamental zone. One of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic'. Used by orix when available; the fallback coloring always uses cubic reduction.

Source code in src/nrxrdct/laue/layered_map.py
def plot_ipf_map(
    self,
    layer: int,
    *,
    direction=None,
    symmetry: str = "cubic",
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    ax=None,
):
    """
    Inverse pole figure colour map for *layer*.

    Args:
        layer: Layer index.
        direction: Reference direction in the sample frame as a length-3
            sequence (default: ``[0, 0, 1]``, the beam/z axis).
        symmetry: Crystal point-group symmetry for reducing orientations to
            the fundamental zone.  One of ``'cubic'``, ``'hexagonal'``,
            ``'tetragonal'``, ``'orthorhombic'``.  Used by orix when
            available; the fallback coloring always uses cubic reduction.
    """
    _dir = np.asarray(direction if direction is not None else [0, 0, 1],
                      dtype=float)
    _dir = _dir / np.linalg.norm(_dir)

    U_map = self.U[layer]                     # (ny, nx, 3, 3)
    valid = ~np.any(np.isnan(U_map), axis=(-2, -1))

    idx = np.argwhere(valid)
    if len(idx) == 0:
        print("No valid orientations to plot.")
        return ax

    U_valid = U_map[idx[:, 0], idx[:, 1]]    # (M, 3, 3)

    # ── Try modern orix API (>= 0.11) ────────────────────────────────────
    rgb = None
    try:
        from orix.quaternion import Rotation as ORotation
        from orix.vector import Vector3d as OVector3d
        from orix.plot import IPFColorKeyTSL
        from orix.crystal_map import Phase

        _sym_map = {
            "cubic":        "m-3m",
            "hexagonal":    "6/mmm",
            "tetragonal":   "4/mmm",
            "orthorhombic": "mmm",
        }
        pg_str = _sym_map.get(symmetry, "m-3m")
        phase  = Phase(point_group=pg_str)

        # scipy [x,y,z,w] → orix [w,x,y,z]
        q_arr  = Rotation.from_matrix(U_valid).as_quat()          # (M,4)
        orot   = ORotation(q_arr[:, [3, 0, 1, 2]])
        ipf_key = IPFColorKeyTSL(phase.point_group,
                                 direction=OVector3d(_dir))
        rgb = np.clip(ipf_key.orientation2color(orot), 0, 1)     # (M,3)
    except Exception:
        pass

    # ── Fallback: pure-scipy coloring (no orix needed) ───────────────────
    if rgb is None:
        rgb = _ipf_color_fallback(U_valid, _dir)

    img = np.ones((self.ny, self.nx, 3))
    img[idx[:, 0], idx[:, 1]] = rgb

    extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
    if ax is None:
        _, ax = plt.subplots(figsize=(6, 5))

    imkw = dict(origin="upper")
    if extent is not None:
        imkw.update(extent=extent, aspect="auto")
    ax.imshow(img, **imkw)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(f"IPF map — {self.layer_labels[layer]}  [{symmetry}]")
    return ax

plot_kam

plot_kam(layer: int, *, order: int = 1, symmetry: str = 'cubic', use_eff: bool = False, motor_x: 'str | None' = None, motor_y: 'str | None' = None, cmap: str = 'inferno', vmin: float = 0.0, vmax: 'float | None' = None, plot: bool = True, ax=None) -> np.ndarray

Kernel Average Misorientation (KAM) map for layer.

For each valid pixel the mean disorientation angle to all valid neighbors within Chebyshev distance order is computed after minimisation over crystal symmetry operators. The result is the standard KAM metric used in EBSD analysis to highlight orientation gradients caused by geometrically necessary dislocations or grain sub-structure.

Parameters:
  • layer (int) –

    Index into stack.all_layers selecting which layer's orientation to analyse. Each layer has its own independent U / U_eff array, so the substrate and film will produce separate KAM maps reflecting gradients in their respective materials.

  • order (int, default: 1 ) –

    Chebyshev shell radius in pixels. 1 (default) uses the 8 immediate neighbors; 2 adds the next ring for 24 neighbors total; and so on. Larger values smooth the map and capture longer-range gradients but blur sharp boundaries. Standard EBSD convention is order=1.

  • symmetry (str, default: 'cubic' ) –

    Point-group symmetry applied when minimising the misorientation angle between neighbors. Must match the crystal structure of layer: 'cubic', 'hexagonal', 'tetragonal', or 'orthorhombic'. Using the wrong symmetry (e.g. 'orthorhombic' for a cubic crystal) causes symmetry-equivalent orientations to be reported as real gradients, inflating KAM everywhere.

  • use_eff (bool, default: False ) –

    If True, use U_eff (which carries the strain factor I + ε) instead of the pure rotation U. Before computing misorientations the matrices are projected onto SO(3), so large inter-pixel strain differences can still bleed into the KAM value. Keep False (default) to isolate orientation gradients from strain.

  • motor_x, motor_y –

    Names of motor position arrays stored in self.motors. When supplied the axes are labeled in physical units and the map extent is set from the motor ranges; without them row/column pixel indices are used.

  • cmap (str, default: 'inferno' ) –

    Matplotlib colormap. 'inferno' (default) is the standard choice for KAM because near-zero values appear black and gradient regions become progressively brighter.

  • vmin (float, default: 0.0 ) –

    Lower colorscale bound in degrees. Almost always left at 0.0 since KAM is non-negative by construction.

  • vmax ('float | None', default: None ) –

    Upper colorscale bound in degrees. Set an explicit value when comparing maps across different scans so all images share the same scale. None (default) auto-scales to the 99th percentile of valid pixels, which avoids isolated outlier pixels blowing out the colour range.

  • plot (bool, default: True ) –

    Render the map when True (default). Set False to compute and return the array without any drawing, e.g. for batch processing or when embedding in a custom figure.

  • ax –

    Existing Axes to draw into. A new figure is created when None.

Returns:
  • ndarray –

    (ny, nx) float64 array of KAM angles in degrees. Pixels

  • ndarray –

    with no valid orientation or no valid neighbors are NaN.

Source code in src/nrxrdct/laue/layered_map.py
def plot_kam(
    self,
    layer: int,
    *,
    order: int = 1,
    symmetry: str = "cubic",
    use_eff: bool = False,
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    cmap: str = "inferno",
    vmin: float = 0.0,
    vmax: "float | None" = None,
    plot: bool = True,
    ax=None,
) -> np.ndarray:
    """
    Kernel Average Misorientation (KAM) map for *layer*.

    For each valid pixel the mean disorientation angle to all valid
    neighbors within Chebyshev distance *order* is computed after
    minimisation over crystal symmetry operators.  The result is the
    standard KAM metric used in EBSD analysis to highlight orientation
    gradients caused by geometrically necessary dislocations or grain
    sub-structure.

    Args:
        layer: Index into ``stack.all_layers`` selecting which layer's
            orientation to analyse.  Each layer has its own independent
            ``U`` / ``U_eff`` array, so the substrate and film will
            produce separate KAM maps reflecting gradients in their
            respective materials.
        order: Chebyshev shell radius in pixels.  ``1`` (default)
            uses the 8 immediate neighbors; ``2`` adds the next ring
            for 24 neighbors total; and so on.  Larger values smooth
            the map and capture longer-range gradients but blur sharp
            boundaries.  Standard EBSD convention is ``order=1``.
        symmetry: Point-group symmetry applied when minimising the
            misorientation angle between neighbors.  Must match the
            crystal structure of *layer*: ``'cubic'``,
            ``'hexagonal'``, ``'tetragonal'``, or
            ``'orthorhombic'``.  Using the wrong symmetry
            (e.g. ``'orthorhombic'`` for a cubic crystal) causes
            symmetry-equivalent orientations to be reported as real
            gradients, inflating KAM everywhere.
        use_eff: If ``True``, use ``U_eff`` (which carries the strain
            factor ``I + ε``) instead of the pure rotation ``U``.
            Before computing misorientations the matrices are projected
            onto SO(3), so large inter-pixel strain differences can
            still bleed into the KAM value.  Keep ``False`` (default)
            to isolate orientation gradients from strain.
        motor_x, motor_y: Names of motor position arrays stored in
            ``self.motors``.  When supplied the axes are labeled in
            physical units and the map extent is set from the motor
            ranges; without them row/column pixel indices are used.
        cmap: Matplotlib colormap.  ``'inferno'`` (default) is the
            standard choice for KAM because near-zero values appear
            black and gradient regions become progressively brighter.
        vmin: Lower colorscale bound in degrees.  Almost always left
            at ``0.0`` since KAM is non-negative by construction.
        vmax: Upper colorscale bound in degrees.  Set an explicit
            value when comparing maps across different scans so all
            images share the same scale.  ``None`` (default)
            auto-scales to the 99th percentile of valid pixels,
            which avoids isolated outlier pixels blowing out the
            colour range.
        plot: Render the map when ``True`` (default).  Set ``False``
            to compute and return the array without any drawing, e.g.
            for batch processing or when embedding in a custom figure.
        ax: Existing ``Axes`` to draw into.  A new figure is created
            when ``None``.

    Returns:
        ``(ny, nx)`` float64 array of KAM angles in degrees.  Pixels
        with no valid orientation or no valid neighbors are ``NaN``.
    """
    from .simulation import _symmetry_ops_np

    # Choose U source
    if use_eff and not np.all(np.isnan(self.U_eff[layer])):
        U_src = self.U_eff[layer]   # (ny, nx, 3, 3)
    else:
        U_src = self.U[layer]

    valid = ~np.any(np.isnan(U_src), axis=(-2, -1))   # (ny, nx) bool

    ny, nx = self.ny, self.nx
    kam_map = np.full((ny, nx), np.nan)

    if not valid.any():
        if plot:
            if ax is None:
                _, ax = plt.subplots(figsize=(7, 6))
            ax.set_title(f"KAM — {self.layer_labels[layer]} (no data)")
        return kam_map

    # Project all valid orientations to SO(3) once (handles U_eff correctly).
    U_rot = np.full((ny, nx, 3, 3), np.nan)
    U_rot[valid] = Rotation.from_matrix(U_src[valid]).as_matrix()

    ops   = _symmetry_ops_np(symmetry)   # (N_sym, 3, 3)

    # Accumulate per-pixel misorientation sums and neighbor counts.
    angle_sum = np.zeros((ny, nx), dtype=np.float64)
    count     = np.zeros((ny, nx), dtype=np.int32)

    # All neighbor offsets with 1 ≤ Chebyshev distance ≤ order.
    offsets = [
        (diy, dix)
        for diy in range(-order, order + 1)
        for dix in range(-order, order + 1)
        if 1 <= max(abs(diy), abs(dix)) <= order
    ]

    for diy, dix in offsets:
        # Source pixel range: rows/cols that have a valid neighbor at (diy, dix).
        iy0_s = max(0, -diy);  iy1_s = min(ny, ny - diy)
        ix0_s = max(0, -dix);  ix1_s = min(nx, nx - dix)

        IY_s, IX_s = np.meshgrid(
            np.arange(iy0_s, iy1_s),
            np.arange(ix0_s, ix1_s),
            indexing="ij",
        )
        IY_n = IY_s + diy
        IX_n = IX_s + dix

        mask = valid[IY_s, IX_s] & valid[IY_n, IX_n]
        if not mask.any():
            continue

        iy_s = IY_s[mask]; ix_s = IX_s[mask]
        iy_n = IY_n[mask]; ix_n = IX_n[mask]

        Ra = U_rot[iy_s, ix_s]                        # (M, 3, 3)
        Rb = U_rot[iy_n, ix_n]                        # (M, 3, 3)

        # Misorientation: R_mis[m] = Rb[m] @ Ra[m].T
        R_mis = Rb @ Ra.transpose(0, 2, 1)            # (M, 3, 3)

        # ops[s] @ R_mis[m] → (N_sym, M, 3, 3)
        ops_R = np.einsum("sij,mjk->smik", ops, R_mis)

        # trace(ops_R[s,m] @ ops[t].T) for all (s, t, m)
        # = einsum smij, tji -> stm
        traces = np.einsum("smij,tji->stm", ops_R, ops)   # (N_sym, N_sym, M)

        # Minimum angle over all symmetry-equivalent pairs
        cos_ang    = np.clip((traces - 1.0) / 2.0, -1.0, 1.0)
        angles_sym = np.degrees(np.arccos(cos_ang))        # (N_sym, N_sym, M)
        min_ang    = angles_sym.reshape(-1, len(iy_s)).min(axis=0)  # (M,)

        np.add.at(angle_sum, (iy_s, ix_s), min_ang)
        np.add.at(count,     (iy_s, ix_s), 1)

    has_nbrs = count > 0
    kam_map[has_nbrs] = angle_sum[has_nbrs] / count[has_nbrs]

    if not plot:
        return kam_map

    # ── Plot ──────────────────────────────────────────────────────────────
    valid_vals = kam_map[np.isfinite(kam_map)]
    if vmax is None:
        vmax = float(np.percentile(valid_vals, 99)) if len(valid_vals) else 1.0
    vmax = max(float(vmax), float(vmin) + 1e-6)   # prevent blank image when all angles ≈ 0

    extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
    if ax is None:
        _, ax = plt.subplots(figsize=(7, 6))

    imkw = dict(origin="upper", cmap=cmap, vmin=vmin, vmax=vmax)
    if extent is not None:
        imkw.update(extent=extent, aspect="auto")

    im = ax.imshow(kam_map, **imkw)
    plt.colorbar(im, ax=ax, label="KAM (°)")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(
        f"KAM — {self.layer_labels[layer]}  "
        f"(order={order}, {symmetry})"
    )
    return kam_map

plot_map

plot_map(quantity: str, *, layer: 'int | None' = None, strain_component: 'str | None' = None, frame: str = 'crystal', motor_x: 'str | None' = None, motor_y: 'str | None' = None, cmap: str = 'viridis', vmin=None, vmax=None, title: 'str | None' = None, ax=None)

Plot a scalar quantity map.

Parameters:
  • quantity (str) –

    One of 'rms_px', 'mean_px', 'match_rate', 'n_matched', 'cost', 'score', 'score0', 'n_sim', 'rotation_deg' (magnitude of global rotation), or 'strain' (requires layer and strain_component).

  • layer ('int | None', default: None ) –

    Layer index (required for 'strain').

  • strain_component ('str | None', default: None ) –

    One of 'e_xx', 'e_yy', 'e_zz', 'e_xy', 'e_xz', 'e_yz'.

  • frame (str, default: 'crystal' ) –

    'crystal' (default), 'deviatoric' (strain only).

Source code in src/nrxrdct/laue/layered_map.py
def plot_map(
    self,
    quantity: str,
    *,
    layer: "int | None" = None,
    strain_component: "str | None" = None,
    frame: str = "crystal",
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    cmap: str = "viridis",
    vmin=None,
    vmax=None,
    title: "str | None" = None,
    ax=None,
):
    """
    Plot a scalar quantity map.

    Args:
        quantity: One of ``'rms_px'``, ``'mean_px'``, ``'match_rate'``,
            ``'n_matched'``, ``'cost'``, ``'score'``, ``'score0'``,
            ``'n_sim'``, ``'rotation_deg'`` (magnitude of global rotation),
            or ``'strain'`` (requires *layer* and *strain_component*).
        layer: Layer index (required for ``'strain'``).
        strain_component: One of ``'e_xx'``, ``'e_yy'``, ``'e_zz'``,
            ``'e_xy'``, ``'e_xz'``, ``'e_yz'``.
        frame: ``'crystal'`` (default), ``'deviatoric'`` (strain only).
    """
    if quantity == "strain":
        if layer is None or strain_component is None:
            raise ValueError(
                "plot_map('strain') requires layer= and strain_component="
            )
        ti, tj = _VOIGT_TENSOR[strain_component]
        if frame == "deviatoric":
            data = self.strain_tensor_deviatoric[layer, :, :, ti, tj]
        else:
            data = self.strain_tensor[layer, :, :, ti, tj]
        label = f"ε {strain_component}"
        if layer is not None:
            label += f" [{self.layer_labels[layer]}]"

    elif quantity == "rotation_deg":
        norms = np.linalg.norm(self.rotvec, axis=-1)
        data  = np.where(np.isnan(self.rotvec[:, :, 0]), np.nan,
                         np.degrees(norms))
        label = "|δω| (°)"

    else:
        arr = getattr(self, quantity, None)
        if arr is None:
            raise ValueError(f"Unknown quantity {quantity!r}")
        data  = np.where(arr == -1, np.nan, arr).astype(float)
        label = quantity.replace("_", " ")

    extent, xlabel, ylabel = self._motor_extent(motor_x, motor_y)
    if ax is None:
        _, ax = plt.subplots(figsize=(7, 6))

    kw = dict(origin="upper", cmap=cmap, vmin=vmin, vmax=vmax)
    if extent is not None:
        kw.update(extent=extent, aspect="auto")

    im = ax.imshow(data, **kw)
    plt.colorbar(im, ax=ax, label=label)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(title or label)
    return ax

plot_overview

plot_overview(layer: int = 0, *, strain_components: tuple = ('e_xx', 'e_yy', 'e_zz'), motor_x: 'str | None' = None, motor_y: 'str | None' = None, cmap_scalar: str = 'viridis', cmap_strain: str = 'RdBu_r', figsize: 'tuple | None' = None)

Multi-panel overview: match quality + strain components for layer.

Panels: match_rate, rms_px, rotation_deg, then one panel per entry in strain_components.

Source code in src/nrxrdct/laue/layered_map.py
def plot_overview(
    self,
    layer: int = 0,
    *,
    strain_components: tuple = ("e_xx", "e_yy", "e_zz"),
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    cmap_scalar: str = "viridis",
    cmap_strain: str = "RdBu_r",
    figsize: "tuple | None" = None,
):
    """
    Multi-panel overview: match quality + strain components for *layer*.

    Panels: ``match_rate``, ``rms_px``, ``rotation_deg``, then one panel
    per entry in *strain_components*.
    """
    n_panels = 3 + len(strain_components)
    if figsize is None:
        figsize = (5 * n_panels, 4)
    fig, axes = plt.subplots(1, n_panels, figsize=figsize)

    scalar_kw = dict(motor_x=motor_x, motor_y=motor_y, cmap=cmap_scalar)
    self.plot_map("match_rate",   ax=axes[0], **scalar_kw)
    self.plot_map("rms_px",       ax=axes[1], **scalar_kw)
    self.plot_map("rotation_deg", ax=axes[2], **scalar_kw)

    for ii, comp in enumerate(strain_components):
        self.plot_strain_component(
            comp, layer,
            motor_x=motor_x, motor_y=motor_y,
            cmap=cmap_strain, ax=axes[3 + ii],
        )

    fig.suptitle(
        f"LayeredMap — layer {self.layer_labels[layer]}", fontsize=13
    )
    fig.tight_layout()
    return fig, axes

plot_strain_component

plot_strain_component(component: str, layer: int, *, frame: str = 'crystal', motor_x: 'str | None' = None, motor_y: 'str | None' = None, cmap: str = 'RdBu_r', vmin=None, vmax=None, ax=None)

Plot one strain component for layer.

Shortcut for plot_map('strain', layer=layer, strain_component=component).

Source code in src/nrxrdct/laue/layered_map.py
def plot_strain_component(
    self,
    component: str,
    layer: int,
    *,
    frame: str = "crystal",
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    cmap: str = "RdBu_r",
    vmin=None,
    vmax=None,
    ax=None,
):
    """
    Plot one strain component for *layer*.

    Shortcut for ``plot_map('strain', layer=layer, strain_component=component)``.
    """
    return self.plot_map(
        "strain",
        layer=layer,
        strain_component=component,
        frame=frame,
        motor_x=motor_x,
        motor_y=motor_y,
        cmap=cmap,
        vmin=vmin,
        vmax=vmax,
        ax=ax,
        title=f"ε {component} — {self.layer_labels[layer]}",
    )

reindex_frame

reindex_frame(camera, base_dir: str, *, h5_dataset: 'str | None' = None, tiff_dir: 'str | None' = None, seg_dir: 'str | None' = None, map_quantity: str = 'match_rate', motor_x: 'str | None' = None, motor_y: 'str | None' = None, motor_units: 'dict | None' = None, E_min_eV: float = 5000.0, E_max_eV: float = 27000.0, f2_thresh: float = 0.0001, max_match_px: float = 5.0, fit_max_match_px: 'float | list[float]' = (30.0, 10.0, 3.0), fit_strain: 'tuple | None' = None, r_squared_min: float = 0.0, include_unfitted: bool = True, kernel_sigma: float = 0.3, bg_sigma: float = 251.0, max_angle_deg: float = 0.2, max_shift_px: 'float | list[float] | None' = None, correct_depth: bool = False, figsize: tuple = (14, 7)) -> None

Interactive single-frame fitter and inspector for a :class:~nrxrdct.laue.layers.LayeredCrystal stack.

Click a pixel on the left map panel to load the frame, then use the buttons to refit and store the result:

  1. ⚡ Fit — runs :func:~nrxrdct.laue.fitting.fit_orientation_stack starting from the current map orientation (or the template stack U matrices if no result exists for that pixel). Per-layer simulated spots are drawn in distinct colors; green lines connect matched pairs.
  2. 🔩 Fit strain — runs :func:~nrxrdct.laue.fitting.fit_strain_orientation_stack from the best available orientation. Enabled after a successful spot-based orientation fit.
  3. 🖼 Img orient — runs :func:~nrxrdct.laue.fitting.refine_orientation_image_stack on the raw pixel image. Enabled whenever a starting orientation is available (existing map result or fit result).
  4. 🖼 Img strain — runs :func:~nrxrdct.laue.fitting.refine_strain_image_stack jointly refining orientation and strain against the raw image. The max_shift_px constraint (if set) is forwarded to the optimizer.
  5. ⬆ Store — writes the best available result back into the map at the selected pixel via :meth:set_result. If self.save_path is set the map is also persisted to disk.
  6. 💾 Save UBs — saves the per-layer U matrices to auto-numbered .npy files in the current directory.
Parameters:
  • camera –

    Detector geometry (:class:~nrxrdct.laue.camera.Camera).

  • base_dir (str) –

    Processing root directory. The seg sub-folder defaults to <base_dir>/seg unless seg_dir is given explicitly.

  • h5_dataset ('str | None', default: None ) –

    HDF5 dataset path for the image stack (e.g. "1.1/measurement/eiger4m"). Mutually exclusive with tiff_dir.

  • tiff_dir ('str | None', default: None ) –

    Directory of img_*.tif files. Mutually exclusive with h5_dataset.

  • seg_dir ('str | None', default: None ) –

    Directory containing frame_?????.h5 segmentation files. Defaults to <base_dir>/seg.

  • map_quantity (str, default: 'match_rate' ) –

    Scalar quantity displayed on the left panel. One of 'match_rate', 'rms_px', 'n_matched', 'score', 'cost'.

  • motor_x, motor_y –

    Motor names for physical axis labels and click-to-pixel conversion.

  • motor_units ('dict | None', default: None ) –

    Unit labels per motor, e.g. {'sy': 'mm', 'sz': 'mm'}.

  • E_min_eV, E_max_eV –

    Energy range for spot simulation.

  • f2_thresh (float, default: 0.0001 ) –

    Structure-factor threshold for allowed-HKL precomputation.

  • max_match_px (float, default: 5.0 ) –

    Pixel radius used when drawing match lines between observed and simulated spots.

  • fit_max_match_px ('float | list[float]', default: (30.0, 10.0, 3.0) ) –

    Match-radius schedule passed to :func:~nrxrdct.laue.fitting.fit_orientation_stack. A list enables staged refinement.

  • fit_strain ('tuple | None', default: None ) –

    Strain components to refine (e.g. ('e_xx', 'e_yy', 'e_zz')). None refines all six.

  • r_squared_min (float, default: 0.0 ) –

    Minimum Gaussian-fit R² when loading the seg file.

  • include_unfitted (bool, default: True ) –

    Include raw centroids from the seg file.

  • kernel_sigma (float, default: 0.3 ) –

    Gaussian kernel width (px) for image-based refinement.

  • bg_sigma (float, default: 251.0 ) –

    Background subtraction kernel width (px).

  • max_angle_deg (float, default: 0.2 ) –

    Local-search radius (°) for image-based orientation.

  • max_shift_px ('float | list[float] | None', default: None ) –

    Per-layer pixel-displacement budget forwarded to :func:~nrxrdct.laue.fitting.refine_strain_image_stack.

  • figsize (tuple, default: (14, 7) ) –

    Figure size in inches.

Source code in src/nrxrdct/laue/layered_map.py
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
def reindex_frame(
    self,
    camera,
    base_dir: str,
    *,
    h5_dataset: "str | None" = None,
    tiff_dir: "str | None" = None,
    seg_dir: "str | None" = None,
    map_quantity: str = "match_rate",
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    motor_units: "dict | None" = None,
    E_min_eV: float = 5_000.0,
    E_max_eV: float = 27_000.0,
    f2_thresh: float = 1e-4,
    max_match_px: float = 5.0,
    fit_max_match_px: "float | list[float]" = (30.0, 10.0, 3.0),
    fit_strain: "tuple | None" = None,
    r_squared_min: float = 0.0,
    include_unfitted: bool = True,
    kernel_sigma: float = 0.3,
    bg_sigma: float = 251.0,
    max_angle_deg: float = 0.2,
    max_shift_px: "float | list[float] | None" = None,
    correct_depth: bool = False,
    figsize: tuple = (14, 7),
) -> None:
    """
    Interactive single-frame fitter and inspector for a
    :class:`~nrxrdct.laue.layers.LayeredCrystal` stack.

    Click a pixel on the left map panel to load the frame, then use the
    buttons to refit and store the result:

    1. **⚡ Fit** — runs :func:`~nrxrdct.laue.fitting.fit_orientation_stack`
       starting from the current map orientation (or the template stack U
       matrices if no result exists for that pixel).  Per-layer simulated
       spots are drawn in distinct colors; green lines connect matched pairs.
    2. **🔩 Fit strain** — runs
       :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack` from the
       best available orientation.  Enabled after a successful spot-based
       orientation fit.
    3. **🖼 Img orient** — runs
       :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack` on the
       raw pixel image.  Enabled whenever a starting orientation is
       available (existing map result or fit result).
    4. **🖼 Img strain** — runs
       :func:`~nrxrdct.laue.fitting.refine_strain_image_stack` jointly
       refining orientation and strain against the raw image.  The
       ``max_shift_px`` constraint (if set) is forwarded to the optimizer.
    5. **⬆ Store** — writes the best available result back into the map at
       the selected pixel via :meth:`set_result`.  If ``self.save_path`` is
       set the map is also persisted to disk.
    6. **💾 Save UBs** — saves the per-layer U matrices to auto-numbered
       ``.npy`` files in the current directory.

    Args:
        camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
        base_dir: Processing root directory.  The seg sub-folder defaults to
            ``<base_dir>/seg`` unless *seg_dir* is given explicitly.
        h5_dataset: HDF5 dataset path for the image stack (e.g.
            ``"1.1/measurement/eiger4m"``).  Mutually exclusive with
            *tiff_dir*.
        tiff_dir: Directory of ``img_*.tif`` files.  Mutually exclusive with
            *h5_dataset*.
        seg_dir: Directory containing ``frame_?????.h5`` segmentation files.
            Defaults to ``<base_dir>/seg``.
        map_quantity: Scalar quantity displayed on the left panel.  One of
            ``'match_rate'``, ``'rms_px'``, ``'n_matched'``, ``'score'``,
            ``'cost'``.
        motor_x, motor_y: Motor names for physical axis labels and
            click-to-pixel conversion.
        motor_units: Unit labels per motor, e.g. ``{'sy': 'mm', 'sz': 'mm'}``.
        E_min_eV, E_max_eV: Energy range for spot simulation.
        f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
        max_match_px: Pixel radius used when drawing match lines between
            observed and simulated spots.
        fit_max_match_px: Match-radius schedule passed to
            :func:`~nrxrdct.laue.fitting.fit_orientation_stack`.  A list
            enables staged refinement.
        fit_strain: Strain components to refine (e.g. ``('e_xx', 'e_yy',
            'e_zz')``).  ``None`` refines all six.
        r_squared_min: Minimum Gaussian-fit R² when loading the seg file.
        include_unfitted: Include raw centroids from the seg file.
        kernel_sigma: Gaussian kernel width (px) for image-based refinement.
        bg_sigma: Background subtraction kernel width (px).
        max_angle_deg: Local-search radius (°) for image-based orientation.
        max_shift_px: Per-layer pixel-displacement budget forwarded to
            :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`.
        figsize: Figure size in inches.
    """
    import re as _re
    import ipywidgets as ipw
    from IPython.display import display as _ipy_display
    from .simulation import simulate_laue, precompute_allowed_hkl
    from .segmentation import convert_spotsfile2peaklist
    from .fitting import (
        fit_orientation_stack,
        fit_strain_orientation_stack,
        refine_orientation_image_stack,
        refine_strain_image_stack,
        _match_spots,
        _STRAIN_ALL,
    )

    _seg_dir    = seg_dir or os.path.join(base_dir, "seg")
    _fit_strain = tuple(fit_strain) if fit_strain is not None else _STRAIN_ALL

    # Precompute allowed HKL for each unique crystal in the stack.
    _allowed_by_crystal: dict = {}
    for _layer in self.stack.all_layers:
        _cid = id(_layer.crystal)
        if _cid not in _allowed_by_crystal:
            _allowed_by_crystal[_cid] = precompute_allowed_hkl(
                _layer.crystal, E_max_eV=E_max_eV, f2_thresh=f2_thresh
            )

    _LAYER_COLORS = [
        "#ff6b35", "#44aaff", "#44dd66", "#ffcc44", "#ff44aa", "#aa44ff",
    ]

    mu = motor_units or {}
    mx = self.motors.get(motor_x) if motor_x else None
    my = self.motors.get(motor_y) if motor_y else None

    if mx is not None and my is not None:
        extent_map = [mx[0, 0], mx[0, -1], my[-1, 0], my[0, 0]]
        xu_ = mu.get(motor_x, "")
        yu_ = mu.get(motor_y, "")
        xlabel_map = f"{motor_x} ({xu_})" if xu_ else motor_x
        ylabel_map = f"{motor_y} ({yu_})" if yu_ else motor_y
    else:
        extent_map = [0, self.nx, self.ny, 0]
        xlabel_map = "column (ix)"
        ylabel_map = "row (iy)"

    def _click_to_iy_ix(xdata: float, ydata: float):
        if mx is not None and my is not None:
            dist = (mx - xdata) ** 2 + (my - ydata) ** 2
            iy, ix = np.unravel_index(int(np.argmin(dist)), dist.shape)
        else:
            ix = int(np.clip(int(xdata), 0, self.nx - 1))
            iy = int(np.clip(int(ydata), 0, self.ny - 1))
        return int(iy), int(ix)

    _tiff_index: list = []

    def _load_image(frame_idx: int) -> "np.ndarray | None":
        if tiff_dir is not None:
            if not _tiff_index:
                pat = _re.compile(r'(\d+)\.tiff?$', _re.IGNORECASE)
                files = []
                for fname in os.listdir(tiff_dir):
                    m = pat.search(fname)
                    if m:
                        files.append((int(m.group(1)), os.path.join(tiff_dir, fname)))
                files.sort(key=lambda t: t[0])
                _tiff_index.extend(p for _, p in files)
            if not _tiff_index or frame_idx >= len(_tiff_index):
                return None
            try:
                import skimage.io
                return skimage.io.imread(_tiff_index[frame_idx]).astype(np.float32)
            except Exception as exc:
                print(f"  ✗ TIFF read error frame {frame_idx}: {exc}", flush=True)
                return None
        elif h5_dataset is not None:
            _h5 = self.h5_path
            if _h5 is None:
                print("  ✗ h5_path not set on this LayeredMap.", flush=True)
                return None
            try:
                with h5py.File(_h5, "r") as fh:
                    if h5_dataset not in fh:
                        print(f"  ✗ dataset {h5_dataset!r} not in {_h5!r}", flush=True)
                        return None
                    return fh[h5_dataset][frame_idx].astype(np.float32)
            except Exception as exc:
                print(f"  ✗ HDF5 read error frame {frame_idx}: {exc}", flush=True)
                return None
        return None

    _map_opts = {
        "match_rate": (self.match_rate,                                      "Match rate", "viridis"),
        "rms_px":     (self.rms_px,                                          "RMS (px)",   "plasma_r"),
        "n_matched":  (np.where(self.n_matched == -1, np.nan,
                                self.n_matched.astype(float)),               "N matched",  "YlOrRd"),
        "score":      (self.score,                                           "Img score",  "viridis"),
        "cost":       (self.cost,                                            "Cost",       "plasma_r"),
    }
    map_data, map_label, map_cmap = _map_opts.get(
        map_quantity, _map_opts["match_rate"]
    )

    with plt.ioff():
        fig = plt.figure(figsize=figsize)
    try:
        fig.canvas.manager.set_window_title("Laue — LayeredMap re-index")
    except Exception:
        pass

    gs = fig.add_gridspec(
        1, 2, width_ratios=[1, 1.8], wspace=0.08,
        left=0.07, right=0.97, bottom=0.09, top=0.91,
    )
    ax_map = fig.add_subplot(gs[0])
    ax_det = fig.add_subplot(gs[1])

    im_map = ax_map.imshow(
        map_data, origin="upper", extent=extent_map,
        cmap=map_cmap, interpolation="nearest", aspect="auto",
    )
    cbar_map = fig.colorbar(im_map, ax=ax_map, fraction=0.04, pad=0.03,
                             shrink=0.8, label=map_label)
    ax_map.set_xlabel(xlabel_map, fontsize=9)
    ax_map.set_ylabel(ylabel_map, fontsize=9)

    def _map_title(label: str) -> str:
        return f"Click to select — {label}"

    ax_map.set_title(_map_title(map_label), fontsize=9)
    sel_dot, = ax_map.plot([], [], "w+", ms=11, mew=2.0, zorder=10)

    ax_det.set_facecolor("k")
    ax_det.set_xlim(0, camera.Nh)
    ax_det.set_ylim(camera.Nv, 0)
    ax_det.set_aspect("equal")
    ax_det.set_xlabel("x (px)", fontsize=9)
    ax_det.set_ylabel("y (px)", fontsize=9)
    ax_det.set_title("← click map to select a frame", fontsize=9, color="#888")
    fig.suptitle(
        "LayeredMap re-index  —  click map → Fit → Store",
        fontsize=9, color="#555",
    )

    _state: dict = {
        "frame_idx": None, "iy": None, "ix": None,
        "obs_xy": np.empty((0, 2)),
        "fit_result": None,
        "drawn": False,
    }

    def _best_U_layers() -> "list | None":
        """Return U_layers from the current fit result or map arrays."""
        r = _state["fit_result"]
        iy, ix = _state["iy"], _state["ix"]
        if r is not None:
            return (r.U_eff_layers if hasattr(r, "U_eff_layers") else r.U_layers)
        if iy is not None:
            U_src = (
                self.U_eff if not np.all(np.isnan(self.U_eff[:, iy, ix]))
                else self.U
            )
            if not np.all(np.isnan(U_src[:, iy, ix])):
                return [U_src[li, iy, ix].copy() for li in range(self.n_layers)]
        return None

    def _overlay_sim(U_layers_list: list, obs_xy: np.ndarray) -> None:
        """Draw per-layer simulated spots (colored) with match lines."""
        for li, (layer, U) in enumerate(
            zip(self.stack.all_layers, U_layers_list)
        ):
            if np.any(np.isnan(U)):
                continue
            color = _LAYER_COLORS[li % len(_LAYER_COLORS)]
            label = getattr(layer, "label", f"layer {li}")
            try:
                spots = simulate_laue(
                    layer.crystal, U, camera,
                    E_min=E_min_eV, E_max=E_max_eV,
                    geometry_only=True,
                    allowed_hkl=_allowed_by_crystal.get(id(layer.crystal)),
                )
                sim_xy = np.array(
                    [s["pix"] for s in spots if s.get("pix") is not None],
                    dtype=float,
                ) if spots else np.empty((0, 2))
                if not len(sim_xy):
                    continue
                ax_det.scatter(
                    sim_xy[:, 0], sim_xy[:, 1],
                    s=24, c=color, marker="D", linewidths=0,
                    zorder=5, alpha=0.85,
                    label=f"{label} ({len(sim_xy)})",
                )
                if len(obs_xy) and len(sim_xy):
                    row_ind, col_ind, dist_px = _match_spots(
                        obs_xy, sim_xy, max_match_px
                    )
                    for r, c, d in zip(row_ind, col_ind, dist_px):
                        if d < max_match_px:
                            ax_det.plot(
                                [obs_xy[r, 0], sim_xy[c, 0]],
                                [obs_xy[r, 1], sim_xy[c, 1]],
                                color="#44dd66", lw=0.7, alpha=0.55, zorder=3,
                            )
            except Exception as exc:
                print(f"  layer {li} sim error: {exc}", flush=True)

    def _draw_det() -> None:
        frame_idx  = _state["frame_idx"]
        obs_xy     = _state["obs_xy"]
        fit_result = _state["fit_result"]
        iy, ix     = _state["iy"], _state["ix"]

        saved_xlim = ax_det.get_xlim()
        saved_ylim = ax_det.get_ylim()
        ax_det.cla()
        ax_det.set_facecolor("k")

        image = _load_image(frame_idx)
        if image is not None:
            pos  = image[image > 0]
            vmin = float(np.percentile(pos, 1)) if pos.size else 0.0
            vmax = float(np.percentile(pos, 99.9)) if pos.size else 1.0
            if vmax <= vmin:
                vmax = vmin + 1.0
            nv_im, nh_im = image.shape
            disp_norm = np.clip((image - vmin) / (vmax - vmin), 0, None)
            ax_det.imshow(
                np.log1p(disp_norm * 1000),
                origin="upper", extent=[0, nh_im, nv_im, 0],
                cmap="gray", aspect="equal", zorder=0,
            )
        else:
            ax_det.set_xlim(0, camera.Nh)
            ax_det.set_ylim(camera.Nv, 0)
        ax_det.set_aspect("equal")

        if len(obs_xy):
            ax_det.scatter(
                obs_xy[:, 0], obs_xy[:, 1],
                s=40, c="none", edgecolors="white", linewidths=0.8,
                zorder=4, label=f"observed ({len(obs_xy)})",
            )

        U_layers_draw = _best_U_layers()
        if U_layers_draw is not None:
            _overlay_sim(U_layers_draw, obs_xy)

        if len(obs_xy) or U_layers_draw is not None:
            ax_det.legend(
                fontsize=7, loc="upper right",
                facecolor="#111", edgecolor="#444", labelcolor="white",
                framealpha=0.85,
            )

        ax_det.set_xlabel("x (px)", fontsize=9)
        ax_det.set_ylabel("y (px)", fontsize=9)
        suffix = f"  — {fit_result}" if fit_result is not None else ""
        ax_det.set_title(
            f"Frame {frame_idx}  (iy={iy}, ix={ix}){suffix}",
            fontsize=8,
        )
        if _state["drawn"]:
            ax_det.set_xlim(saved_xlim)
            ax_det.set_ylim(saved_ylim)
        _state["drawn"] = True
        fig.canvas.draw_idle()

    def _on_click(event) -> None:
        if event.inaxes is not ax_map:
            return
        if event.xdata is None or event.ydata is None:
            return
        try:
            if fig.canvas.toolbar.mode != "":
                return
        except Exception:
            pass

        iy, ix    = _click_to_iy_ix(event.xdata, event.ydata)
        frame_idx = self.frame_index(iy, ix)

        if mx is not None and my is not None:
            sel_dot.set_data([mx[iy, ix]], [my[iy, ix]])
        else:
            sel_dot.set_data([ix + 0.5], [iy + 0.5])

        seg_path = os.path.join(_seg_dir, f"frame_{frame_idx:05d}.h5")
        if os.path.exists(seg_path):
            try:
                obs_xy = convert_spotsfile2peaklist(
                    seg_path,
                    r_squared_min=r_squared_min,
                    include_unfitted=include_unfitted,
                )[:, :2]
            except Exception:
                obs_xy = np.empty((0, 2))
        else:
            obs_xy = np.empty((0, 2))

        has_map_result = not np.all(np.isnan(self.U[:, iy, ix, 0, 0]))
        has_image      = (h5_dataset is not None or tiff_dir is not None)
        enough_obs     = len(obs_xy) >= 3

        _state.update(
            frame_idx=frame_idx, iy=iy, ix=ix,
            obs_xy=obs_xy, fit_result=None,
        )

        _info.value = (
            f"<span style='color:#aaa'>Frame {frame_idx} — "
            f"{len(obs_xy)} observed spots"
            + (" — existing map result" if has_map_result else "")
            + "</span>"
        )
        btn_fit_ori.disabled = not (enough_obs and (has_map_result or True))
        btn_fit_str.disabled = True
        btn_img_ori.disabled = not (has_image and (has_map_result or enough_obs))
        btn_img_str.disabled = not (has_image and (has_map_result or enough_obs))
        btn_store.disabled   = True
        btn_save.disabled    = True
        btn_reload.disabled  = False
        _draw_det()

    fig.canvas.mpl_connect("button_press_event", _on_click)

    # ── widgets ────────────────────────────────────────────────────────────
    _bkw  = dict(layout=ipw.Layout(width="130px", height="32px"))
    _bkw2 = dict(layout=ipw.Layout(width="140px", height="32px"))

    btn_fit_ori = ipw.Button(description="⚡ Fit",       button_style="primary", **_bkw)
    btn_fit_str = ipw.Button(description="🔩 Fit strain", button_style="warning", **_bkw2)
    btn_img_ori = ipw.Button(description="🖼 Img orient", button_style="info",    **_bkw2)
    btn_img_str = ipw.Button(description="🖼 Img strain", button_style="warning", **_bkw2)
    btn_store   = ipw.Button(description="⬆ Store",      button_style="success", **_bkw)
    btn_save    = ipw.Button(description="💾 Save UBs",  button_style="",        **_bkw)
    btn_reload  = ipw.Button(description="↺ Reload",     button_style="danger",  **_bkw)

    for _b in (btn_fit_ori, btn_fit_str, btn_img_ori, btn_img_str,
               btn_store, btn_save, btn_reload):
        _b.disabled = True

    _info = ipw.HTML(
        "<span style='color:#666;font-style:italic'>"
        "click a map pixel to select a frame"
        "</span>",
        layout=ipw.Layout(margin="4px 0 0 6px"),
    )

    w_map_quantity = ipw.Dropdown(
        options=[(label, key) for key, (_, label, _) in _map_opts.items()],
        value=map_quantity if map_quantity in _map_opts else "match_rate",
        layout=ipw.Layout(width="150px", height="32px"),
    )

    def _cb_map_quantity(change) -> None:
        data, label, cmap = _map_opts[change["new"]]
        im_map.set_data(data)
        im_map.set_cmap(cmap)
        im_map.autoscale()
        cbar_map.set_label(label)
        ax_map.set_title(_map_title(label), fontsize=9)
        fig.canvas.draw_idle()

    w_map_quantity.observe(_cb_map_quantity, names="value")

    # ── async-threaded button callbacks ───────────────────────────────────

    def _async_run(worker_fn, btn, label_running, label_done, on_success):
        import asyncio
        import queue as _qmod
        import threading

        if getattr(btn, "_running", False):
            return
        btn._running    = True
        btn.disabled    = True
        btn.description = label_running

        q: _qmod.Queue = _qmod.Queue()

        def _run():
            try:
                q.put(("ok", worker_fn()))
            except Exception as exc:
                q.put(("err", exc))

        async def _wait():
            threading.Thread(target=_run, daemon=True).start()
            while q.empty():
                await asyncio.sleep(0.15)
            tag, payload = q.get_nowait()
            if tag == "err":
                _info.value = (
                    f"<b style='color:#f44'>{label_done} error: {payload}</b>"
                )
            else:
                on_success(payload)
            btn.description = label_done
            btn.disabled    = False
            btn._running    = False

        try:
            asyncio.get_event_loop().create_task(_wait())
        except RuntimeError:
            asyncio.ensure_future(_wait())

    def _cb_fit_ori(_) -> None:
        obs_xy = _state["obs_xy"]
        if len(obs_xy) < 3:
            return

        start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
        saved_U = [l.U.copy() for l in self.stack.all_layers]
        for l, U in zip(self.stack.all_layers, start_U):
            l.U = U.copy()

        def _work():
            try:
                return fit_orientation_stack(
                    self.stack, camera, obs_xy,
                    E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                    max_match_px=list(fit_max_match_px)
                    if hasattr(fit_max_match_px, "__iter__")
                    else fit_max_match_px,
                    allowed_hkl=_allowed_by_crystal,
                    geometry_only=True,
                    correct_depth=correct_depth,
                    update_stack=False,
                    verbose=True,
                )
            finally:
                for l, U in zip(self.stack.all_layers, saved_U):
                    l.U = U

        def _on_ok(res):
            _state["fit_result"] = res
            col = "#44aaff" if res.success else "#ffaa33"
            _info.value = f"<b style='color:{col}'>{res}</b>"
            btn_fit_str.disabled = len(_state["obs_xy"]) < 3
            btn_img_str.disabled = False
            btn_store.disabled   = False
            btn_save.disabled    = False
            _draw_det()

        _async_run(_work, btn_fit_ori, "Fitting…", "⚡ Fit", _on_ok)

    def _cb_fit_str(_) -> None:
        obs_xy = _state["obs_xy"]
        if len(obs_xy) < 3:
            return

        start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
        saved_U = [l.U.copy() for l in self.stack.all_layers]
        for l, U in zip(self.stack.all_layers, start_U):
            l.U = U.copy()

        def _work():
            try:
                return fit_strain_orientation_stack(
                    self.stack, camera, obs_xy,
                    fit_strain=_fit_strain,
                    E_min_eV=E_min_eV, E_max_eV=E_max_eV,
                    max_match_px=[3.0],
                    allowed_hkl=_allowed_by_crystal,
                    geometry_only=True,
                    correct_depth=correct_depth,
                    update_stack=False,
                    verbose=True,
                )
            finally:
                for l, U in zip(self.stack.all_layers, saved_U):
                    l.U = U

        def _on_ok(res):
            _state["fit_result"] = res
            col = "#ffcc44" if res.success else "#ffaa33"
            _info.value = f"<b style='color:{col}'>{res}</b>"
            btn_img_str.disabled = False
            btn_store.disabled   = False
            btn_save.disabled    = False
            _draw_det()

        _async_run(_work, btn_fit_str, "Fitting…", "🔩 Fit strain", _on_ok)

    def _cb_img_ori(_) -> None:
        frame_idx = _state["frame_idx"]
        if frame_idx is None:
            return

        start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
        if any(np.any(np.isnan(U)) for U in start_U):
            _info.value = "<b style='color:#f44'>No starting orientation available</b>"
            return

        saved_U = [l.U.copy() for l in self.stack.all_layers]
        for l, U in zip(self.stack.all_layers, start_U):
            l.U = U.copy()

        image = _load_image(frame_idx)
        if image is None:
            _info.value = "<b style='color:#f44'>Could not load image</b>"
            return

        def _work():
            try:
                return refine_orientation_image_stack(
                    self.stack, camera, image.astype(np.float64),
                    allowed_hkl=_allowed_by_crystal,
                    kernel_sigma=kernel_sigma,
                    bg_sigma=bg_sigma,
                    max_angle_deg=max_angle_deg,
                    E_min=E_min_eV, E_max=E_max_eV,
                    correct_depth=correct_depth,
                    verbose=True,
                )
            finally:
                for l, U in zip(self.stack.all_layers, saved_U):
                    l.U = U

        def _on_ok(res):
            _state["fit_result"] = res
            _info.value = f"<b style='color:#44aaff'>{res}</b>"
            btn_img_str.disabled = False
            btn_store.disabled   = False
            btn_save.disabled    = False
            _draw_det()

        _async_run(_work, btn_img_ori, "Refining…", "🖼 Img orient", _on_ok)

    def _cb_img_str(_) -> None:
        frame_idx = _state["frame_idx"]
        if frame_idx is None:
            return

        start_U = _best_U_layers() or [l.U.copy() for l in self.stack.all_layers]
        if any(np.any(np.isnan(U)) for U in start_U):
            _info.value = "<b style='color:#f44'>No starting orientation available</b>"
            return

        r = _state["fit_result"]
        strain0_list = (
            r.strain_tensors if hasattr(r, "strain_tensors") else None
        )

        saved_U = [l.U.copy() for l in self.stack.all_layers]
        for l, U in zip(self.stack.all_layers, start_U):
            l.U = U.copy()

        image = _load_image(frame_idx)
        if image is None:
            _info.value = "<b style='color:#f44'>Could not load image</b>"
            return

        def _work():
            try:
                kw: dict = dict(
                    allowed_hkl   = _allowed_by_crystal,
                    fit_strain    = _fit_strain,
                    kernel_sigma  = kernel_sigma,
                    bg_sigma      = bg_sigma,
                    max_angle_deg = max_angle_deg,
                    E_min         = E_min_eV,
                    E_max         = E_max_eV,
                    correct_depth = correct_depth,
                    verbose       = True,
                )
                if strain0_list is not None:
                    kw["strain0_list"] = strain0_list
                if max_shift_px is not None:
                    kw["max_shift_px"] = max_shift_px
                return refine_strain_image_stack(
                    self.stack, camera, image.astype(np.float64), **kw
                )
            finally:
                for l, U in zip(self.stack.all_layers, saved_U):
                    l.U = U

        def _on_ok(res):
            _state["fit_result"] = res
            _info.value = f"<b style='color:#ffcc44'>{res}</b>"
            btn_store.disabled = False
            btn_save.disabled  = False
            _draw_det()

        _async_run(_work, btn_img_str, "Refining…", "🖼 Img strain", _on_ok)

    def _cb_store(_) -> None:
        r = _state["fit_result"]
        if r is None:
            return
        iy, ix = _state["iy"], _state["ix"]
        self.set_result(iy, ix, r)
        # Refresh the map image so the stored pixel is visible immediately
        im_map.set_data(_map_opts[w_map_quantity.value][0])
        im_map.autoscale()
        fig.canvas.draw_idle()
        save_note = ""
        if self.save_path:
            self.save(self.save_path)
            save_note = f" — saved to {os.path.basename(self.save_path)}"
        else:
            save_note = " — <b style='color:#ffaa33'>no save_path, result in memory only</b>"
        _info.value = (
            f"<b style='color:#44dd66'>Stored → (iy={iy}, ix={ix})</b>"
            f"&emsp;{r}"
            f"<span style='color:#aaa'>{save_note}</span>"
        )
        print(
            f"  ⬆ Stored result at (iy={iy}, ix={ix})"
            + (f"  → {self.save_path}" if self.save_path else " (in memory only)"),
            flush=True,
        )

    def _cb_save(_) -> None:
        r = _state["fit_result"]
        if r is None:
            return
        U_layers = (
            r.U_eff_layers if hasattr(r, "U_eff_layers") else r.U_layers
        )
        saved = []
        for li, U in enumerate(U_layers):
            existing = glob.glob(os.path.join(os.getcwd(), f"UB_layer{li}_*.npy"))
            max_n = -1
            for fpath in existing:
                m = _re.search(r"UB_layer\d+_(\d+)\.npy$", os.path.basename(fpath))
                if m:
                    max_n = max(max_n, int(m.group(1)))
            fname = f"UB_layer{li}_{max_n + 1:02d}.npy"
            np.save(fname, U)
            saved.append(fname)
            print(f"  💾 Saved U layer {li} → {os.path.abspath(fname)}")
        _info.value = (
            f"<b style='color:#44dd66'>Saved {len(saved)} UB files: "
            + ", ".join(saved) + "</b>"
        )

    def _cb_reload(_) -> None:
        if _state["frame_idx"] is None:
            return
        _state["fit_result"] = None
        btn_fit_str.disabled = True
        btn_store.disabled   = True
        btn_save.disabled    = True
        iy, ix = _state["iy"], _state["ix"]
        has_map = not np.all(np.isnan(self.U[:, iy, ix, 0, 0]))
        _info.value = (
            "<span style='color:#aaa'>Reloaded — showing "
            + ("existing map orientation" if has_map else "template stack orientation")
            + "</span>"
        )
        _draw_det()

    btn_fit_ori.on_click(_cb_fit_ori)
    btn_fit_str.on_click(_cb_fit_str)
    btn_img_ori.on_click(_cb_img_ori)
    btn_img_str.on_click(_cb_img_str)
    btn_store.on_click(_cb_store)
    btn_save.on_click(_cb_save)
    btn_reload.on_click(_cb_reload)

    _row_kw = dict(layout=ipw.Layout(gap="6px", margin="2px 0 0 0", align_items="center"))
    _controls = ipw.VBox([
        ipw.HBox([btn_fit_ori, btn_fit_str, btn_img_ori, btn_img_str], **_row_kw),
        ipw.HBox([btn_store,   btn_save,    btn_reload,
                  ipw.HTML("<span style='color:#aaa;align-self:center'>map:</span>",
                           layout=ipw.Layout(margin="0 2px 0 10px")),
                  w_map_quantity],                                     **_row_kw),
        _info,
    ], layout=ipw.Layout(padding="6px 8px"))

    _ipy_display(ipw.VBox([fig.canvas, _controls]))

run_image_orientation_local

run_image_orientation_local(camera, h5_path: str, h5_dataset: str, out_dir: str, *, geometry_only: bool = True, correct_depth: bool = False, f2_thresh: float = 0.0001, n_workers: 'int | None' = None, overwrite: bool = False, frame_indices: 'list[int] | None' = None, **fit_kwargs) -> int

Image-based orientation refinement for every frame using local cores.

Calls :func:~nrxrdct.laue.fitting.refine_orientation_image_stack. The stack's layer U matrices must already be set to a good starting orientation (e.g. via a prior :meth:run_orientation_local + stack update).

Parameters:
  • h5_path (str) –

    Path to the HDF5 scan file.

  • h5_dataset (str) –

    Dataset path inside h5_path, e.g. "1.1/measurement/eiger4m".

  • out_dir (str) –

    Output directory for result .npz files.

Source code in src/nrxrdct/laue/layered_map.py
def run_image_orientation_local(
    self,
    camera,
    h5_path: str,
    h5_dataset: str,
    out_dir: str,
    *,
    geometry_only: bool = True,
    correct_depth: bool = False,
    f2_thresh: float = 1e-4,
    n_workers: "int | None" = None,
    overwrite: bool = False,
    frame_indices: "list[int] | None" = None,
    **fit_kwargs,
) -> int:
    """
    Image-based orientation refinement for every frame using local cores.

    Calls :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack`.
    The stack's layer U matrices must already be set to a good starting
    orientation (e.g. via a prior :meth:`run_orientation_local` + stack
    update).

    Args:
        h5_path: Path to the HDF5 scan file.
        h5_dataset: Dataset path inside *h5_path*, e.g.
            ``"1.1/measurement/eiger4m"``.
        out_dir: Output directory for result ``.npz`` files.
    """
    os.makedirs(out_dir, exist_ok=True)

    if frame_indices is None:
        frame_indices = list(range(self.ny * self.nx))

    allowed_hkl = None
    if geometry_only:
        _E_max = fit_kwargs.get("E_max", 27_000)
        allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

    frames = self._load_frames(h5_path, h5_dataset, frame_indices)
    print(
        f"run_image_orientation_local: {len(frame_indices)} frames loaded",
        flush=True,
    )

    common = dict(out_dir=out_dir,
                  fit_kwargs={**fit_kwargs, "correct_depth": correct_depth},
                  overwrite=overwrite)
    stack_pkl = self._serialize_stack()
    try:
        n_ok = self._run_pool(
            _lm_img_orient_frame, frame_indices, frames, common,
            stack_pkl, camera, allowed_hkl,
            n_workers or os.cpu_count() or 1,
        )
    finally:
        os.unlink(stack_pkl)

    return n_ok

run_orientation_local

run_orientation_local(camera, seg_dir: str, out_dir: str, *, r_squared_min: float = 0.0, include_unfitted: bool = False, max_match_px=(30, 10, 3), min_matched: int = 5, min_match_rate: float = 0.2, max_rms_px: 'float | None' = None, geometry_only: bool = True, correct_depth: bool = False, engine: str = 'stack', f2_thresh: float = 0.0001, n_workers: 'int | None' = None, overwrite: bool = False, frame_indices: 'list[int] | None' = None, **fit_kwargs) -> int

Fit stack orientation for every frame in seg_dir using local CPU cores.

Results are written as frame_?????.npz in out_dir. Call :meth:collect afterwards to load them into the map arrays.

Parameters:
  • camera –

    Detector geometry.

  • seg_dir (str) –

    Directory with frame_?????.h5 peaklist files.

  • out_dir (str) –

    Output directory for frame_?????.npz result files.

  • max_match_px –

    Pixel match radius; a decreasing list enables staged refinement (e.g. [30, 10, 3]).

  • correct_depth (bool, default: False ) –

    Project each layer's spots from its centre depth. Default False.

  • engine (str, default: 'stack' ) –

    Simulation engine — 'stack' (default, kinematical) or 'darwin' (Darwin primary extinction). The Darwin engine uses physically correct intensities for thick layers but is somewhat slower per frame.

  • fit_kwargs –

    Forwarded to :func:~nrxrdct.laue.fitting.fit_orientation_stack.

Returns:
  • int –

    Number of frames successfully fitted.

Source code in src/nrxrdct/laue/layered_map.py
def run_orientation_local(
    self,
    camera,
    seg_dir: str,
    out_dir: str,
    *,
    r_squared_min: float = 0.0,
    include_unfitted: bool = False,
    max_match_px=(30, 10, 3),
    min_matched: int = 5,
    min_match_rate: float = 0.2,
    max_rms_px: "float | None" = None,
    geometry_only: bool = True,
    correct_depth: bool = False,
    engine: str = "stack",
    f2_thresh: float = 1e-4,
    n_workers: "int | None" = None,
    overwrite: bool = False,
    frame_indices: "list[int] | None" = None,
    **fit_kwargs,
) -> int:
    """
    Fit stack orientation for every frame in *seg_dir* using local CPU cores.

    Results are written as ``frame_?????.npz`` in *out_dir*.
    Call :meth:`collect` afterwards to load them into the map arrays.

    Args:
        camera: Detector geometry.
        seg_dir: Directory with ``frame_?????.h5`` peaklist files.
        out_dir: Output directory for ``frame_?????.npz`` result files.
        max_match_px: Pixel match radius; a decreasing list enables staged
            refinement (e.g. ``[30, 10, 3]``).
        correct_depth: Project each layer's spots from its centre depth.
            Default ``False``.
        engine: Simulation engine — ``'stack'`` (default, kinematical) or
            ``'darwin'`` (Darwin primary extinction).  The Darwin engine
            uses physically correct intensities for thick layers
            but is somewhat slower per frame.
        fit_kwargs: Forwarded to :func:`~nrxrdct.laue.fitting.fit_orientation_stack`.

    Returns:
        Number of frames successfully fitted.
    """
    os.makedirs(out_dir, exist_ok=True)

    if frame_indices is None:
        h5s = sorted(glob.glob(os.path.join(seg_dir, "frame_?????.h5")))
        frame_indices = [int(os.path.basename(p)[6:11]) for p in h5s]

    allowed_hkl = None
    if geometry_only:
        _E_max = fit_kwargs.get("E_max_eV", 27_000)
        allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

    peaklists = self._load_peaklists(
        seg_dir, frame_indices, r_squared_min, include_unfitted, min_matched
    )
    print(
        f"run_orientation_local: {len(frame_indices)} frames | "
        f"{len(peaklists)} with ≥{min_matched} spots | "
        f"{self.n_layers} layers",
        flush=True,
    )

    common = dict(
        out_dir        = out_dir,
        max_match_px   = max_match_px,
        min_matched    = min_matched,
        min_match_rate = min_match_rate,
        max_rms_px     = max_rms_px,
        fit_kwargs     = {**fit_kwargs, "geometry_only": geometry_only,
                           "correct_depth": correct_depth, "engine": engine},
        overwrite      = overwrite,
    )
    stack_pkl = self._serialize_stack()
    try:
        n_ok = self._run_pool(
            _lm_orient_frame, frame_indices, peaklists, common,
            stack_pkl, camera, allowed_hkl,
            n_workers or os.cpu_count() or 1,
        )
    finally:
        os.unlink(stack_pkl)

    print(f"  → {n_ok}/{len(frame_indices)} frames fitted", flush=True)
    return n_ok

run_strain_image_local

run_strain_image_local(camera, h5_path: str, h5_dataset: str, out_dir: str, *, fit_strain: 'tuple | None' = None, geometry_only: bool = True, correct_depth: bool = False, f2_thresh: float = 0.0001, n_workers: 'int | None' = None, overwrite: bool = False, frame_indices: 'list[int] | None' = None, **fit_kwargs) -> int

Image-based orientation + per-layer strain refinement using local cores.

Calls :func:~nrxrdct.laue.fitting.refine_strain_image_stack. Pass strain0_list via fit_kwargs to warm-start from a prior strain fit.

Parameters:
  • fit_strain ('tuple | None', default: None ) –

    Strain components to refine. None refines all six.

Source code in src/nrxrdct/laue/layered_map.py
def run_strain_image_local(
    self,
    camera,
    h5_path: str,
    h5_dataset: str,
    out_dir: str,
    *,
    fit_strain: "tuple | None" = None,
    geometry_only: bool = True,
    correct_depth: bool = False,
    f2_thresh: float = 1e-4,
    n_workers: "int | None" = None,
    overwrite: bool = False,
    frame_indices: "list[int] | None" = None,
    **fit_kwargs,
) -> int:
    """
    Image-based orientation + per-layer strain refinement using local cores.

    Calls :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`.
    Pass ``strain0_list`` via *fit_kwargs* to warm-start from a prior
    strain fit.

    Args:
        fit_strain: Strain components to refine.  ``None`` refines all six.
    """
    from .fitting import _STRAIN_ALL
    _fit_strain = tuple(fit_strain) if fit_strain is not None else _STRAIN_ALL
    os.makedirs(out_dir, exist_ok=True)

    if frame_indices is None:
        frame_indices = list(range(self.ny * self.nx))

    allowed_hkl = None
    if geometry_only:
        _E_max = fit_kwargs.get("E_max", 27_000)
        allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

    frames = self._load_frames(h5_path, h5_dataset, frame_indices)
    print(
        f"run_strain_image_local: {len(frame_indices)} frames | "
        f"fit_strain={list(_fit_strain)}",
        flush=True,
    )

    common = dict(
        out_dir=out_dir, fit_strain=_fit_strain,
        fit_kwargs={**fit_kwargs, "correct_depth": correct_depth},
        overwrite=overwrite,
    )
    stack_pkl = self._serialize_stack()
    try:
        n_ok = self._run_pool(
            _lm_img_strain_frame, frame_indices, frames, common,
            stack_pkl, camera, allowed_hkl,
            n_workers or os.cpu_count() or 1,
        )
    finally:
        os.unlink(stack_pkl)

    return n_ok

run_strain_local

run_strain_local(camera, seg_dir: str, out_dir: str, *, fit_strain: 'tuple | None' = None, orient_dir: 'str | None' = None, r_squared_min: float = 0.0, include_unfitted: bool = False, max_match_px=(10, 3), min_matched: int = 5, min_match_rate: float = 0.2, max_rms_px: 'float | None' = None, geometry_only: bool = True, correct_depth: bool = False, engine: str = 'stack', f2_thresh: float = 0.0001, n_workers: 'int | None' = None, overwrite: bool = False, frame_indices: 'list[int] | None' = None, **fit_kwargs) -> int

Fit stack orientation + per-layer strain for every frame using local cores.

Mirrors :meth:run_orientation_local but calls :func:~nrxrdct.laue.fitting.fit_strain_orientation_stack instead. Start from a good orientation (run :meth:run_orientation_local first and :meth:collect the result into the stack's layer U matrices).

Parameters:
  • fit_strain ('tuple | None', default: None ) –

    Strain components to refine, e.g. ('e_xx', 'e_yy', 'e_zz'). None refines all six.

  • correct_depth (bool, default: False ) –

    Project each layer's spots from its centre depth. Default False.

  • engine (str, default: 'stack' ) –

    Simulation engine — 'stack' (default) or 'darwin'. See :meth:run_orientation_local.

Source code in src/nrxrdct/laue/layered_map.py
def run_strain_local(
    self,
    camera,
    seg_dir: str,
    out_dir: str,
    *,
    fit_strain: "tuple | None" = None,
    orient_dir: "str | None" = None,
    r_squared_min: float = 0.0,
    include_unfitted: bool = False,
    max_match_px=(10, 3),
    min_matched: int = 5,
    min_match_rate: float = 0.2,
    max_rms_px: "float | None" = None,
    geometry_only: bool = True,
    correct_depth: bool = False,
    engine: str = "stack",
    f2_thresh: float = 1e-4,
    n_workers: "int | None" = None,
    overwrite: bool = False,
    frame_indices: "list[int] | None" = None,
    **fit_kwargs,
) -> int:
    """
    Fit stack orientation + per-layer strain for every frame using local cores.

    Mirrors :meth:`run_orientation_local` but calls
    :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack` instead.
    Start from a good orientation (run :meth:`run_orientation_local` first
    and :meth:`collect` the result into the stack's layer U matrices).

    Args:
        fit_strain: Strain components to refine, e.g.
            ``('e_xx', 'e_yy', 'e_zz')``.  ``None`` refines all six.
        correct_depth: Project each layer's spots from its centre depth.
            Default ``False``.
        engine: Simulation engine — ``'stack'`` (default) or
            ``'darwin'``.  See :meth:`run_orientation_local`.
    """
    from .fitting import _STRAIN_ALL
    _fit_strain = tuple(fit_strain) if fit_strain is not None else _STRAIN_ALL
    os.makedirs(out_dir, exist_ok=True)

    if frame_indices is None:
        h5s = sorted(glob.glob(os.path.join(seg_dir, "frame_?????.h5")))
        frame_indices = [int(os.path.basename(p)[6:11]) for p in h5s]

    allowed_hkl = None
    if geometry_only:
        _E_max = fit_kwargs.get("E_max_eV", 27_000)
        allowed_hkl = self._precompute_allowed(_E_max, f2_thresh)

    peaklists = self._load_peaklists(
        seg_dir, frame_indices, r_squared_min, include_unfitted, min_matched
    )
    print(
        f"run_strain_local: {len(frame_indices)} frames | "
        f"{len(peaklists)} with ≥{min_matched} spots | "
        f"fit_strain={list(_fit_strain)}",
        flush=True,
    )

    # Load per-frame orientation warm-starts if an orient_dir was given.
    orient_data: dict = {}
    if orient_dir is not None:
        for fi in frame_indices:
            path = os.path.join(orient_dir, f"frame_{fi:05d}.npz")
            if os.path.exists(path):
                try:
                    d = np.load(path, allow_pickle=False)
                    if "U_layers" in d:
                        orient_data[fi] = d["U_layers"]   # (n_layers, 3, 3)
                except Exception as exc:
                    print(f"  ✗  frame {fi}: orient load: {exc}", flush=True)
        print(
            f"  orient warm-start: {len(orient_data)}/{len(frame_indices)} "
            f"frames from {orient_dir!r}",
            flush=True,
        )

    common = dict(
        out_dir        = out_dir,
        fit_strain     = _fit_strain,
        max_match_px   = max_match_px,
        min_matched    = min_matched,
        min_match_rate = min_match_rate,
        max_rms_px     = max_rms_px,
        fit_kwargs     = {**fit_kwargs, "geometry_only": geometry_only,
                           "correct_depth": correct_depth, "engine": engine},
        overwrite      = overwrite,
        orient_data    = orient_data or None,
    )
    stack_pkl = self._serialize_stack()
    try:
        n_ok = self._run_pool(
            _lm_strain_frame, frame_indices, peaklists, common,
            stack_pkl, camera, allowed_hkl,
            n_workers or os.cpu_count() or 1,
        )
    finally:
        os.unlink(stack_pkl)

    print(f"  → {n_ok}/{len(frame_indices)} frames fitted", flush=True)
    return n_ok

save

save(path: str, compress: bool = True) -> None

Save the map to an HDF5 file.

All per-pixel arrays are stored under their attribute names. Motor positions land in motors/<name>.

Source code in src/nrxrdct/laue/layered_map.py
def save(self, path: str, compress: bool = True) -> None:
    """
    Save the map to an HDF5 file.

    All per-pixel arrays are stored under their attribute names.
    Motor positions land in ``motors/<name>``.
    """
    kw = {"compression": "gzip", "compression_opts": 4} if compress else {}

    with h5py.File(path, "w") as hf:
        meta = hf.create_group("meta")
        meta.attrs["ny"]       = self.ny
        meta.attrs["nx"]       = self.nx
        meta.attrs["n_layers"] = self.n_layers
        meta.attrs["h5_path"]  = self.h5_path or ""
        meta.attrs["entry"]    = self.entry
        meta.attrs["labels"]   = json.dumps(self.layer_labels)

        for name in (
            "R_global", "rotvec",
            "U", "U_eff",
            "rms_px", "mean_px", "n_matched", "match_rate",
            "cost", "n_sim", "score", "score0",
            "strain_tensor", "strain_voigt", "strain_tensor_deviatoric",
        ):
            hf.create_dataset(name, data=getattr(self, name), **kw)

        for name, arr in self.motors.items():
            hf.create_dataset(f"motors/{name}", data=arr, **kw)

    print(f"LayeredMap saved → {path!r}", flush=True)

segment_frame

segment_frame(base_dir: str, detector_mask: 'np.ndarray | None' = None, *, h5_dataset: 'str | None' = None, tiff_dir: 'str | None' = None, map_quantity: str = 'n_obs', motor_x: 'str | None' = None, motor_y: 'str | None' = None, motor_units: 'dict | None' = None, figsize: tuple = (14, 7)) -> None

Interactive single-frame segmentation tuner.

Click a pixel on the left map panel to load the frame, adjust segmentation parameters, press ⚙ Segment to preview, then 💾 Save to write <base_dir>/seg/frame_NNNNN.h5.

Parameters:
  • base_dir (str) –

    Processing root; seg files go to <base_dir>/seg/.

  • detector_mask ('np.ndarray | None', default: None ) –

    Valid-pixel mask (True = active).

  • h5_dataset ('str | None', default: None ) –

    Dataset path inside self.h5_path. Mutually exclusive with tiff_dir.

  • tiff_dir ('str | None', default: None ) –

    Folder of img_*.tif files. Mutually exclusive with h5_dataset.

  • map_quantity (str, default: 'n_obs' ) –

    Left-panel overview — 'n_obs' (default), 'match_rate', 'rms_px', 'score', 'cost'.

  • motor_x, motor_y –

    Motor names in self.motors for physical axes.

  • motor_units ('dict | None', default: None ) –

    Unit labels, e.g. {'sy': 'mm', 'sz': 'mm'}.

  • figsize (tuple, default: (14, 7) ) –

    Figure size in inches.

Source code in src/nrxrdct/laue/layered_map.py
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
def segment_frame(
    self,
    base_dir: str,
    detector_mask: "np.ndarray | None" = None,
    *,
    h5_dataset: "str | None" = None,
    tiff_dir: "str | None" = None,
    map_quantity: str = "n_obs",
    motor_x: "str | None" = None,
    motor_y: "str | None" = None,
    motor_units: "dict | None" = None,
    figsize: tuple = (14, 7),
) -> None:
    """
    Interactive single-frame segmentation tuner.

    Click a pixel on the left map panel to load the frame, adjust
    segmentation parameters, press **⚙ Segment** to preview, then
    **💾 Save** to write ``<base_dir>/seg/frame_NNNNN.h5``.

    Args:
        base_dir: Processing root; seg files go to ``<base_dir>/seg/``.
        detector_mask: Valid-pixel mask (``True`` = active).
        h5_dataset: Dataset path inside ``self.h5_path``.
            Mutually exclusive with *tiff_dir*.
        tiff_dir: Folder of ``img_*.tif`` files.
            Mutually exclusive with *h5_dataset*.
        map_quantity: Left-panel overview — ``'n_obs'`` (default),
            ``'match_rate'``, ``'rms_px'``, ``'score'``, ``'cost'``.
        motor_x, motor_y: Motor names in ``self.motors`` for physical axes.
        motor_units: Unit labels, e.g. ``{'sy': 'mm', 'sz': 'mm'}``.
        figsize: Figure size in inches.
    """
    import ipywidgets as ipw
    from IPython.display import display as _ipy_display
    from .segmentation import (
        LoG_segmentation, WTH_segmentation, hybrid_segmentation,
        clean_segmentation, label_segmented_image, measure_peaks,
        filter_and_rescale_images, gaussian_background, write_h5_spotsfile,
    )

    seg_dir = os.path.join(base_dir, "seg")
    os.makedirs(seg_dir, exist_ok=True)

    mu = motor_units or {}
    mx = self.motors.get(motor_x) if motor_x else None
    my = self.motors.get(motor_y) if motor_y else None

    if mx is not None and my is not None:
        extent_map = [mx[0, 0], mx[0, -1], my[-1, 0], my[0, 0]]
        xu_ = mu.get(motor_x, "")
        yu_ = mu.get(motor_y, "")
        xlabel_map = f"{motor_x} ({xu_})" if xu_ else motor_x
        ylabel_map = f"{motor_y} ({yu_})" if yu_ else motor_y
    else:
        extent_map = [0, self.nx, self.ny, 0]
        xlabel_map = "column (ix)"
        ylabel_map = "row (iy)"

    def _click_to_iy_ix(xdata: float, ydata: float):
        if mx is not None and my is not None:
            dist = (mx - xdata) ** 2 + (my - ydata) ** 2
            iy, ix = np.unravel_index(int(np.argmin(dist)), dist.shape)
        else:
            ix = int(np.clip(int(xdata), 0, self.nx - 1))
            iy = int(np.clip(int(ydata), 0, self.ny - 1))
        return int(iy), int(ix)

    _tiff_index: list = []

    def _load_image(frame_idx: int) -> "np.ndarray | None":
        if tiff_dir is not None:
            if not _tiff_index:
                import re as _re
                pat = _re.compile(r'(\d+)\.tiff?$', _re.IGNORECASE)
                files = []
                for fname in os.listdir(tiff_dir):
                    m = pat.search(fname)
                    if m:
                        files.append((int(m.group(1)), os.path.join(tiff_dir, fname)))
                files.sort(key=lambda t: t[0])
                _tiff_index.extend(p for _, p in files)
                if not _tiff_index:
                    print(f"  ✗ No .tif/.tiff files found in {tiff_dir!r}", flush=True)
                    return None
            if frame_idx >= len(_tiff_index):
                print(f"  ✗ frame {frame_idx} out of range", flush=True)
                return None
            try:
                import skimage.io
                return skimage.io.imread(_tiff_index[frame_idx]).astype(np.float32)
            except Exception as exc:
                print(f"  ✗ TIFF read error frame {frame_idx}: {exc}", flush=True)
                return None
        elif h5_dataset is not None:
            _h5 = self.h5_path
            if _h5 is None:
                print("  ✗ h5_path not set on this LayeredMap.", flush=True)
                return None
            try:
                with h5py.File(_h5, "r") as fh:
                    if h5_dataset not in fh:
                        print(f"  ✗ dataset {h5_dataset!r} not in {_h5!r}", flush=True)
                        return None
                    img = fh[h5_dataset][frame_idx].astype(np.float32)
                    if self.monitor and self.monitor in fh:
                        mon_val = float(fh[self.monitor][frame_idx])
                        if mon_val > 0:
                            img /= mon_val
                    return img
            except Exception as exc:
                print(f"  ✗ HDF5 read error frame {frame_idx}: {exc}", flush=True)
                return None
        return None

    def _build_n_obs_data() -> np.ndarray:
        raw = self.load_n_obs_map(seg_dir)
        return np.where(raw >= 0, raw.astype(float), np.nan)

    _map_opts = {
        "n_obs":       (_build_n_obs_data,                 "N spots (seg)",  "YlOrRd"),
        "match_rate":  (lambda: self.match_rate,           "Match rate",     "viridis"),
        "rms_px":      (lambda: self.rms_px,               "RMS (px)",       "plasma_r"),
        "mean_px":     (lambda: self.mean_px,              "Mean dev (px)",  "plasma_r"),
        "score":       (lambda: self.score,                "Image score",    "viridis"),
        "cost":        (lambda: self.cost,                 "Cost",           "plasma_r"),
    }
    _data_fn, map_label, map_cmap = _map_opts.get(
        map_quantity, _map_opts["n_obs"]
    )
    map_data = _data_fn()

    # ── figure ────────────────────────────────────────────────────────────
    with plt.ioff():
        fig = plt.figure(figsize=figsize)
    try:
        fig.canvas.manager.set_window_title("Laue — segment frame")
    except Exception:
        pass

    gs = fig.add_gridspec(
        1, 2, width_ratios=[1, 1.8], wspace=0.08,
        left=0.07, right=0.97, bottom=0.09, top=0.91,
    )
    ax_map = fig.add_subplot(gs[0])
    ax_det = fig.add_subplot(gs[1])

    im_map = ax_map.imshow(
        map_data, origin="upper", extent=extent_map,
        cmap=map_cmap, interpolation="nearest", aspect="auto",
    )
    cbar_map = fig.colorbar(im_map, ax=ax_map, fraction=0.04, pad=0.03,
                             shrink=0.8, label=map_label)
    ax_map.set_xlabel(xlabel_map, fontsize=9)
    ax_map.set_ylabel(ylabel_map, fontsize=9)

    def _map_title(label: str) -> str:
        return f"Click to select — {label}"

    ax_map.set_title(_map_title(map_label), fontsize=9)
    sel_dot, = ax_map.plot([], [], "w+", ms=11, mew=2.0, zorder=10)

    ax_det.set_facecolor("k")
    ax_det.set_aspect("equal")
    ax_det.set_xlabel("x (px)", fontsize=9)
    ax_det.set_ylabel("y (px)", fontsize=9)
    ax_det.set_title("← click map to select a frame", fontsize=9, color="#888")
    fig.suptitle(
        "Segment frame  —  click map → adjust params → Segment → Save",
        fontsize=9, color="#555",
    )

    _state: dict = {
        "frame_idx": None, "iy": None, "ix": None,
        "image": None, "proc_image": None, "props": None, "drawn": False,
        "saved_xy": None,   # (N,2) xy from existing seg file, or None
    }

    def _parse(s: str):
        parts = [x.strip() for x in s.split(",") if x.strip()]
        if not parts:
            raise ValueError(f"Empty field: {s!r}")
        nums = [float(p) if "." in p else int(p) for p in parts]
        return nums[0] if len(nums) == 1 else nums

    def _draw_det(props=None) -> None:
        disp = _state["proc_image"] if _state["proc_image"] is not None else _state["image"]
        saved_xlim = ax_det.get_xlim()
        saved_ylim = ax_det.get_ylim()
        ax_det.cla()
        ax_det.set_facecolor("k")
        if disp is None:
            ax_det.set_title("← click map to select a frame", fontsize=9, color="#888")
            fig.canvas.draw_idle()
            return
        nv, nh = disp.shape
        clip_min, clip_max = w_vrange.value
        clip_min, clip_max = float(clip_min), float(clip_max)
        if clip_max <= clip_min:
            clip_max = clip_min + 1.0
        disp_clipped = np.clip(disp, clip_min, clip_max)
        disp_norm    = (disp_clipped - clip_min) / (clip_max - clip_min)
        disp_show = np.log1p(disp_norm * 1000) if w_log_scale.value else disp_norm
        ax_det.imshow(disp_show, origin="upper", extent=[0, nh, nv, 0],
                      cmap=w_cmap.value, aspect="equal", zorder=0)
        _has_legend = False
        saved_xy = _state.get("saved_xy")
        if saved_xy is not None and len(saved_xy) > 0:
            ax_det.scatter(saved_xy[:, 0], saved_xy[:, 1], s=35,
                           c="none", edgecolors="#ffcc00",
                           linewidths=0.9, zorder=3,
                           label=f"saved ({len(saved_xy)})")
            _has_legend = True
        if props is not None and len(props) > 0:
            ys = np.array([p.centroid_weighted[0] for p in props])
            xs = np.array([p.centroid_weighted[1] for p in props])
            ax_det.scatter(xs, ys, s=35, c="none", edgecolors="#44aaff",
                           linewidths=0.9, zorder=4, label=f"new ({len(props)})")
            _has_legend = True
        if _has_legend:
            ax_det.legend(fontsize=7, loc="upper right",
                          facecolor="#111", edgecolor="#444", labelcolor="white",
                          framealpha=0.85)
        ax_det.set_aspect("equal")
        ax_det.set_xlabel("x (px)", fontsize=9)
        ax_det.set_ylabel("y (px)", fontsize=9)
        iy, ix = _state["iy"], _state["ix"]
        n_new   = len(props) if props is not None else None
        n_saved = len(saved_xy) if saved_xy is not None else None
        if n_new is not None and n_saved is not None:
            suffix = f"  — {n_new} new  |  {n_saved} saved"
        elif n_new is not None:
            suffix = f"  — {n_new} spots"
        elif n_saved is not None:
            suffix = f"  — {n_saved} saved spots"
        else:
            suffix = ""
        ax_det.set_title(f"Frame {_state['frame_idx']}  (iy={iy}, ix={ix}){suffix}", fontsize=9)
        if _state["drawn"]:
            ax_det.set_xlim(saved_xlim)
            ax_det.set_ylim(saved_ylim)
        _state["drawn"] = True
        fig.canvas.draw_idle()

    def _on_click(event) -> None:
        if event.inaxes is not ax_map:
            return
        if event.xdata is None or event.ydata is None:
            return
        try:
            if fig.canvas.toolbar.mode != "":
                return
        except Exception:
            pass
        iy, ix    = _click_to_iy_ix(event.xdata, event.ydata)
        frame_idx = self.frame_index(iy, ix)
        if mx is not None and my is not None:
            sel_dot.set_data([mx[iy, ix]], [my[iy, ix]])
        else:
            sel_dot.set_data([ix + 0.5], [iy + 0.5])
        image = _load_image(frame_idx)
        # Load existing segmentation if present
        saved_xy = None
        seg_path = os.path.join(seg_dir, f"frame_{frame_idx:05d}.h5")
        if os.path.exists(seg_path):
            try:
                from .segmentation import convert_spotsfile2peaklist
                pl = convert_spotsfile2peaklist(
                    seg_path, include_unfitted=True, r_squared_min=0.0
                )
                if len(pl) > 0:
                    saved_xy = pl[:, :2]   # (N, 2) x, y
            except Exception:
                pass
        _state.update(frame_idx=frame_idx, iy=iy, ix=ix,
                      image=image, proc_image=None, props=None,
                      saved_xy=saved_xy)
        _update_vrange(image)
        btn_segment.disabled = image is None
        btn_save.disabled    = True
        n_saved = len(saved_xy) if saved_xy is not None else 0
        _info.value = (
            f"<span style='color:#aaa'>Frame {frame_idx} loaded"
            + (f" — {n_saved} existing spots" if n_saved else "")
            + (" — no image data" if image is None else "") + "</span>"
        )
        _draw_det(props=None)

    fig.canvas.mpl_connect("button_press_event", _on_click)

    # ── widgets ───────────────────────────────────────────────────────────
    _sk  = dict(continuous_update=False, style={"description_width": "110px"},
                layout=ipw.Layout(width="320px"))
    _isk = dict(style={"description_width": "90px"}, layout=ipw.Layout(width="160px"))

    w_method = ipw.Dropdown(
        options=["LoG", "WTH", "Hybrid"], value="LoG",
        description="Method:", layout=ipw.Layout(width="220px"),
        style={"description_width": "70px"},
    )
    w_log_sigmas = ipw.Text(value="2, 4, 8", description="Sigmas:", **_sk,
                            placeholder="e.g. 2, 4, 8  or  4")
    w_wth_radius = ipw.Text(value="5, 7",    description="Disk radii:", **_sk,
                            placeholder="e.g. 5, 7  or  7")
    w_hyb_log    = ipw.Text(value="2, 4, 8", description="LoG sigmas:", **_sk,
                            placeholder="e.g. 2, 4, 8")
    w_hyb_wth    = ipw.Text(value="5, 7",    description="WTH radii:", **_sk,
                            placeholder="e.g. 5, 7")
    w_thresh     = ipw.FloatText(value=99.9, description="Threshold %:", **_sk)
    w_bg_sigma   = ipw.FloatText(value=5.0,  description="BG sigma:", **_sk)
    w_min_size   = ipw.IntText(value=3,   description="min_size:",    **_isk)
    w_max_size   = ipw.IntText(value=500, description="max_size:",    **_isk)
    w_gap_excl   = ipw.IntText(value=3,   description="gap_exclude:", **_isk)
    w_gap_clos   = ipw.IntText(value=3,   description="gap_closing:", **_isk)
    w_d          = ipw.IntText(value=10,  description="Crop d (px):", **_isk)
    w_r2         = ipw.FloatText(value=0.9, description="R² min:",    **_isk)
    w_fit_spots  = ipw.Checkbox(value=True, description="Fit spots (Gaussian)",
                                layout=ipw.Layout(width="200px"),
                                style={"description_width": "initial"})
    w_overwrite  = ipw.Checkbox(value=True, description="Overwrite existing",
                                layout=ipw.Layout(width="200px"))

    box_log    = ipw.VBox([w_log_sigmas])
    box_wth    = ipw.VBox([w_wth_radius])
    box_hybrid = ipw.VBox([w_hyb_log, w_hyb_wth])
    box_wth.layout.display    = "none"
    box_hybrid.layout.display = "none"

    def _on_method(change) -> None:
        m = change["new"]
        box_log.layout.display    = "" if m == "LoG"    else "none"
        box_wth.layout.display    = "" if m == "WTH"    else "none"
        box_hybrid.layout.display = "" if m == "Hybrid" else "none"

    w_method.observe(_on_method, names="value")

    _bkw = dict(layout=ipw.Layout(width="130px", height="32px"))
    btn_segment = ipw.Button(description="⚙ Segment", button_style="primary", **_bkw)
    btn_save    = ipw.Button(description="💾 Save",   button_style="success", **_bkw)
    btn_segment.disabled = True
    btn_save.disabled    = True

    _info = ipw.HTML(
        "<span style='color:#666;font-style:italic'>click a map pixel to load a frame</span>",
        layout=ipw.Layout(margin="4px 0 0 6px"),
    )

    def _cb_segment(_) -> None:
        import asyncio
        import queue as _qmod
        import threading

        image = _state["image"]
        if image is None:
            return
        if getattr(_cb_segment, "_running", False):
            return
        _cb_segment._running    = True
        btn_segment.disabled    = True
        btn_segment.description = "Running…"

        method = w_method.value
        try:
            if method == "LoG":
                method_kwargs = {"sigmas": _parse(w_log_sigmas.value),
                                 "threshold_percentile": w_thresh.value}
            elif method == "WTH":
                method_kwargs = {"disk_radius": _parse(w_wth_radius.value),
                                 "threshold_percentile": w_thresh.value}
            else:
                method_kwargs = {"log_sigmas": _parse(w_hyb_log.value),
                                 "wth_disk_radius": _parse(w_hyb_wth.value),
                                 "threshold_percentile": w_thresh.value}
        except ValueError as exc:
            _info.value = f"<b style='color:#f44'>Parameter error: {exc}</b>"
            btn_segment.description = "⚙ Segment"
            btn_segment.disabled    = False
            _cb_segment._running    = False
            return

        clean_kw = dict(min_size=w_min_size.value, max_size=w_max_size.value,
                        gap_exclude=w_gap_excl.value, gap_closing=w_gap_clos.value)
        bg_sigma = w_bg_sigma.value
        _det_mask = (detector_mask.astype(bool) if detector_mask is not None
                     else np.ones(image.shape, dtype=bool))

        q: _qmod.Queue = _qmod.Queue()

        def _run() -> None:
            try:
                valid = _det_mask
                frame = image.copy().astype(np.float32)
                if bg_sigma > 0:
                    bg    = gaussian_background(frame, valid, sigma=bg_sigma)
                    frame = frame - bg
                frame -= frame[valid].min()
                frame[~valid] = 0.0
                if method == "WTH":
                    seg = WTH_segmentation(frame, valid, **method_kwargs)
                elif method == "Hybrid":
                    seg = hybrid_segmentation(frame, valid, **method_kwargs)
                else:
                    seg = LoG_segmentation(frame, valid, **method_kwargs)
                final_mask, _ = clean_segmentation(seg, valid, frame, **clean_kw)
                filt = filter_and_rescale_images(frame, cutoff_freq=0.001)
                labels, _, _ = label_segmented_image(final_mask, filt)
                props = measure_peaks(labels, filt)
                q.put(("ok", props, filt))
            except Exception as exc:
                q.put(("err", exc))

        async def _wait() -> None:
            threading.Thread(target=_run, daemon=True).start()
            while q.empty():
                await asyncio.sleep(0.15)
            tag, *payload = q.get_nowait()
            if tag == "err":
                _info.value = f"<b style='color:#f44'>Error: {payload[0]}</b>"
            else:
                props, filt = payload
                _state["props"] = props
                _state["proc_image"] = filt
                n = len(props)
                col = "#44dd66" if n > 0 else "#ffaa33"
                _info.value = f"<b style='color:{col}'>{n} spots detected</b>"
                btn_save.disabled = n == 0
                _draw_det(props=props)
                if n > 0:
                    _cb_save(None)
            btn_segment.description = "⚙ Segment"
            btn_segment.disabled    = False
            _cb_segment._running    = False

        try:
            asyncio.get_event_loop().create_task(_wait())
        except RuntimeError:
            asyncio.ensure_future(_wait())

    def _cb_save(_) -> None:
        props = _state["props"]
        if not props:
            return
        frame_idx = _state["frame_idx"]
        out_path  = os.path.join(seg_dir, f"frame_{frame_idx:05d}.h5")
        try:
            write_h5_spotsfile(
                _state["image"], props, outpath=out_path,
                d=w_d.value, r_squared_min=w_r2.value,
                overwrite=w_overwrite.value, fit_spots=w_fit_spots.value,
            )
            _info.value = f"<b style='color:#44dd66'>Saved → {out_path}</b>"
            print(f"  💾 Saved → {os.path.abspath(out_path)}")
            _state["saved_xy"] = None   # new result replaces old overlay
            if w_map_quantity.value == "n_obs":
                new_data = _build_n_obs_data()
                im_map.set_data(new_data)
                valid = new_data[np.isfinite(new_data)]
                if valid.size:
                    im_map.set_clim(valid.min(), valid.max())
                fig.canvas.draw_idle()
        except Exception as exc:
            _info.value = f"<b style='color:#f44'>Save error: {exc}</b>"

    w_map_quantity = ipw.Dropdown(
        options=[(label, key) for key, (_, label, _) in _map_opts.items()],
        value=map_quantity if map_quantity in _map_opts else "n_obs",
        layout=ipw.Layout(width="150px", height="32px"),
    )

    def _cb_map_quantity(change) -> None:
        data_fn, label, cmap = _map_opts[change["new"]]
        im_map.set_data(data_fn())
        im_map.set_cmap(cmap)
        im_map.autoscale()
        cbar_map.set_label(label)
        ax_map.set_title(_map_title(label), fontsize=9)
        fig.canvas.draw_idle()

    w_map_quantity.observe(_cb_map_quantity, names="value")

    w_log_scale = ipw.Checkbox(value=True, description="Log scale",
                               layout=ipw.Layout(width="110px"),
                               style={"description_width": "initial"})
    w_vrange = ipw.FloatRangeSlider(
        value=[0.0, 1.0], min=0.0, max=1.0, step=0.01,
        description="Range:", continuous_update=False,
        readout_format=".3g",
        layout=ipw.Layout(width="320px"),
        style={"description_width": "50px"},
    )
    w_cmap = ipw.Dropdown(
        options=sorted(plt.colormaps()), value="gray",
        description="Colormap:",
        layout=ipw.Layout(width="200px"),
        style={"description_width": "70px"},
    )

    def _update_vrange(img: "np.ndarray | None") -> None:
        if img is None:
            return
        pos = img[img > 0]
        lo_default = float(np.percentile(pos, 1)) if pos.size else 0.0
        hi_default = float(np.percentile(pos, 99.9)) if pos.size else 1.0
        if hi_default <= lo_default:
            hi_default = lo_default + 1.0
        # Cap the track at a high percentile rather than the raw pixel max —
        # a single saturated/hot pixel would otherwise stretch the slider so
        # far that the vmin/vmax handles bunch up in a sliver near the low end.
        slider_max = hi_default * 1.2
        w_vrange.max = max(slider_max, w_vrange.max)  # avoid a transient value > max
        w_vrange.value = [lo_default, hi_default]
        w_vrange.max = slider_max
        w_vrange.step = max(slider_max / 200.0, 1e-6)

    def _redraw(_=None) -> None:
        if _state["image"] is not None:
            _draw_det(props=_state["props"])

    def _on_fit_toggle(change) -> None:
        w_r2.disabled = not change["new"]

    w_log_scale.observe(_redraw, names="value")
    w_vrange.observe(_redraw, names="value")
    w_cmap.observe(_redraw, names="value")
    w_fit_spots.observe(_on_fit_toggle, names="value")
    btn_segment.on_click(_cb_segment)
    btn_save.on_click(_cb_save)

    _controls = ipw.VBox([
        ipw.HBox([w_method], layout=ipw.Layout(margin="4px 0 2px 0")),
        ipw.HBox([
            ipw.VBox([box_log, box_wth, box_hybrid, w_thresh, w_bg_sigma],
                     layout=ipw.Layout(padding="0 16px 0 0")),
            ipw.VBox([
                ipw.HTML("<b>Clean:</b>"),
                ipw.HBox([w_min_size, w_max_size]),
                ipw.HBox([w_gap_excl, w_gap_clos]),
                ipw.HTML("<b>Save:</b>"),
                ipw.HBox([w_d, w_r2]),
                w_fit_spots, w_overwrite,
            ]),
        ]),
        ipw.HBox([btn_segment, btn_save,
                  ipw.HTML("<span style='color:#aaa;align-self:center'>map:</span>",
                           layout=ipw.Layout(margin="0 2px 0 10px")),
                  w_map_quantity],
                 layout=ipw.Layout(gap="8px", margin="6px 0 0 0", align_items="center")),
        ipw.HBox(
            [ipw.HTML("<b style='line-height:26px;margin-right:6px'>Display:</b>"),
             w_log_scale, w_vrange, w_cmap],
            layout=ipw.Layout(gap="6px", margin="4px 0 0 0", align_items="center"),
        ),
        _info,
    ], layout=ipw.Layout(padding="6px 8px"))

    _ipy_display(ipw.VBox([fig.canvas, _controls]))

set_result

set_result(iy: int, ix: int, result) -> None

Store a stack fitting result for pixel (iy, ix).

Accepts :class:~nrxrdct.laue.fitting.StackFitResult, :class:~nrxrdct.laue.fitting.StackStrainFitResult, :class:~nrxrdct.laue.fitting.StackImageRefinementResult, and :class:~nrxrdct.laue.fitting.StackStrainImageRefinementResult.

Source code in src/nrxrdct/laue/layered_map.py
def set_result(self, iy: int, ix: int, result) -> None:
    """
    Store a stack fitting result for pixel ``(iy, ix)``.

    Accepts :class:`~nrxrdct.laue.fitting.StackFitResult`,
    :class:`~nrxrdct.laue.fitting.StackStrainFitResult`,
    :class:`~nrxrdct.laue.fitting.StackImageRefinementResult`, and
    :class:`~nrxrdct.laue.fitting.StackStrainImageRefinementResult`.
    """
    from .fitting import (
        StackFitResult, StackStrainFitResult,
        StackImageRefinementResult, StackStrainImageRefinementResult,
    )

    self._results[iy][ix] = result

    self.R_global[iy, ix] = result.R_global
    self.rotvec[iy, ix]   = result.rotvec
    for li, U in enumerate(result.U_layers):
        self.U[li, iy, ix] = U

    if isinstance(result, (StackFitResult, StackStrainFitResult)):
        self.rms_px[iy, ix]     = result.rms_px
        self.mean_px[iy, ix]    = result.mean_px
        self.n_matched[iy, ix]  = result.n_matched
        self.match_rate[iy, ix] = result.match_rate
        self.cost[iy, ix]       = result.cost
        self.n_sim[iy, ix]      = result.n_sim

    if isinstance(result, (StackImageRefinementResult, StackStrainImageRefinementResult)):
        self.score[iy, ix]  = result.score
        self.score0[iy, ix] = result.score0
        self.n_sim[iy, ix]  = result.n_sim

    if isinstance(result, (StackStrainFitResult, StackStrainImageRefinementResult)):
        for li, (U_eff, eps, voigt) in enumerate(zip(
            result.U_eff_layers, result.strain_tensors, result.strain_voigts
        )):
            self.U_eff[li, iy, ix]           = U_eff
            self.strain_tensor[li, iy, ix]   = eps
            self.strain_voigt[li, iy, ix]    = voigt
            self.strain_tensor_deviatoric[li, iy, ix] = (
                eps - np.trace(eps) / 3.0 * np.eye(3)
            )

submit_guided_segmentation

submit_guided_segmentation(base_dir: str, camera, h5_dataset: str, mask_path: str, *, n_jobs: int = 10, partition: str = 'all', time: str = '02:00:00', mem: str = '8G', cpus_per_task: int = 1, python_bin: str = 'python', f2_thresh: float = 0.0001, correct_depth: bool = False, overwrite: bool = False, extra_sbatch: 'dict | None' = None, **seg_kwargs) -> list

Submit simulation-guided segmentation jobs to SLURM.

The stack's current U matrices (set interactively or from a previous fit) are serialised to a pickle and shipped to each job. Every worker simulates Laue spots once with that fixed orientation and uses the predicted positions to drive :func:~nrxrdct.laue.segmentation.simulation_guided_segmentation on its assigned frames.

This is the right strategy when one orientation estimate is a good approximation for the whole map — typically true for well-ordered substrate materials. Results are written to <base_dir>/seg/frame_?????.h5 in the same HDF5 format produced by :func:~nrxrdct.laue.segmentation.write_h5_spotsfile, so the output is directly compatible with :meth:run_orientation_local and :meth:run_strain_local.

Workflow::

lmap.stack.all_layers[0].U = my_U    # set orientation estimate
lmap.submit_guided_segmentation(
    "proc/", camera, "1.1/measurement/eiger4m", "mask.npy",
    search_radius=8, min_snr=2.0,
)
# Wait for jobs, then:
lmap.run_orientation_local(camera, seg_dir="proc/seg/", out_dir="proc/ubs/")
Parameters:
  • base_dir (str) –

    Processing root directory. Sub-directories seg/, slurm_logs/, and job_meta/ are created inside it automatically.

  • camera –

    Detector geometry (Camera object).

  • h5_dataset (str) –

    Dataset path inside self.h5_path, e.g. '1.1/measurement/eiger4m'.

  • mask_path (str) –

    Path to a .npy file containing the boolean detector validity mask (True = active pixel).

  • n_jobs (int, default: 10 ) –

    Number of SLURM array jobs. Frames are split evenly.

  • partition (str, default: 'all' ) –

    SLURM partition name.

  • time (str, default: '02:00:00' ) –

    SLURM wall-clock limit ('HH:MM:SS').

  • mem (str, default: '8G' ) –

    Memory per job (e.g. '8G').

  • cpus_per_task (int, default: 1 ) –

    CPU threads per SLURM task.

  • python_bin (str, default: 'python' ) –

    Python interpreter path on the compute nodes.

  • f2_thresh (float, default: 0.0001 ) –

    Structure-factor threshold for :func:~nrxrdct.laue.simulate_laue_stack (spot pre-filter). Default 1e-4.

  • correct_depth (bool, default: False ) –

    Pass True to depth-correct predicted spot positions before guiding the search.

  • overwrite (bool, default: False ) –

    If True, re-segment frames that already have an output file.

  • extra_sbatch ('dict | None', default: None ) –

    Additional --key=value sbatch arguments.

  • **seg_kwargs –

    Forwarded to :func:~nrxrdct.laue.segmentation.simulation_guided_segmentation: psf_sigma, search_radius, min_distance, min_snr, bg_sigma, d, r_squared_min, include_unfitted, fit_spots.

Returns:
  • list –

    List of SLURM job ID strings.

Source code in src/nrxrdct/laue/layered_map.py
def submit_guided_segmentation(
    self,
    base_dir: str,
    camera,
    h5_dataset: str,
    mask_path: str,
    *,
    n_jobs: int = 10,
    partition: str = "all",
    time: str = "02:00:00",
    mem: str = "8G",
    cpus_per_task: int = 1,
    python_bin: str = "python",
    f2_thresh: float = 1e-4,
    correct_depth: bool = False,
    overwrite: bool = False,
    extra_sbatch: "dict | None" = None,
    **seg_kwargs,
) -> list:
    """
    Submit simulation-guided segmentation jobs to SLURM.

    The stack's **current U matrices** (set interactively or from a
    previous fit) are serialised to a pickle and shipped to each job.
    Every worker simulates Laue spots **once** with that fixed orientation
    and uses the predicted positions to drive
    :func:`~nrxrdct.laue.segmentation.simulation_guided_segmentation`
    on its assigned frames.

    This is the right strategy when one orientation estimate is a good
    approximation for the whole map — typically true for well-ordered
    substrate materials.  Results are written to
    ``<base_dir>/seg/frame_?????.h5`` in the same HDF5 format produced by
    :func:`~nrxrdct.laue.segmentation.write_h5_spotsfile`, so the output
    is directly compatible with
    :meth:`run_orientation_local` and :meth:`run_strain_local`.

    Workflow::

        lmap.stack.all_layers[0].U = my_U    # set orientation estimate
        lmap.submit_guided_segmentation(
            "proc/", camera, "1.1/measurement/eiger4m", "mask.npy",
            search_radius=8, min_snr=2.0,
        )
        # Wait for jobs, then:
        lmap.run_orientation_local(camera, seg_dir="proc/seg/", out_dir="proc/ubs/")

    Args:
        base_dir: Processing root directory.  Sub-directories
            ``seg/``, ``slurm_logs/``, and ``job_meta/`` are created
            inside it automatically.
        camera: Detector geometry (``Camera`` object).
        h5_dataset: Dataset path inside ``self.h5_path``, e.g.
            ``'1.1/measurement/eiger4m'``.
        mask_path: Path to a ``.npy`` file containing the boolean
            detector validity mask (``True`` = active pixel).
        n_jobs: Number of SLURM array jobs.  Frames are split evenly.
        partition: SLURM partition name.
        time: SLURM wall-clock limit (``'HH:MM:SS'``).
        mem: Memory per job (e.g. ``'8G'``).
        cpus_per_task: CPU threads per SLURM task.
        python_bin: Python interpreter path on the compute nodes.
        f2_thresh: Structure-factor threshold for
            :func:`~nrxrdct.laue.simulate_laue_stack` (spot
            pre-filter).  Default ``1e-4``.
        correct_depth: Pass ``True`` to depth-correct predicted spot
            positions before guiding the search.
        overwrite: If ``True``, re-segment frames that already have an
            output file.
        extra_sbatch: Additional ``--key=value`` sbatch arguments.
        **seg_kwargs: Forwarded to
            :func:`~nrxrdct.laue.segmentation.simulation_guided_segmentation`:
            ``psf_sigma``, ``search_radius``, ``min_distance``,
            ``min_snr``, ``bg_sigma``, ``d``, ``r_squared_min``,
            ``include_unfitted``, ``fit_spots``.

    Returns:
        List of SLURM job ID strings.
    """
    if self.h5_path is None:
        raise ValueError("h5_path not set on this LayeredMap.")

    dirs      = self._setup_slurm_dirs(base_dir, "seg")
    stack_pkl = self._write_stack_pkl(base_dir)

    all_frames = list(range(self.ny * self.nx))
    chunks = [
        list(map(int, c))
        for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
        if len(c) > 0
    ]

    meta = {
        "stack_pkl":     stack_pkl,
        "camera":        self._camera_to_dict(camera),
        "h5_path":       self.h5_path,
        "h5_dataset":    h5_dataset,
        "mask_path":     mask_path,
        "monitor":       self.monitor,
        "seg_dir":       dirs["out"],
        "f2_thresh":     f2_thresh,
        "correct_depth": correct_depth,
        "overwrite":     overwrite,
        **seg_kwargs,
    }
    meta_path = os.path.join(dirs["job_meta"], "guided_seg_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    job_ids = self._submit_jobs(
        "lm_gseg", "nrxrdct.laue.workers.slurm_guided_seg_worker",
        meta_path, chunks, dirs["slurm_logs"],
        partition=partition, time=time, mem=mem,
        cpus_per_task=cpus_per_task, python_bin=python_bin,
        extra_sbatch=extra_sbatch,
    )
    print(f"Guided segmentation: {len(job_ids)} jobs → {dirs['out']}")
    return job_ids

submit_image_orientation

submit_image_orientation(base_dir: str, camera, h5_path: 'str | None' = None, h5_dataset: 'str | None' = None, *, n_jobs: int = 10, partition: str = 'all', time: str = '02:00:00', mem: str = '8G', cpus_per_task: int = 1, python_bin: str = 'python', geometry_only: bool = True, f2_thresh: float = 1e-06, correct_depth: bool = False, overwrite: bool = False, extra_sbatch: 'dict | None' = None, **fit_kwargs) -> list

Submit image-based orientation refinement to SLURM.

Unlike :meth:submit_orientation, which works from a pre-extracted peak list, this method refines the orientation directly from the raw detector image using :func:~nrxrdct.laue.fitting.refine_orientation_image_stack. The fit correlates a simulated spot pattern against the measured intensity image, which is useful when segmentation is difficult or unreliable.

Requires self.h5_path to be set on the object, or an explicit h5_path argument.

Workflow::

lmap.h5_path = "/data/scan.h5"
job_ids = lmap.submit_image_orientation(
    base_dir, camera, h5_dataset="1.1/measurement/eiger4m"
)
# wait for SLURM jobs to finish
lmap.collect("path/to/base_dir/layered_img_ori/")

Output files are written to <base_dir>/layered_img_ori/frame_?????.npz. Each file contains R_global, rotvec, U_layers, score, score0, and n_sim.

Parameters:
  • base_dir (str) –

    Root directory for all job artefacts.

  • camera –

    Detector geometry (:class:~nrxrdct.laue.camera.Camera).

  • h5_path ('str | None', default: None ) –

    Path to the HDF5 scan file. Defaults to self.h5_path.

  • h5_dataset ('str | None', default: None ) –

    Dataset path within the HDF5 file, e.g. "1.1/measurement/eiger4m". Required.

  • n_jobs (int, default: 10 ) –

    Number of SLURM array jobs.

  • partition (str, default: 'all' ) –

    SLURM partition name.

  • time (str, default: '02:00:00' ) –

    Wall-clock time limit per job (HH:MM:SS).

  • mem (str, default: '8G' ) –

    Memory limit per job. Image-based fitting loads full detector frames; increase if jobs are killed for OOM.

  • cpus_per_task (int, default: 1 ) –

    CPU cores per job / ProcessPoolExecutor workers.

  • python_bin (str, default: 'python' ) –

    Python interpreter on the cluster.

  • geometry_only (bool, default: True ) –

    Use precomputed allowed-HKL set instead of computing structure factors per spot. Strongly recommended (default True).

  • f2_thresh (float, default: 1e-06 ) –

    Structure-factor threshold for allowed-HKL precomputation.

  • correct_depth (bool, default: False ) –

    Apply depth correction to pixel projections.

  • overwrite (bool, default: False ) –

    Re-process frames that already have a result file.

  • extra_sbatch ('dict | None', default: None ) –

    Additional #SBATCH directives.

  • **fit_kwargs –

    Extra keyword arguments forwarded to :func:~nrxrdct.laue.fitting.refine_orientation_image_stack (e.g. E_min_eV, E_max_eV, kernel_sigma, bg_sigma, max_angle_deg).

Returns:
  • list –

    List of SLURM job IDs (strings).

Source code in src/nrxrdct/laue/layered_map.py
def submit_image_orientation(
    self,
    base_dir: str,
    camera,
    h5_path: "str | None" = None,
    h5_dataset: "str | None" = None,
    *,
    n_jobs: int = 10,
    partition: str = "all",
    time: str = "02:00:00",
    mem: str = "8G",
    cpus_per_task: int = 1,
    python_bin: str = "python",
    geometry_only: bool = True,
    f2_thresh: float = 1e-6,
    correct_depth: bool = False,
    overwrite: bool = False,
    extra_sbatch: "dict | None" = None,
    **fit_kwargs,
) -> list:
    """
    Submit image-based orientation refinement to SLURM.

    Unlike :meth:`submit_orientation`, which works from a pre-extracted
    peak list, this method refines the orientation directly from the raw
    detector image using
    :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack`.
    The fit correlates a simulated spot pattern against the measured
    intensity image, which is useful when segmentation is difficult or
    unreliable.

    Requires ``self.h5_path`` to be set on the object, or an explicit
    ``h5_path`` argument.

    **Workflow**::

        lmap.h5_path = "/data/scan.h5"
        job_ids = lmap.submit_image_orientation(
            base_dir, camera, h5_dataset="1.1/measurement/eiger4m"
        )
        # wait for SLURM jobs to finish
        lmap.collect("path/to/base_dir/layered_img_ori/")

    Output files are written to ``<base_dir>/layered_img_ori/frame_?????.npz``.
    Each file contains ``R_global``, ``rotvec``, ``U_layers``, ``score``,
    ``score0``, and ``n_sim``.

    Args:
        base_dir: Root directory for all job artefacts.
        camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
        h5_path: Path to the HDF5 scan file.  Defaults to ``self.h5_path``.
        h5_dataset: Dataset path within the HDF5 file, e.g.
            ``"1.1/measurement/eiger4m"``.  Required.
        n_jobs: Number of SLURM array jobs.
        partition: SLURM partition name.
        time: Wall-clock time limit per job (``HH:MM:SS``).
        mem: Memory limit per job.  Image-based fitting loads full detector
            frames; increase if jobs are killed for OOM.
        cpus_per_task: CPU cores per job / ``ProcessPoolExecutor`` workers.
        python_bin: Python interpreter on the cluster.
        geometry_only: Use precomputed allowed-HKL set instead of computing
            structure factors per spot.  Strongly recommended (default ``True``).
        f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
        correct_depth: Apply depth correction to pixel projections.
        overwrite: Re-process frames that already have a result file.
        extra_sbatch: Additional ``#SBATCH`` directives.
        **fit_kwargs: Extra keyword arguments forwarded to
            :func:`~nrxrdct.laue.fitting.refine_orientation_image_stack`
            (e.g. ``E_min_eV``, ``E_max_eV``, ``kernel_sigma``,
            ``bg_sigma``, ``max_angle_deg``).

    Returns:
        List of SLURM job IDs (strings).
    """
    h5_path = h5_path or self.h5_path
    if h5_path is None:
        raise ValueError("h5_path not set on the object and not passed as argument.")
    if h5_dataset is None:
        raise ValueError("h5_dataset is required.")
    dirs = self._setup_slurm_dirs(base_dir, "layered_img_ori")
    stack_pkl = self._write_stack_pkl(base_dir)

    meta = {
        "stack_pkl":    stack_pkl,
        "camera":       self._camera_to_dict(camera),
        "h5_path":      h5_path,
        "h5_dataset":   h5_dataset,
        "out_dir":      dirs["out"],
        "geometry_only":  geometry_only,
        "f2_thresh":      f2_thresh,
        "correct_depth":  correct_depth,
        "overwrite":      overwrite,
        **fit_kwargs,
    }
    meta_path = os.path.join(dirs["job_meta"], "layered_img_orient_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    all_frames = list(range(self.ny * self.nx))
    chunks = [
        list(map(int, c))
        for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
        if len(c) > 0
    ]

    return self._submit_jobs(
        "lm_img_ori",
        "nrxrdct.laue.workers.slurm_layered_img_orient_worker",
        meta_path, chunks, dirs["slurm_logs"],
        partition=partition, time=time, mem=mem,
        cpus_per_task=cpus_per_task, python_bin=python_bin,
        extra_sbatch=extra_sbatch,
    )

submit_orientation

submit_orientation(base_dir: str, camera, *, seg_dir: 'str | None' = None, n_jobs: int = 10, partition: str = 'all', time: str = '02:00:00', mem: str = '4G', cpus_per_task: int = 1, python_bin: str = 'python', max_match_px=(30, 10, 3), min_matched: int = 5, min_match_rate: float = 0.2, max_rms_px: 'float | None' = None, r_squared_min: float = 0.0, include_unfitted: bool = False, geometry_only: bool = True, f2_thresh: float = 1e-06, correct_depth: bool = False, overwrite: bool = False, extra_sbatch: 'dict | None' = None, **fit_kwargs) -> list

Submit peak-list-based orientation fitting for the full LayeredCrystal stack to SLURM.

Each frame is fitted with :func:~nrxrdct.laue.fitting.fit_orientation_stack, which finds a single global rotation shared by all layers simultaneously. Fitting is staged: max_match_px is applied as a sequence of decreasing matching radii so the optimizer coarsely locks onto the orientation before tightening.

Workflow::

job_ids = lmap.submit_orientation(base_dir, camera, seg_dir="path/to/seg")
# wait for SLURM jobs to finish
lmap.collect("path/to/base_dir/layered_ori/")

Output files are written to <base_dir>/layered_ori/frame_?????.npz.

Parameters:
  • base_dir (str) –

    Root directory for all job artefacts. Sub-directories layered_ori/, slurm_logs/ and job_meta/ are created automatically.

  • camera –

    Detector geometry (:class:~nrxrdct.laue.camera.Camera).

  • seg_dir ('str | None', default: None ) –

    Directory containing frame_?????.h5 segmentation files produced by :meth:segment_frame or the segmentation workers. Defaults to <base_dir>/seg.

  • n_jobs (int, default: 10 ) –

    Number of SLURM array jobs. Frames are split evenly across jobs; each job runs all its frames in a ProcessPoolExecutor with up to cpus_per_task workers.

  • partition (str, default: 'all' ) –

    SLURM partition name.

  • time (str, default: '02:00:00' ) –

    Wall-clock time limit per job (HH:MM:SS).

  • mem (str, default: '4G' ) –

    Memory limit per job (e.g. "4G").

  • cpus_per_task (int, default: 1 ) –

    CPU cores per job, also the ProcessPoolExecutor worker count. Set to > 1 to parallelise frames within a job.

  • python_bin (str, default: 'python' ) –

    Python interpreter to invoke on the cluster (e.g. "python" or "/path/to/env/bin/python").

  • max_match_px –

    Staged matching threshold(s) in pixels. A sequence (30, 10, 3) runs three successive refinement stages. Each stage uses the previous stage's solution as the starting point.

  • min_matched (int, default: 5 ) –

    Minimum number of matched spots required to accept and save a result.

  • min_match_rate (float, default: 0.2 ) –

    Minimum fraction of simulated spots that must be matched (n_matched / n_sim).

  • max_rms_px ('float | None', default: None ) –

    If set, frames with RMS pixel residual above this value are rejected even if min_matched is satisfied.

  • r_squared_min (float, default: 0.0 ) –

    Minimum Gaussian-fit R² for peaks loaded from the segmentation file. 0.0 (default) keeps all peaks including those with poor fits.

  • include_unfitted (bool, default: False ) –

    If True, also use peaks that failed Gaussian fitting (stored with fitted=False in the segmentation file).

  • geometry_only (bool, default: True ) –

    If True (default), precompute the allowed-HKL set from structure factors at rest and skip per-spot F² evaluation during the fit. Much faster; disable only if you need exact intensity weighting.

  • f2_thresh (float, default: 1e-06 ) –

    Structure-factor threshold used when precomputing the allowed-HKL set (geometry_only=True) or filtering spots (geometry_only=False).

  • correct_depth (bool, default: False ) –

    Apply depth correction to the pixel projection to account for the displacement of the diffracting volume below the sample surface.

  • overwrite (bool, default: False ) –

    Re-process frames that already have a result file.

  • extra_sbatch ('dict | None', default: None ) –

    Additional #SBATCH directives passed verbatim, e.g. {"account": "myproject", "constraint": "gpu"}.

  • **fit_kwargs –

    Extra keyword arguments forwarded to :func:~nrxrdct.laue.fitting.fit_orientation_stack (e.g. E_min_eV, E_max_eV, source, ftol).

Returns:
  • list –

    List of SLURM job IDs (strings).

Source code in src/nrxrdct/laue/layered_map.py
def submit_orientation(
    self,
    base_dir: str,
    camera,
    *,
    seg_dir: "str | None" = None,
    n_jobs: int = 10,
    partition: str = "all",
    time: str = "02:00:00",
    mem: str = "4G",
    cpus_per_task: int = 1,
    python_bin: str = "python",
    max_match_px=(30, 10, 3),
    min_matched: int = 5,
    min_match_rate: float = 0.2,
    max_rms_px: "float | None" = None,
    r_squared_min: float = 0.0,
    include_unfitted: bool = False,
    geometry_only: bool = True,
    f2_thresh: float = 1e-6,
    correct_depth: bool = False,
    overwrite: bool = False,
    extra_sbatch: "dict | None" = None,
    **fit_kwargs,
) -> list:
    """
    Submit peak-list-based orientation fitting for the full LayeredCrystal
    stack to SLURM.

    Each frame is fitted with :func:`~nrxrdct.laue.fitting.fit_orientation_stack`,
    which finds a single global rotation shared by all layers simultaneously.
    Fitting is staged: ``max_match_px`` is applied as a sequence of decreasing
    matching radii so the optimizer coarsely locks onto the orientation before
    tightening.

    **Workflow**::

        job_ids = lmap.submit_orientation(base_dir, camera, seg_dir="path/to/seg")
        # wait for SLURM jobs to finish
        lmap.collect("path/to/base_dir/layered_ori/")

    Output files are written to ``<base_dir>/layered_ori/frame_?????.npz``.

    Args:
        base_dir: Root directory for all job artefacts.  Sub-directories
            ``layered_ori/``, ``slurm_logs/`` and ``job_meta/`` are created
            automatically.
        camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
        seg_dir: Directory containing ``frame_?????.h5`` segmentation files
            produced by :meth:`segment_frame` or the segmentation workers.
            Defaults to ``<base_dir>/seg``.
        n_jobs: Number of SLURM array jobs.  Frames are split evenly across
            jobs; each job runs all its frames in a ``ProcessPoolExecutor``
            with up to ``cpus_per_task`` workers.
        partition: SLURM partition name.
        time: Wall-clock time limit per job (``HH:MM:SS``).
        mem: Memory limit per job (e.g. ``"4G"``).
        cpus_per_task: CPU cores per job, also the ``ProcessPoolExecutor``
            worker count.  Set to ``> 1`` to parallelise frames within a job.
        python_bin: Python interpreter to invoke on the cluster (e.g.
            ``"python"`` or ``"/path/to/env/bin/python"``).
        max_match_px: Staged matching threshold(s) in pixels.  A sequence
            ``(30, 10, 3)`` runs three successive refinement stages.  Each
            stage uses the previous stage's solution as the starting point.
        min_matched: Minimum number of matched spots required to accept and
            save a result.
        min_match_rate: Minimum fraction of simulated spots that must be
            matched (``n_matched / n_sim``).
        max_rms_px: If set, frames with RMS pixel residual above this value
            are rejected even if ``min_matched`` is satisfied.
        r_squared_min: Minimum Gaussian-fit R² for peaks loaded from the
            segmentation file.  ``0.0`` (default) keeps all peaks including
            those with poor fits.
        include_unfitted: If ``True``, also use peaks that failed Gaussian
            fitting (stored with ``fitted=False`` in the segmentation file).
        geometry_only: If ``True`` (default), precompute the allowed-HKL
            set from structure factors at rest and skip per-spot F² evaluation
            during the fit.  Much faster; disable only if you need exact
            intensity weighting.
        f2_thresh: Structure-factor threshold used when precomputing the
            allowed-HKL set (``geometry_only=True``) or filtering spots
            (``geometry_only=False``).
        correct_depth: Apply depth correction to the pixel projection to
            account for the displacement of the diffracting volume below
            the sample surface.
        overwrite: Re-process frames that already have a result file.
        extra_sbatch: Additional ``#SBATCH`` directives passed verbatim,
            e.g. ``{"account": "myproject", "constraint": "gpu"}``.
        **fit_kwargs: Extra keyword arguments forwarded to
            :func:`~nrxrdct.laue.fitting.fit_orientation_stack`
            (e.g. ``E_min_eV``, ``E_max_eV``, ``source``, ``ftol``).

    Returns:
        List of SLURM job IDs (strings).
    """
    dirs = self._setup_slurm_dirs(base_dir, "layered_ori")
    stack_pkl = self._write_stack_pkl(base_dir)

    meta = {
        "stack_pkl":       stack_pkl,
        "camera":          self._camera_to_dict(camera),
        "seg_dir":         seg_dir or os.path.join(base_dir, "seg"),
        "out_dir":         dirs["out"],
        "max_match_px":    list(max_match_px) if hasattr(max_match_px, "__iter__") else [float(max_match_px)],
        "min_matched":     min_matched,
        "min_match_rate":  min_match_rate,
        "max_rms_px":      max_rms_px,
        "r_squared_min":   r_squared_min,
        "include_unfitted": include_unfitted,
        "geometry_only":   geometry_only,
        "f2_thresh":       f2_thresh,
        "correct_depth":   correct_depth,
        "overwrite":       overwrite,
        **fit_kwargs,
    }
    meta_path = os.path.join(dirs["job_meta"], "layered_orient_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    all_frames = list(range(self.ny * self.nx))
    chunks = [
        list(map(int, c))
        for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
        if len(c) > 0
    ]

    return self._submit_jobs(
        "lm_ori",
        "nrxrdct.laue.workers.slurm_layered_orient_worker",
        meta_path, chunks, dirs["slurm_logs"],
        partition=partition, time=time, mem=mem,
        cpus_per_task=cpus_per_task, python_bin=python_bin,
        extra_sbatch=extra_sbatch,
    )

submit_segmentation

submit_segmentation(base_dir: str, h5_path: 'str | None' = None, h5_dataset: 'str | None' = None, n_jobs: int = 10, *, tiff_dir: 'str | None' = None, partition: str = 'all', time: str = '01:00:00', mem: str = '4G', cpus_per_task: int = 1, python_bin: str = 'python', mask_path: 'str | None' = None, method: str = 'LoG', method_kwargs: 'dict | None' = None, min_size: int = 3, max_size: int = 500, gap_exclude: int = 3, gap_closing: int = 3, bg_sigma: float = 251, max_components: int = 1, d: int = 10, r_squared_min: float = 0.0, include_unfitted: bool = False, fit_spots: bool = True, extra_sbatch: 'dict | None' = None) -> list

Submit segmentation jobs to SLURM.

Peak-list files are written to <base_dir>/seg/frame_?????.h5. Pass seg_dir to the submit_orientation / submit_strain calls (defaults to the same path automatically).

Parameters:
  • base_dir (str) –

    Root processing directory.

  • h5_path ('str | None', default: None ) –

    Path to the HDF5 scan file (must be accessible from compute nodes).

  • h5_dataset ('str | None', default: None ) –

    Dataset path inside h5_path, e.g. '1.1/measurement/eiger4m'. Mutually exclusive with tiff_dir; exactly one must be supplied.

  • tiff_dir ('str | None', default: None ) –

    Path to a directory of img_*.tif files. Mutually exclusive with h5_dataset.

  • n_jobs (int, default: 10 ) –

    Number of SLURM array jobs.

  • method (str, default: 'LoG' ) –

    'LoG', 'WTH', or 'HYBRID'.

  • bg_sigma (float, default: 251 ) –

    Gaussian sigma for background estimation (pixels).

  • r_squared_min (float, default: 0.0 ) –

    Minimum Gaussian-fit R² to accept a spot.

Returns:
  • list –

    List of SLURM job IDs.

Source code in src/nrxrdct/laue/layered_map.py
def submit_segmentation(
    self,
    base_dir: str,
    h5_path: "str | None" = None,
    h5_dataset: "str | None" = None,
    n_jobs: int = 10,
    *,
    tiff_dir: "str | None" = None,
    partition: str = "all",
    time: str = "01:00:00",
    mem: str = "4G",
    cpus_per_task: int = 1,
    python_bin: str = "python",
    mask_path: "str | None" = None,
    method: str = "LoG",
    method_kwargs: "dict | None" = None,
    min_size: int = 3,
    max_size: int = 500,
    gap_exclude: int = 3,
    gap_closing: int = 3,
    bg_sigma: float = 251,
    max_components: int = 1,
    d: int = 10,
    r_squared_min: float = 0.0,
    include_unfitted: bool = False,
    fit_spots: bool = True,
    extra_sbatch: "dict | None" = None,
) -> list:
    """
    Submit segmentation jobs to SLURM.

    Peak-list files are written to ``<base_dir>/seg/frame_?????.h5``.
    Pass *seg_dir* to the ``submit_orientation`` / ``submit_strain`` calls
    (defaults to the same path automatically).

    Args:
        base_dir: Root processing directory.
        h5_path: Path to the HDF5 scan file (must be accessible from
            compute nodes).
        h5_dataset: Dataset path inside *h5_path*, e.g.
            ``'1.1/measurement/eiger4m'``.  Mutually exclusive with
            *tiff_dir*; exactly one must be supplied.
        tiff_dir: Path to a directory of ``img_*.tif`` files.
            Mutually exclusive with *h5_dataset*.
        n_jobs: Number of SLURM array jobs.
        method: ``'LoG'``, ``'WTH'``, or ``'HYBRID'``.
        bg_sigma: Gaussian sigma for background estimation (pixels).
        r_squared_min: Minimum Gaussian-fit R² to accept a spot.

    Returns:
        List of SLURM job IDs.
    """
    h5_path = h5_path or self.h5_path
    if h5_path is None and h5_dataset is not None:
        raise ValueError("h5_path not set on the object and not passed as argument.")
    if h5_dataset is None and tiff_dir is None:
        raise ValueError("Provide either h5_dataset or tiff_dir.")
    if h5_dataset is not None and tiff_dir is not None:
        raise ValueError("Provide h5_dataset or tiff_dir, not both.")

    dirs = self._setup_slurm_dirs(base_dir, "seg")
    all_frames = list(range(self.ny * self.nx))
    chunks = [
        list(map(int, c))
        for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
        if len(c) > 0
    ]
    meta = {
        "h5_path":        h5_path,
        "h5_dataset":     h5_dataset,
        "tiff_dir":       tiff_dir,
        "seg_dir":        dirs["out"],
        "mask_path":      mask_path,
        "monitor":        self.monitor,
        "method":         method,
        "method_kwargs":  method_kwargs or {},
        "min_size":       min_size,
        "max_size":       max_size,
        "gap_exclude":    gap_exclude,
        "gap_closing":    gap_closing,
        "bg_sigma":       bg_sigma,
        "max_components": max_components,
        "d":              d,
        "r_squared_min":  r_squared_min,
        "include_unfitted": include_unfitted,
        "fit_spots":      fit_spots,
    }
    meta_path = os.path.join(dirs["job_meta"], "seg_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    job_ids = self._submit_jobs(
        "lm_seg", "nrxrdct.laue.workers.slurm_seg_worker",
        meta_path, chunks, dirs["slurm_logs"],
        partition=partition, time=time, mem=mem,
        cpus_per_task=cpus_per_task, python_bin=python_bin,
        extra_sbatch=extra_sbatch,
    )
    print(f"Segmentation: {len(job_ids)} jobs → {dirs['out']}")
    return job_ids

submit_strain

submit_strain(base_dir: str, camera, *, seg_dir: 'str | None' = None, orient_dir: 'str | None' = None, fit_strain: 'tuple | None' = None, n_jobs: int = 10, partition: str = 'all', time: str = '04:00:00', mem: str = '4G', cpus_per_task: int = 1, python_bin: str = 'python', max_match_px=(10, 3), min_matched: int = 5, min_match_rate: float = 0.2, max_rms_px: 'float | None' = None, r_squared_min: float = 0.0, include_unfitted: bool = False, geometry_only: bool = True, f2_thresh: float = 1e-06, correct_depth: bool = False, overwrite: bool = False, extra_sbatch: 'dict | None' = None, **fit_kwargs) -> list

Submit simultaneous orientation + per-layer strain fitting to SLURM.

Each frame is fitted with :func:~nrxrdct.laue.fitting.fit_strain_orientation_stack, which refines a single shared global rotation (3 parameters) and an independent strain tensor for every layer (N_layers × len(fit_strain) parameters). Because the parameter count grows with the number of layers, this is inherently slower than single-crystal strain fitting; reducing fit_strain to only the physically expected components is the main lever to control cost.

Workflow::

job_ids = lmap.submit_strain(base_dir, camera, seg_dir="path/to/seg",
                             fit_strain=("e_xx", "e_yy", "e_zz"))
# wait for SLURM jobs to finish
lmap.collect("path/to/base_dir/layered_strain/")

Output files are written to <base_dir>/layered_strain/frame_?????.npz. Each file contains R_global, rotvec, U_layers, U_eff_layers, strain_tensors, strain_voigts, rms_px, n_matched, match_rate, and n_sim.

Parameters:
  • base_dir (str) –

    Root directory for all job artefacts.

  • camera –

    Detector geometry (:class:~nrxrdct.laue.camera.Camera).

  • seg_dir ('str | None', default: None ) –

    Directory containing frame_?????.h5 segmentation files. Defaults to <base_dir>/seg.

  • fit_strain ('tuple | None', default: None ) –

    Strain tensor components to refine, e.g. ("e_xx", "e_yy", "e_zz") for diagonal/biaxial strain only. None (default) refines all six independent components (e_xx, e_yy, e_zz, e_xy, e_xz, e_yz). Reducing this set is the most effective way to speed up the fit for systems with known symmetry constraints.

  • n_jobs (int, default: 10 ) –

    Number of SLURM array jobs.

  • partition (str, default: 'all' ) –

    SLURM partition name.

  • time (str, default: '04:00:00' ) –

    Wall-clock time limit per job (HH:MM:SS). Strain fitting is significantly slower than orientation-only; increase if jobs time out.

  • mem (str, default: '4G' ) –

    Memory limit per job.

  • cpus_per_task (int, default: 1 ) –

    CPU cores per job / ProcessPoolExecutor workers.

  • python_bin (str, default: 'python' ) –

    Python interpreter on the cluster.

  • max_match_px –

    Staged matching threshold(s) in pixels. A sequence (10, 3) runs two stages.

  • min_matched (int, default: 5 ) –

    Minimum matched spots to save a result.

  • min_match_rate (float, default: 0.2 ) –

    Minimum fraction of simulated spots matched.

  • max_rms_px ('float | None', default: None ) –

    Maximum RMS pixel residual to accept.

  • r_squared_min (float, default: 0.0 ) –

    Minimum peak R² for loading from segmentation files. 0.0 (default) keeps all peaks.

  • include_unfitted (bool, default: False ) –

    Include peaks that failed Gaussian fitting.

  • geometry_only (bool, default: True ) –

    Skip per-spot F² evaluation during fitting by using a precomputed allowed-HKL set. Recommended (default True).

  • f2_thresh (float, default: 1e-06 ) –

    Structure-factor threshold for allowed-HKL precomputation.

  • correct_depth (bool, default: False ) –

    Apply depth correction to pixel projections.

  • overwrite (bool, default: False ) –

    Re-process frames that already have a result file.

  • extra_sbatch ('dict | None', default: None ) –

    Additional #SBATCH directives.

  • **fit_kwargs –

    Extra keyword arguments forwarded to :func:~nrxrdct.laue.fitting.fit_strain_orientation_stack (e.g. E_min_eV, E_max_eV, strain_scale, ftol).

Returns:
  • list –

    List of SLURM job IDs (strings).

Source code in src/nrxrdct/laue/layered_map.py
def submit_strain(
    self,
    base_dir: str,
    camera,
    *,
    seg_dir: "str | None" = None,
    orient_dir: "str | None" = None,
    fit_strain: "tuple | None" = None,
    n_jobs: int = 10,
    partition: str = "all",
    time: str = "04:00:00",
    mem: str = "4G",
    cpus_per_task: int = 1,
    python_bin: str = "python",
    max_match_px=(10, 3),
    min_matched: int = 5,
    min_match_rate: float = 0.2,
    max_rms_px: "float | None" = None,
    r_squared_min: float = 0.0,
    include_unfitted: bool = False,
    geometry_only: bool = True,
    f2_thresh: float = 1e-6,
    correct_depth: bool = False,
    overwrite: bool = False,
    extra_sbatch: "dict | None" = None,
    **fit_kwargs,
) -> list:
    """
    Submit simultaneous orientation + per-layer strain fitting to SLURM.

    Each frame is fitted with
    :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack`, which
    refines a single shared global rotation (3 parameters) and an
    independent strain tensor for every layer (``N_layers × len(fit_strain)``
    parameters).  Because the parameter count grows with the number of
    layers, this is inherently slower than single-crystal strain fitting;
    reducing ``fit_strain`` to only the physically expected components is
    the main lever to control cost.

    **Workflow**::

        job_ids = lmap.submit_strain(base_dir, camera, seg_dir="path/to/seg",
                                     fit_strain=("e_xx", "e_yy", "e_zz"))
        # wait for SLURM jobs to finish
        lmap.collect("path/to/base_dir/layered_strain/")

    Output files are written to ``<base_dir>/layered_strain/frame_?????.npz``.
    Each file contains ``R_global``, ``rotvec``, ``U_layers``,
    ``U_eff_layers``, ``strain_tensors``, ``strain_voigts``, ``rms_px``,
    ``n_matched``, ``match_rate``, and ``n_sim``.

    Args:
        base_dir: Root directory for all job artefacts.
        camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
        seg_dir: Directory containing ``frame_?????.h5`` segmentation files.
            Defaults to ``<base_dir>/seg``.
        fit_strain: Strain tensor components to refine, e.g.
            ``("e_xx", "e_yy", "e_zz")`` for diagonal/biaxial strain only.
            ``None`` (default) refines all six independent components
            ``(e_xx, e_yy, e_zz, e_xy, e_xz, e_yz)``.  Reducing this set
            is the most effective way to speed up the fit for systems with
            known symmetry constraints.
        n_jobs: Number of SLURM array jobs.
        partition: SLURM partition name.
        time: Wall-clock time limit per job (``HH:MM:SS``).  Strain fitting
            is significantly slower than orientation-only; increase if jobs
            time out.
        mem: Memory limit per job.
        cpus_per_task: CPU cores per job / ``ProcessPoolExecutor`` workers.
        python_bin: Python interpreter on the cluster.
        max_match_px: Staged matching threshold(s) in pixels.  A sequence
            ``(10, 3)`` runs two stages.
        min_matched: Minimum matched spots to save a result.
        min_match_rate: Minimum fraction of simulated spots matched.
        max_rms_px: Maximum RMS pixel residual to accept.
        r_squared_min: Minimum peak R² for loading from segmentation files.
            ``0.0`` (default) keeps all peaks.
        include_unfitted: Include peaks that failed Gaussian fitting.
        geometry_only: Skip per-spot F² evaluation during fitting by using
            a precomputed allowed-HKL set.  Recommended (default ``True``).
        f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
        correct_depth: Apply depth correction to pixel projections.
        overwrite: Re-process frames that already have a result file.
        extra_sbatch: Additional ``#SBATCH`` directives.
        **fit_kwargs: Extra keyword arguments forwarded to
            :func:`~nrxrdct.laue.fitting.fit_strain_orientation_stack`
            (e.g. ``E_min_eV``, ``E_max_eV``, ``strain_scale``, ``ftol``).

    Returns:
        List of SLURM job IDs (strings).
    """
    from .fitting import _STRAIN_ALL
    _fit_strain = list(fit_strain) if fit_strain is not None else list(_STRAIN_ALL)

    dirs = self._setup_slurm_dirs(base_dir, "layered_strain")
    stack_pkl = self._write_stack_pkl(base_dir)

    meta = {
        "stack_pkl":       stack_pkl,
        "camera":          self._camera_to_dict(camera),
        "seg_dir":         seg_dir or os.path.join(base_dir, "seg"),
        "orient_dir":      orient_dir,
        "out_dir":         dirs["out"],
        "fit_strain":      _fit_strain,
        "max_match_px":    list(max_match_px) if hasattr(max_match_px, "__iter__") else [float(max_match_px)],
        "min_matched":     min_matched,
        "min_match_rate":  min_match_rate,
        "max_rms_px":      max_rms_px,
        "r_squared_min":   r_squared_min,
        "include_unfitted": include_unfitted,
        "geometry_only":   geometry_only,
        "f2_thresh":       f2_thresh,
        "correct_depth":   correct_depth,
        "overwrite":       overwrite,
        **fit_kwargs,
    }
    meta_path = os.path.join(dirs["job_meta"], "layered_strain_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    all_frames = list(range(self.ny * self.nx))
    chunks = [
        list(map(int, c))
        for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
        if len(c) > 0
    ]

    return self._submit_jobs(
        "lm_strain",
        "nrxrdct.laue.workers.slurm_layered_strain_worker",
        meta_path, chunks, dirs["slurm_logs"],
        partition=partition, time=time, mem=mem,
        cpus_per_task=cpus_per_task, python_bin=python_bin,
        extra_sbatch=extra_sbatch,
    )

submit_strain_image

submit_strain_image(base_dir: str, camera, h5_path: 'str | None' = None, h5_dataset: 'str | None' = None, *, fit_strain: 'tuple | None' = None, n_jobs: int = 10, partition: str = 'all', time: str = '04:00:00', mem: str = '8G', cpus_per_task: int = 1, python_bin: str = 'python', geometry_only: bool = True, f2_thresh: float = 1e-06, correct_depth: bool = False, overwrite: bool = False, extra_sbatch: 'dict | None' = None, **fit_kwargs) -> list

Submit image-based orientation + per-layer strain refinement to SLURM.

Combines image-based fitting with full per-layer strain refinement using :func:~nrxrdct.laue.fitting.refine_strain_image_stack. This is the most computationally intensive submit method: it fits a shared global rotation plus an independent strain tensor per layer directly against the raw detector image.

Use this method when you want strain maps without a prior segmentation step, or as a refinement stage after :meth:submit_image_orientation.

Workflow::

lmap.h5_path = "/data/scan.h5"
job_ids = lmap.submit_strain_image(
    base_dir, camera,
    h5_dataset="1.1/measurement/eiger4m",
    fit_strain=("e_xx", "e_yy", "e_zz"),
)
# wait for SLURM jobs to finish
lmap.collect("path/to/base_dir/layered_img_strain/")

Output files are written to <base_dir>/layered_img_strain/frame_?????.npz. Each file contains R_global, rotvec, U_layers, U_eff_layers, strain_tensors, strain_voigts, score, score0, and n_sim.

Parameters:
  • base_dir (str) –

    Root directory for all job artefacts.

  • camera –

    Detector geometry (:class:~nrxrdct.laue.camera.Camera).

  • h5_path ('str | None', default: None ) –

    Path to the HDF5 scan file. Defaults to self.h5_path.

  • h5_dataset ('str | None', default: None ) –

    Dataset path within the HDF5 file. Required.

  • fit_strain ('tuple | None', default: None ) –

    Strain tensor components to refine, e.g. ("e_xx", "e_yy", "e_zz"). None refines all six. Reducing this set is the most effective way to lower compute cost.

  • n_jobs (int, default: 10 ) –

    Number of SLURM array jobs.

  • partition (str, default: 'all' ) –

    SLURM partition name.

  • time (str, default: '04:00:00' ) –

    Wall-clock time limit per job. This method is the slowest of the four; budget generously.

  • mem (str, default: '8G' ) –

    Memory limit per job.

  • cpus_per_task (int, default: 1 ) –

    CPU cores per job / ProcessPoolExecutor workers.

  • python_bin (str, default: 'python' ) –

    Python interpreter on the cluster.

  • geometry_only (bool, default: True ) –

    Use precomputed allowed-HKL set. Strongly recommended (default True).

  • f2_thresh (float, default: 1e-06 ) –

    Structure-factor threshold for allowed-HKL precomputation.

  • correct_depth (bool, default: False ) –

    Apply depth correction to pixel projections.

  • overwrite (bool, default: False ) –

    Re-process frames that already have a result file.

  • extra_sbatch ('dict | None', default: None ) –

    Additional #SBATCH directives.

  • **fit_kwargs –

    Extra keyword arguments forwarded to :func:~nrxrdct.laue.fitting.refine_strain_image_stack (e.g. E_min_eV, E_max_eV, kernel_sigma, strain_scale, max_angle_deg).

Returns:
  • list –

    List of SLURM job IDs (strings).

Source code in src/nrxrdct/laue/layered_map.py
def submit_strain_image(
    self,
    base_dir: str,
    camera,
    h5_path: "str | None" = None,
    h5_dataset: "str | None" = None,
    *,
    fit_strain: "tuple | None" = None,
    n_jobs: int = 10,
    partition: str = "all",
    time: str = "04:00:00",
    mem: str = "8G",
    cpus_per_task: int = 1,
    python_bin: str = "python",
    geometry_only: bool = True,
    f2_thresh: float = 1e-6,
    correct_depth: bool = False,
    overwrite: bool = False,
    extra_sbatch: "dict | None" = None,
    **fit_kwargs,
) -> list:
    """
    Submit image-based orientation + per-layer strain refinement to SLURM.

    Combines image-based fitting with full per-layer strain refinement using
    :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`.  This is the
    most computationally intensive submit method: it fits a shared global
    rotation plus an independent strain tensor per layer directly against
    the raw detector image.

    Use this method when you want strain maps without a prior segmentation
    step, or as a refinement stage after :meth:`submit_image_orientation`.

    **Workflow**::

        lmap.h5_path = "/data/scan.h5"
        job_ids = lmap.submit_strain_image(
            base_dir, camera,
            h5_dataset="1.1/measurement/eiger4m",
            fit_strain=("e_xx", "e_yy", "e_zz"),
        )
        # wait for SLURM jobs to finish
        lmap.collect("path/to/base_dir/layered_img_strain/")

    Output files are written to ``<base_dir>/layered_img_strain/frame_?????.npz``.
    Each file contains ``R_global``, ``rotvec``, ``U_layers``,
    ``U_eff_layers``, ``strain_tensors``, ``strain_voigts``, ``score``,
    ``score0``, and ``n_sim``.

    Args:
        base_dir: Root directory for all job artefacts.
        camera: Detector geometry (:class:`~nrxrdct.laue.camera.Camera`).
        h5_path: Path to the HDF5 scan file.  Defaults to ``self.h5_path``.
        h5_dataset: Dataset path within the HDF5 file.  Required.
        fit_strain: Strain tensor components to refine, e.g.
            ``("e_xx", "e_yy", "e_zz")``.  ``None`` refines all six.
            Reducing this set is the most effective way to lower compute cost.
        n_jobs: Number of SLURM array jobs.
        partition: SLURM partition name.
        time: Wall-clock time limit per job.  This method is the slowest of
            the four; budget generously.
        mem: Memory limit per job.
        cpus_per_task: CPU cores per job / ``ProcessPoolExecutor`` workers.
        python_bin: Python interpreter on the cluster.
        geometry_only: Use precomputed allowed-HKL set.  Strongly recommended
            (default ``True``).
        f2_thresh: Structure-factor threshold for allowed-HKL precomputation.
        correct_depth: Apply depth correction to pixel projections.
        overwrite: Re-process frames that already have a result file.
        extra_sbatch: Additional ``#SBATCH`` directives.
        **fit_kwargs: Extra keyword arguments forwarded to
            :func:`~nrxrdct.laue.fitting.refine_strain_image_stack`
            (e.g. ``E_min_eV``, ``E_max_eV``, ``kernel_sigma``,
            ``strain_scale``, ``max_angle_deg``).

    Returns:
        List of SLURM job IDs (strings).
    """
    h5_path = h5_path or self.h5_path
    if h5_path is None:
        raise ValueError("h5_path not set on the object and not passed as argument.")
    if h5_dataset is None:
        raise ValueError("h5_dataset is required.")
    from .fitting import _STRAIN_ALL
    _fit_strain = list(fit_strain) if fit_strain is not None else list(_STRAIN_ALL)

    dirs = self._setup_slurm_dirs(base_dir, "layered_img_strain")
    stack_pkl = self._write_stack_pkl(base_dir)

    meta = {
        "stack_pkl":    stack_pkl,
        "camera":       self._camera_to_dict(camera),
        "h5_path":      h5_path,
        "h5_dataset":   h5_dataset,
        "out_dir":      dirs["out"],
        "fit_strain":   _fit_strain,
        "geometry_only":  geometry_only,
        "f2_thresh":      f2_thresh,
        "correct_depth":  correct_depth,
        "overwrite":      overwrite,
        **fit_kwargs,
    }
    meta_path = os.path.join(dirs["job_meta"], "layered_img_strain_meta.json")
    with open(meta_path, "w") as fh:
        json.dump(meta, fh, indent=2)

    all_frames = list(range(self.ny * self.nx))
    chunks = [
        list(map(int, c))
        for c in np.array_split(all_frames, min(n_jobs, len(all_frames)))
        if len(c) > 0
    ]

    return self._submit_jobs(
        "lm_img_strain",
        "nrxrdct.laue.workers.slurm_layered_img_strain_worker",
        meta_path, chunks, dirs["slurm_logs"],
        partition=partition, time=time, mem=mem,
        cpus_per_task=cpus_per_task, python_bin=python_bin,
        extra_sbatch=extra_sbatch,
    )