Skip to content

Engines

BaseEngine

Bases: object

Base class providing shared functionality for PtyLab reconstruction engines.

BaseEngine coordinates operations that are common to different reconstruction algorithms, including wave propagation, intensity projection, error evaluation, reconstruction constraints, position correction, monitoring, and CPU/GPU data transfer.

The engine operates on shared Reconstruction, ExperimentalData, Params, and Monitor objects. These objects are referenced directly rather than copied, so updates performed by the engine are reflected in the associated reconstruction state.

Specific reconstruction engines inherit from this class and implement their algorithm-specific reconstruction and update steps. BaseEngine is therefore generally not intended to be instantiated directly.

Many methods in BaseEngine implement functionality controlled by user-facing Params switches. The Params API documentation describes when and why these options are used, while the corresponding BaseEngine methods document their implementation details.

Parameters:

Name Type Description Default
reconstruction Reconstruction

Mutable reconstruction state containing the current object, probe, geometry, and reconstruction results.

required
experimentalData ExperimentalData

Experimental diffraction data and acquisition geometry.

required
params Params

Reconstruction parameters controlling propagation, constraints, correction methods, GPU usage, and other algorithm settings.

required
monitor Monitor

Monitor used to visualize and report reconstruction progress.

required

Attributes:

betaObject (float):
    Object update weight used by shared object-update routines.
    Initialized to ``0.25``.
Source code in PtyLab/Engines/BaseEngine.py
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
class BaseEngine(object):
    """
    Base class providing shared functionality for PtyLab reconstruction engines.

    ``BaseEngine`` coordinates operations that are common to different
    reconstruction algorithms, including wave propagation, intensity
    projection, error evaluation, reconstruction constraints, position
    correction, monitoring, and CPU/GPU data transfer.

    The engine operates on shared ``Reconstruction``, ``ExperimentalData``,
    ``Params``, and ``Monitor`` objects. These objects are referenced directly
    rather than copied, so updates performed by the engine are reflected in
    the associated reconstruction state.

    Specific reconstruction engines inherit from this class and implement
    their algorithm-specific reconstruction and update steps. ``BaseEngine``
    is therefore generally not intended to be instantiated directly.

    Many methods in `BaseEngine` implement functionality controlled by user-facing
    `Params` switches. The `Params` API documentation describes when and why these
    options are used, while the corresponding `BaseEngine` methods document their
    implementation details.

    Args:
        reconstruction (Reconstruction):
            Mutable reconstruction state containing the current object, probe,
            geometry, and reconstruction results.

        experimentalData (ExperimentalData):
            Experimental diffraction data and acquisition geometry.

        params (Params):
            Reconstruction parameters controlling propagation, constraints,
            correction methods, GPU usage, and other algorithm settings.

        monitor (Monitor):
            Monitor used to visualize and report reconstruction progress.

    Attributes:

        betaObject (float):
            Object update weight used by shared object-update routines.
            Initialized to ``0.25``.

    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        # Keep references to the shared PtyLab components; no data are copied.
        self.betaObject = 0.25
        self.reconstruction: Reconstruction = reconstruction
        self.experimentalData = experimentalData
        self.params = params
        self.monitor = monitor

        # datalogger
        self.logger = logging.getLogger("BaseEngine")
        # messages already shown by _logOnce
        self._loggedOnce = set()

    def _logOnce(self, message, *args):
        """
        Log a message at INFO the first time, and at DEBUG on every repeat.

        For steps that run every iteration (e.g. probe COM stabilization), so the
        output says once that the step is active instead of once per iteration.

        Args:
            message (str):
                Logging format string; also identifies the message.
            *args:
                Arguments for the format string.
        """
        level = logging.DEBUG if message in self._loggedOnce else logging.INFO
        self._loggedOnce.add(message)
        self.logger.log(level, message, *args)

    def _prepareReconstruction(self):
        """
        Prepare the reconstruction state before iterative updates.

        This method validates user-configurable settings and initializes shared
        engine state, including FFT conventions, probe constraints, error arrays,
        monitoring regions, position-correction parameters, and CPU/GPU data
        placement.

        GPU setup is performed last because the preceding initialization steps
        operate on host-side reconstruction data.
        """
        # check miscellaneous quantities specific for certain Engines
        self._checkMISC()
        self._checkFFT()
        # self._initializeQuadraticPhase()
        self._initialProbePowerCorrection()
        self._probeWindow()
        self._initializeErrors()
        self._setObjectProbeROI()
        self._showInitialGuesses()
        self._initializePCParameters()
        self._checkGPU()  # checkGPU needs to be the last

        # one line per run; the detailed messages are INFO logs, hidden by default
        iterations = getattr(self, "numIterations", None)
        print(
            f"Starting {type(self).__name__}"
            + (f": {iterations} iterations" if iterations is not None else "")
            + (" on the GPU" if self.params.gpuFlag else " on the CPU")
        )

        # self.reconstruction.probe_storage.push(self.reconstruction.probe, 0, self.experimentalData.ptychogram.shape[0])

    def _setCPSC(self):
        """
        Configure the constrained-pixel-sum (CPSC) model.

        CPSC reconstructs the diffraction field on a finer computational detector
        grid while constraining the summed intensity within each group of subpixels
        to match the corresponding measured detector pixel. The finer grid preserves
        the detector field of view and therefore the real-space sampling, while
        increasing the reconstruction field of view.
        """

        # save the measured ptychogram into ptychograpmDownsampled
        self.experimentalData.ptychogramDownsampled = self.experimentalData.ptychogram

        # pad the probe
        padNum_before = (
            (self.params.CPSCupsamplingFactor - 1) * self.reconstruction.Np // 2
        )
        padNum_after = (
            self.params.CPSCupsamplingFactor - 1
        ) * self.reconstruction.Np - padNum_before
        self.reconstruction.probe = np.pad(
            self.reconstruction.probe,
            (
                (0, 0),
                (0, 0),
                (0, 0),
                (0, 0),
                (padNum_before, padNum_after),
                (padNum_before, padNum_after),
            ),
        )

        # pad the momentums, buffers
        if hasattr(self.reconstruction, "probeBuffer"):
            self.reconstruction.probeBuffer = self.reconstruction.probe.copy()
        if hasattr(self.reconstruction, "probeMomentum"):
            self.reconstruction.probeMomentum = np.pad(
                self.reconstruction.probeMomentum,
                (
                    (0, 0),
                    (0, 0),
                    (0, 0),
                    (0, 0),
                    (padNum_before, padNum_after),
                    (padNum_before, padNum_after),
                ),
            )

        # update coordinates (only need to update the Nd and dxd, the rest updates automatically)
        self.reconstruction.Nd = (
            self.experimentalData.ptychogramDownsampled.shape[-1]
            * self.params.CPSCupsamplingFactor
        )
        self.reconstruction.dxd = (
            self.reconstruction.dxd / self.params.CPSCupsamplingFactor
        )

        self.logger.info("CPSCswitch is on, coordinates(dxd,dxp,dxo) have been updated")

    def update_data(self, experimentalData, reconstruction=None):
        """
        Update the data objects referenced by the engine.

        Args:
            experimentalData (ExperimentalData):
                Experimental dataset to use for subsequent reconstruction steps.

            reconstruction (Reconstruction, optional):
                Replacement reconstruction state. If None, the current
                reconstruction object is retained.
        """
        self.experimentalData = experimentalData
        if reconstruction is not None:
            self.reconstruction = reconstruction

    def _initializePCParameters(self):
        """
        Initialize parameters and state for pcPIE correction.

        When position correction is enabled, this method initializes the
        feedback and momentum factors, the per-position correction vectors,
        the candidate pixel shifts used for local correlation searches, and
        the iteration threshold for starting position updates.
        """
        if self.params.positionCorrectionSwitch:
            # additional pcPIE parameters as they appear in Matlab
            self.daleth = 0.5  # feedback
            self.beth = 0.9  # friction
            self.adaptStep = 1  # adaptive step size
            self.D = np.zeros(
                (self.experimentalData.numFrames, 2)
            )  # position search direction
            # predefine shifts
            rmax = 2
            dy, dx = np.mgrid[-rmax : rmax + 1, -rmax : rmax + 1]

            # self.rowShifts = dy.flatten()#np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1])
            self.rowShifts = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1])
            # self.colShifts = dx.flatten()#np.array([-1, 0, 1, -1, 0, 1, -1, 0, 1])
            self.colShifts = np.array([-1, 0, 1, -1, 0, 1, -1, 0, 1])
            self.startAtIteration = 1
            self.meanEncoder00 = np.mean(self.experimentalData.encoder[:, 0]).copy()
            self.meanEncoder01 = np.mean(self.experimentalData.encoder[:, 1]).copy()

    def _initializeErrors(self):
        """
        Initialize reconstruction error storage.

        Depending on ``saveMemory``, detector-plane errors are either stored for
        every scan position or reduced immediately to per-position error values.
        The method also initializes the per-position error array and the global
        reconstruction error history.
        """
        # initialize detector error matrices
        if self.params.saveMemory:
            self.reconstruction.detectorError = 0
        else:
            if not hasattr(self.reconstruction, "detectorError"):
                self.reconstruction.detectorError = np.zeros(
                    (
                        self.experimentalData.numFrames,
                        self.reconstruction.Nd,
                        self.reconstruction.Nd,
                    )
                )
        # initialize energy at each scan position
        if not hasattr(self.reconstruction, "errorAtPos"):
            self.reconstruction.errorAtPos = np.zeros(
                (self.experimentalData.numFrames, 1), dtype=np.float32
            )
        # initialize final error
        if not hasattr(self.reconstruction, "error"):
            self.reconstruction.error = []

    def _initialProbePowerCorrection(self):
        r"""
        Scale the initial probe to the measured diffraction power.

        When `probePowerCorrectionSwitch` is enabled, rescale the complex probe
        $P$ using the measured amplitude scale $P_{\max}$:

        $$
        P_{\mathrm{new}} = \frac{P}{\sqrt{\sum |P|^2}} P_{\max}
        $$

        The sum in the normalization includes every element of the probe array.
        The amplitude scale is derived from the brightest measured diffraction
        pattern:

        $$
        P_{\max} = \sqrt{\max_j \sum_{x,y} I_j(x,y)}
        $$

        Here, $I_j(x,y)$ is the measured intensity at detector pixel $(x,y)$
        in frame $j$. The correction preserves the probe shape and phase while
        placing its total power on the scale of the experimental data, reducing
        large amplitude corrections at the beginning of reconstruction.

        """
        if self.params.probePowerCorrectionSwitch:
            self.reconstruction.probe = (
                self.reconstruction.probe
                / np.sqrt(
                    np.sum(self.reconstruction.probe * self.reconstruction.probe.conj())
                )
                * self.experimentalData.maxProbePower
            )

    def _probeWindow(self):
        r"""
        Create the spatial window used by probe-boundary constraints.

        For `absorbingProbeBoundary`, a smooth super-Gaussian window is defined as

        $$
        W(x,y) = \exp\left[-\left(\frac{x^2+y^2}{2\sigma^2}\right)^{10}\right]
        $$

        where

        $$
        \sigma = \frac{3}{4}\frac{N_p dx_p}{2.355}
        $$

        For `probeBoundary`, a circular support window is generated from the
        entrance pupil diameter.

        The generated window is stored in `probeWindow` and applied later by
        `applyConstraints()`.
        """
        # absorbing probe boundary: filter probe with super-gaussian window function
        if not self.params.saveMemory or self.params.absorbingProbeBoundary:
            self.probeWindow = np.exp(
                -(
                    (
                        (self.reconstruction.Xp**2 + self.reconstruction.Yp**2)
                        / (
                            2
                            * (
                                3
                                / 4
                                * self.reconstruction.Np
                                * self.reconstruction.dxp
                                / 2.355
                            )
                            ** 2
                        )
                    )
                    ** 10
                )
            )

        if self.params.probeBoundary:
            self.probeWindow = circ(
                self.reconstruction.Xp,
                self.reconstruction.Yp,
                self.experimentalData.entrancePupilDiameter
                + self.experimentalData.entrancePupilDiameter * 0.2,
            )

    def _setObjectProbeROI(self, update=False):
        """
        Set the object and probe regions of interest used for monitoring.

        The regions are stored on the engine as ``objectROI`` and ``probeROI``
        and handed to the monitor in each `MonitorFrame`. ``objectROI`` also
        sets the reference region of ``params.objectContrastSwitch``.

        The object ROI is derived from the scan-position extent and probe size,
        scaled by ``monitor.objectZoom``. The probe ROI is centered on the probe
        grid and derived from the entrance pupil diameter and
        ``monitor.probeZoom``.

        If the corresponding zoom value is ``"full"`` or ``None``, the complete
        object or probe is displayed.

        Args:
            update (bool, optional):
                If True, recompute existing ROIs. Otherwise, ROIs are only created
                when they are not already defined. Defaults to False.
        """
        if getattr(self, "objectROI", None) is None or update:
            if self.monitor.objectZoom == "full" or self.monitor.objectZoom is None:
                self.objectROI = [
                    slice(None, None, None),
                    slice(None, None, None),
                ]
            else:
                rx, ry = (
                    (
                        np.max(self.reconstruction.positions, axis=0)
                        - np.min(self.reconstruction.positions, axis=0)
                        + self.reconstruction.Np
                    )
                    / self.monitor.objectZoom
                ).astype(int)
                xc, yc = (
                    (
                        np.max(self.reconstruction.positions, axis=0)
                        + np.min(self.reconstruction.positions, axis=0)
                        + self.reconstruction.Np
                    )
                    / 2
                ).astype(int)

                # self.objectROI = [
                #     slice(
                #         max(0, yc - ry // 2), min(self.reconstruction.No, yc + ry // 2)
                #     ),
                #     slice(
                #         max(0, xc - rx // 2), min(self.reconstruction.No, xc + rx // 2)
                #     ),
                # ]
                self.objectROI = [
                    slice(
                        max(0, xc - rx // 2), min(self.reconstruction.No, xc + rx // 2)
                    ),
                    slice(
                        max(0, yc - ry // 2), min(self.reconstruction.No, yc + ry // 2)
                    ),
                ]

        if getattr(self, "probeROI", None) is None or update:
            if self.monitor.probeZoom == "full" or self.monitor.probeZoom is None:
                self.probeROI = [slice(None, None), slice(None, None)]
            else:
                r = int(
                    self.experimentalData.entrancePupilDiameter
                    / self.reconstruction.dxp
                    / self.monitor.probeZoom
                )
                self.probeROI = [
                    slice(
                        max(0, self.reconstruction.Np // 2 - r),
                        min(self.reconstruction.Np, self.reconstruction.Np // 2 + r),
                    ),
                    slice(
                        max(0, self.reconstruction.Np // 2 - r),
                        min(self.reconstruction.Np, self.reconstruction.Np // 2 + r),
                    ),
                ]

    def _showInitialGuesses(self):
        """
        Display the initial object and probe estimates in the reconstruction monitor.
        """
        self.monitor.initializeMonitors()
        self.monitor.update(self._monitorFrame())

    def _monitorFrame(self, **fields):
        """
        Snapshot of the current reconstruction state for the monitor.

        Args:
            **fields:
                Further `MonitorFrame` fields, e.g. the encoder positions or the
                diffraction intensities.

        Returns:
            MonitorFrame:
                Frame holding references to the live object and probe, with the
                engine's display regions ``objectROI`` and ``probeROI``.
        """
        return MonitorFrame.from_reconstruction(
            self.reconstruction,
            object_roi=self.objectROI,
            probe_roi=self.probeROI,
            **fields,
        )

    def _checkMISC(self):
        """
        Initialize auxiliary reconstruction state and validate special settings.

        This method prepares additional variables required by selected intensity
        constraints or background reconstruction, checks incompatible parameter
        combinations, and initializes the constrained-pixel-sum configuration
        when enabled.

        Raises:
            ValueError:
                If incompatible reconstruction options are enabled or required
                parameters for a selected constraint are missing.
        """
        if self.params.backgroundModeSwitch:
            self.reconstruction.background = 1e-1 * np.ones(
                (self.reconstruction.Np, self.reconstruction.Np)
            )

        # preallocate intensity scaling vector
        if self.params.intensityConstraint == "fluctuation":
            self.intensityScaling = np.ones(self.experimentalData.numFrames)

        if self.params.intensityConstraint == "interferometric":
            self.reconstruction.reference = np.ones(
                self.reconstruction.probe[0, 0, 0, 0, ...].shape
            )

        # check if both probePoprobePowerCorrectionSwitch and modulusEnforcedProbeSwitch are on.
        # Since this can cause a contradiction, it raises an error
        if (
            self.params.probePowerCorrectionSwitch
            and self.params.modulusEnforcedProbeSwitch
        ):
            raise ValueError(
                "probePowerCorrectionSwitch and modulusEnforcedProbeSwitch "
                "can not simultaneously be switched on!"
            )

        if self.params.propagatorType == "ASP" and self.params.fftshiftSwitch:
            raise ValueError(
                "ASP propagatorType works only with fftshiftSwitch = False"
            )
        if self.params.propagatorType == "scaledASP" and self.params.fftshiftSwitch:
            raise ValueError(
                "scaledASP propagatorType works only with fftshiftSwitch = False"
            )

        if self.params.CPSCswitch:
            if not hasattr(self.experimentalData, "ptychogramDownsampled"):
                if self.params.CPSCupsamplingFactor == None:
                    raise ValueError(
                        "CPSCswitch is on, CPSCupsamplingFactor need to be set"
                    )
                else:
                    self._setCPSC()

    def _checkFFT(self):
        """
        Synchronize detector-domain arrays with the selected FFT convention.

        When ``fftshiftSwitch`` is enabled, detector-side quantities are shifted
        to the FFT-native ordering using ``ifftshift``. When the switch is
        disabled after a previous shift, the arrays are restored using
        ``fftshift``.

        ``fftshiftFlag`` tracks the current data ordering to avoid applying the
        shift repeatedly.
        """
        if self.params.fftshiftSwitch:
            if self.params.fftshiftFlag == 0:
                print("check fftshift...")
                print("fftshift data for fast far-field update")
                # shift detector quantities
                self.experimentalData.ptychogram = np.fft.ifftshift(
                    self.experimentalData.ptychogram, axes=(-1, -2)
                )
                if hasattr(self.experimentalData, "ptychogramDownsampled"):
                    self.experimentalData.ptychogramDownsampled = np.fft.ifftshift(
                        self.experimentalData.ptychogramDownsampled, axes=(-1, -2)
                    )
                if hasattr(self.experimentalData, "W"):
                    if self.experimentalData.W is not None:
                        self.experimentalData.W = np.fft.ifftshift(
                            self.experimentalData.W, axes=(-1, -2)
                        )
                if self.experimentalData.emptyBeam is not None:
                    self.experimentalData.emptyBeam = np.fft.ifftshift(
                        self.experimentalData.emptyBeam, axes=(-1, -2)
                    )
                if hasattr(self.experimentalData, "PSD"):
                    if self.experimentalData.PSD is not None:
                        self.experimentalData.PSD = np.fft.ifftshift(
                            self.experimentalData.PSD, axes=(-1, -2)
                        )
                self.params.fftshiftFlag = 1
        else:
            if self.params.fftshiftFlag == 1:
                print("check fftshift...")
                print("ifftshift data")
                self.experimentalData.ptychogram = np.fft.fftshift(
                    self.experimentalData.ptychogram, axes=(-1, -2)
                )
                if hasattr(self.experimentalData, "ptychogramDownsampled"):
                    self.experimentalData.ptychogramDownsampled = np.fft.fftshift(
                        self.experimentalData.ptychogramDownsampled, axes=(-1, -2)
                    )
                if self.experimentalData.W != None:
                    self.experimentalData.W = np.fft.fftshift(
                        self.experimentalData.W, axes=(-1, -2)
                    )
                if self.experimentalData.emptyBeam != None:
                    self.experimentalData.emptyBeam = np.fft.fftshift(
                        self.experimentalData.emptyBeam, axes=(-1, -2)
                    )
                if hasattr(self.experimentalData, "PSD"):
                    if self.experimentalData.PSD is not None:
                        self.experimentalData.PSD = np.fft.fftshift(
                            self.experimentalData.PSD, axes=(-1, -2)
                        )
                self.params.fftshiftFlag = 0

    def _move_data_to_gpu(self):
        """
        Move reconstruction data required by the engine to the GPU.

        Reconstruction and experimental-data fields are transferred by their
        respective container classes. Engine-specific fields, including the probe
        window and additional aPIE data when required, are transferred separately.
        """

        self.reconstruction._move_data_to_gpu()
        self.experimentalData._move_data_to_gpu()

        transfer_fields_to_gpu(
            self,
            [
                "probeWindow",
            ],
            self.logger,
        )  # '.probeWindow = cp.array(self.probeWindow)

        # reconstruction parameters
        # self.reconstruction.probe = cp.array(self.reconstruction.probe, cp.complex64)
        # self.reconstruction.object = cp.array(self.reconstruction.object, cp.complex64)
        # self.reconstruction.detectorError = cp.array(self.reconstruction.detectorError, cp.float32)

        # if self.params.momentumAcceleration:
        #     self.reconstruction.probeBuffer = cp.array(self.reconstruction.probeBuffer, cp.complex64)
        #     self.reconstruction.objectBuffer = cp.array(self.reconstruction.objectBuffer, cp.complex64)
        #     self.reconstruction.probeMomentum = cp.array(self.reconstruction.probeMomentum, cp.complex64)
        #     self.reconstruction.objectMomentum = cp.array(self.reconstruction.objectMomentum, cp.complex64)

        # for doing the coordinate transform and especially the otherwise slow interpolation of aPIE on the gpu
        if hasattr(self.params, "aPIEflag"):
            if self.params.aPIEflag == True:
                fields_to_transfer = [
                    "ptychogramUntransformed",
                    "Uq",
                    "Vq",
                    "theta",
                    "wavelength",
                    "Xd",
                    "Yd",
                    "dxd",
                    "zo",
                ]
                self.theta = self.reconstruction.theta
                self.wavelength = self.reconstruction.wavelength

                transfer_fields_to_gpu(self, fields_to_transfer, self.logger)
                # self.ptychogramUntransformed = cp.array(self.ptychogramUntransformed)
                # self.Uq = cp.array(self.Uq)
                # self.Vq = cp.array(self.Vq)
                # self.theta = cp.array(self.reconstruction.theta)
                # self.wavelength = cp.array(self.reconstruction.wavelength)
                # self.Xd = cp.array(self.Xd)
                # self.Yd = cp.array(self.Yd)
                # self.dxd = cp.array(self.dxd)
                # self.zo = cp.array(self.zo)
                # self.experimentalData.W = cp.array(self.experimentalData.W)

        # non-reconstruction parameters
        # if hasattr(self.experimentalData, 'ptychogramDownsampled'):
        #     self.experimentalData.ptychogramDownsampled = cp.array(self.experimentalData.ptychogramDownsampled,
        #                                                            cp.float32)
        # else:
        #     self.experimentalData.ptychogram = cp.array(self.experimentalData.ptychogram, cp.float32)

        # propagators
        # if self.params.propagatorType == 'Fresnel':
        #     self.reconstruction.quadraticPhase = cp.array(self.reconstruction.quadraticPhase)
        # elif self.params.propagatorType == 'ASP' or self.params.propagatorType == 'polychromeASP':
        #     self.reconstruction.transferFunction = cp.array(self.reconstruction.transferFunction)
        # elif self.params.propagatorType == 'scaledASP' or self.params.propagatorType == 'scaledPolychromeASP':
        #     self.reconstruction.Q1 = cp.array(self.reconstruction.Q1)
        #     self.reconstruction.Q2 = cp.array(self.reconstruction.Q2)
        # elif self.params.propagatorType == 'twoStepPolychrome':
        #     self.reconstruction.quadraticPhase = cp.array(self.reconstruction.quadraticPhase)
        #     self.reconstruction.transferFunction = cp.array(self.reconstruction.transferFunction)

        # other parameters
        # if self.params.backgroundModeSwitch:
        #     self.reconstruction.background = cp.array(self.reconstruction.background)
        # if self.params.absorbingProbeBoundary or self.params.probeBoundary:

        # if self.params.modulusEnforcedProbeSwitch:
        #     self.experimentalData.emptyBeam = cp.array(self.experimentalData.emptyBeam)
        # if self.params.intensityConstraint == 'interferometric':
        #     self.reconstruction.reference = cp.array(self.reconstruction.reference)

    def _move_data_to_cpu(self):
        """
        Move reconstruction data required by the engine to the CPU.

        Reconstruction and experimental-data fields are transferred by their
        respective container classes, together with engine-specific fields such
        as the probe window.
        """
        # reconstruction parameters

        self.reconstruction._move_data_to_cpu()
        self.experimentalData._move_data_to_cpu()
        transfer_fields_to_cpu(
            self,
            [
                "probeWindow",
            ],
            self.logger,
        )

        # self.reconstruction.move_to_CPU()
        # self.params.move_to_CPU()

        # self.reconstruction.probe = asNumpyArray(self.reconstruction.probe)
        # self.reconstruction.object = asNumpyArray(self.reconstruction.object)

        # if self.params.momentumAcceleration:
        # reconstruction_fields_to_transfer = ['probeBuffer', 'objectBuffer', 'probeMomentum',' objectMomentum']
        # for field in reconstruction_fields_to_transfer:
        #
        #     setattr(self.reconstruction, field,)
        # self.reconstruction.probeBuffer = self.reconstruction.probeBuffer.get()
        # self.reconstruction.objectBuffer = self.reconstruction.objectBuffer.get()
        # self.reconstruction.probeMomentum = self.reconstruction.probeMomentum.get()
        # self.reconstruction.objectMomentum = self.reconstruction.objectMomentum.get()

        # for doing the coordinate transform and especially the otherwise slow interpolation of aPIE on the gpu
        # if hasattr(self.params, 'aPIEflag'):
        #     if self.params.aPIEflag:
        #         self.theta = self.theta.get()
        #
        # fields_to_transfer = ["theta", "probeWindow"]
        # self.probeWindow = self.probeWindow.get()

        # non-reconstruction parameters
        # if hasattr(self.experimentalData, 'ptychogramDownsampled'):
        #     self.experimentalData.ptychogramDownsampled = self.experimentalData.ptychogramDownsampled.get()
        # else:
        #     self.experimentalData.ptychogram = self.experimentalData.ptychogram.get()
        # self.reconstruction.detectorError = self.reconstruction.detectorError.get()

        # propagators
        # if self.params.propagatorType == 'Fresnel':
        # self.reconstruction.quadraticPhase = self.reconstruction.quadraticPhase.get()
        # elif self.params.propagatorType == 'ASP' or self.params.propagatorType == 'polychromeASP':
        #     self.reconstruction.transferFunction = self.reconstruction.transferFunction.get()
        # elif self.params.propagatorType == 'scaledASP' or self.params.propagatorType == 'scaledPolychromeASP':
        #     self.reconstruction.Q1 = self.reconstruction.Q1.get()
        #     self.reconstruction.Q2 = self.reconstruction.Q2.get()
        # elif self.params.propagatorType == 'twoStepPolychrome':
        #     self.reconstruction.quadraticPhase = self.reconstruction.quadraticPhase.get()
        #     self.reconstruction.transferFunction = self.reconstruction.transferFunction.get()

        # other parameters
        # if self.params.backgroundModeSwitch:
        #     # self.reconstruction.background = self.reconstruction.background.get()
        # if self.params.absorbingProbeBoundary or self.params.probeBoundary:

        # if self.params.modulusEnforcedProbeSwitch:
        #     self.experimentalData.emptyBeam = self.experimentalData.emptyBeam.get()
        # # if self.params.intensityConstraint == 'interferometric':
        #     self.reconstruction.reference = self.reconstruction.reference.get()

    def _checkGPU(self):
        """
        Synchronize reconstruction data with the selected computation device.

        If GPU execution is enabled, required reconstruction, experimental-data,
        and engine fields are transferred to the GPU. If GPU execution is
        disabled, the corresponding data are transferred back to the CPU.

        ``gpuFlag`` tracks the current device state, while repeated transfers
        ensure that fields created after a previous device switch are also
        synchronized.

        Raises:
            ImportError:
                If GPU execution is requested but CuPy is not available.
        """
        if not hasattr(self.params, "gpuFlag"):
            self.params.gpuFlag = 0

        if self.params._gpuSwitch:
            if cp is None:
                raise ImportError(
                    "Could not import cupy, therefore no GPU reconstruction is possible. To reconstruct, set the params.gpuSwitch to False."
                )
            if not self.params.gpuFlag:
                self.logger.info("switch to gpu")

                # load data to gpu
                self._move_data_to_gpu()
                self.params.gpuFlag = 1
            # always do this as it gets away with hard to debug errors
            self._move_data_to_gpu()
        else:
            self._move_data_to_cpu()
            if self.params.gpuFlag:
                self.logger.info("switch to cpu")
                self._move_data_to_cpu()
                self.params.gpuFlag = 0

    def setPositionOrder(self):
        """
        Set the order in which scan positions are processed.

        The ordering is controlled by ``params.positionOrder``:

        - ``"sequential"`` processes frames in their original order.
        - ``"random"`` uses the original order during the first two iterations
        and randomly shuffles the positions afterwards.
        - ``"NA"`` sorts positions by their distance from the scan center,
        processing central positions first. This ordering is intended for FPM,
        where central illumination angles correspond to bright-field data.

        The resulting frame indices are stored in ``positionIndices``.

        Raises:
            ValueError:
                If ``positionOrder`` is not one of the supported options.
        """
        if self.params.positionOrder == "sequential":
            self.positionIndices = np.arange(self.experimentalData.numFrames)

        elif self.params.positionOrder == "random":
            if len(self.reconstruction.error) == 0:
                self.positionIndices = np.arange(self.experimentalData.numFrames)
            else:
                if len(self.reconstruction.error) < 2:
                    self.positionIndices = np.arange(self.experimentalData.numFrames)
                else:
                    self.positionIndices = np.arange(self.experimentalData.numFrames)
                    np.random.shuffle(self.positionIndices)

        # order by illumiantion angles. Use smallest angles first
        # (i.e. start with brightfield data first, then add the low SNR
        # darkfield)
        # todo check this with Antonios
        elif self.params.positionOrder == "NA":
            rows = self.reconstruction.positions[:, 0] - np.mean(
                self.reconstruction.positions[:, 0]
            )
            cols = self.reconstruction.positions[:, 1] - np.mean(
                self.reconstruction.positions[:, 1]
            )
            dist = np.sqrt(rows**2 + cols**2)
            self.positionIndices = np.argsort(dist)
        else:
            raise ValueError("position order not properly set")

    def changeExperimentalData(self, experimentalData: ExperimentalData):
        """
        Replace the experimental-data object referenced by the engine.

        Args:
            experimentalData (ExperimentalData):
                Experimental dataset to use in subsequent reconstruction steps.

        Raises:
            TypeError:
                If ``experimentalData`` is not an ``ExperimentalData`` instance.
        """
        if experimentalData is not None:
            if not isinstance(experimentalData, ExperimentalData):
                raise TypeError("Experimental data should be of class ExperimentalData")
            self.experimentalData = experimentalData

    def changeOptimizable(self, optimizable: Reconstruction):
        """
        Replace the reconstruction object referenced by the engine.

        Args:
            optimizable (Reconstruction):
                Reconstruction state to use in subsequent engine operations.

        Raises:
            TypeError:
                If ``optimizable`` is not a ``Reconstruction`` instance.
        """
        if optimizable is not None:
            if not isinstance(optimizable, Reconstruction):
                raise TypeError(
                    f"Argument should be an subclass of Reconstruction, but it is {type(optimizable)}"
                )
            self.reconstruction = optimizable

    def convert2single(self):
        """
        Configure single-precision data types for reconstruction arrays.

        This method sets the target complex and real data types to
        ``numpy.complex64`` and ``numpy.float32`` and delegates the actual
        conversion to dtype-matching helpers.

        """
        self.dtype_complex = np.complex64
        self.dtype_real = np.float32
        self._match_dtypes_complex()
        self._match_dtypes_real()

    def _match_dtypes_complex(self):
        """
        Convert complex-valued arrays to the configured complex dtype.

        Complex arrays stored by the engine, reconstruction, and experimental
        data containers are converted to ``self.dtype_complex``. Non-array
        attributes and non-complex arrays are left unchanged.
        """
        array_types = (np.ndarray,)
        if cp is not None:
            array_types += (cp.ndarray,)

        for container in (self, self.reconstruction, self.experimentalData):
            for name, value in vars(container).items():
                if not isinstance(value, array_types):
                    continue

                if value.dtype.kind == "c":
                    setattr(
                        container,
                        name,
                        value.astype(self.dtype_complex, copy=False),
                    )

    def _match_dtypes_real(self):
        """
        Convert floating-point arrays to the configured real dtype.

        Floating-point arrays stored by the engine, reconstruction, and
        experimental data containers are converted to ``self.dtype_real``.
        Integer, boolean, complex, and non-array attributes are left unchanged.
        """
        array_types = (np.ndarray,)
        if cp is not None:
            array_types += (cp.ndarray,)

        for container in (self, self.reconstruction, self.experimentalData):
            for name, value in vars(container).items():
                if not isinstance(value, array_types):
                    continue

                if value.dtype.kind == "f":
                    setattr(
                        container,
                        name,
                        value.astype(self.dtype_real, copy=False),
                    )

    def object2detector(self, esw=None):
        """
        Propagate the exit surface wave from the object plane to the detector plane.

        If ``esw`` is not provided, ``reconstruction.esw`` is used. The propagation
        is performed by the operator selected through the reconstruction
        parameters, and the propagated detector-plane field is stored in
        ``reconstruction.ESW``.

        Args:
            esw (ndarray, optional):
                Object-plane exit surface wave. If None, use
                ``reconstruction.esw``.
        """
        if esw is None:
            # todo: check this, it seems weird to store it in self.esw
            esw = self.reconstruction.esw
        self.esw, self.reconstruction.ESW = Operators.Operators.object2detector(
            esw, self.params, self.reconstruction
        )

    def detector2object(self, ESW=None):
        """
        Propagate the detector-plane field back to the object plane.

        If ``ESW`` is not provided, ``reconstruction.ESW`` is used. The
        back-propagated exit surface wave is stored in ``reconstruction.esw``,
        together with the corresponding update field in
        ``reconstruction.eswUpdate``.

        Args:
            ESW (ndarray, optional):
                Detector-plane wavefield. If None, use
                ``reconstruction.ESW``.
        """
        if ESW is None:
            ESW = self.reconstruction.ESW
        esw, eswUpdate = Operators.Operators.detector2object(
            ESW, self.params, self.reconstruction
        )
        # Dirk is not sure why this has to be changed at all but it sometimes is changed for some reason
        self.reconstruction.esw = esw
        # this is the new estimate which will be processed later
        self.reconstruction.eswUpdate = eswUpdate

    def fft2s(self):
        """
        Computes the fourier transform of the exit surface wave.
        :return:
        """
        self.reconstruction.ESW = FT2(
            self.reconstruction.esw, self.params.fftshiftSwitch
        )

    def ifft2s(self):
        """Inverse FFT"""
        # find out if this should be performed on the GPU
        self.reconstruction.eswUpdate = IFT(
            self.reconstruction.ESW, self.params.fftshiftSwitch
        )

    def getBeamWidth(self):
        r"""
        Estimate the probe beam width from the second moment of its intensity.

        The probe intensity is summed over the non-spatial dimensions and
        normalized as

        $$
        \tilde{P}(x,y) = \frac{P(x,y)}{\sum_{x,y} P(x,y)}
        $$

        The intensity-weighted centroid and variance are then calculated, for
        example along $x$ as

        $$
        \langle x \rangle = \sum_{x,y} x\tilde{P}(x,y)
        $$

        $$
        \sigma_x^2 = \sum_{x,y}(x-\langle x\rangle)^2\tilde{P}(x,y)
        $$

        and converted to a Gaussian-equivalent full width at half maximum:

        $$
        \mathrm{FWHM}_x = 2\sqrt{2\ln 2}\sigma_x
        $$

        The same calculation is applied along $y$.

        Returns:
            tuple:
                ``(beamWidthY, beamWidthX)`` in meters.

        Notes:
            For non-Gaussian probe
            profiles, the returned values should be interpreted as second-moment
            Gaussian-equivalent beam widths rather than direct half-maximum widths.
        """
        xp = getArrayModule(self.reconstruction.probe)
        P = xp.sum(
            abs((self.reconstruction.probe[..., -1, :, :])) ** 2,
            axis=(0, 1, 2),
        )
        P = P / xp.sum(P, axis=(-1, -2))
        P = asNumpyArray(P)
        xMean = np.sum(self.reconstruction.Xp * P, axis=(-1, -2))
        yMean = np.sum(self.reconstruction.Yp * P, axis=(-1, -2))
        xVariance = np.sum((self.reconstruction.Xp - xMean) ** 2 * P, axis=(-1, -2))
        yVariance = np.sum((self.reconstruction.Yp - yMean) ** 2 * P, axis=(-1, -2))

        c = (
            2 * xp.sqrt(2 * xp.log(2))
        )  # constant for converting variance to FWHM (see e.g. https://en.wikipedia.org/wiki/Full_width_at_half_maximum)

        self.reconstruction.beamWidthX = asNumpyArray(c * np.sqrt(xVariance))
        self.reconstruction.beamWidthY = asNumpyArray(c * np.sqrt(yVariance))

        return self.reconstruction.beamWidthY, self.reconstruction.beamWidthX

    def getOverlap(self, ind1, ind2):
        r"""
        Estimate the probe overlap between two scan positions.

        The physical displacement between the two positions is calculated from
        their pixel-coordinate difference and the probe-plane pixel size:

        $$
        s_x = |x_2-x_1|dx_p,\qquad s_y = |y_2-y_1|dx_p
        $$

        The linear overlap is estimated from the radial scan displacement and
        the smaller of the reconstructed probe widths:

        $$
        O_{\mathrm{linear}} = \max\left(1-\frac{\sqrt{s_x^2+s_y^2}}{\min(w_x,w_y)},0\right)
        $$

        where $w_x$ and $w_y$ are the Gaussian-equivalent probe widths returned
        by `getBeamWidth()`.

        The area overlap is calculated from the normalized autocorrelation of the
        probe amplitude. Let

        $$
        P(x,y) = |\mathrm{probe}(x,y)|
        $$

        and

        $$
        Q(f_x,f_y) = \mathcal{F}\{P(x,y)\}.
        $$

        Using the Fourier correlation theorem, the normalized area overlap is

        $$
        O_{\mathrm{area}} = \frac{1}{N_\lambda}\sum_\lambda\frac{\left|\sum_{f_x,f_y}|Q_\lambda(f_x,f_y)|^2\exp[-i2\pi(f_xs_x+f_ys_y)]\right|}{\sum_{f_x,f_y}|Q_\lambda(f_x,f_y)|^2}.
        $$

        This definition is invariant to the absolute centering of the probe and
        yields an overlap of one for zero displacement.

        The current implementation uses the first probe mode and the last slice
        when evaluating the area overlap.

        Args:
            ind1 (int):
                Index of the first scan position.
            ind2 (int):
                Index of the second scan position.

        Returns:
            tuple:
                ``(linearOverlap, areaOverlap)``.

        Notes:
            The calculated values are also stored in
            ``reconstruction.linearOverlap`` and ``reconstruction.areaOverlap``.
        """
        sy = (
            abs(
                self.reconstruction.positions[ind2, 0]
                - self.reconstruction.positions[ind1, 0]
            )
            * self.reconstruction.dxp
        )
        sx = (
            abs(
                self.reconstruction.positions[ind2, 1]
                - self.reconstruction.positions[ind1, 1]
            )
            * self.reconstruction.dxp
        )

        # task 1: get linear overlap
        self.getBeamWidth()
        self.reconstruction.linearOverlap = 1 - np.sqrt(sx**2 + sy**2) / np.minimum(
            self.reconstruction.beamWidthX, self.reconstruction.beamWidthY
        )
        self.reconstruction.linearOverlap = np.maximum(
            self.reconstruction.linearOverlap, 0
        )

        # task 2: get area overlap
        # spatial frequency pixel size
        df = 1 / (self.reconstruction.Np * self.reconstruction.dxp)
        # spatial frequency meshgrid
        fx = np.arange(-self.reconstruction.Np // 2, self.reconstruction.Np // 2) * df
        Fx, Fy = np.meshgrid(fx, fx)
        # absolute value of probe and 2D fft
        P = abs(asNumpyArray(self.reconstruction.probe[:, 0, 0, -1, ...]))
        Q = fft2c(P)
        # calculate overlap between positions
        self.reconstruction.areaOverlap = np.mean(
            abs(
                np.sum(
                    abs(Q) ** 2 * np.exp(-1.0j * 2 * np.pi * (Fx * sx + Fy * sy)),
                    axis=(-1, -2),
                )
            )
            / np.sum(abs(Q) ** 2, axis=(-1, -2)),
            axis=0,
        )
        return (
            self.reconstruction.linearOverlap,
            self.reconstruction.areaOverlap,
        )

    def getErrorMetrics(self):
        r"""
        Compute the normalized reconstruction error for the current iteration.

        For each scan position $j$, the detector-domain error is summed over all
        detector pixels:

        $$
        e_j = \sum_{x,y} E_j(x,y)
        $$

        where $E_j(x,y)$ is the absolute difference between measured and estimated
        detector intensities. If `FourierMaskSwitch` is enabled, the detector error
        is weighted by the Fourier mask $W$:

        $$
        e_j = \sum_{x,y} E_j(x,y)W(x,y)
        $$

        The error at each scan position is normalized by the measured diffraction
        energy:

        $$
        \tilde{e}_j = \frac{e_j}{E_j^{\mathrm{meas}} + 10^{-20}}
        $$

        The total error for the current iteration is then

        $$
        e_{\mathrm{iter}} = \sum_j \tilde{e}_j
        $$

        and is appended to `reconstruction.error`.

        Notes:
            If `saveMemory` is enabled, the per-position errors are accumulated
            during the reconstruction loop instead of storing the full detector
            error array.
        """
        if not self.params.saveMemory:
            # Calculate mean error for all positions (make separate function for all of that)
            if self.params.FourierMaskSwitch:
                self.reconstruction.errorAtPos = np.sum(
                    np.abs(self.reconstruction.detectorError) * self.experimentalData.W,
                    axis=(-1, -2),
                )
            else:
                self.reconstruction.errorAtPos = np.sum(
                    np.abs(self.reconstruction.detectorError), axis=(-1, -2)
                )
        self.reconstruction.errorAtPos = asNumpyArray(
            self.reconstruction.errorAtPos
        ) / asNumpyArray(self.experimentalData.energyAtPos + 1e-20)
        eAverage = np.sum(self.reconstruction.errorAtPos)

        # append to error vector (for plotting error as function of iteration)
        self.reconstruction.error = np.append(self.reconstruction.error, eAverage)

    def getRMSD(self, positionIndex):
        r"""
        Compute the detector-domain intensity error for one scan position.

        The pixel-wise detector error is defined as

        $$
        E(x,y) = \left|I_{\mathrm{measured}}(x,y) - I_{\mathrm{estimated}}(x,y)\right|.
        $$

        If `saveMemory` is disabled, the full detector-error map is stored in
        `reconstruction.detectorError`.

        If `saveMemory` is enabled, the detector error is reduced immediately to
        a per-position scalar:

        $$
        e_j = \sum_{x,y} E_j(x,y).
        $$

        When `FourierMaskSwitch` is enabled, the masked error is used instead:

        $$
        e_j = \sum_{x,y} E_j(x,y)W(x,y).
        $$

        Args:
            positionIndex (int):
                Index of the current scan position.

        Raises:
            NotImplementedError:
                If `saveMemory`, `FourierMaskSwitch`, and `CPSCswitch` are all
                enabled simultaneously.

        Notes:
            Despite its name, this method does not currently compute a root mean
            square deviation. It computes an absolute detector-intensity
            difference.
        """
        # find out wether or not to use the GPU
        xp = getArrayModule(self.reconstruction.Iestimated)
        self.currentDetectorError = abs(
            self.reconstruction.Imeasured - self.reconstruction.Iestimated
        )

        # todo saveMemory implementation
        if self.params.saveMemory:
            if self.params.FourierMaskSwitch and not self.params.CPSCswitch:
                self.reconstruction.errorAtPos[positionIndex] = xp.sum(
                    self.currentDetectorError * self.experimentalData.W
                )
            elif self.params.FourierMaskSwitch and self.params.CPSCswitch:
                raise NotImplementedError
            else:
                self.reconstruction.errorAtPos[positionIndex] = asNumpyArray(
                    xp.sum(self.currentDetectorError)
                )
        else:
            self.reconstruction.detectorError[positionIndex] = self.currentDetectorError

    def intensityProjection(self, positionIndex):
        r"""
        Apply the detector-plane intensity constraint for one scan position.

        The current exit surface wave is first propagated to the detector plane.
        The estimated intensity is calculated from the propagated field as

        $$
        I_{\mathrm{estimated}}(x,y)=\sum_m |\Psi_m(x,y)|^2.
        $$

        For the standard intensity constraint, the detector-plane field is scaled
        by

        $$
        f(x,y)=\sqrt{\frac{I_{\mathrm{measured}}(x,y)}{I_{\mathrm{estimated}}(x,y)+\epsilon}},
        $$

        so that

        $$
        \Psi_{\mathrm{updated}}(x,y)=\Psi(x,y)f(x,y).
        $$

        Alternative projection rules are selected through
        ``params.intensityConstraint``. The current implementation supports
        ``"standard"``, ``"fluctuation"``, ``"exponential"``,
        ``"poisson"``, and ``"interferometric"``.

        Depending on the active parameters, the method may additionally apply
        constrained-pixel-sum decompression, adaptive denoising, Fourier masking,
        background estimation, or an interferometric reference update.

        The constrained detector-plane field is finally propagated back to the
        object plane.

        Args:
            positionIndex (int):
                Index of the current diffraction frame.

        Raises:
            ValueError:
                If ``intensityConstraint`` is not a supported value.
        """
        # figure out whether or not to use the GPU
        xp = getArrayModule(self.reconstruction.esw)
        # zero division mitigator
        gimmel = 1e-10

        # propagate to detector
        self.object2detector()

        # get estimated intensity (2D array, in the case of multislice, only take the last slice)
        if self.params.intensityConstraint == "interferometric":
            self.reconstruction.Iestimated = xp.sum(
                xp.abs(self.reconstruction.ESW + self.reconstruction.reference) ** 2,
                axis=(0, 1, 2),
            )[-1]
        else:
            self.reconstruction.Iestimated = xp.sum(
                xp.abs(self.reconstruction.ESW) ** 2, axis=(0, 1, 2)
            )[-1]
            self.logger.debug(
                f"Estimated intensity: {self.reconstruction.Iestimated.sum()}, Measured: {self.experimentalData.ptychogram[positionIndex].sum()}"
            )
        if self.params.backgroundModeSwitch:
            self.reconstruction.Iestimated += self.reconstruction.background

        # get measured intensity todo implement kPIE
        if self.params.CPSCswitch:
            self.decompressionProjection(positionIndex)
        else:
            self.reconstruction.Imeasured = self.experimentalData.ptychogram[
                positionIndex
            ]

        self.getRMSD(positionIndex)

        # adaptive denoising
        if self.params.adaptiveDenoisingSwitch:
            self.adaptiveDenoising()

        # intensity projection constraints
        if self.params.intensityConstraint == "fluctuation":
            # scaling
            if self.params.FourierMaskSwitch:
                aleph = xp.sum(
                    self.reconstruction.Imeasured
                    * self.reconstruction.Iestimated
                    * self.experimentalData.W
                ) / xp.sum(
                    self.reconstruction.Imeasured
                    * self.reconstruction.Imeasured
                    * self.experimentalData.W
                )
            else:
                aleph = xp.sum(
                    self.reconstruction.Imeasured * self.reconstruction.Iestimated
                ) / xp.sum(
                    self.reconstruction.Imeasured * self.reconstruction.Imeasured
                )
            self.params.intensityScaling[positionIndex] = aleph
            # scaled projection
            frac = (
                (1 + aleph)
                / 2
                * self.reconstruction.Imeasured
                / (self.reconstruction.Iestimated + gimmel)
            )

        elif self.params.intensityConstraint == "exponential":
            x = self.currentDetectorError / (self.reconstruction.Iestimated + gimmel)
            W = xp.exp(-0.05 * x)
            frac = xp.sqrt(
                self.reconstruction.Imeasured
                / (self.reconstruction.Iestimated + gimmel)
            )
            frac = W * frac + (1 - W)

        elif self.params.intensityConstraint == "poisson":
            frac = self.reconstruction.Imeasured / (
                self.reconstruction.Iestimated + gimmel
            )

        elif (
            self.params.intensityConstraint == "standard"
            or self.params.intensityConstraint == "interferometric"
        ):
            frac = xp.sqrt(
                self.reconstruction.Imeasured
                / (self.reconstruction.Iestimated + gimmel)
            )

        else:
            raise ValueError("intensity constraint not properly specified!")

        # apply mask
        if (
            self.params.FourierMaskSwitch
            and self.params.CPSCswitch
            and len(self.reconstruction.error) > 5
        ):
            frac = self.experimentalData.W * frac + (1 - self.experimentalData.W)

        # update ESW
        if self.params.intensityConstraint == "interferometric":
            temp = (
                self.reconstruction.ESW + self.reconstruction.reference
            ) * frac - self.reconstruction.ESW
            self.reconstruction.ESW = (
                self.reconstruction.ESW + self.reconstruction.reference
            ) * frac - self.reconstruction.reference
            self.reconstruction.reference = temp
        else:
            if hasattr(self.params, "intensityMask"):
                if self.params.intensityMask:
                    self.reconstruction.ESW = self.reconstruction.ESW * (
                        frac * (self.reconstruction.intensity_mask)
                        + (self.reconstruction.intensity_mask - 1)
                    )
                else:
                    self.reconstruction.ESW = self.reconstruction.ESW * frac
            else:
                self.reconstruction.ESW = self.reconstruction.ESW * frac

        # update background (see PhD thsis by Peng Li)
        if self.params.backgroundModeSwitch:
            if self.params.FourierMaskSwitch:
                self.reconstruction.background = (
                    self.reconstruction.background
                    * (1 + 1 / self.experimentalData.numFrames * (xp.sqrt(frac) - 1))
                    ** 2
                    * self.experimentalData.W
                )
            else:
                self.reconstruction.background = (
                    self.reconstruction.background
                    * (1 + 1 / self.experimentalData.numFrames * (xp.sqrt(frac) - 1))
                    ** 2
                )

        # back propagate to object plane
        self.detector2object()

    def decompressionProjection(self, positionIndex):
        r"""
            Construct a high-resolution measured intensity for the
        constrained-pixel-sum projection.

        The current high-resolution estimated intensity is divided into blocks
        of size $s \times s$, where $s$ is `CPSCupsamplingFactor`.

        For each detector block, the predicted low-resolution intensity is

        $$
        \hat{I}^{\mathrm{LR}}_{mn} = \sum_{i,j \in \mathrm{block}_{mn}} I_{\mathrm{estimated}}(i,j)
        $$

        A block-wise correction factor is calculated from the measured
        low-resolution diffraction intensity:

        $$
        S_{mn} = \frac{I^{\mathrm{LR}}_{\mathrm{measured},mn}}{\hat{I}^{\mathrm{LR}}_{mn} + \epsilon}
        $$

        The factor is expanded over the corresponding high-resolution block
        and used to construct an effective high-resolution measured intensity:

        $$
        I^{\mathrm{HR}}_{\mathrm{measured}}(i,j) = I_{\mathrm{estimated}}(i,j) S_{mn}
        $$

        This preserves the current estimate of the sub-pixel intensity
        distribution while enforcing that the summed intensity in each
        high-resolution block matches the experimentally measured
        low-resolution pixel intensity.

        Args:
            positionIndex (int):
                Index of the current diffraction frame.

        Notes:
            The generated high-resolution intensity is stored in
            `reconstruction.Imeasured`. When `FourierMaskSwitch` is enabled,
            the CPSC correction is restricted by `experimentalData.W` after
            the first five reconstruction iterations.
        """
        # overwrite the measured intensity (just to have same dimensions as Iestimated)
        xp = getArrayModule(self.reconstruction.Iestimated)

        # determine downsampled fraction (Sl)
        frac = self.experimentalData.ptychogramDownsampled[positionIndex] / (
            xp.sum(
                self.reconstruction.Iestimated.reshape(
                    self.reconstruction.Nd // self.params.CPSCupsamplingFactor,
                    self.params.CPSCupsamplingFactor,
                    self.reconstruction.Nd // self.params.CPSCupsamplingFactor,
                    self.params.CPSCupsamplingFactor,
                ),
                axis=(1, 3),
            )
            + np.finfo(np.float32).eps
        )
        if self.params.FourierMaskSwitch and len(self.reconstruction.error) > 5:
            frac = self.experimentalData.W * frac + (1 - self.experimentalData.W)
        # overwrite up-sampled measured intensity
        self.reconstruction.Imeasured = self.reconstruction.Iestimated * xp.repeat(
            xp.repeat(frac, self.params.CPSCupsamplingFactor, axis=-1),
            self.params.CPSCupsamplingFactor,
            axis=-2,
        )

    def showReconstruction(self, loop, force=False):
        """
        Update reconstruction monitoring and optional iteration output.

        The object, probe, reconstruction error, propagation distance, mode
        purities, scan positions, and beam width are sent to the active monitor
        at intervals defined by ``monitor.figureUpdateFrequency``.

        For Fourier ptychography, the object is transformed to real space before
        visualization. When the monitor verbosity is set to ``"high"``, the
        current measured and estimated diffraction intensities and the estimated
        scan overlap are also sent, and the last iteration prints a summary of
        the final error and overlap.

        If object dumping is enabled, the current reconstructed object is written
        to disk for each iteration.

        Args:
            loop (int):
                Current reconstruction iteration.
            force (bool, optional):
                Force an immediate monitor update regardless of
                `monitor.figureUpdateFrequency`. Default is `False`.
        """
        if self.monitor.verboseLevel == "high" and loop == self.numIterations - 1:
            # one summary at the end of the run, not one per monitor update
            self.getOverlap(0, 1)
            self.pbar.write("")
            self.pbar.write("final iteration: %i" % loop)
            self.pbar.write("error: %.1f" % self.reconstruction.error[-1])
            self.pbar.write(
                "estimated linear overlap: %.1f %%"
                % (100 * self.reconstruction.linearOverlap)
            )
            self.pbar.write(
                "estimated area overlap: %.1f %%"
                % (100 * self.reconstruction.areaOverlap)
            )

        if force or np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
            fields = {
                "engine_name": repr(type(self)),
                "encoder_original": self.experimentalData.encoder,
                "encoder_corrected": self.reconstruction.encoder_corrected,
                "beam_width": self.getBeamWidth(),
            }

            if self.monitor.verboseLevel == "high":
                Iestimated = asNumpyArray(self.reconstruction.Iestimated)
                Imeasured = asNumpyArray(self.reconstruction.Imeasured)
                if self.params.fftshiftSwitch:
                    # the engine works on fftshifted detector frames; shift back
                    # so the zero frequency is in the centre of the image
                    Iestimated = np.fft.fftshift(Iestimated)
                    Imeasured = np.fft.fftshift(Imeasured)

                # sets reconstruction.areaOverlap and .linearOverlap
                self.getOverlap(0, 1)

                fields.update(
                    I_estimated=Iestimated,
                    I_measured=Imeasured,
                    area_overlap=self.reconstruction.areaOverlap,
                    linear_overlap=self.reconstruction.linearOverlap,
                )

            self.monitor.update(self._monitorFrame(**fields))

            if self.params.positionCorrectionSwitch:
                # show reconstruction
                return
                if (
                    len(self.reconstruction.error) > self.startAtIteration
                ):  # & (np.mod(loop,
                    # self.monitor.figureUpdateFrequency) == 0):
                    figure, ax = plt.subplots(
                        1, 1, num=102, squeeze=True, clear=True, figsize=(5, 5)
                    )
                    ax.set_title("Estimated scan grid positions")
                    ax.set_xlabel("(um)")
                    ax.set_ylabel("(um)")
                    # ax.set_xscale('symlog')
                    (line1,) = plt.plot(
                        (
                            self.reconstruction.positions0[:, 1]
                            - self.reconstruction.No // 2
                            + self.reconstruction.Np // 2
                        )
                        * self.reconstruction.dxo
                        * 1e6,
                        (
                            self.reconstruction.positions0[:, 0]
                            - self.reconstruction.No // 2
                            + self.reconstruction.Np // 2
                        )
                        * self.reconstruction.dxo
                        * 1e6,
                        "bo",
                        label="before correction",
                    )
                    (line2,) = plt.plot(
                        (
                            self.reconstruction.positions[:, 1]
                            - self.reconstruction.No // 2
                            + self.reconstruction.Np // 2
                        )
                        * self.reconstruction.dxo
                        * 1e6,
                        (
                            self.reconstruction.positions[:, 0]
                            - self.reconstruction.No // 2
                            + self.reconstruction.Np // 2
                        )
                        * self.reconstruction.dxo
                        * 1e6,
                        "yo",
                        label="after correction",
                    )
                    # plt.xlabel('(um))')
                    # plt.ylabel('(um))')
                    # plt.show()
                    plt.legend(handles=[line1, line2])
                    plt.tight_layout()
                    # plt.show(block=False)

                    figure2, ax2 = plt.subplots(
                        1, 1, num=103, squeeze=True, clear=True, figsize=(5, 5)
                    )
                    ax2.set_title("Displacement")
                    ax2.set_xlabel("(um)")
                    ax2.set_ylabel("(um)")
                    plt.plot(
                        self.D[:, 1] * self.reconstruction.dxo * 1e6,
                        self.D[:, 0] * self.reconstruction.dxo * 1e6,
                        "o",
                    )
                    # ax.set_xscale('symlog')
                    plt.tight_layout()
                    # plt.show(block=False)

                    # elif np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
                    figure.show()
                    figure2.show()
                    figure.canvas.draw()
                    figure.canvas.flush_events()
                    figure2.canvas.draw()
                    figure2.canvas.flush_events()
                    # self.showReconstruction(loop)
            # print('iteration:%i' %len(self.reconstruction.error))
            # print('runtime:')
            # print('error:')

        # Dump each iteration the current object
        if self.params.dump_obj:
            folder_path = "dumps"
            if loop == 0:
                if not os.path.exists(folder_path):
                    # Create the folder
                    os.makedirs(folder_path)
                    print(f"Folder '{folder_path}' created.")
                else:
                    print(f"Folder '{folder_path}' already exists.")

            filename = "obj_dump_" + str(loop) + ".h5py"
            import h5py

            file_path = os.path.join(folder_path, filename)
            with h5py.File(file_path, "w") as hdf:
                obj = asNumpyArray(self.reconstruction.object)
                hdf.create_dataset("Object", data=obj)

    def positionCorrection(self, objectPatch, positionIndex, sy, sx):
        r"""
        Estimate the position correction for one scan position.

        The current object patch is compared with the corresponding region of the
        reconstructed object using cross-correlation. For small search radii,
        shifted object patches are evaluated directly. For larger search radii,
        the cross-correlation is calculated in the Fourier domain.

        A correlation-weighted displacement estimate is obtained from the tested
        shifts. Conceptually,

        $$
        g_x = \beta \sum_k \frac{C_k-\bar{C}}{\|O_{\mathrm{patch}}\|_2^2}\Delta x_k
        $$

        and similarly for $g_y$, where $C_k$ is the correlation obtained for the
        candidate shift $(\Delta y_k,\Delta x_k)$.

        The estimated correction is scaled by the position-correction feedback
        factor and accumulated into the position search direction used by
        `positionCorrectionUpdate()`.

        Args:
            objectPatch (ndarray):
                Current reconstructed object patch for the scan position.
            positionIndex (int):
                Index of the current scan position.
            sy (slice):
                Row slice locating the current object patch in the full object.
            sx (slice):
                Column slice locating the current object patch in the full object.

        Returns:
            ndarray:
                Estimated position correction ``[delta_y, delta_x]`` in pixels.
                Returns zeros before position correction becomes active.
        """

        xp = getArrayModule(objectPatch)
        if len(self.reconstruction.error) > self.startAtIteration:
            self.logger.debug("Calculating position correction")
            # position gradients
            # shiftedImages = xp.zeros((self.rowShifts.shape + objectPatch.shape))
            # complex cross-correlation per trial shift; its magnitude is taken below
            cc = xp.zeros((len(self.rowShifts), 1), dtype=objectPatch.dtype)

            # use the real-space object (FFT for FPM)
            O = self.reconstruction.object
            Opatch = objectPatch
            if self.experimentalData.operationMode == "FPM":
                O = fft2c(self.reconstruction.object)
                Opatch = fft2c(objectPatch)

            if self.params.positionCorrectionSwitch_radius < 2:
                # do the direct one as it's a bit faster

                for shifts in range(len(self.rowShifts)):
                    tempShift = xp.roll(Opatch, self.rowShifts[shifts], axis=-2)
                    # shiftedImages[shifts, ...] = xp.roll(tempShift, self.colShifts[shifts], axis=-1)
                    shiftedImages = xp.roll(tempShift, self.colShifts[shifts], axis=-1)
                    cc[shifts] = xp.squeeze(
                        xp.sum(shiftedImages.conj() * O[..., sy, sx], axis=(-2, -1))
                    )
                    del tempShift, shiftedImages
                    betaGrad = 1000
                    r = 3
            else:
                # print('doing FT position correction')
                ss = slice(
                    -self.params.positionCorrectionSwitch_radius,
                    self.params.positionCorrectionSwitch_radius + 1,
                )
                rowShifts, colShifts = xp.mgrid[ss, ss]
                self.rowShifts = rowShifts.flatten()
                self.colShifts = colShifts.flatten()
                FT_O = xp.fft.fft2(O[..., sy, sx] - O[..., sy, sx].mean())
                FT_Op = xp.fft.fft2(Opatch - O.mean())
                xcor = xp.fft.ifft2(FT_O * FT_Op.conj())
                xcor = abs(xp.fft.fftshift(xcor))
                N = xcor.shape[-1]
                sy = slice(
                    N // 2 - self.params.positionCorrectionSwitch_radius,
                    N // 2 + self.params.positionCorrectionSwitch_radius + 1,
                )
                xcor = xcor[..., sy, sy]
                cc = xcor.flatten()
                betaGrad = 5
                r = 10
                # dy, dx = xp.unravel_index(xp.argmax(xcor), xcor.shape)
                # dx = dx.get()
            # truncated cross - correlation
            # cc = xp.squeeze(xp.sum(shiftedImages.conj() * self.reconstruction.object[..., sy, sx], axis=(-2, -1)))
            cc = abs(cc)

            normFactor = xp.sum(Opatch.conj() * Opatch, axis=(-2, -1)).real
            grad_x = betaGrad * xp.sum(
                (cc.T - xp.mean(cc)) / normFactor * xp.array(self.colShifts)
            )
            grad_y = betaGrad * xp.sum(
                (cc.T - xp.mean(cc)) / normFactor * xp.array(self.rowShifts)
            )
            # r = np.clip(self.params.positionCorrectionSwitch_radius//5, 3, self.reconstruction.Np//10) # maximum shift in pixels?

            if abs(grad_x) > r:
                grad_x = r * grad_x / abs(grad_x)
            if abs(grad_y) > r:
                grad_y = r * grad_y / abs(grad_y)
            grad_y = asNumpyArray(grad_y)
            grad_x = asNumpyArray(grad_x)
            delta_p = self.daleth * np.array([grad_y, grad_x])
            self.D[positionIndex, :] = delta_p + self.beth * self.D[positionIndex, :]
            return delta_p
        return np.zeros(2)

    def position_update_to_change_in_z(self, loop):
        r"""
        Map the global scaling of corrected scan positions to an update of the
        propagation distance.

        The corrected and original encoder positions are centered and their
        relative spatial scale is estimated as

        $$
        s = \frac{\sigma_{\mathrm{corrected}}}{\sigma_{\mathrm{original}}}
        $$

        A corresponding target propagation distance is estimated as

        $$
        z_{\mathrm{target}} = \frac{z}{s}
        $$

        Rather than jumping to $z_{\mathrm{target}}$, the distance moves a fixed
        fraction $\alpha = 0.2$ of the way there on each call, so that noisy position
        estimates do not make it jump:

        $$
        z \leftarrow z + \alpha \, (z_{\mathrm{target}} - z)
        $$

        After updating the propagation distance,
        the corrected scan positions are rescaled around their center so that the
        global scale change is transferred from the position correction to the
        propagation distance.

        Args:
            loop (int):
                Current reconstruction iteration.

        Notes:
            This method is used together with position correction and is called
            periodically when `map_position_to_z_change` is enabled.
        """
        self._logOnce("Updating zo from the scale of the corrected positions")
        X0 = self.reconstruction.encoder_corrected
        Y0 = self.experimentalData.encoder
        msqdisplacement = np.linalg.norm(1e6 * X0 - 1e6 * Y0)

        # center both
        X0 = X0 - X0.mean(axis=0, keepdims=True)
        Y0 = Y0 - Y0.mean(axis=0, keepdims=True)

        # now, find the scaling with respect to the original one
        factor = np.std(X0) / np.std(Y0)

        # target distance implied by the scale change of the positions
        target_z = self.reconstruction.zo / factor
        step = target_z - self.reconstruction.zo
        self.logger.debug(
            f"Naive estimate of new z: {target_z:.3f}, stepsize {step:.3f}"
        )
        if abs(step) < 2e-5:  # same skip threshold as before (it used 5 * step < 1e-4)
            self.logger.debug("Skipping update as step is too small")
            return
        # damped update: move a fraction of the way toward the target each call
        damping = 0.2
        z_new = self.reconstruction.zo + damping * step

        self.logger.debug(f"Loop: {loop} step: {step}")
        self.logger.debug(
            f"old z: {self.reconstruction.zo:.3f}\n new z calculated: {z_new:.3f}\n diff: {self.reconstruction.zo - z_new}\n"
        )
        # scale the coordinates accordingly
        factor = self.reconstruction.zo / z_new
        self.reconstruction.zo = z_new
        new_encoder = self.reconstruction.encoder_corrected.copy()
        new_encoder -= new_encoder.mean(axis=0, keepdims=True)
        new_encoder /= factor  # this should be the correct one!

        new_encoder += self.experimentalData.encoder.mean(axis=0, keepdims=True)

        msqdisplacement_a = np.linalg.norm(
            1e6 * new_encoder - self.experimentalData.encoder * 1e6
        )

        self.reconstruction.encoder_corrected = new_encoder
        self.logger.debug(
            f"Mean square displacement: before: {msqdisplacement:.3f} after: {msqdisplacement_a:.3f}"
        )

    def positionCorrectionUpdate(self):
        r"""
        Apply the accumulated position corrections to the scan coordinates.

        Position corrections estimated by `positionCorrection()` are stored in
        `D` in pixel units and are applied after the position-correction warm-up.

        For conventional ptychography, the corrected encoder coordinates are
        updated as

        $$
        \mathbf{r}_j^{\mathrm{new}} = \mathbf{r}_j^{\mathrm{old}} - \alpha D_j d_{xo}
        $$

        where $\alpha$ is the adaptive step size and $d_{xo}$ is the object-plane
        pixel size. The corrected scan grid is then recentered to the mean of the
        original encoder positions.

        For Fourier ptychography, the corrected Fourier-space positions are
        converted back to illumination coordinates using the inverse FPM
        illumination geometry:

        $$
        \mathbf{r} = \operatorname{sign}(c)\frac{\mathbf{k}z_{\mathrm{LED}}}{\sqrt{c^2-k_x^2-k_y^2}}
        $$

        with

        $$
        c = -\frac{N_p d_{xo}}{\lambda}
        $$

        Notes:
            The method updates `reconstruction.encoder_corrected` in place and is
            called when position correction is enabled.
        """

        # fit the scaling out, to put in the z
        if len(self.reconstruction.error) > self.startAtIteration:
            self._logOnce(
                "Position correction: updating scan positions every iteration"
            )

            # update positions
            if self.experimentalData.operationMode == "FPM":
                conv = (
                    -(1 / self.reconstruction.wavelength)
                    * self.reconstruction.dxo
                    * self.reconstruction.Np
                )
                z = self.reconstruction.zled
                k = (
                    self.reconstruction.positions
                    - self.adaptStep * self.D
                    - self.reconstruction.No // 2
                    + self.reconstruction.Np // 2
                )
                self.reconstruction.encoder_corrected = (
                    np.sign(conv)
                    * k
                    * z
                    / (np.sqrt(conv**2 - k[:, 0] ** 2 - k[:, 1] ** 2))[..., None]
                )
            else:
                new_encoder = (
                    self.reconstruction.encoder_corrected
                    - self.adaptStep * self.D * self.reconstruction.dxo
                )
                new_encoder = new_encoder - new_encoder.mean(axis=0, keepdims=True)
                new_encoder = new_encoder + self.experimentalData.encoder.mean(
                    axis=0, keepdims=True
                )

                self.reconstruction.encoder_corrected = new_encoder
                self.logger.debug(
                    f"Average update size: {abs(self.D).mean():.2f} pixels"
                )

    def applyConstraints(self, loop):
        """
        Apply enabled reconstruction constraints after an iteration.

        This method acts as the central dispatcher for object, probe, position,
        and autofocus constraints selected through `Params`. Depending on the
        active switches, it may apply regularization, probe normalization,
        modal orthogonalization, probe-boundary constraints, smoothing,
        amplitude constraints, spectral coupling, position correction, or
        autofocus updates.

        Constraints are applied sequentially in the order defined by this method,
        so enabling multiple constraints may cause later operations to act on the
        result of earlier ones.

        Args:
            loop (int):
                Current reconstruction iteration.

        Raises:
            NotImplementedError:
                If PSD estimation is enabled.
        """
        # dirks additions, untested
        if self.params.l2reg:
            #     turns down areas that are not updated. Similar to an
            # l2 regularizer
            self.reconstruction.object *= 1 - self.params.l2reg_object_aleph
            self.reconstruction.probe *= 1 - self.params.l2reg_probe_aleph

        # enforce empty beam constraint
        if self.params.modulusEnforcedProbeSwitch:
            self.modulusEnforcedProbe()

        if self.params.orthogonalizationSwitch:
            if np.mod(loop, self.params.orthogonalizationFrequency) == 0:
                self.orthogonalization()

        # probe normalization to measured PSD todo: check for multiwave and multi object states
        if self.params.probePowerCorrectionSwitch:
            self.reconstruction.probe = (
                self.reconstruction.probe
                / np.sqrt(
                    np.sum(self.reconstruction.probe * self.reconstruction.probe.conj())
                )
                * self.experimentalData.maxProbePower
            )
        if self.params.probeSpectralPowerCorrectionSwitch:
            for wl in range(self.reconstruction.probe.shape[0]):
                self.reconstruction.probe[wl, ...] *= (
                    self.experimentalData.maxProbePower
                    * self.experimentalData.spectralPower[wl]
                    / np.sqrt(
                        np.sum(
                            self.reconstruction.probe[wl, ...]
                            * self.reconstruction.probe[wl, ...].conj()
                        )
                    )
                )

        if (
            self.params.comStabilizationSwitch is not None
            and self.params.comStabilizationSwitch is not False
        ):
            if loop % int(self.params.comStabilizationSwitch) == 0:
                self.comStabilization()

        if self.params.PSDestimationSwitch:
            raise NotImplementedError()

        if self.params.probeBoundary:
            self.reconstruction.probe *= self.probeWindow

        if self.params.absorbingProbeBoundary:
            if self.experimentalData.operationMode == "FPM":
                self.absorbingProbeBoundaryAleph = 1

            self.reconstruction.probe = (
                (1 - self.params.absorbingProbeBoundaryAleph)
                * self.reconstruction.probe
                + self.params.absorbingProbeBoundaryAleph
                * self.reconstruction.probe
                * self.probeWindow
            )

            # experimental: also apply in fourier space
            # self.reconstruction.probe = ifft2c(fft2c(self.reconstruction.probe)*self.probeWindow)

        # Todo: objectSmoothenessSwitch,probeSmoothenessSwitch,
        if self.params.probeSmoothenessSwitch:
            self.reconstruction.probe = smooth_amplitude(
                self.reconstruction.probe,
                self.params.probeSmoothenessWidth,
                self.params.probeSmoothnessAleph,
            )

        if self.params.objectSmoothenessSwitch:
            self.reconstruction.object = smooth_amplitude(
                self.reconstruction.object,
                self.params.objectSmoothenessWidth,
                self.params.objectSmoothnessAleph,
            )

        if self.params.absObjectSwitch:
            self.reconstruction.object = (
                1 - self.params.absObjectBeta
            ) * self.reconstruction.object + self.params.absObjectBeta * abs(
                self.reconstruction.object
            )

        if self.params.absProbeSwitch:
            self.reconstruction.probe = (
                1 - self.params.absProbeBeta
            ) * self.reconstruction.probe + self.params.absProbeBeta * abs(
                self.reconstruction.probe
            )

        # this is intended to slowly push non-measured object region to abs value lower than
        # the max abs inside object ROI allowing for good contrast when monitoring object
        if self.params.objectContrastSwitch:
            self.reconstruction.object = (
                0.995 * self.reconstruction.object
                + 0.005
                * np.mean(
                    abs(
                        self.reconstruction.object[
                            ..., self.objectROI[0], self.objectROI[1]
                        ]
                    )
                )
            )
        if self.params.couplingSwitch and self.reconstruction.nlambda > 1:
            self.reconstruction.probe[0] = (
                1 - self.params.couplingAleph
            ) * self.reconstruction.probe[
                0
            ] + self.params.couplingAleph * self.reconstruction.probe[1]
            for lambdaLoop in np.arange(1, self.reconstruction.nlambda - 1):
                self.reconstruction.probe[lambdaLoop] = (
                    1 - self.params.couplingAleph
                ) * self.reconstruction.probe[
                    lambdaLoop
                ] + self.params.couplingAleph * (
                    self.reconstruction.probe[lambdaLoop + 1]
                    + self.reconstruction.probe[lambdaLoop - 1]
                ) / 2

            self.reconstruction.probe[-1] = (
                1 - self.params.couplingAleph
            ) * self.reconstruction.probe[
                -1
            ] + self.params.couplingAleph * self.reconstruction.probe[-2]
        if self.params.binaryProbeSwitch:
            probePeakAmplitude = np.max(abs(self.reconstruction.probe))
            probeThresholded = self.reconstruction.probe.copy()
            probeThresholded[
                (
                    abs(probeThresholded)
                    < self.params.binaryProbeThreshold * probePeakAmplitude
                )
            ] = 0

            self.reconstruction.probe = (
                (1 - self.params.binaryProbeAleph) * self.reconstruction.probe
                + self.params.binaryProbeAleph * probeThresholded
            )

        if self.params.positionCorrectionSwitch:
            self.positionCorrectionUpdate()

        if (
            self.params.map_position_to_z_change
            and (loop % 5 == 1)
            and self.params.positionCorrectionSwitch
        ):
            self.position_update_to_change_in_z(loop)

        if self.params.TV_autofocus:
            merit, AOI_image, allmerits = self.reconstruction.TV_autofocus(
                self.params, loop=loop
            )
            if merit is not None:  # None on iterations where autofocus is skipped
                self._logOnce(
                    "TV autofocus: updating zo every %d iterations",
                    self.params.TV_autofocus_run_every,
                )
            self.monitor.update_focusing_metric(
                merit,
                AOI_image,
                metric_name=self.params.TV_autofocus_metric,
                allmerits=allmerits,
            )

        # if self.params.OPRP and loop % self.params.OPRP_tsvd_interval == 0:
        #     self.reconstruction.probe_storage.tsvd()

    def orthogonalization(self):
        r"""
        Orthogonalize mixed-state probe or object modes.

        For multiple probe modes, the reconstructed modes are transformed to an
        orthogonal modal basis independently for each wavelength and slice.
        Conceptually, the transformed modes are

        $$
        P'_k(x,y) = \sum_j U_{kj}P_j(x,y)
        $$

        where $U$ is the modal transformation returned by `orthogonalizeModes()`.

        The normalized modal eigenvalues are used to calculate the probe purity:

        $$
        \mu = \sqrt{\sum_k \tilde{\lambda}_k^2}
        $$

        where

        $$
        \tilde{\lambda}_k = \frac{\lambda_k}{\sum_j \lambda_j}
        $$

        are the normalized modal eigenvalues. A purity of one
        corresponds to a single dominant mode, while lower values indicate a
        stronger mixed-state contribution.

        If momentum acceleration is enabled, the same modal transformation is
        applied to the corresponding momentum and buffer arrays so that all
        reconstruction state variables remain expressed in the same modal basis.

        If only multiple object modes are present, the analogous procedure is
        applied to the object modes and `purityObject` is updated.

        Notes:
            Probe modes are orthogonalized independently for each wavelength and
            slice. The resulting probe purity is stored in
            `reconstruction.purityProbe` and appended to
            `reconstruction.purityProbeHist`.
        """
        xp = getArrayModule(self.reconstruction.probe)
        if self.reconstruction.npsm > 1:
            # orthogonalize the probe for each wavelength and each slice
            for id_l in range(self.reconstruction.nlambda):
                for id_s in range(self.reconstruction.nslice):
                    (
                        self.reconstruction.probe[id_l, 0, :, id_s, :, :],
                        self.normalizedEigenvaluesProbe,
                        self.MSPVprobe,
                    ) = orthogonalizeModes(
                        self.reconstruction.probe[id_l, 0, :, id_s, :, :],
                        method="snapShots",
                    )
                    # normalizedEigenvalues can live on either device, and is only
                    # npsm values long -- reducing it on the host is both cheaper
                    # than launching kernels for it and device-independent.
                    eigenvalues = asNumpyArray(self.normalizedEigenvaluesProbe)
                    self.reconstruction.purityProbe = float(
                        np.sqrt(np.sum(eigenvalues**2))
                    )
                    self.reconstruction.purityProbeHist.append(
                        self.reconstruction.purityProbe
                    )
                    # orthogonolize momentum operator
                    if self.params.momentumAcceleration:
                        # orthogonalize probe Buffer
                        p = self.reconstruction.probeBuffer[
                            id_l, 0, :, id_s, :, :
                        ].reshape((self.reconstruction.npsm, self.reconstruction.Np**2))
                        self.reconstruction.probeBuffer[id_l, 0, :, id_s, :, :] = (
                            xp.array(self.MSPVprobe) @ p
                        ).reshape(
                            (
                                self.reconstruction.npsm,
                                self.reconstruction.Np,
                                self.reconstruction.Np,
                            )
                        )
                        # orthogonalize probe momentum
                        p = self.reconstruction.probeMomentum[
                            id_l, 0, :, id_s, :, :
                        ].reshape((self.reconstruction.npsm, self.reconstruction.Np**2))
                        self.reconstruction.probeMomentum[id_l, 0, :, id_s, :, :] = (
                            xp.array(self.MSPVprobe) @ p
                        ).reshape(
                            (
                                self.reconstruction.npsm,
                                self.reconstruction.Np,
                                self.reconstruction.Np,
                            )
                        )

                        # if self.comStabilizationSwitch:
                        #     self.comStabilization()
            # self.reconstruction.probe_storage.push(self.reconstruction.probe, None, len(self.experimentalData.ptychogram), force=True)

        elif self.reconstruction.nosm > 1:
            # orthogonalize the object for each wavelength and each slice
            for id_l in range(self.reconstruction.nlambda):
                for id_s in range(self.reconstruction.nslice):
                    (
                        self.reconstruction.object[id_l, :, 0, id_s, :, :],
                        self.normalizedEigenvaluesObject,
                        self.MSPVobject,
                    ) = orthogonalizeModes(
                        self.reconstruction.object[id_l, :, 0, id_s, :, :],
                        method="snapShots",
                    )
                    eigenvalues = asNumpyArray(self.normalizedEigenvaluesObject)
                    self.reconstruction.purityObject = float(
                        np.sqrt(np.sum(eigenvalues**2))
                    )

                    # orthogonolize momentum operator
                    if self.params.momentumAcceleration:
                        # orthogonalize object Buffer
                        p = self.reconstruction.objectBuffer[
                            id_l, :, 0, id_s, :, :
                        ].reshape((self.reconstruction.nosm, self.reconstruction.No**2))
                        self.reconstruction.objectBuffer[id_l, :, 0, id_s, :, :] = (
                            xp.array(self.MSPVobject) @ p
                        ).reshape(
                            (
                                self.reconstruction.nosm,
                                self.reconstruction.No,
                                self.reconstruction.No,
                            )
                        )
                        # orthogonalize object momentum
                        p = self.reconstruction.objectMomentum[
                            id_l, :, 0, id_s, :, :
                        ].reshape((self.reconstruction.nosm, self.reconstruction.No**2))
                        self.reconstruction.objectMomentum[id_l, :, 0, id_s, :, :] = (
                            xp.array(self.MSPVobject) @ p
                        ).reshape(
                            (
                                self.reconstruction.nosm,
                                self.reconstruction.No,
                                self.reconstruction.No,
                            )
                        )

        else:
            pass

    def comStabilization(self):
        r"""
        Stabilize the probe center of mass to suppress translational drift.

        Ptychographic reconstruction contains a translational ambiguity that can
        allow the reconstructed probe and object to drift within their numerical
        arrays without strongly affecting the data consistency. This method
        estimates the probe center relative to the center of the reconstruction
        window and shifts the reconstruction when the displacement exceeds
        approximately one pixel.

        The current probe center is estimated as

        $$
        x_c = \frac{\sum_{x,y}X_p(x,y)A(x,y)}{d_{xp}\sum_{x,y}A(x,y)}
        $$

        and

        $$
        y_c = \frac{\sum_{x,y}Y_p(x,y)A(x,y)}{d_{xp}\sum_{x,y}A(x,y)}
        $$

        where $A(x,y)$ is the probe amplitude and $d_{xp}$ is the probe-plane
        pixel size. The resulting coordinates are rounded to integer pixel
        shifts.

        If the probe center is displaced by more than approximately one pixel,
        both the probe and object are shifted by `(-yc, -xc)` to recenter the
        reconstruction while preserving their relative spatial registration.

        When momentum acceleration is enabled, the corresponding probe and object
        momentum and buffer arrays are shifted by the same amount.

        Notes:
            For multislice reconstruction, the last probe slice is used to
            estimate the center.
        """
        self._logOnce("Doing probe com stabilization every iteration")
        xp = getArrayModule(self.reconstruction.probe)
        # calculate center of mass of the probe (for multislice cases, the probe for the last slice is used)
        P2 = xp.sum(
            abs(self.reconstruction.probe[:, :, :, -1, ...]) ** 2, axis=(0, 1, 2)
        )
        P2 = abs(self.reconstruction.probe[0, 0, 0, -1]) ** 2
        demon = xp.sum(P2) * self.reconstruction.dxp
        xc = int(
            xp.around(xp.sum(xp.array(self.reconstruction.Xp, xp.float32) * P2) / demon)
        )
        yc = int(
            xp.around(xp.sum(xp.array(self.reconstruction.Yp, xp.float32) * P2) / demon)
        )
        # print('Center of mass:', yc, xc)
        # shift only if necessary
        if xc**2 + yc**2 > 1:
            # self.reconstruction.probe_storage._push_hard(self.reconstruction.probe, 100)
            # self.reconstruction.probe_storage.roll(-yc, -xc)

            # shift probe
            self.reconstruction.probe = xp.roll(
                self.reconstruction.probe, (-yc, -xc), axis=(-2, -1)
            )
            # for k in xp.arange(self.reconstruction.npsm):
            #     self.reconstruction.probe[:, :, k, -1, ...] = \
            #         xp.roll(self.reconstruction.probe[:, :, k, -1, ...], (-yc, -xc), axis=(-2, -1))
            #     # for mPIE
            if self.params.momentumAcceleration:
                self.reconstruction.probeMomentum = xp.roll(
                    self.reconstruction.probeMomentum, (-yc, -xc), axis=(-2, -1)
                )
                self.reconstruction.probeBuffer = xp.roll(
                    self.reconstruction.probeBuffer, (-yc, -xc), axis=(-2, -1)
                )

            # shift object
            self.reconstruction.object = xp.roll(
                self.reconstruction.object, (-yc, -xc), axis=(-2, -1)
            )
            # for mPIE
            if self.params.momentumAcceleration:
                self.reconstruction.objectMomentum = xp.roll(
                    self.reconstruction.objectMomentum, (-yc, -xc), axis=(-2, -1)
                )
                self.reconstruction.objectBuffer = xp.roll(
                    self.reconstruction.objectBuffer, (-yc, -xc), axis=(-2, -1)
                )

    def modulusEnforcedProbe(self):
        r"""
        Constrain the reconstructed probe using a measured empty-beam intensity.

        The current probe is propagated to the detector plane, where its
        estimated intensity is compared with `experimentalData.emptyBeam`.

        The detector-plane probe is scaled by

        $$
        f(x,y) = \sqrt{\frac{I_{\mathrm{empty}}(x,y)}{I_{\mathrm{probe}}(x,y)+\epsilon}}
        $$

        and updated as

        $$
        \Psi_{\mathrm{updated}}(x,y) = \Psi(x,y)f(x,y)
        $$

        so that the measured detector-plane amplitude is enforced while the
        current phase estimate is retained.

        The constrained field is then propagated back to the probe plane and
        stored in `reconstruction.probe`.

        If `FourierMaskSwitch` is enabled, the modulus constraint is applied only
        inside the active Fourier mask, while the detector-plane field outside
        the mask is left unchanged.

        Notes:
            This constraint requires `experimentalData.emptyBeam`, containing a
            measured detector intensity of the illumination without the sample.
        """
        xp = getArrayModule(self.reconstruction.esw)
        self.reconstruction.esw = self.reconstruction.probe
        self.object2detector()

        if self.params.FourierMaskSwitch:
            self.reconstruction.ESW = self.reconstruction.ESW * xp.sqrt(
                self.experimentalData.emptyBeam
                / (
                    1e-10
                    + xp.sum(
                        xp.abs(self.reconstruction.ESW) ** 2,
                        axis=(0, 1, 2, 3),
                    )
                )
            ) * self.experimentalData.W + self.reconstruction.ESW * (
                1 - self.experimentalData.W
            )
        else:
            self.reconstruction.ESW = self.reconstruction.ESW * np.sqrt(
                self.experimentalData.emptyBeam
                / (1e-10 + xp.sum(abs(self.reconstruction.ESW) ** 2, axis=(0, 1, 2, 3)))
            )

        self.detector2object()

        if self.params.OPRP:
            pass
            # self.probes.append(self.reconstruction.esw.reshape(-))

        self.reconstruction.probe = self.reconstruction.esw

    def adaptiveDenoising(self):
        r"""
        Apply an adaptive amplitude-domain noise-floor correction.

        The measured and estimated detector intensities are converted to
        amplitudes.

        A global noise level is estimated from their mean amplitude difference:

        $$
        n = \left|\left\langle A_{\mathrm{meas}} - A_{\mathrm{est}} \right\rangle\right|
        $$

        The estimated noise floor is subtracted from the measured amplitude and
        negative values are clipped to zero:

        $$
        A'_{\mathrm{meas}} = \max(A_{\mathrm{meas}} - n, 0)
        $$

        The corrected measured intensity is then reconstructed as

        $$
        I'_{\mathrm{meas}} = \left(A'_{\mathrm{meas}}\right)^2
        $$

        Notes:
            This method modifies `reconstruction.Imeasured` in place and is
            applied before the detector-plane intensity constraint.
        """
        # figure out wether or not to use the GPU
        xp = getArrayModule(self.reconstruction.esw)

        Ameasured = self.reconstruction.Imeasured**0.5
        Aestimated = xp.abs(self.reconstruction.Iestimated) ** 0.5

        noise = xp.abs(xp.mean(Ameasured - Aestimated))

        Ameasured = Ameasured - noise
        Ameasured[Ameasured < 0] = 0
        self.reconstruction.Imeasured = Ameasured**2

    def z_update(self, stepsize=0.01, roi_bounds=[0.3, 0.7], d=10):
        """
        Update Z based on TV
        :param stepsize:
        :return:
        """
        self.reconstruction.TV_autofocus()

    def objectPatchUpdate_TV(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Apply total-variation regularization to the engine-specific object update.

        The data-driven object update is first calculated using the current
        engine's `objectPatchUpdate()` implementation:

        $$
        O_{\mathrm{data}} = U_{\mathrm{engine}}(O_j,\Delta\Psi_j)
        $$

        where $U_{\mathrm{engine}}$ denotes the object-update rule implemented by
        the active reconstruction engine. For example, `ePIE` uses the standard
        ePIE update, while `mPIE` uses its regularized mPIE/rPIE update.

        A total-variation regularization term is then added:

        $$
        O'_j = O_{\mathrm{data}} + \lambda\beta_O G_{\mathrm{TV}}(O_j)
        $$

        where $G_{\mathrm{TV}}(O_j)$ is calculated by `grad_TV()` using
        `epsilon=1e-2`, $\beta_O$ is the engine's object update step size, and
        $\lambda$ is controlled by `params.objectTVregStepSize`.

        This design keeps the TV regularization independent of the underlying
        reconstruction engine, allowing different engines to retain their native
        object-update rules while sharing the same TV regularizer.

        The activation and application frequency of this update are controlled by
        `params.objectTVregSwitch` and `params.objectTVfreq` in the reconstruction
        loop.

        Args:
            objectPatch (ndarray):
                Current object patch at the active scan position.
            DELTA (ndarray):
                Exit-wave correction, typically
                `reconstruction.eswUpdate - reconstruction.esw`.

        Returns:
            ndarray:
                Engine-specific object update with the additional TV
                regularization term.
        """

        # xp = getArrayModule(objectPatch)
        # frac = self.reconstruction.probe.conj() / xp.max(
        #    xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
        # )

        # gradient = xp.gradient(objectPatch, axis=(4, 5))
        #
        # # norm = xp.abs(gradient[0] + gradient[1]) ** 2
        # norm = (gradient[0] + gradient[1]) ** 2
        # temp = [gradient[0] / xp.sqrt(norm + epsilon), gradient[1] / xp.sqrt(norm + epsilon)]
        # TV_update = divergence(temp)

        TV_update = grad_TV(objectPatch, epsilon=1e-2)

        updated_object = self.objectPatchUpdate(objectPatch, DELTA)

        lam = self.params.objectTVregStepSize

        return updated_object + lam * self.betaObject * TV_update

_initialProbePowerCorrection()

Scale the initial probe to the measured diffraction power.

When probePowerCorrectionSwitch is enabled, rescale the complex probe \(P\) using the measured amplitude scale \(P_{\max}\):

\[ P_{\mathrm{new}} = \frac{P}{\sqrt{\sum |P|^2}} P_{\max} \]

The sum in the normalization includes every element of the probe array. The amplitude scale is derived from the brightest measured diffraction pattern:

\[ P_{\max} = \sqrt{\max_j \sum_{x,y} I_j(x,y)} \]

Here, \(I_j(x,y)\) is the measured intensity at detector pixel \((x,y)\) in frame \(j\). The correction preserves the probe shape and phase while placing its total power on the scale of the experimental data, reducing large amplitude corrections at the beginning of reconstruction.

Source code in PtyLab/Engines/BaseEngine.py
def _initialProbePowerCorrection(self):
    r"""
    Scale the initial probe to the measured diffraction power.

    When `probePowerCorrectionSwitch` is enabled, rescale the complex probe
    $P$ using the measured amplitude scale $P_{\max}$:

    $$
    P_{\mathrm{new}} = \frac{P}{\sqrt{\sum |P|^2}} P_{\max}
    $$

    The sum in the normalization includes every element of the probe array.
    The amplitude scale is derived from the brightest measured diffraction
    pattern:

    $$
    P_{\max} = \sqrt{\max_j \sum_{x,y} I_j(x,y)}
    $$

    Here, $I_j(x,y)$ is the measured intensity at detector pixel $(x,y)$
    in frame $j$. The correction preserves the probe shape and phase while
    placing its total power on the scale of the experimental data, reducing
    large amplitude corrections at the beginning of reconstruction.

    """
    if self.params.probePowerCorrectionSwitch:
        self.reconstruction.probe = (
            self.reconstruction.probe
            / np.sqrt(
                np.sum(self.reconstruction.probe * self.reconstruction.probe.conj())
            )
            * self.experimentalData.maxProbePower
        )

_probeWindow()

Create the spatial window used by probe-boundary constraints.

For absorbingProbeBoundary, a smooth super-Gaussian window is defined as

\[ W(x,y) = \exp\left[-\left(\frac{x^2+y^2}{2\sigma^2}\right)^{10}\right] \]

where

\[ \sigma = \frac{3}{4}\frac{N_p dx_p}{2.355} \]

For probeBoundary, a circular support window is generated from the entrance pupil diameter.

The generated window is stored in probeWindow and applied later by applyConstraints().

Source code in PtyLab/Engines/BaseEngine.py
def _probeWindow(self):
    r"""
    Create the spatial window used by probe-boundary constraints.

    For `absorbingProbeBoundary`, a smooth super-Gaussian window is defined as

    $$
    W(x,y) = \exp\left[-\left(\frac{x^2+y^2}{2\sigma^2}\right)^{10}\right]
    $$

    where

    $$
    \sigma = \frac{3}{4}\frac{N_p dx_p}{2.355}
    $$

    For `probeBoundary`, a circular support window is generated from the
    entrance pupil diameter.

    The generated window is stored in `probeWindow` and applied later by
    `applyConstraints()`.
    """
    # absorbing probe boundary: filter probe with super-gaussian window function
    if not self.params.saveMemory or self.params.absorbingProbeBoundary:
        self.probeWindow = np.exp(
            -(
                (
                    (self.reconstruction.Xp**2 + self.reconstruction.Yp**2)
                    / (
                        2
                        * (
                            3
                            / 4
                            * self.reconstruction.Np
                            * self.reconstruction.dxp
                            / 2.355
                        )
                        ** 2
                    )
                )
                ** 10
            )
        )

    if self.params.probeBoundary:
        self.probeWindow = circ(
            self.reconstruction.Xp,
            self.reconstruction.Yp,
            self.experimentalData.entrancePupilDiameter
            + self.experimentalData.entrancePupilDiameter * 0.2,
        )

update_data(experimentalData, reconstruction=None)

Update the data objects referenced by the engine.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for subsequent reconstruction steps.

required
reconstruction Reconstruction

Replacement reconstruction state. If None, the current reconstruction object is retained.

None
Source code in PtyLab/Engines/BaseEngine.py
def update_data(self, experimentalData, reconstruction=None):
    """
    Update the data objects referenced by the engine.

    Args:
        experimentalData (ExperimentalData):
            Experimental dataset to use for subsequent reconstruction steps.

        reconstruction (Reconstruction, optional):
            Replacement reconstruction state. If None, the current
            reconstruction object is retained.
    """
    self.experimentalData = experimentalData
    if reconstruction is not None:
        self.reconstruction = reconstruction

setPositionOrder()

Set the order in which scan positions are processed.

The ordering is controlled by params.positionOrder:

  • "sequential" processes frames in their original order.
  • "random" uses the original order during the first two iterations and randomly shuffles the positions afterwards.
  • "NA" sorts positions by their distance from the scan center, processing central positions first. This ordering is intended for FPM, where central illumination angles correspond to bright-field data.

The resulting frame indices are stored in positionIndices.

Raises:

Type Description
ValueError

If positionOrder is not one of the supported options.

Source code in PtyLab/Engines/BaseEngine.py
def setPositionOrder(self):
    """
    Set the order in which scan positions are processed.

    The ordering is controlled by ``params.positionOrder``:

    - ``"sequential"`` processes frames in their original order.
    - ``"random"`` uses the original order during the first two iterations
    and randomly shuffles the positions afterwards.
    - ``"NA"`` sorts positions by their distance from the scan center,
    processing central positions first. This ordering is intended for FPM,
    where central illumination angles correspond to bright-field data.

    The resulting frame indices are stored in ``positionIndices``.

    Raises:
        ValueError:
            If ``positionOrder`` is not one of the supported options.
    """
    if self.params.positionOrder == "sequential":
        self.positionIndices = np.arange(self.experimentalData.numFrames)

    elif self.params.positionOrder == "random":
        if len(self.reconstruction.error) == 0:
            self.positionIndices = np.arange(self.experimentalData.numFrames)
        else:
            if len(self.reconstruction.error) < 2:
                self.positionIndices = np.arange(self.experimentalData.numFrames)
            else:
                self.positionIndices = np.arange(self.experimentalData.numFrames)
                np.random.shuffle(self.positionIndices)

    # order by illumiantion angles. Use smallest angles first
    # (i.e. start with brightfield data first, then add the low SNR
    # darkfield)
    # todo check this with Antonios
    elif self.params.positionOrder == "NA":
        rows = self.reconstruction.positions[:, 0] - np.mean(
            self.reconstruction.positions[:, 0]
        )
        cols = self.reconstruction.positions[:, 1] - np.mean(
            self.reconstruction.positions[:, 1]
        )
        dist = np.sqrt(rows**2 + cols**2)
        self.positionIndices = np.argsort(dist)
    else:
        raise ValueError("position order not properly set")

convert2single()

Configure single-precision data types for reconstruction arrays.

This method sets the target complex and real data types to numpy.complex64 and numpy.float32 and delegates the actual conversion to dtype-matching helpers.

Source code in PtyLab/Engines/BaseEngine.py
def convert2single(self):
    """
    Configure single-precision data types for reconstruction arrays.

    This method sets the target complex and real data types to
    ``numpy.complex64`` and ``numpy.float32`` and delegates the actual
    conversion to dtype-matching helpers.

    """
    self.dtype_complex = np.complex64
    self.dtype_real = np.float32
    self._match_dtypes_complex()
    self._match_dtypes_real()

object2detector(esw=None)

Propagate the exit surface wave from the object plane to the detector plane.

If esw is not provided, reconstruction.esw is used. The propagation is performed by the operator selected through the reconstruction parameters, and the propagated detector-plane field is stored in reconstruction.ESW.

Parameters:

Name Type Description Default
esw ndarray

Object-plane exit surface wave. If None, use reconstruction.esw.

None
Source code in PtyLab/Engines/BaseEngine.py
def object2detector(self, esw=None):
    """
    Propagate the exit surface wave from the object plane to the detector plane.

    If ``esw`` is not provided, ``reconstruction.esw`` is used. The propagation
    is performed by the operator selected through the reconstruction
    parameters, and the propagated detector-plane field is stored in
    ``reconstruction.ESW``.

    Args:
        esw (ndarray, optional):
            Object-plane exit surface wave. If None, use
            ``reconstruction.esw``.
    """
    if esw is None:
        # todo: check this, it seems weird to store it in self.esw
        esw = self.reconstruction.esw
    self.esw, self.reconstruction.ESW = Operators.Operators.object2detector(
        esw, self.params, self.reconstruction
    )

detector2object(ESW=None)

Propagate the detector-plane field back to the object plane.

If ESW is not provided, reconstruction.ESW is used. The back-propagated exit surface wave is stored in reconstruction.esw, together with the corresponding update field in reconstruction.eswUpdate.

Parameters:

Name Type Description Default
ESW ndarray

Detector-plane wavefield. If None, use reconstruction.ESW.

None
Source code in PtyLab/Engines/BaseEngine.py
def detector2object(self, ESW=None):
    """
    Propagate the detector-plane field back to the object plane.

    If ``ESW`` is not provided, ``reconstruction.ESW`` is used. The
    back-propagated exit surface wave is stored in ``reconstruction.esw``,
    together with the corresponding update field in
    ``reconstruction.eswUpdate``.

    Args:
        ESW (ndarray, optional):
            Detector-plane wavefield. If None, use
            ``reconstruction.ESW``.
    """
    if ESW is None:
        ESW = self.reconstruction.ESW
    esw, eswUpdate = Operators.Operators.detector2object(
        ESW, self.params, self.reconstruction
    )
    # Dirk is not sure why this has to be changed at all but it sometimes is changed for some reason
    self.reconstruction.esw = esw
    # this is the new estimate which will be processed later
    self.reconstruction.eswUpdate = eswUpdate

getBeamWidth()

Estimate the probe beam width from the second moment of its intensity.

The probe intensity is summed over the non-spatial dimensions and normalized as

\[ \tilde{P}(x,y) = \frac{P(x,y)}{\sum_{x,y} P(x,y)} \]

The intensity-weighted centroid and variance are then calculated, for example along \(x\) as

\[ \langle x \rangle = \sum_{x,y} x\tilde{P}(x,y) \]
\[ \sigma_x^2 = \sum_{x,y}(x-\langle x\rangle)^2\tilde{P}(x,y) \]

and converted to a Gaussian-equivalent full width at half maximum:

\[ \mathrm{FWHM}_x = 2\sqrt{2\ln 2}\sigma_x \]

The same calculation is applied along \(y\).

Returns:

Type Description
tuple

(beamWidthY, beamWidthX) in meters.

Notes

For non-Gaussian probe profiles, the returned values should be interpreted as second-moment Gaussian-equivalent beam widths rather than direct half-maximum widths.

Source code in PtyLab/Engines/BaseEngine.py
def getBeamWidth(self):
    r"""
    Estimate the probe beam width from the second moment of its intensity.

    The probe intensity is summed over the non-spatial dimensions and
    normalized as

    $$
    \tilde{P}(x,y) = \frac{P(x,y)}{\sum_{x,y} P(x,y)}
    $$

    The intensity-weighted centroid and variance are then calculated, for
    example along $x$ as

    $$
    \langle x \rangle = \sum_{x,y} x\tilde{P}(x,y)
    $$

    $$
    \sigma_x^2 = \sum_{x,y}(x-\langle x\rangle)^2\tilde{P}(x,y)
    $$

    and converted to a Gaussian-equivalent full width at half maximum:

    $$
    \mathrm{FWHM}_x = 2\sqrt{2\ln 2}\sigma_x
    $$

    The same calculation is applied along $y$.

    Returns:
        tuple:
            ``(beamWidthY, beamWidthX)`` in meters.

    Notes:
        For non-Gaussian probe
        profiles, the returned values should be interpreted as second-moment
        Gaussian-equivalent beam widths rather than direct half-maximum widths.
    """
    xp = getArrayModule(self.reconstruction.probe)
    P = xp.sum(
        abs((self.reconstruction.probe[..., -1, :, :])) ** 2,
        axis=(0, 1, 2),
    )
    P = P / xp.sum(P, axis=(-1, -2))
    P = asNumpyArray(P)
    xMean = np.sum(self.reconstruction.Xp * P, axis=(-1, -2))
    yMean = np.sum(self.reconstruction.Yp * P, axis=(-1, -2))
    xVariance = np.sum((self.reconstruction.Xp - xMean) ** 2 * P, axis=(-1, -2))
    yVariance = np.sum((self.reconstruction.Yp - yMean) ** 2 * P, axis=(-1, -2))

    c = (
        2 * xp.sqrt(2 * xp.log(2))
    )  # constant for converting variance to FWHM (see e.g. https://en.wikipedia.org/wiki/Full_width_at_half_maximum)

    self.reconstruction.beamWidthX = asNumpyArray(c * np.sqrt(xVariance))
    self.reconstruction.beamWidthY = asNumpyArray(c * np.sqrt(yVariance))

    return self.reconstruction.beamWidthY, self.reconstruction.beamWidthX

getOverlap(ind1, ind2)

Estimate the probe overlap between two scan positions.

The physical displacement between the two positions is calculated from their pixel-coordinate difference and the probe-plane pixel size:

\[ s_x = |x_2-x_1|dx_p,\qquad s_y = |y_2-y_1|dx_p \]

The linear overlap is estimated from the radial scan displacement and the smaller of the reconstructed probe widths:

\[ O_{\mathrm{linear}} = \max\left(1-\frac{\sqrt{s_x^2+s_y^2}}{\min(w_x,w_y)},0\right) \]

where \(w_x\) and \(w_y\) are the Gaussian-equivalent probe widths returned by getBeamWidth().

The area overlap is calculated from the normalized autocorrelation of the probe amplitude. Let

\[ P(x,y) = |\mathrm{probe}(x,y)| \]

and

\[ Q(f_x,f_y) = \mathcal{F}\{P(x,y)\}. \]

Using the Fourier correlation theorem, the normalized area overlap is

\[ O_{\mathrm{area}} = \frac{1}{N_\lambda}\sum_\lambda\frac{\left|\sum_{f_x,f_y}|Q_\lambda(f_x,f_y)|^2\exp[-i2\pi(f_xs_x+f_ys_y)]\right|}{\sum_{f_x,f_y}|Q_\lambda(f_x,f_y)|^2}. \]

This definition is invariant to the absolute centering of the probe and yields an overlap of one for zero displacement.

The current implementation uses the first probe mode and the last slice when evaluating the area overlap.

Parameters:

Name Type Description Default
ind1 int

Index of the first scan position.

required
ind2 int

Index of the second scan position.

required

Returns:

Type Description
tuple

(linearOverlap, areaOverlap).

Notes

The calculated values are also stored in reconstruction.linearOverlap and reconstruction.areaOverlap.

Source code in PtyLab/Engines/BaseEngine.py
def getOverlap(self, ind1, ind2):
    r"""
    Estimate the probe overlap between two scan positions.

    The physical displacement between the two positions is calculated from
    their pixel-coordinate difference and the probe-plane pixel size:

    $$
    s_x = |x_2-x_1|dx_p,\qquad s_y = |y_2-y_1|dx_p
    $$

    The linear overlap is estimated from the radial scan displacement and
    the smaller of the reconstructed probe widths:

    $$
    O_{\mathrm{linear}} = \max\left(1-\frac{\sqrt{s_x^2+s_y^2}}{\min(w_x,w_y)},0\right)
    $$

    where $w_x$ and $w_y$ are the Gaussian-equivalent probe widths returned
    by `getBeamWidth()`.

    The area overlap is calculated from the normalized autocorrelation of the
    probe amplitude. Let

    $$
    P(x,y) = |\mathrm{probe}(x,y)|
    $$

    and

    $$
    Q(f_x,f_y) = \mathcal{F}\{P(x,y)\}.
    $$

    Using the Fourier correlation theorem, the normalized area overlap is

    $$
    O_{\mathrm{area}} = \frac{1}{N_\lambda}\sum_\lambda\frac{\left|\sum_{f_x,f_y}|Q_\lambda(f_x,f_y)|^2\exp[-i2\pi(f_xs_x+f_ys_y)]\right|}{\sum_{f_x,f_y}|Q_\lambda(f_x,f_y)|^2}.
    $$

    This definition is invariant to the absolute centering of the probe and
    yields an overlap of one for zero displacement.

    The current implementation uses the first probe mode and the last slice
    when evaluating the area overlap.

    Args:
        ind1 (int):
            Index of the first scan position.
        ind2 (int):
            Index of the second scan position.

    Returns:
        tuple:
            ``(linearOverlap, areaOverlap)``.

    Notes:
        The calculated values are also stored in
        ``reconstruction.linearOverlap`` and ``reconstruction.areaOverlap``.
    """
    sy = (
        abs(
            self.reconstruction.positions[ind2, 0]
            - self.reconstruction.positions[ind1, 0]
        )
        * self.reconstruction.dxp
    )
    sx = (
        abs(
            self.reconstruction.positions[ind2, 1]
            - self.reconstruction.positions[ind1, 1]
        )
        * self.reconstruction.dxp
    )

    # task 1: get linear overlap
    self.getBeamWidth()
    self.reconstruction.linearOverlap = 1 - np.sqrt(sx**2 + sy**2) / np.minimum(
        self.reconstruction.beamWidthX, self.reconstruction.beamWidthY
    )
    self.reconstruction.linearOverlap = np.maximum(
        self.reconstruction.linearOverlap, 0
    )

    # task 2: get area overlap
    # spatial frequency pixel size
    df = 1 / (self.reconstruction.Np * self.reconstruction.dxp)
    # spatial frequency meshgrid
    fx = np.arange(-self.reconstruction.Np // 2, self.reconstruction.Np // 2) * df
    Fx, Fy = np.meshgrid(fx, fx)
    # absolute value of probe and 2D fft
    P = abs(asNumpyArray(self.reconstruction.probe[:, 0, 0, -1, ...]))
    Q = fft2c(P)
    # calculate overlap between positions
    self.reconstruction.areaOverlap = np.mean(
        abs(
            np.sum(
                abs(Q) ** 2 * np.exp(-1.0j * 2 * np.pi * (Fx * sx + Fy * sy)),
                axis=(-1, -2),
            )
        )
        / np.sum(abs(Q) ** 2, axis=(-1, -2)),
        axis=0,
    )
    return (
        self.reconstruction.linearOverlap,
        self.reconstruction.areaOverlap,
    )

getErrorMetrics()

Compute the normalized reconstruction error for the current iteration.

For each scan position \(j\), the detector-domain error is summed over all detector pixels:

\[ e_j = \sum_{x,y} E_j(x,y) \]

where \(E_j(x,y)\) is the absolute difference between measured and estimated detector intensities. If FourierMaskSwitch is enabled, the detector error is weighted by the Fourier mask \(W\):

\[ e_j = \sum_{x,y} E_j(x,y)W(x,y) \]

The error at each scan position is normalized by the measured diffraction energy:

\[ \tilde{e}_j = \frac{e_j}{E_j^{\mathrm{meas}} + 10^{-20}} \]

The total error for the current iteration is then

\[ e_{\mathrm{iter}} = \sum_j \tilde{e}_j \]

and is appended to reconstruction.error.

Notes

If saveMemory is enabled, the per-position errors are accumulated during the reconstruction loop instead of storing the full detector error array.

Source code in PtyLab/Engines/BaseEngine.py
def getErrorMetrics(self):
    r"""
    Compute the normalized reconstruction error for the current iteration.

    For each scan position $j$, the detector-domain error is summed over all
    detector pixels:

    $$
    e_j = \sum_{x,y} E_j(x,y)
    $$

    where $E_j(x,y)$ is the absolute difference between measured and estimated
    detector intensities. If `FourierMaskSwitch` is enabled, the detector error
    is weighted by the Fourier mask $W$:

    $$
    e_j = \sum_{x,y} E_j(x,y)W(x,y)
    $$

    The error at each scan position is normalized by the measured diffraction
    energy:

    $$
    \tilde{e}_j = \frac{e_j}{E_j^{\mathrm{meas}} + 10^{-20}}
    $$

    The total error for the current iteration is then

    $$
    e_{\mathrm{iter}} = \sum_j \tilde{e}_j
    $$

    and is appended to `reconstruction.error`.

    Notes:
        If `saveMemory` is enabled, the per-position errors are accumulated
        during the reconstruction loop instead of storing the full detector
        error array.
    """
    if not self.params.saveMemory:
        # Calculate mean error for all positions (make separate function for all of that)
        if self.params.FourierMaskSwitch:
            self.reconstruction.errorAtPos = np.sum(
                np.abs(self.reconstruction.detectorError) * self.experimentalData.W,
                axis=(-1, -2),
            )
        else:
            self.reconstruction.errorAtPos = np.sum(
                np.abs(self.reconstruction.detectorError), axis=(-1, -2)
            )
    self.reconstruction.errorAtPos = asNumpyArray(
        self.reconstruction.errorAtPos
    ) / asNumpyArray(self.experimentalData.energyAtPos + 1e-20)
    eAverage = np.sum(self.reconstruction.errorAtPos)

    # append to error vector (for plotting error as function of iteration)
    self.reconstruction.error = np.append(self.reconstruction.error, eAverage)

getRMSD(positionIndex)

Compute the detector-domain intensity error for one scan position.

The pixel-wise detector error is defined as

\[ E(x,y) = \left|I_{\mathrm{measured}}(x,y) - I_{\mathrm{estimated}}(x,y)\right|. \]

If saveMemory is disabled, the full detector-error map is stored in reconstruction.detectorError.

If saveMemory is enabled, the detector error is reduced immediately to a per-position scalar:

\[ e_j = \sum_{x,y} E_j(x,y). \]

When FourierMaskSwitch is enabled, the masked error is used instead:

\[ e_j = \sum_{x,y} E_j(x,y)W(x,y). \]

Parameters:

Name Type Description Default
positionIndex int

Index of the current scan position.

required

Raises:

Type Description
NotImplementedError

If saveMemory, FourierMaskSwitch, and CPSCswitch are all enabled simultaneously.

Notes

Despite its name, this method does not currently compute a root mean square deviation. It computes an absolute detector-intensity difference.

Source code in PtyLab/Engines/BaseEngine.py
def getRMSD(self, positionIndex):
    r"""
    Compute the detector-domain intensity error for one scan position.

    The pixel-wise detector error is defined as

    $$
    E(x,y) = \left|I_{\mathrm{measured}}(x,y) - I_{\mathrm{estimated}}(x,y)\right|.
    $$

    If `saveMemory` is disabled, the full detector-error map is stored in
    `reconstruction.detectorError`.

    If `saveMemory` is enabled, the detector error is reduced immediately to
    a per-position scalar:

    $$
    e_j = \sum_{x,y} E_j(x,y).
    $$

    When `FourierMaskSwitch` is enabled, the masked error is used instead:

    $$
    e_j = \sum_{x,y} E_j(x,y)W(x,y).
    $$

    Args:
        positionIndex (int):
            Index of the current scan position.

    Raises:
        NotImplementedError:
            If `saveMemory`, `FourierMaskSwitch`, and `CPSCswitch` are all
            enabled simultaneously.

    Notes:
        Despite its name, this method does not currently compute a root mean
        square deviation. It computes an absolute detector-intensity
        difference.
    """
    # find out wether or not to use the GPU
    xp = getArrayModule(self.reconstruction.Iestimated)
    self.currentDetectorError = abs(
        self.reconstruction.Imeasured - self.reconstruction.Iestimated
    )

    # todo saveMemory implementation
    if self.params.saveMemory:
        if self.params.FourierMaskSwitch and not self.params.CPSCswitch:
            self.reconstruction.errorAtPos[positionIndex] = xp.sum(
                self.currentDetectorError * self.experimentalData.W
            )
        elif self.params.FourierMaskSwitch and self.params.CPSCswitch:
            raise NotImplementedError
        else:
            self.reconstruction.errorAtPos[positionIndex] = asNumpyArray(
                xp.sum(self.currentDetectorError)
            )
    else:
        self.reconstruction.detectorError[positionIndex] = self.currentDetectorError

intensityProjection(positionIndex)

Apply the detector-plane intensity constraint for one scan position.

The current exit surface wave is first propagated to the detector plane. The estimated intensity is calculated from the propagated field as

\[ I_{\mathrm{estimated}}(x,y)=\sum_m |\Psi_m(x,y)|^2. \]

For the standard intensity constraint, the detector-plane field is scaled by

\[ f(x,y)=\sqrt{\frac{I_{\mathrm{measured}}(x,y)}{I_{\mathrm{estimated}}(x,y)+\epsilon}}, \]

so that

\[ \Psi_{\mathrm{updated}}(x,y)=\Psi(x,y)f(x,y). \]

Alternative projection rules are selected through params.intensityConstraint. The current implementation supports "standard", "fluctuation", "exponential", "poisson", and "interferometric".

Depending on the active parameters, the method may additionally apply constrained-pixel-sum decompression, adaptive denoising, Fourier masking, background estimation, or an interferometric reference update.

The constrained detector-plane field is finally propagated back to the object plane.

Parameters:

Name Type Description Default
positionIndex int

Index of the current diffraction frame.

required

Raises:

Type Description
ValueError

If intensityConstraint is not a supported value.

Source code in PtyLab/Engines/BaseEngine.py
def intensityProjection(self, positionIndex):
    r"""
    Apply the detector-plane intensity constraint for one scan position.

    The current exit surface wave is first propagated to the detector plane.
    The estimated intensity is calculated from the propagated field as

    $$
    I_{\mathrm{estimated}}(x,y)=\sum_m |\Psi_m(x,y)|^2.
    $$

    For the standard intensity constraint, the detector-plane field is scaled
    by

    $$
    f(x,y)=\sqrt{\frac{I_{\mathrm{measured}}(x,y)}{I_{\mathrm{estimated}}(x,y)+\epsilon}},
    $$

    so that

    $$
    \Psi_{\mathrm{updated}}(x,y)=\Psi(x,y)f(x,y).
    $$

    Alternative projection rules are selected through
    ``params.intensityConstraint``. The current implementation supports
    ``"standard"``, ``"fluctuation"``, ``"exponential"``,
    ``"poisson"``, and ``"interferometric"``.

    Depending on the active parameters, the method may additionally apply
    constrained-pixel-sum decompression, adaptive denoising, Fourier masking,
    background estimation, or an interferometric reference update.

    The constrained detector-plane field is finally propagated back to the
    object plane.

    Args:
        positionIndex (int):
            Index of the current diffraction frame.

    Raises:
        ValueError:
            If ``intensityConstraint`` is not a supported value.
    """
    # figure out whether or not to use the GPU
    xp = getArrayModule(self.reconstruction.esw)
    # zero division mitigator
    gimmel = 1e-10

    # propagate to detector
    self.object2detector()

    # get estimated intensity (2D array, in the case of multislice, only take the last slice)
    if self.params.intensityConstraint == "interferometric":
        self.reconstruction.Iestimated = xp.sum(
            xp.abs(self.reconstruction.ESW + self.reconstruction.reference) ** 2,
            axis=(0, 1, 2),
        )[-1]
    else:
        self.reconstruction.Iestimated = xp.sum(
            xp.abs(self.reconstruction.ESW) ** 2, axis=(0, 1, 2)
        )[-1]
        self.logger.debug(
            f"Estimated intensity: {self.reconstruction.Iestimated.sum()}, Measured: {self.experimentalData.ptychogram[positionIndex].sum()}"
        )
    if self.params.backgroundModeSwitch:
        self.reconstruction.Iestimated += self.reconstruction.background

    # get measured intensity todo implement kPIE
    if self.params.CPSCswitch:
        self.decompressionProjection(positionIndex)
    else:
        self.reconstruction.Imeasured = self.experimentalData.ptychogram[
            positionIndex
        ]

    self.getRMSD(positionIndex)

    # adaptive denoising
    if self.params.adaptiveDenoisingSwitch:
        self.adaptiveDenoising()

    # intensity projection constraints
    if self.params.intensityConstraint == "fluctuation":
        # scaling
        if self.params.FourierMaskSwitch:
            aleph = xp.sum(
                self.reconstruction.Imeasured
                * self.reconstruction.Iestimated
                * self.experimentalData.W
            ) / xp.sum(
                self.reconstruction.Imeasured
                * self.reconstruction.Imeasured
                * self.experimentalData.W
            )
        else:
            aleph = xp.sum(
                self.reconstruction.Imeasured * self.reconstruction.Iestimated
            ) / xp.sum(
                self.reconstruction.Imeasured * self.reconstruction.Imeasured
            )
        self.params.intensityScaling[positionIndex] = aleph
        # scaled projection
        frac = (
            (1 + aleph)
            / 2
            * self.reconstruction.Imeasured
            / (self.reconstruction.Iestimated + gimmel)
        )

    elif self.params.intensityConstraint == "exponential":
        x = self.currentDetectorError / (self.reconstruction.Iestimated + gimmel)
        W = xp.exp(-0.05 * x)
        frac = xp.sqrt(
            self.reconstruction.Imeasured
            / (self.reconstruction.Iestimated + gimmel)
        )
        frac = W * frac + (1 - W)

    elif self.params.intensityConstraint == "poisson":
        frac = self.reconstruction.Imeasured / (
            self.reconstruction.Iestimated + gimmel
        )

    elif (
        self.params.intensityConstraint == "standard"
        or self.params.intensityConstraint == "interferometric"
    ):
        frac = xp.sqrt(
            self.reconstruction.Imeasured
            / (self.reconstruction.Iestimated + gimmel)
        )

    else:
        raise ValueError("intensity constraint not properly specified!")

    # apply mask
    if (
        self.params.FourierMaskSwitch
        and self.params.CPSCswitch
        and len(self.reconstruction.error) > 5
    ):
        frac = self.experimentalData.W * frac + (1 - self.experimentalData.W)

    # update ESW
    if self.params.intensityConstraint == "interferometric":
        temp = (
            self.reconstruction.ESW + self.reconstruction.reference
        ) * frac - self.reconstruction.ESW
        self.reconstruction.ESW = (
            self.reconstruction.ESW + self.reconstruction.reference
        ) * frac - self.reconstruction.reference
        self.reconstruction.reference = temp
    else:
        if hasattr(self.params, "intensityMask"):
            if self.params.intensityMask:
                self.reconstruction.ESW = self.reconstruction.ESW * (
                    frac * (self.reconstruction.intensity_mask)
                    + (self.reconstruction.intensity_mask - 1)
                )
            else:
                self.reconstruction.ESW = self.reconstruction.ESW * frac
        else:
            self.reconstruction.ESW = self.reconstruction.ESW * frac

    # update background (see PhD thsis by Peng Li)
    if self.params.backgroundModeSwitch:
        if self.params.FourierMaskSwitch:
            self.reconstruction.background = (
                self.reconstruction.background
                * (1 + 1 / self.experimentalData.numFrames * (xp.sqrt(frac) - 1))
                ** 2
                * self.experimentalData.W
            )
        else:
            self.reconstruction.background = (
                self.reconstruction.background
                * (1 + 1 / self.experimentalData.numFrames * (xp.sqrt(frac) - 1))
                ** 2
            )

    # back propagate to object plane
    self.detector2object()

decompressionProjection(positionIndex)

Construct a high-resolution measured intensity for the

constrained-pixel-sum projection.

The current high-resolution estimated intensity is divided into blocks of size \(s \times s\), where \(s\) is CPSCupsamplingFactor.

For each detector block, the predicted low-resolution intensity is

\[ \hat{I}^{\mathrm{LR}}_{mn} = \sum_{i,j \in \mathrm{block}_{mn}} I_{\mathrm{estimated}}(i,j) \]

A block-wise correction factor is calculated from the measured low-resolution diffraction intensity:

\[ S_{mn} = \frac{I^{\mathrm{LR}}_{\mathrm{measured},mn}}{\hat{I}^{\mathrm{LR}}_{mn} + \epsilon} \]

The factor is expanded over the corresponding high-resolution block and used to construct an effective high-resolution measured intensity:

\[ I^{\mathrm{HR}}_{\mathrm{measured}}(i,j) = I_{\mathrm{estimated}}(i,j) S_{mn} \]

This preserves the current estimate of the sub-pixel intensity distribution while enforcing that the summed intensity in each high-resolution block matches the experimentally measured low-resolution pixel intensity.

Parameters:

Name Type Description Default
positionIndex int

Index of the current diffraction frame.

required
Notes

The generated high-resolution intensity is stored in reconstruction.Imeasured. When FourierMaskSwitch is enabled, the CPSC correction is restricted by experimentalData.W after the first five reconstruction iterations.

Source code in PtyLab/Engines/BaseEngine.py
def decompressionProjection(self, positionIndex):
    r"""
        Construct a high-resolution measured intensity for the
    constrained-pixel-sum projection.

    The current high-resolution estimated intensity is divided into blocks
    of size $s \times s$, where $s$ is `CPSCupsamplingFactor`.

    For each detector block, the predicted low-resolution intensity is

    $$
    \hat{I}^{\mathrm{LR}}_{mn} = \sum_{i,j \in \mathrm{block}_{mn}} I_{\mathrm{estimated}}(i,j)
    $$

    A block-wise correction factor is calculated from the measured
    low-resolution diffraction intensity:

    $$
    S_{mn} = \frac{I^{\mathrm{LR}}_{\mathrm{measured},mn}}{\hat{I}^{\mathrm{LR}}_{mn} + \epsilon}
    $$

    The factor is expanded over the corresponding high-resolution block
    and used to construct an effective high-resolution measured intensity:

    $$
    I^{\mathrm{HR}}_{\mathrm{measured}}(i,j) = I_{\mathrm{estimated}}(i,j) S_{mn}
    $$

    This preserves the current estimate of the sub-pixel intensity
    distribution while enforcing that the summed intensity in each
    high-resolution block matches the experimentally measured
    low-resolution pixel intensity.

    Args:
        positionIndex (int):
            Index of the current diffraction frame.

    Notes:
        The generated high-resolution intensity is stored in
        `reconstruction.Imeasured`. When `FourierMaskSwitch` is enabled,
        the CPSC correction is restricted by `experimentalData.W` after
        the first five reconstruction iterations.
    """
    # overwrite the measured intensity (just to have same dimensions as Iestimated)
    xp = getArrayModule(self.reconstruction.Iestimated)

    # determine downsampled fraction (Sl)
    frac = self.experimentalData.ptychogramDownsampled[positionIndex] / (
        xp.sum(
            self.reconstruction.Iestimated.reshape(
                self.reconstruction.Nd // self.params.CPSCupsamplingFactor,
                self.params.CPSCupsamplingFactor,
                self.reconstruction.Nd // self.params.CPSCupsamplingFactor,
                self.params.CPSCupsamplingFactor,
            ),
            axis=(1, 3),
        )
        + np.finfo(np.float32).eps
    )
    if self.params.FourierMaskSwitch and len(self.reconstruction.error) > 5:
        frac = self.experimentalData.W * frac + (1 - self.experimentalData.W)
    # overwrite up-sampled measured intensity
    self.reconstruction.Imeasured = self.reconstruction.Iestimated * xp.repeat(
        xp.repeat(frac, self.params.CPSCupsamplingFactor, axis=-1),
        self.params.CPSCupsamplingFactor,
        axis=-2,
    )

showReconstruction(loop, force=False)

Update reconstruction monitoring and optional iteration output.

The object, probe, reconstruction error, propagation distance, mode purities, scan positions, and beam width are sent to the active monitor at intervals defined by monitor.figureUpdateFrequency.

For Fourier ptychography, the object is transformed to real space before visualization. When the monitor verbosity is set to "high", the current measured and estimated diffraction intensities and the estimated scan overlap are also sent, and the last iteration prints a summary of the final error and overlap.

If object dumping is enabled, the current reconstructed object is written to disk for each iteration.

Parameters:

Name Type Description Default
loop int

Current reconstruction iteration.

required
force bool

Force an immediate monitor update regardless of monitor.figureUpdateFrequency. Default is False.

False
Source code in PtyLab/Engines/BaseEngine.py
def showReconstruction(self, loop, force=False):
    """
    Update reconstruction monitoring and optional iteration output.

    The object, probe, reconstruction error, propagation distance, mode
    purities, scan positions, and beam width are sent to the active monitor
    at intervals defined by ``monitor.figureUpdateFrequency``.

    For Fourier ptychography, the object is transformed to real space before
    visualization. When the monitor verbosity is set to ``"high"``, the
    current measured and estimated diffraction intensities and the estimated
    scan overlap are also sent, and the last iteration prints a summary of
    the final error and overlap.

    If object dumping is enabled, the current reconstructed object is written
    to disk for each iteration.

    Args:
        loop (int):
            Current reconstruction iteration.
        force (bool, optional):
            Force an immediate monitor update regardless of
            `monitor.figureUpdateFrequency`. Default is `False`.
    """
    if self.monitor.verboseLevel == "high" and loop == self.numIterations - 1:
        # one summary at the end of the run, not one per monitor update
        self.getOverlap(0, 1)
        self.pbar.write("")
        self.pbar.write("final iteration: %i" % loop)
        self.pbar.write("error: %.1f" % self.reconstruction.error[-1])
        self.pbar.write(
            "estimated linear overlap: %.1f %%"
            % (100 * self.reconstruction.linearOverlap)
        )
        self.pbar.write(
            "estimated area overlap: %.1f %%"
            % (100 * self.reconstruction.areaOverlap)
        )

    if force or np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
        fields = {
            "engine_name": repr(type(self)),
            "encoder_original": self.experimentalData.encoder,
            "encoder_corrected": self.reconstruction.encoder_corrected,
            "beam_width": self.getBeamWidth(),
        }

        if self.monitor.verboseLevel == "high":
            Iestimated = asNumpyArray(self.reconstruction.Iestimated)
            Imeasured = asNumpyArray(self.reconstruction.Imeasured)
            if self.params.fftshiftSwitch:
                # the engine works on fftshifted detector frames; shift back
                # so the zero frequency is in the centre of the image
                Iestimated = np.fft.fftshift(Iestimated)
                Imeasured = np.fft.fftshift(Imeasured)

            # sets reconstruction.areaOverlap and .linearOverlap
            self.getOverlap(0, 1)

            fields.update(
                I_estimated=Iestimated,
                I_measured=Imeasured,
                area_overlap=self.reconstruction.areaOverlap,
                linear_overlap=self.reconstruction.linearOverlap,
            )

        self.monitor.update(self._monitorFrame(**fields))

        if self.params.positionCorrectionSwitch:
            # show reconstruction
            return
            if (
                len(self.reconstruction.error) > self.startAtIteration
            ):  # & (np.mod(loop,
                # self.monitor.figureUpdateFrequency) == 0):
                figure, ax = plt.subplots(
                    1, 1, num=102, squeeze=True, clear=True, figsize=(5, 5)
                )
                ax.set_title("Estimated scan grid positions")
                ax.set_xlabel("(um)")
                ax.set_ylabel("(um)")
                # ax.set_xscale('symlog')
                (line1,) = plt.plot(
                    (
                        self.reconstruction.positions0[:, 1]
                        - self.reconstruction.No // 2
                        + self.reconstruction.Np // 2
                    )
                    * self.reconstruction.dxo
                    * 1e6,
                    (
                        self.reconstruction.positions0[:, 0]
                        - self.reconstruction.No // 2
                        + self.reconstruction.Np // 2
                    )
                    * self.reconstruction.dxo
                    * 1e6,
                    "bo",
                    label="before correction",
                )
                (line2,) = plt.plot(
                    (
                        self.reconstruction.positions[:, 1]
                        - self.reconstruction.No // 2
                        + self.reconstruction.Np // 2
                    )
                    * self.reconstruction.dxo
                    * 1e6,
                    (
                        self.reconstruction.positions[:, 0]
                        - self.reconstruction.No // 2
                        + self.reconstruction.Np // 2
                    )
                    * self.reconstruction.dxo
                    * 1e6,
                    "yo",
                    label="after correction",
                )
                # plt.xlabel('(um))')
                # plt.ylabel('(um))')
                # plt.show()
                plt.legend(handles=[line1, line2])
                plt.tight_layout()
                # plt.show(block=False)

                figure2, ax2 = plt.subplots(
                    1, 1, num=103, squeeze=True, clear=True, figsize=(5, 5)
                )
                ax2.set_title("Displacement")
                ax2.set_xlabel("(um)")
                ax2.set_ylabel("(um)")
                plt.plot(
                    self.D[:, 1] * self.reconstruction.dxo * 1e6,
                    self.D[:, 0] * self.reconstruction.dxo * 1e6,
                    "o",
                )
                # ax.set_xscale('symlog')
                plt.tight_layout()
                # plt.show(block=False)

                # elif np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
                figure.show()
                figure2.show()
                figure.canvas.draw()
                figure.canvas.flush_events()
                figure2.canvas.draw()
                figure2.canvas.flush_events()
                # self.showReconstruction(loop)
        # print('iteration:%i' %len(self.reconstruction.error))
        # print('runtime:')
        # print('error:')

    # Dump each iteration the current object
    if self.params.dump_obj:
        folder_path = "dumps"
        if loop == 0:
            if not os.path.exists(folder_path):
                # Create the folder
                os.makedirs(folder_path)
                print(f"Folder '{folder_path}' created.")
            else:
                print(f"Folder '{folder_path}' already exists.")

        filename = "obj_dump_" + str(loop) + ".h5py"
        import h5py

        file_path = os.path.join(folder_path, filename)
        with h5py.File(file_path, "w") as hdf:
            obj = asNumpyArray(self.reconstruction.object)
            hdf.create_dataset("Object", data=obj)

positionCorrection(objectPatch, positionIndex, sy, sx)

Estimate the position correction for one scan position.

The current object patch is compared with the corresponding region of the reconstructed object using cross-correlation. For small search radii, shifted object patches are evaluated directly. For larger search radii, the cross-correlation is calculated in the Fourier domain.

A correlation-weighted displacement estimate is obtained from the tested shifts. Conceptually,

\[ g_x = \beta \sum_k \frac{C_k-\bar{C}}{\|O_{\mathrm{patch}}\|_2^2}\Delta x_k \]

and similarly for \(g_y\), where \(C_k\) is the correlation obtained for the candidate shift \((\Delta y_k,\Delta x_k)\).

The estimated correction is scaled by the position-correction feedback factor and accumulated into the position search direction used by positionCorrectionUpdate().

Parameters:

Name Type Description Default
objectPatch ndarray

Current reconstructed object patch for the scan position.

required
positionIndex int

Index of the current scan position.

required
sy slice

Row slice locating the current object patch in the full object.

required
sx slice

Column slice locating the current object patch in the full object.

required

Returns:

Type Description
ndarray

Estimated position correction [delta_y, delta_x] in pixels. Returns zeros before position correction becomes active.

Source code in PtyLab/Engines/BaseEngine.py
def positionCorrection(self, objectPatch, positionIndex, sy, sx):
    r"""
    Estimate the position correction for one scan position.

    The current object patch is compared with the corresponding region of the
    reconstructed object using cross-correlation. For small search radii,
    shifted object patches are evaluated directly. For larger search radii,
    the cross-correlation is calculated in the Fourier domain.

    A correlation-weighted displacement estimate is obtained from the tested
    shifts. Conceptually,

    $$
    g_x = \beta \sum_k \frac{C_k-\bar{C}}{\|O_{\mathrm{patch}}\|_2^2}\Delta x_k
    $$

    and similarly for $g_y$, where $C_k$ is the correlation obtained for the
    candidate shift $(\Delta y_k,\Delta x_k)$.

    The estimated correction is scaled by the position-correction feedback
    factor and accumulated into the position search direction used by
    `positionCorrectionUpdate()`.

    Args:
        objectPatch (ndarray):
            Current reconstructed object patch for the scan position.
        positionIndex (int):
            Index of the current scan position.
        sy (slice):
            Row slice locating the current object patch in the full object.
        sx (slice):
            Column slice locating the current object patch in the full object.

    Returns:
        ndarray:
            Estimated position correction ``[delta_y, delta_x]`` in pixels.
            Returns zeros before position correction becomes active.
    """

    xp = getArrayModule(objectPatch)
    if len(self.reconstruction.error) > self.startAtIteration:
        self.logger.debug("Calculating position correction")
        # position gradients
        # shiftedImages = xp.zeros((self.rowShifts.shape + objectPatch.shape))
        # complex cross-correlation per trial shift; its magnitude is taken below
        cc = xp.zeros((len(self.rowShifts), 1), dtype=objectPatch.dtype)

        # use the real-space object (FFT for FPM)
        O = self.reconstruction.object
        Opatch = objectPatch
        if self.experimentalData.operationMode == "FPM":
            O = fft2c(self.reconstruction.object)
            Opatch = fft2c(objectPatch)

        if self.params.positionCorrectionSwitch_radius < 2:
            # do the direct one as it's a bit faster

            for shifts in range(len(self.rowShifts)):
                tempShift = xp.roll(Opatch, self.rowShifts[shifts], axis=-2)
                # shiftedImages[shifts, ...] = xp.roll(tempShift, self.colShifts[shifts], axis=-1)
                shiftedImages = xp.roll(tempShift, self.colShifts[shifts], axis=-1)
                cc[shifts] = xp.squeeze(
                    xp.sum(shiftedImages.conj() * O[..., sy, sx], axis=(-2, -1))
                )
                del tempShift, shiftedImages
                betaGrad = 1000
                r = 3
        else:
            # print('doing FT position correction')
            ss = slice(
                -self.params.positionCorrectionSwitch_radius,
                self.params.positionCorrectionSwitch_radius + 1,
            )
            rowShifts, colShifts = xp.mgrid[ss, ss]
            self.rowShifts = rowShifts.flatten()
            self.colShifts = colShifts.flatten()
            FT_O = xp.fft.fft2(O[..., sy, sx] - O[..., sy, sx].mean())
            FT_Op = xp.fft.fft2(Opatch - O.mean())
            xcor = xp.fft.ifft2(FT_O * FT_Op.conj())
            xcor = abs(xp.fft.fftshift(xcor))
            N = xcor.shape[-1]
            sy = slice(
                N // 2 - self.params.positionCorrectionSwitch_radius,
                N // 2 + self.params.positionCorrectionSwitch_radius + 1,
            )
            xcor = xcor[..., sy, sy]
            cc = xcor.flatten()
            betaGrad = 5
            r = 10
            # dy, dx = xp.unravel_index(xp.argmax(xcor), xcor.shape)
            # dx = dx.get()
        # truncated cross - correlation
        # cc = xp.squeeze(xp.sum(shiftedImages.conj() * self.reconstruction.object[..., sy, sx], axis=(-2, -1)))
        cc = abs(cc)

        normFactor = xp.sum(Opatch.conj() * Opatch, axis=(-2, -1)).real
        grad_x = betaGrad * xp.sum(
            (cc.T - xp.mean(cc)) / normFactor * xp.array(self.colShifts)
        )
        grad_y = betaGrad * xp.sum(
            (cc.T - xp.mean(cc)) / normFactor * xp.array(self.rowShifts)
        )
        # r = np.clip(self.params.positionCorrectionSwitch_radius//5, 3, self.reconstruction.Np//10) # maximum shift in pixels?

        if abs(grad_x) > r:
            grad_x = r * grad_x / abs(grad_x)
        if abs(grad_y) > r:
            grad_y = r * grad_y / abs(grad_y)
        grad_y = asNumpyArray(grad_y)
        grad_x = asNumpyArray(grad_x)
        delta_p = self.daleth * np.array([grad_y, grad_x])
        self.D[positionIndex, :] = delta_p + self.beth * self.D[positionIndex, :]
        return delta_p
    return np.zeros(2)

position_update_to_change_in_z(loop)

Map the global scaling of corrected scan positions to an update of the propagation distance.

The corrected and original encoder positions are centered and their relative spatial scale is estimated as

\[ s = \frac{\sigma_{\mathrm{corrected}}}{\sigma_{\mathrm{original}}} \]

A corresponding target propagation distance is estimated as

\[ z_{\mathrm{target}} = \frac{z}{s} \]

Rather than jumping to \(z_{\mathrm{target}}\), the distance moves a fixed fraction \(\alpha = 0.2\) of the way there on each call, so that noisy position estimates do not make it jump:

\[ z \leftarrow z + \alpha \, (z_{\mathrm{target}} - z) \]

After updating the propagation distance, the corrected scan positions are rescaled around their center so that the global scale change is transferred from the position correction to the propagation distance.

Parameters:

Name Type Description Default
loop int

Current reconstruction iteration.

required
Notes

This method is used together with position correction and is called periodically when map_position_to_z_change is enabled.

Source code in PtyLab/Engines/BaseEngine.py
def position_update_to_change_in_z(self, loop):
    r"""
    Map the global scaling of corrected scan positions to an update of the
    propagation distance.

    The corrected and original encoder positions are centered and their
    relative spatial scale is estimated as

    $$
    s = \frac{\sigma_{\mathrm{corrected}}}{\sigma_{\mathrm{original}}}
    $$

    A corresponding target propagation distance is estimated as

    $$
    z_{\mathrm{target}} = \frac{z}{s}
    $$

    Rather than jumping to $z_{\mathrm{target}}$, the distance moves a fixed
    fraction $\alpha = 0.2$ of the way there on each call, so that noisy position
    estimates do not make it jump:

    $$
    z \leftarrow z + \alpha \, (z_{\mathrm{target}} - z)
    $$

    After updating the propagation distance,
    the corrected scan positions are rescaled around their center so that the
    global scale change is transferred from the position correction to the
    propagation distance.

    Args:
        loop (int):
            Current reconstruction iteration.

    Notes:
        This method is used together with position correction and is called
        periodically when `map_position_to_z_change` is enabled.
    """
    self._logOnce("Updating zo from the scale of the corrected positions")
    X0 = self.reconstruction.encoder_corrected
    Y0 = self.experimentalData.encoder
    msqdisplacement = np.linalg.norm(1e6 * X0 - 1e6 * Y0)

    # center both
    X0 = X0 - X0.mean(axis=0, keepdims=True)
    Y0 = Y0 - Y0.mean(axis=0, keepdims=True)

    # now, find the scaling with respect to the original one
    factor = np.std(X0) / np.std(Y0)

    # target distance implied by the scale change of the positions
    target_z = self.reconstruction.zo / factor
    step = target_z - self.reconstruction.zo
    self.logger.debug(
        f"Naive estimate of new z: {target_z:.3f}, stepsize {step:.3f}"
    )
    if abs(step) < 2e-5:  # same skip threshold as before (it used 5 * step < 1e-4)
        self.logger.debug("Skipping update as step is too small")
        return
    # damped update: move a fraction of the way toward the target each call
    damping = 0.2
    z_new = self.reconstruction.zo + damping * step

    self.logger.debug(f"Loop: {loop} step: {step}")
    self.logger.debug(
        f"old z: {self.reconstruction.zo:.3f}\n new z calculated: {z_new:.3f}\n diff: {self.reconstruction.zo - z_new}\n"
    )
    # scale the coordinates accordingly
    factor = self.reconstruction.zo / z_new
    self.reconstruction.zo = z_new
    new_encoder = self.reconstruction.encoder_corrected.copy()
    new_encoder -= new_encoder.mean(axis=0, keepdims=True)
    new_encoder /= factor  # this should be the correct one!

    new_encoder += self.experimentalData.encoder.mean(axis=0, keepdims=True)

    msqdisplacement_a = np.linalg.norm(
        1e6 * new_encoder - self.experimentalData.encoder * 1e6
    )

    self.reconstruction.encoder_corrected = new_encoder
    self.logger.debug(
        f"Mean square displacement: before: {msqdisplacement:.3f} after: {msqdisplacement_a:.3f}"
    )

positionCorrectionUpdate()

Apply the accumulated position corrections to the scan coordinates.

Position corrections estimated by positionCorrection() are stored in D in pixel units and are applied after the position-correction warm-up.

For conventional ptychography, the corrected encoder coordinates are updated as

\[ \mathbf{r}_j^{\mathrm{new}} = \mathbf{r}_j^{\mathrm{old}} - \alpha D_j d_{xo} \]

where \(\alpha\) is the adaptive step size and \(d_{xo}\) is the object-plane pixel size. The corrected scan grid is then recentered to the mean of the original encoder positions.

For Fourier ptychography, the corrected Fourier-space positions are converted back to illumination coordinates using the inverse FPM illumination geometry:

\[ \mathbf{r} = \operatorname{sign}(c)\frac{\mathbf{k}z_{\mathrm{LED}}}{\sqrt{c^2-k_x^2-k_y^2}} \]

with

\[ c = -\frac{N_p d_{xo}}{\lambda} \]
Notes

The method updates reconstruction.encoder_corrected in place and is called when position correction is enabled.

Source code in PtyLab/Engines/BaseEngine.py
def positionCorrectionUpdate(self):
    r"""
    Apply the accumulated position corrections to the scan coordinates.

    Position corrections estimated by `positionCorrection()` are stored in
    `D` in pixel units and are applied after the position-correction warm-up.

    For conventional ptychography, the corrected encoder coordinates are
    updated as

    $$
    \mathbf{r}_j^{\mathrm{new}} = \mathbf{r}_j^{\mathrm{old}} - \alpha D_j d_{xo}
    $$

    where $\alpha$ is the adaptive step size and $d_{xo}$ is the object-plane
    pixel size. The corrected scan grid is then recentered to the mean of the
    original encoder positions.

    For Fourier ptychography, the corrected Fourier-space positions are
    converted back to illumination coordinates using the inverse FPM
    illumination geometry:

    $$
    \mathbf{r} = \operatorname{sign}(c)\frac{\mathbf{k}z_{\mathrm{LED}}}{\sqrt{c^2-k_x^2-k_y^2}}
    $$

    with

    $$
    c = -\frac{N_p d_{xo}}{\lambda}
    $$

    Notes:
        The method updates `reconstruction.encoder_corrected` in place and is
        called when position correction is enabled.
    """

    # fit the scaling out, to put in the z
    if len(self.reconstruction.error) > self.startAtIteration:
        self._logOnce(
            "Position correction: updating scan positions every iteration"
        )

        # update positions
        if self.experimentalData.operationMode == "FPM":
            conv = (
                -(1 / self.reconstruction.wavelength)
                * self.reconstruction.dxo
                * self.reconstruction.Np
            )
            z = self.reconstruction.zled
            k = (
                self.reconstruction.positions
                - self.adaptStep * self.D
                - self.reconstruction.No // 2
                + self.reconstruction.Np // 2
            )
            self.reconstruction.encoder_corrected = (
                np.sign(conv)
                * k
                * z
                / (np.sqrt(conv**2 - k[:, 0] ** 2 - k[:, 1] ** 2))[..., None]
            )
        else:
            new_encoder = (
                self.reconstruction.encoder_corrected
                - self.adaptStep * self.D * self.reconstruction.dxo
            )
            new_encoder = new_encoder - new_encoder.mean(axis=0, keepdims=True)
            new_encoder = new_encoder + self.experimentalData.encoder.mean(
                axis=0, keepdims=True
            )

            self.reconstruction.encoder_corrected = new_encoder
            self.logger.debug(
                f"Average update size: {abs(self.D).mean():.2f} pixels"
            )

applyConstraints(loop)

Apply enabled reconstruction constraints after an iteration.

This method acts as the central dispatcher for object, probe, position, and autofocus constraints selected through Params. Depending on the active switches, it may apply regularization, probe normalization, modal orthogonalization, probe-boundary constraints, smoothing, amplitude constraints, spectral coupling, position correction, or autofocus updates.

Constraints are applied sequentially in the order defined by this method, so enabling multiple constraints may cause later operations to act on the result of earlier ones.

Parameters:

Name Type Description Default
loop int

Current reconstruction iteration.

required

Raises:

Type Description
NotImplementedError

If PSD estimation is enabled.

Source code in PtyLab/Engines/BaseEngine.py
def applyConstraints(self, loop):
    """
    Apply enabled reconstruction constraints after an iteration.

    This method acts as the central dispatcher for object, probe, position,
    and autofocus constraints selected through `Params`. Depending on the
    active switches, it may apply regularization, probe normalization,
    modal orthogonalization, probe-boundary constraints, smoothing,
    amplitude constraints, spectral coupling, position correction, or
    autofocus updates.

    Constraints are applied sequentially in the order defined by this method,
    so enabling multiple constraints may cause later operations to act on the
    result of earlier ones.

    Args:
        loop (int):
            Current reconstruction iteration.

    Raises:
        NotImplementedError:
            If PSD estimation is enabled.
    """
    # dirks additions, untested
    if self.params.l2reg:
        #     turns down areas that are not updated. Similar to an
        # l2 regularizer
        self.reconstruction.object *= 1 - self.params.l2reg_object_aleph
        self.reconstruction.probe *= 1 - self.params.l2reg_probe_aleph

    # enforce empty beam constraint
    if self.params.modulusEnforcedProbeSwitch:
        self.modulusEnforcedProbe()

    if self.params.orthogonalizationSwitch:
        if np.mod(loop, self.params.orthogonalizationFrequency) == 0:
            self.orthogonalization()

    # probe normalization to measured PSD todo: check for multiwave and multi object states
    if self.params.probePowerCorrectionSwitch:
        self.reconstruction.probe = (
            self.reconstruction.probe
            / np.sqrt(
                np.sum(self.reconstruction.probe * self.reconstruction.probe.conj())
            )
            * self.experimentalData.maxProbePower
        )
    if self.params.probeSpectralPowerCorrectionSwitch:
        for wl in range(self.reconstruction.probe.shape[0]):
            self.reconstruction.probe[wl, ...] *= (
                self.experimentalData.maxProbePower
                * self.experimentalData.spectralPower[wl]
                / np.sqrt(
                    np.sum(
                        self.reconstruction.probe[wl, ...]
                        * self.reconstruction.probe[wl, ...].conj()
                    )
                )
            )

    if (
        self.params.comStabilizationSwitch is not None
        and self.params.comStabilizationSwitch is not False
    ):
        if loop % int(self.params.comStabilizationSwitch) == 0:
            self.comStabilization()

    if self.params.PSDestimationSwitch:
        raise NotImplementedError()

    if self.params.probeBoundary:
        self.reconstruction.probe *= self.probeWindow

    if self.params.absorbingProbeBoundary:
        if self.experimentalData.operationMode == "FPM":
            self.absorbingProbeBoundaryAleph = 1

        self.reconstruction.probe = (
            (1 - self.params.absorbingProbeBoundaryAleph)
            * self.reconstruction.probe
            + self.params.absorbingProbeBoundaryAleph
            * self.reconstruction.probe
            * self.probeWindow
        )

        # experimental: also apply in fourier space
        # self.reconstruction.probe = ifft2c(fft2c(self.reconstruction.probe)*self.probeWindow)

    # Todo: objectSmoothenessSwitch,probeSmoothenessSwitch,
    if self.params.probeSmoothenessSwitch:
        self.reconstruction.probe = smooth_amplitude(
            self.reconstruction.probe,
            self.params.probeSmoothenessWidth,
            self.params.probeSmoothnessAleph,
        )

    if self.params.objectSmoothenessSwitch:
        self.reconstruction.object = smooth_amplitude(
            self.reconstruction.object,
            self.params.objectSmoothenessWidth,
            self.params.objectSmoothnessAleph,
        )

    if self.params.absObjectSwitch:
        self.reconstruction.object = (
            1 - self.params.absObjectBeta
        ) * self.reconstruction.object + self.params.absObjectBeta * abs(
            self.reconstruction.object
        )

    if self.params.absProbeSwitch:
        self.reconstruction.probe = (
            1 - self.params.absProbeBeta
        ) * self.reconstruction.probe + self.params.absProbeBeta * abs(
            self.reconstruction.probe
        )

    # this is intended to slowly push non-measured object region to abs value lower than
    # the max abs inside object ROI allowing for good contrast when monitoring object
    if self.params.objectContrastSwitch:
        self.reconstruction.object = (
            0.995 * self.reconstruction.object
            + 0.005
            * np.mean(
                abs(
                    self.reconstruction.object[
                        ..., self.objectROI[0], self.objectROI[1]
                    ]
                )
            )
        )
    if self.params.couplingSwitch and self.reconstruction.nlambda > 1:
        self.reconstruction.probe[0] = (
            1 - self.params.couplingAleph
        ) * self.reconstruction.probe[
            0
        ] + self.params.couplingAleph * self.reconstruction.probe[1]
        for lambdaLoop in np.arange(1, self.reconstruction.nlambda - 1):
            self.reconstruction.probe[lambdaLoop] = (
                1 - self.params.couplingAleph
            ) * self.reconstruction.probe[
                lambdaLoop
            ] + self.params.couplingAleph * (
                self.reconstruction.probe[lambdaLoop + 1]
                + self.reconstruction.probe[lambdaLoop - 1]
            ) / 2

        self.reconstruction.probe[-1] = (
            1 - self.params.couplingAleph
        ) * self.reconstruction.probe[
            -1
        ] + self.params.couplingAleph * self.reconstruction.probe[-2]
    if self.params.binaryProbeSwitch:
        probePeakAmplitude = np.max(abs(self.reconstruction.probe))
        probeThresholded = self.reconstruction.probe.copy()
        probeThresholded[
            (
                abs(probeThresholded)
                < self.params.binaryProbeThreshold * probePeakAmplitude
            )
        ] = 0

        self.reconstruction.probe = (
            (1 - self.params.binaryProbeAleph) * self.reconstruction.probe
            + self.params.binaryProbeAleph * probeThresholded
        )

    if self.params.positionCorrectionSwitch:
        self.positionCorrectionUpdate()

    if (
        self.params.map_position_to_z_change
        and (loop % 5 == 1)
        and self.params.positionCorrectionSwitch
    ):
        self.position_update_to_change_in_z(loop)

    if self.params.TV_autofocus:
        merit, AOI_image, allmerits = self.reconstruction.TV_autofocus(
            self.params, loop=loop
        )
        if merit is not None:  # None on iterations where autofocus is skipped
            self._logOnce(
                "TV autofocus: updating zo every %d iterations",
                self.params.TV_autofocus_run_every,
            )
        self.monitor.update_focusing_metric(
            merit,
            AOI_image,
            metric_name=self.params.TV_autofocus_metric,
            allmerits=allmerits,
        )

orthogonalization()

Orthogonalize mixed-state probe or object modes.

For multiple probe modes, the reconstructed modes are transformed to an orthogonal modal basis independently for each wavelength and slice. Conceptually, the transformed modes are

\[ P'_k(x,y) = \sum_j U_{kj}P_j(x,y) \]

where \(U\) is the modal transformation returned by orthogonalizeModes().

The normalized modal eigenvalues are used to calculate the probe purity:

\[ \mu = \sqrt{\sum_k \tilde{\lambda}_k^2} \]

where

\[ \tilde{\lambda}_k = \frac{\lambda_k}{\sum_j \lambda_j} \]

are the normalized modal eigenvalues. A purity of one corresponds to a single dominant mode, while lower values indicate a stronger mixed-state contribution.

If momentum acceleration is enabled, the same modal transformation is applied to the corresponding momentum and buffer arrays so that all reconstruction state variables remain expressed in the same modal basis.

If only multiple object modes are present, the analogous procedure is applied to the object modes and purityObject is updated.

Notes

Probe modes are orthogonalized independently for each wavelength and slice. The resulting probe purity is stored in reconstruction.purityProbe and appended to reconstruction.purityProbeHist.

Source code in PtyLab/Engines/BaseEngine.py
def orthogonalization(self):
    r"""
    Orthogonalize mixed-state probe or object modes.

    For multiple probe modes, the reconstructed modes are transformed to an
    orthogonal modal basis independently for each wavelength and slice.
    Conceptually, the transformed modes are

    $$
    P'_k(x,y) = \sum_j U_{kj}P_j(x,y)
    $$

    where $U$ is the modal transformation returned by `orthogonalizeModes()`.

    The normalized modal eigenvalues are used to calculate the probe purity:

    $$
    \mu = \sqrt{\sum_k \tilde{\lambda}_k^2}
    $$

    where

    $$
    \tilde{\lambda}_k = \frac{\lambda_k}{\sum_j \lambda_j}
    $$

    are the normalized modal eigenvalues. A purity of one
    corresponds to a single dominant mode, while lower values indicate a
    stronger mixed-state contribution.

    If momentum acceleration is enabled, the same modal transformation is
    applied to the corresponding momentum and buffer arrays so that all
    reconstruction state variables remain expressed in the same modal basis.

    If only multiple object modes are present, the analogous procedure is
    applied to the object modes and `purityObject` is updated.

    Notes:
        Probe modes are orthogonalized independently for each wavelength and
        slice. The resulting probe purity is stored in
        `reconstruction.purityProbe` and appended to
        `reconstruction.purityProbeHist`.
    """
    xp = getArrayModule(self.reconstruction.probe)
    if self.reconstruction.npsm > 1:
        # orthogonalize the probe for each wavelength and each slice
        for id_l in range(self.reconstruction.nlambda):
            for id_s in range(self.reconstruction.nslice):
                (
                    self.reconstruction.probe[id_l, 0, :, id_s, :, :],
                    self.normalizedEigenvaluesProbe,
                    self.MSPVprobe,
                ) = orthogonalizeModes(
                    self.reconstruction.probe[id_l, 0, :, id_s, :, :],
                    method="snapShots",
                )
                # normalizedEigenvalues can live on either device, and is only
                # npsm values long -- reducing it on the host is both cheaper
                # than launching kernels for it and device-independent.
                eigenvalues = asNumpyArray(self.normalizedEigenvaluesProbe)
                self.reconstruction.purityProbe = float(
                    np.sqrt(np.sum(eigenvalues**2))
                )
                self.reconstruction.purityProbeHist.append(
                    self.reconstruction.purityProbe
                )
                # orthogonolize momentum operator
                if self.params.momentumAcceleration:
                    # orthogonalize probe Buffer
                    p = self.reconstruction.probeBuffer[
                        id_l, 0, :, id_s, :, :
                    ].reshape((self.reconstruction.npsm, self.reconstruction.Np**2))
                    self.reconstruction.probeBuffer[id_l, 0, :, id_s, :, :] = (
                        xp.array(self.MSPVprobe) @ p
                    ).reshape(
                        (
                            self.reconstruction.npsm,
                            self.reconstruction.Np,
                            self.reconstruction.Np,
                        )
                    )
                    # orthogonalize probe momentum
                    p = self.reconstruction.probeMomentum[
                        id_l, 0, :, id_s, :, :
                    ].reshape((self.reconstruction.npsm, self.reconstruction.Np**2))
                    self.reconstruction.probeMomentum[id_l, 0, :, id_s, :, :] = (
                        xp.array(self.MSPVprobe) @ p
                    ).reshape(
                        (
                            self.reconstruction.npsm,
                            self.reconstruction.Np,
                            self.reconstruction.Np,
                        )
                    )

                    # if self.comStabilizationSwitch:
                    #     self.comStabilization()
        # self.reconstruction.probe_storage.push(self.reconstruction.probe, None, len(self.experimentalData.ptychogram), force=True)

    elif self.reconstruction.nosm > 1:
        # orthogonalize the object for each wavelength and each slice
        for id_l in range(self.reconstruction.nlambda):
            for id_s in range(self.reconstruction.nslice):
                (
                    self.reconstruction.object[id_l, :, 0, id_s, :, :],
                    self.normalizedEigenvaluesObject,
                    self.MSPVobject,
                ) = orthogonalizeModes(
                    self.reconstruction.object[id_l, :, 0, id_s, :, :],
                    method="snapShots",
                )
                eigenvalues = asNumpyArray(self.normalizedEigenvaluesObject)
                self.reconstruction.purityObject = float(
                    np.sqrt(np.sum(eigenvalues**2))
                )

                # orthogonolize momentum operator
                if self.params.momentumAcceleration:
                    # orthogonalize object Buffer
                    p = self.reconstruction.objectBuffer[
                        id_l, :, 0, id_s, :, :
                    ].reshape((self.reconstruction.nosm, self.reconstruction.No**2))
                    self.reconstruction.objectBuffer[id_l, :, 0, id_s, :, :] = (
                        xp.array(self.MSPVobject) @ p
                    ).reshape(
                        (
                            self.reconstruction.nosm,
                            self.reconstruction.No,
                            self.reconstruction.No,
                        )
                    )
                    # orthogonalize object momentum
                    p = self.reconstruction.objectMomentum[
                        id_l, :, 0, id_s, :, :
                    ].reshape((self.reconstruction.nosm, self.reconstruction.No**2))
                    self.reconstruction.objectMomentum[id_l, :, 0, id_s, :, :] = (
                        xp.array(self.MSPVobject) @ p
                    ).reshape(
                        (
                            self.reconstruction.nosm,
                            self.reconstruction.No,
                            self.reconstruction.No,
                        )
                    )

    else:
        pass

comStabilization()

Stabilize the probe center of mass to suppress translational drift.

Ptychographic reconstruction contains a translational ambiguity that can allow the reconstructed probe and object to drift within their numerical arrays without strongly affecting the data consistency. This method estimates the probe center relative to the center of the reconstruction window and shifts the reconstruction when the displacement exceeds approximately one pixel.

The current probe center is estimated as

\[ x_c = \frac{\sum_{x,y}X_p(x,y)A(x,y)}{d_{xp}\sum_{x,y}A(x,y)} \]

and

\[ y_c = \frac{\sum_{x,y}Y_p(x,y)A(x,y)}{d_{xp}\sum_{x,y}A(x,y)} \]

where \(A(x,y)\) is the probe amplitude and \(d_{xp}\) is the probe-plane pixel size. The resulting coordinates are rounded to integer pixel shifts.

If the probe center is displaced by more than approximately one pixel, both the probe and object are shifted by (-yc, -xc) to recenter the reconstruction while preserving their relative spatial registration.

When momentum acceleration is enabled, the corresponding probe and object momentum and buffer arrays are shifted by the same amount.

Notes

For multislice reconstruction, the last probe slice is used to estimate the center.

Source code in PtyLab/Engines/BaseEngine.py
def comStabilization(self):
    r"""
    Stabilize the probe center of mass to suppress translational drift.

    Ptychographic reconstruction contains a translational ambiguity that can
    allow the reconstructed probe and object to drift within their numerical
    arrays without strongly affecting the data consistency. This method
    estimates the probe center relative to the center of the reconstruction
    window and shifts the reconstruction when the displacement exceeds
    approximately one pixel.

    The current probe center is estimated as

    $$
    x_c = \frac{\sum_{x,y}X_p(x,y)A(x,y)}{d_{xp}\sum_{x,y}A(x,y)}
    $$

    and

    $$
    y_c = \frac{\sum_{x,y}Y_p(x,y)A(x,y)}{d_{xp}\sum_{x,y}A(x,y)}
    $$

    where $A(x,y)$ is the probe amplitude and $d_{xp}$ is the probe-plane
    pixel size. The resulting coordinates are rounded to integer pixel
    shifts.

    If the probe center is displaced by more than approximately one pixel,
    both the probe and object are shifted by `(-yc, -xc)` to recenter the
    reconstruction while preserving their relative spatial registration.

    When momentum acceleration is enabled, the corresponding probe and object
    momentum and buffer arrays are shifted by the same amount.

    Notes:
        For multislice reconstruction, the last probe slice is used to
        estimate the center.
    """
    self._logOnce("Doing probe com stabilization every iteration")
    xp = getArrayModule(self.reconstruction.probe)
    # calculate center of mass of the probe (for multislice cases, the probe for the last slice is used)
    P2 = xp.sum(
        abs(self.reconstruction.probe[:, :, :, -1, ...]) ** 2, axis=(0, 1, 2)
    )
    P2 = abs(self.reconstruction.probe[0, 0, 0, -1]) ** 2
    demon = xp.sum(P2) * self.reconstruction.dxp
    xc = int(
        xp.around(xp.sum(xp.array(self.reconstruction.Xp, xp.float32) * P2) / demon)
    )
    yc = int(
        xp.around(xp.sum(xp.array(self.reconstruction.Yp, xp.float32) * P2) / demon)
    )
    # print('Center of mass:', yc, xc)
    # shift only if necessary
    if xc**2 + yc**2 > 1:
        # self.reconstruction.probe_storage._push_hard(self.reconstruction.probe, 100)
        # self.reconstruction.probe_storage.roll(-yc, -xc)

        # shift probe
        self.reconstruction.probe = xp.roll(
            self.reconstruction.probe, (-yc, -xc), axis=(-2, -1)
        )
        # for k in xp.arange(self.reconstruction.npsm):
        #     self.reconstruction.probe[:, :, k, -1, ...] = \
        #         xp.roll(self.reconstruction.probe[:, :, k, -1, ...], (-yc, -xc), axis=(-2, -1))
        #     # for mPIE
        if self.params.momentumAcceleration:
            self.reconstruction.probeMomentum = xp.roll(
                self.reconstruction.probeMomentum, (-yc, -xc), axis=(-2, -1)
            )
            self.reconstruction.probeBuffer = xp.roll(
                self.reconstruction.probeBuffer, (-yc, -xc), axis=(-2, -1)
            )

        # shift object
        self.reconstruction.object = xp.roll(
            self.reconstruction.object, (-yc, -xc), axis=(-2, -1)
        )
        # for mPIE
        if self.params.momentumAcceleration:
            self.reconstruction.objectMomentum = xp.roll(
                self.reconstruction.objectMomentum, (-yc, -xc), axis=(-2, -1)
            )
            self.reconstruction.objectBuffer = xp.roll(
                self.reconstruction.objectBuffer, (-yc, -xc), axis=(-2, -1)
            )

modulusEnforcedProbe()

Constrain the reconstructed probe using a measured empty-beam intensity.

The current probe is propagated to the detector plane, where its estimated intensity is compared with experimentalData.emptyBeam.

The detector-plane probe is scaled by

\[ f(x,y) = \sqrt{\frac{I_{\mathrm{empty}}(x,y)}{I_{\mathrm{probe}}(x,y)+\epsilon}} \]

and updated as

\[ \Psi_{\mathrm{updated}}(x,y) = \Psi(x,y)f(x,y) \]

so that the measured detector-plane amplitude is enforced while the current phase estimate is retained.

The constrained field is then propagated back to the probe plane and stored in reconstruction.probe.

If FourierMaskSwitch is enabled, the modulus constraint is applied only inside the active Fourier mask, while the detector-plane field outside the mask is left unchanged.

Notes

This constraint requires experimentalData.emptyBeam, containing a measured detector intensity of the illumination without the sample.

Source code in PtyLab/Engines/BaseEngine.py
def modulusEnforcedProbe(self):
    r"""
    Constrain the reconstructed probe using a measured empty-beam intensity.

    The current probe is propagated to the detector plane, where its
    estimated intensity is compared with `experimentalData.emptyBeam`.

    The detector-plane probe is scaled by

    $$
    f(x,y) = \sqrt{\frac{I_{\mathrm{empty}}(x,y)}{I_{\mathrm{probe}}(x,y)+\epsilon}}
    $$

    and updated as

    $$
    \Psi_{\mathrm{updated}}(x,y) = \Psi(x,y)f(x,y)
    $$

    so that the measured detector-plane amplitude is enforced while the
    current phase estimate is retained.

    The constrained field is then propagated back to the probe plane and
    stored in `reconstruction.probe`.

    If `FourierMaskSwitch` is enabled, the modulus constraint is applied only
    inside the active Fourier mask, while the detector-plane field outside
    the mask is left unchanged.

    Notes:
        This constraint requires `experimentalData.emptyBeam`, containing a
        measured detector intensity of the illumination without the sample.
    """
    xp = getArrayModule(self.reconstruction.esw)
    self.reconstruction.esw = self.reconstruction.probe
    self.object2detector()

    if self.params.FourierMaskSwitch:
        self.reconstruction.ESW = self.reconstruction.ESW * xp.sqrt(
            self.experimentalData.emptyBeam
            / (
                1e-10
                + xp.sum(
                    xp.abs(self.reconstruction.ESW) ** 2,
                    axis=(0, 1, 2, 3),
                )
            )
        ) * self.experimentalData.W + self.reconstruction.ESW * (
            1 - self.experimentalData.W
        )
    else:
        self.reconstruction.ESW = self.reconstruction.ESW * np.sqrt(
            self.experimentalData.emptyBeam
            / (1e-10 + xp.sum(abs(self.reconstruction.ESW) ** 2, axis=(0, 1, 2, 3)))
        )

    self.detector2object()

    if self.params.OPRP:
        pass
        # self.probes.append(self.reconstruction.esw.reshape(-))

    self.reconstruction.probe = self.reconstruction.esw

adaptiveDenoising()

Apply an adaptive amplitude-domain noise-floor correction.

The measured and estimated detector intensities are converted to amplitudes.

A global noise level is estimated from their mean amplitude difference:

\[ n = \left|\left\langle A_{\mathrm{meas}} - A_{\mathrm{est}} \right\rangle\right| \]

The estimated noise floor is subtracted from the measured amplitude and negative values are clipped to zero:

\[ A'_{\mathrm{meas}} = \max(A_{\mathrm{meas}} - n, 0) \]

The corrected measured intensity is then reconstructed as

\[ I'_{\mathrm{meas}} = \left(A'_{\mathrm{meas}}\right)^2 \]
Notes

This method modifies reconstruction.Imeasured in place and is applied before the detector-plane intensity constraint.

Source code in PtyLab/Engines/BaseEngine.py
def adaptiveDenoising(self):
    r"""
    Apply an adaptive amplitude-domain noise-floor correction.

    The measured and estimated detector intensities are converted to
    amplitudes.

    A global noise level is estimated from their mean amplitude difference:

    $$
    n = \left|\left\langle A_{\mathrm{meas}} - A_{\mathrm{est}} \right\rangle\right|
    $$

    The estimated noise floor is subtracted from the measured amplitude and
    negative values are clipped to zero:

    $$
    A'_{\mathrm{meas}} = \max(A_{\mathrm{meas}} - n, 0)
    $$

    The corrected measured intensity is then reconstructed as

    $$
    I'_{\mathrm{meas}} = \left(A'_{\mathrm{meas}}\right)^2
    $$

    Notes:
        This method modifies `reconstruction.Imeasured` in place and is
        applied before the detector-plane intensity constraint.
    """
    # figure out wether or not to use the GPU
    xp = getArrayModule(self.reconstruction.esw)

    Ameasured = self.reconstruction.Imeasured**0.5
    Aestimated = xp.abs(self.reconstruction.Iestimated) ** 0.5

    noise = xp.abs(xp.mean(Ameasured - Aestimated))

    Ameasured = Ameasured - noise
    Ameasured[Ameasured < 0] = 0
    self.reconstruction.Imeasured = Ameasured**2

objectPatchUpdate_TV(objectPatch, DELTA)

Apply total-variation regularization to the engine-specific object update.

The data-driven object update is first calculated using the current engine's objectPatchUpdate() implementation:

\[ O_{\mathrm{data}} = U_{\mathrm{engine}}(O_j,\Delta\Psi_j) \]

where \(U_{\mathrm{engine}}\) denotes the object-update rule implemented by the active reconstruction engine. For example, ePIE uses the standard ePIE update, while mPIE uses its regularized mPIE/rPIE update.

A total-variation regularization term is then added:

\[ O'_j = O_{\mathrm{data}} + \lambda\beta_O G_{\mathrm{TV}}(O_j) \]

where \(G_{\mathrm{TV}}(O_j)\) is calculated by grad_TV() using epsilon=1e-2, \(\beta_O\) is the engine's object update step size, and \(\lambda\) is controlled by params.objectTVregStepSize.

This design keeps the TV regularization independent of the underlying reconstruction engine, allowing different engines to retain their native object-update rules while sharing the same TV regularizer.

The activation and application frequency of this update are controlled by params.objectTVregSwitch and params.objectTVfreq in the reconstruction loop.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the active scan position.

required
DELTA ndarray

Exit-wave correction, typically reconstruction.eswUpdate - reconstruction.esw.

required

Returns:

Type Description
ndarray

Engine-specific object update with the additional TV regularization term.

Source code in PtyLab/Engines/BaseEngine.py
def objectPatchUpdate_TV(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Apply total-variation regularization to the engine-specific object update.

    The data-driven object update is first calculated using the current
    engine's `objectPatchUpdate()` implementation:

    $$
    O_{\mathrm{data}} = U_{\mathrm{engine}}(O_j,\Delta\Psi_j)
    $$

    where $U_{\mathrm{engine}}$ denotes the object-update rule implemented by
    the active reconstruction engine. For example, `ePIE` uses the standard
    ePIE update, while `mPIE` uses its regularized mPIE/rPIE update.

    A total-variation regularization term is then added:

    $$
    O'_j = O_{\mathrm{data}} + \lambda\beta_O G_{\mathrm{TV}}(O_j)
    $$

    where $G_{\mathrm{TV}}(O_j)$ is calculated by `grad_TV()` using
    `epsilon=1e-2`, $\beta_O$ is the engine's object update step size, and
    $\lambda$ is controlled by `params.objectTVregStepSize`.

    This design keeps the TV regularization independent of the underlying
    reconstruction engine, allowing different engines to retain their native
    object-update rules while sharing the same TV regularizer.

    The activation and application frequency of this update are controlled by
    `params.objectTVregSwitch` and `params.objectTVfreq` in the reconstruction
    loop.

    Args:
        objectPatch (ndarray):
            Current object patch at the active scan position.
        DELTA (ndarray):
            Exit-wave correction, typically
            `reconstruction.eswUpdate - reconstruction.esw`.

    Returns:
        ndarray:
            Engine-specific object update with the additional TV
            regularization term.
    """

    # xp = getArrayModule(objectPatch)
    # frac = self.reconstruction.probe.conj() / xp.max(
    #    xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
    # )

    # gradient = xp.gradient(objectPatch, axis=(4, 5))
    #
    # # norm = xp.abs(gradient[0] + gradient[1]) ** 2
    # norm = (gradient[0] + gradient[1]) ** 2
    # temp = [gradient[0] / xp.sqrt(norm + epsilon), gradient[1] / xp.sqrt(norm + epsilon)]
    # TV_update = divergence(temp)

    TV_update = grad_TV(objectPatch, epsilon=1e-2)

    updated_object = self.objectPatchUpdate(objectPatch, DELTA)

    lam = self.params.objectTVregStepSize

    return updated_object + lam * self.betaObject * TV_update

ePIE

Bases: BaseEngine

Extended Ptychographical Iterative Engine (ePIE).

ePIE jointly reconstructs the complex object and illumination probe by iterating over overlapping scan positions.1 For each position \(j\), the exit surface wave is formed as

\[ \Psi_j = O_j P \]

where \(O_j\) is the object patch illuminated by the probe \(P\).

After propagation to the detector plane and application of the measured intensity constraint, the corrected exit wave \(\Psi'_j\) is propagated back to the object plane. The resulting exit-wave difference is

\[ \Delta\Psi_j = \Psi'_j - \Psi_j \]

In the classical single-mode ePIE formulation, the object and probe are updated according to

\[ O'_j = O_j + \beta_O \frac{P^*}{\max |P|^2}\Delta\Psi_j \]

and

\[ P' = P + \beta_P \frac{O_j^*}{\max |O_j|^2}\Delta\Psi_j \]

where \(\beta_O\) and \(\beta_P\) control the object and probe update step sizes.

The PtyLab implementation generalizes these updates to its multidimensional reconstruction representation by summing the corresponding contributions over the relevant wavelength, mode, and slice dimensions.

The default ePIE settings are betaObject = 0.25, betaProbe = 0.25, and numIterations = 50.


  1. A. M. Maiden and J. M. Rodenburg, "An improved ptychographical phase retrieval algorithm for diffractive imaging," Ultramicroscopy 109, 1256-1262 (2009). https://doi.org/10.1016/j.ultramic.2009.05.012 ↩

Source code in PtyLab/Engines/ePIE.py
class ePIE(BaseEngine):
    r"""
    Extended Ptychographical Iterative Engine (ePIE).

    ePIE jointly reconstructs the complex object and illumination probe by
    iterating over overlapping scan positions.[^maiden2009] For each position $j$, the
    exit surface wave is formed as

    $$
    \Psi_j = O_j P
    $$

    where $O_j$ is the object patch illuminated by the probe $P$.

    After propagation to the detector plane and application of the measured
    intensity constraint, the corrected exit wave $\Psi'_j$ is propagated
    back to the object plane. The resulting exit-wave difference is

    $$
    \Delta\Psi_j = \Psi'_j - \Psi_j
    $$

    In the classical single-mode ePIE formulation, the object and probe are
    updated according to

    $$
    O'_j = O_j + \beta_O \frac{P^*}{\max |P|^2}\Delta\Psi_j
    $$

    and

    $$
    P' = P + \beta_P \frac{O_j^*}{\max |O_j|^2}\Delta\Psi_j
    $$

    where $\beta_O$ and $\beta_P$ control the object and probe update step
    sizes.

    The PtyLab implementation generalizes these updates to its multidimensional
    reconstruction representation by summing the corresponding contributions
    over the relevant wavelength, mode, and slice dimensions.

    The default ePIE settings are `betaObject = 0.25`,
    `betaProbe = 0.25`, and `numIterations = 50`.

    [^maiden2009]: A. M. Maiden and J. M. Rodenburg,
        "An improved ptychographical phase retrieval algorithm for diffractive
        imaging," Ultramicroscopy 109, 1256-1262 (2009).
        https://doi.org/10.1016/j.ultramic.2009.05.012
    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("ePIE")
        self.logger.info("Sucesfully created ePIE ePIE_engine")
        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        self.initializeReconstructionParams()

    def initializeReconstructionParams(self):
        """
        Initialize ePIE-specific reconstruction parameters.

        Defaults:
            betaObject (float):
                Object update step size. Default is 0.25.
            betaProbe (float):
                Probe update step size. Default is 0.25.
            numIterations (int):
                Number of reconstruction iterations. Default is 50.
        """
        self.betaProbe = 0.25
        self.betaObject = 0.25
        self.numIterations = 50

    def reconstruct(self, experimentalData: ExperimentalData = None):
        """
        Run the ePIE reconstruction to completion.

        This method consumes the generator returned by `reconstruct_stepwise()`
        until all reconstruction iterations and scan positions have been
        processed.

        Use `reconstruct_stepwise()` when custom operations need to be inserted
        between individual scan-position updates.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use for the reconstruction. If provided,
                it replaces the currently attached experimental data.
        """
        for _ in self.reconstruct_stepwise(experimentalData):
            pass

    def reconstruct_stepwise(self, experimentalData: ExperimentalData = None):
        r"""
        Run the ePIE reconstruction one scan-position update at a time.

        For each reconstruction iteration, the scan positions are visited in the
        order selected by `params.positionOrder`. At each position $j$, the
        corresponding object patch is extracted and combined with the current
        probe to form the exit surface wave:

        $$
        \Psi_j = O_j P
        $$

        The exit wave is propagated to the detector plane, constrained by the
        measured diffraction intensity through `intensityProjection()`, and
        propagated back to obtain an updated exit wave $\Psi'_j$.

        The exit-wave correction is

        $$
        \Delta\Psi_j = \Psi'_j - \Psi_j
        $$

        By default, the object is updated using the standard ePIE rule implemented
        by `objectPatchUpdate()`.

        If `params.objectTVregSwitch` is enabled, the TV-regularized update
        `objectPatchUpdate_TV()` is used every `params.objectTVfreq` iterations.
        The standard ePIE object update is retained and an additional TV
        regularization term is added with strength controlled by
        `params.objectTVregStepSize`.

        The probe is updated using `probeUpdate()` after each object update.

        If `params.OPRP` is enabled, position-dependent probe estimates are
        retrieved from `reconstruction.probe_storage` before each scan-position
        update and stored again after the probe update. Without OPRP, a shared
        probe estimate is updated sequentially across all scan positions.

        After all scan positions in an iteration have been processed,
        `getErrorMetrics()` evaluates the reconstruction error,
        `applyConstraints()` applies the enabled reconstruction constraints and
        `showReconstruction()` updates the monitor.

        The method yields after every scan-position update, allowing custom code
        to be interleaved with the reconstruction.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use for the reconstruction. If provided,
                it replaces the currently attached experimental data.

        Yields:
            tuple:
                `(iteration, positionLoop)` after each scan-position update.
        """
        if experimentalData is not None:
            self.reconstruction.data = experimentalData
            self.experimentalData = experimentalData
        self._prepareReconstruction()

        # actual reconstruction ePIE_engine
        self.pbar = trange(self.numIterations, desc="ePIE", file=sys.stdout, leave=True)
        for loop in self.pbar:
            # set position order
            self.setPositionOrder()
            if self.params.OPRP:
                # make the initial guess the default storage
                self.reconstruction.probe_storage.push(
                    self.reconstruction.probe,
                    0,
                    self.experimentalData.ptychogram.shape[0],
                )
            for positionLoop, positionIndex in enumerate(self.positionIndices):
                # get object patch
                if self.params.OPRP:
                    self.reconstruction.probe = self.reconstruction.probe_storage.get(
                        positionIndex
                    )
                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                # object update
                if (
                    self.params.objectTVregSwitch
                    and loop % self.params.objectTVfreq == 0
                ):
                    object_patch = self.objectPatchUpdate_TV(objectPatch, DELTA)
                else:
                    object_patch = self.objectPatchUpdate(objectPatch, DELTA)

                self.reconstruction.object[..., sy, sx] = object_patch

                # self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                #    objectPatch, DELTA
                # )

                # probe update
                self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)
                if self.params.OPRP:
                    self.reconstruction.probe_storage.push(
                        self.reconstruction.probe,
                        positionIndex,
                        self.experimentalData.ptychogram.shape[0],
                    )
                yield loop, positionLoop

            # get error metric
            self.getErrorMetrics()

            # apply Constraints
            self.applyConstraints(loop)

            # update the monitor, as every other engine does after the constraints
            self.showReconstruction(loop)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the object patch using the ePIE object-update rule.

        For the classical single-mode case, the probe weighting is

        $$
        W_P(x,y) = \frac{P^*(x,y)}{\max_{x,y}|P(x,y)|^2}
        $$

        and the object patch is updated according to

        $$
        O'_j = O_j + \beta_O W_P\Delta\Psi_j
        $$

        where $O_j$ is the current object patch, $\Delta\Psi_j$ is the
        exit-wave correction obtained from the detector-plane intensity
        constraint, and $\beta_O$ is `betaObject`.

        In the multidimensional PtyLab representation, contributions from the
        relevant wavelength, probe-mode, and slice dimensions are summed before
        updating the object patch.

        Args:
            objectPatch (ndarray):
                Current object patch at the active scan position.
            DELTA (ndarray):
                Exit-wave correction
                `reconstruction.eswUpdate - reconstruction.esw`.

        Returns:
            ndarray:
                Updated object patch.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)

        frac = self.reconstruction.probe.conj() / xp.max(
            xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2, 3), keepdims=True
        )

    def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the probe using the ePIE probe-update rule.

        For the classical single-mode case, the object weighting is

        $$
        W_O(x,y) = \frac{O_j^*(x,y)}{\max_{x,y}|O_j(x,y)|^2}
        $$

        and the probe is updated according to

        $$
        P' = P + \beta_P W_O\Delta\Psi_j
        $$

        where $O_j$ is the current object patch, $\Delta\Psi_j$ is the
        exit-wave correction obtained from the detector-plane intensity
        constraint, and $\beta_P$ is `betaProbe`.

        In the multidimensional PtyLab representation, the implemented update
        sums the corresponding correction over axes `(0, 1, 3)` while preserving
        the probe-mode dimension.

        Args:
            objectPatch (ndarray):
                Current object patch at the active scan position.
            DELTA (ndarray):
                Exit-wave correction
                `reconstruction.eswUpdate - reconstruction.esw`.

        Returns:
            ndarray:
                Updated probe.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        frac = objectPatch.conj() / xp.max(
            xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))
        )
        r = self.reconstruction.probe + self.betaProbe * xp.sum(
            frac * DELTA, axis=(0, 1, 3), keepdims=True
        )
        return r

initializeReconstructionParams()

Initialize ePIE-specific reconstruction parameters.

Defaults

betaObject (float): Object update step size. Default is 0.25. betaProbe (float): Probe update step size. Default is 0.25. numIterations (int): Number of reconstruction iterations. Default is 50.

Source code in PtyLab/Engines/ePIE.py
def initializeReconstructionParams(self):
    """
    Initialize ePIE-specific reconstruction parameters.

    Defaults:
        betaObject (float):
            Object update step size. Default is 0.25.
        betaProbe (float):
            Probe update step size. Default is 0.25.
        numIterations (int):
            Number of reconstruction iterations. Default is 50.
    """
    self.betaProbe = 0.25
    self.betaObject = 0.25
    self.numIterations = 50

reconstruct(experimentalData=None)

Run the ePIE reconstruction to completion.

This method consumes the generator returned by reconstruct_stepwise() until all reconstruction iterations and scan positions have been processed.

Use reconstruct_stepwise() when custom operations need to be inserted between individual scan-position updates.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for the reconstruction. If provided, it replaces the currently attached experimental data.

None
Source code in PtyLab/Engines/ePIE.py
def reconstruct(self, experimentalData: ExperimentalData = None):
    """
    Run the ePIE reconstruction to completion.

    This method consumes the generator returned by `reconstruct_stepwise()`
    until all reconstruction iterations and scan positions have been
    processed.

    Use `reconstruct_stepwise()` when custom operations need to be inserted
    between individual scan-position updates.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use for the reconstruction. If provided,
            it replaces the currently attached experimental data.
    """
    for _ in self.reconstruct_stepwise(experimentalData):
        pass

reconstruct_stepwise(experimentalData=None)

Run the ePIE reconstruction one scan-position update at a time.

For each reconstruction iteration, the scan positions are visited in the order selected by params.positionOrder. At each position \(j\), the corresponding object patch is extracted and combined with the current probe to form the exit surface wave:

\[ \Psi_j = O_j P \]

The exit wave is propagated to the detector plane, constrained by the measured diffraction intensity through intensityProjection(), and propagated back to obtain an updated exit wave \(\Psi'_j\).

The exit-wave correction is

\[ \Delta\Psi_j = \Psi'_j - \Psi_j \]

By default, the object is updated using the standard ePIE rule implemented by objectPatchUpdate().

If params.objectTVregSwitch is enabled, the TV-regularized update objectPatchUpdate_TV() is used every params.objectTVfreq iterations. The standard ePIE object update is retained and an additional TV regularization term is added with strength controlled by params.objectTVregStepSize.

The probe is updated using probeUpdate() after each object update.

If params.OPRP is enabled, position-dependent probe estimates are retrieved from reconstruction.probe_storage before each scan-position update and stored again after the probe update. Without OPRP, a shared probe estimate is updated sequentially across all scan positions.

After all scan positions in an iteration have been processed, getErrorMetrics() evaluates the reconstruction error, applyConstraints() applies the enabled reconstruction constraints and showReconstruction() updates the monitor.

The method yields after every scan-position update, allowing custom code to be interleaved with the reconstruction.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for the reconstruction. If provided, it replaces the currently attached experimental data.

None

Yields:

Type Description
tuple

(iteration, positionLoop) after each scan-position update.

Source code in PtyLab/Engines/ePIE.py
def reconstruct_stepwise(self, experimentalData: ExperimentalData = None):
    r"""
    Run the ePIE reconstruction one scan-position update at a time.

    For each reconstruction iteration, the scan positions are visited in the
    order selected by `params.positionOrder`. At each position $j$, the
    corresponding object patch is extracted and combined with the current
    probe to form the exit surface wave:

    $$
    \Psi_j = O_j P
    $$

    The exit wave is propagated to the detector plane, constrained by the
    measured diffraction intensity through `intensityProjection()`, and
    propagated back to obtain an updated exit wave $\Psi'_j$.

    The exit-wave correction is

    $$
    \Delta\Psi_j = \Psi'_j - \Psi_j
    $$

    By default, the object is updated using the standard ePIE rule implemented
    by `objectPatchUpdate()`.

    If `params.objectTVregSwitch` is enabled, the TV-regularized update
    `objectPatchUpdate_TV()` is used every `params.objectTVfreq` iterations.
    The standard ePIE object update is retained and an additional TV
    regularization term is added with strength controlled by
    `params.objectTVregStepSize`.

    The probe is updated using `probeUpdate()` after each object update.

    If `params.OPRP` is enabled, position-dependent probe estimates are
    retrieved from `reconstruction.probe_storage` before each scan-position
    update and stored again after the probe update. Without OPRP, a shared
    probe estimate is updated sequentially across all scan positions.

    After all scan positions in an iteration have been processed,
    `getErrorMetrics()` evaluates the reconstruction error,
    `applyConstraints()` applies the enabled reconstruction constraints and
    `showReconstruction()` updates the monitor.

    The method yields after every scan-position update, allowing custom code
    to be interleaved with the reconstruction.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use for the reconstruction. If provided,
            it replaces the currently attached experimental data.

    Yields:
        tuple:
            `(iteration, positionLoop)` after each scan-position update.
    """
    if experimentalData is not None:
        self.reconstruction.data = experimentalData
        self.experimentalData = experimentalData
    self._prepareReconstruction()

    # actual reconstruction ePIE_engine
    self.pbar = trange(self.numIterations, desc="ePIE", file=sys.stdout, leave=True)
    for loop in self.pbar:
        # set position order
        self.setPositionOrder()
        if self.params.OPRP:
            # make the initial guess the default storage
            self.reconstruction.probe_storage.push(
                self.reconstruction.probe,
                0,
                self.experimentalData.ptychogram.shape[0],
            )
        for positionLoop, positionIndex in enumerate(self.positionIndices):
            # get object patch
            if self.params.OPRP:
                self.reconstruction.probe = self.reconstruction.probe_storage.get(
                    positionIndex
                )
            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()

            # make exit surface wave
            self.reconstruction.esw = objectPatch * self.reconstruction.probe

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

            # object update
            if (
                self.params.objectTVregSwitch
                and loop % self.params.objectTVfreq == 0
            ):
                object_patch = self.objectPatchUpdate_TV(objectPatch, DELTA)
            else:
                object_patch = self.objectPatchUpdate(objectPatch, DELTA)

            self.reconstruction.object[..., sy, sx] = object_patch

            # self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
            #    objectPatch, DELTA
            # )

            # probe update
            self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)
            if self.params.OPRP:
                self.reconstruction.probe_storage.push(
                    self.reconstruction.probe,
                    positionIndex,
                    self.experimentalData.ptychogram.shape[0],
                )
            yield loop, positionLoop

        # get error metric
        self.getErrorMetrics()

        # apply Constraints
        self.applyConstraints(loop)

        # update the monitor, as every other engine does after the constraints
        self.showReconstruction(loop)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the ePIE object-update rule.

For the classical single-mode case, the probe weighting is

\[ W_P(x,y) = \frac{P^*(x,y)}{\max_{x,y}|P(x,y)|^2} \]

and the object patch is updated according to

\[ O'_j = O_j + \beta_O W_P\Delta\Psi_j \]

where \(O_j\) is the current object patch, \(\Delta\Psi_j\) is the exit-wave correction obtained from the detector-plane intensity constraint, and \(\beta_O\) is betaObject.

In the multidimensional PtyLab representation, contributions from the relevant wavelength, probe-mode, and slice dimensions are summed before updating the object patch.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the active scan position.

required
DELTA ndarray

Exit-wave correction reconstruction.eswUpdate - reconstruction.esw.

required

Returns:

Type Description
ndarray

Updated object patch.

Source code in PtyLab/Engines/ePIE.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the object patch using the ePIE object-update rule.

    For the classical single-mode case, the probe weighting is

    $$
    W_P(x,y) = \frac{P^*(x,y)}{\max_{x,y}|P(x,y)|^2}
    $$

    and the object patch is updated according to

    $$
    O'_j = O_j + \beta_O W_P\Delta\Psi_j
    $$

    where $O_j$ is the current object patch, $\Delta\Psi_j$ is the
    exit-wave correction obtained from the detector-plane intensity
    constraint, and $\beta_O$ is `betaObject`.

    In the multidimensional PtyLab representation, contributions from the
    relevant wavelength, probe-mode, and slice dimensions are summed before
    updating the object patch.

    Args:
        objectPatch (ndarray):
            Current object patch at the active scan position.
        DELTA (ndarray):
            Exit-wave correction
            `reconstruction.eswUpdate - reconstruction.esw`.

    Returns:
        ndarray:
            Updated object patch.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)

    frac = self.reconstruction.probe.conj() / xp.max(
        xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2, 3), keepdims=True
    )

probeUpdate(objectPatch, DELTA)

Update the probe using the ePIE probe-update rule.

For the classical single-mode case, the object weighting is

\[ W_O(x,y) = \frac{O_j^*(x,y)}{\max_{x,y}|O_j(x,y)|^2} \]

and the probe is updated according to

\[ P' = P + \beta_P W_O\Delta\Psi_j \]

where \(O_j\) is the current object patch, \(\Delta\Psi_j\) is the exit-wave correction obtained from the detector-plane intensity constraint, and \(\beta_P\) is betaProbe.

In the multidimensional PtyLab representation, the implemented update sums the corresponding correction over axes (0, 1, 3) while preserving the probe-mode dimension.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the active scan position.

required
DELTA ndarray

Exit-wave correction reconstruction.eswUpdate - reconstruction.esw.

required

Returns:

Type Description
ndarray

Updated probe.

Source code in PtyLab/Engines/ePIE.py
def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the probe using the ePIE probe-update rule.

    For the classical single-mode case, the object weighting is

    $$
    W_O(x,y) = \frac{O_j^*(x,y)}{\max_{x,y}|O_j(x,y)|^2}
    $$

    and the probe is updated according to

    $$
    P' = P + \beta_P W_O\Delta\Psi_j
    $$

    where $O_j$ is the current object patch, $\Delta\Psi_j$ is the
    exit-wave correction obtained from the detector-plane intensity
    constraint, and $\beta_P$ is `betaProbe`.

    In the multidimensional PtyLab representation, the implemented update
    sums the corresponding correction over axes `(0, 1, 3)` while preserving
    the probe-mode dimension.

    Args:
        objectPatch (ndarray):
            Current object patch at the active scan position.
        DELTA (ndarray):
            Exit-wave correction
            `reconstruction.eswUpdate - reconstruction.esw`.

    Returns:
        ndarray:
            Updated probe.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    frac = objectPatch.conj() / xp.max(
        xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))
    )
    r = self.reconstruction.probe + self.betaProbe * xp.sum(
        frac * DELTA, axis=(0, 1, 3), keepdims=True
    )
    return r

mPIE

Bases: BaseEngine

Momentum-accelerated ptychographic iterative engine (mPIE).

mPIE extends the standard ePIE reconstruction by combining regularized PIE (rPIE) object/probe updates with momentum acceleration.1

As in ePIE, the exit-wave correction at scan position \(j\) is

\[ \Delta\Psi_j = \Psi'_j - \Psi_j \]

For conventional ptychography, the object update is regularized as

\[ O'_j = O_j + \beta_O \frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2}\Delta\Psi_j \]

where \(P_{\max}=\max |P|^2\), \(\beta_O\) controls the object update step size, and \(\alpha_O\) controls the spatial regularization.

The probe is updated analogously:

\[ P' = P + \beta_P \frac{O_j^*}{\alpha_P O_{\max} + (1-\alpha_P)|O_j|^2}\Delta\Psi_j \]

where \(O_{\max}=\max |O_j|^2\), and \(\alpha_P\) and \(\beta_P\) control probe regularization and update strength.

Compared with ePIE, these denominators retain stronger updates in moderately illuminated regions while suppressing unstable updates where the corresponding probe or object intensity is small.

Momentum acceleration is periodically applied to both object and probe. In the PtyLab implementation, the momentum state is updated as

\[ M^{(n)} = G^{(n)} + \eta M^{(n-1)} \]

followed by

\[ X^{(n+1)} = X^{(n)} - \gamma M^{(n)} \]

where \(X\) denotes the object or probe, \(\eta\) is frictionM, and \(\gamma\) is feedbackM. The current implementation applies these momentum updates stochastically during the scan-position loop.

The default mPIE parameters are betaObject = 0.25, betaProbe = 0.25, alphaObject = 0.1, alphaProbe = 0.1, feedbackM = 0.3, and frictionM = 0.7.


  1. A. M. Maiden, D. Johnson, and P. Li, "Further improvements to the ptychographical iterative engine," Optica 4, 736-745 (2017). https://doi.org/10.1364/OPTICA.4.000736 ↩

Attributes:

Name Type Description
keepPatches bool

If enabled, store the reconstructed object patch associated with each scan position for debugging or detailed analysis. This option can require substantial additional memory.

See Also: ePIE Baseline ePIE reconstruction without rPIE regularization or momentum acceleration.

Source code in PtyLab/Engines/mPIE.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
class mPIE(BaseEngine):
    r"""
    Momentum-accelerated ptychographic iterative engine (mPIE).

    mPIE extends the standard ePIE reconstruction by combining
    regularized PIE (rPIE) object/probe updates with momentum
    acceleration.[^maiden2017]

    As in ePIE, the exit-wave correction at scan position $j$ is

    $$
    \Delta\Psi_j = \Psi'_j - \Psi_j
    $$

    For conventional ptychography, the object update is regularized as

    $$
    O'_j = O_j + \beta_O \frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2}\Delta\Psi_j
    $$

    where $P_{\max}=\max |P|^2$, $\beta_O$ controls the object update
    step size, and $\alpha_O$ controls the spatial regularization.

    The probe is updated analogously:

    $$
    P' = P + \beta_P \frac{O_j^*}{\alpha_P O_{\max} + (1-\alpha_P)|O_j|^2}\Delta\Psi_j
    $$

    where $O_{\max}=\max |O_j|^2$, and $\alpha_P$ and $\beta_P$ control
    probe regularization and update strength.

    Compared with ePIE, these denominators retain stronger updates in
    moderately illuminated regions while suppressing unstable updates where
    the corresponding probe or object intensity is small.

    Momentum acceleration is periodically applied to both object and probe.
    In the PtyLab implementation, the momentum state is updated as

    $$
    M^{(n)} = G^{(n)} + \eta M^{(n-1)}
    $$

    followed by

    $$
    X^{(n+1)} = X^{(n)} - \gamma M^{(n)}
    $$

    where $X$ denotes the object or probe, $\eta$ is `frictionM`, and
    $\gamma$ is `feedbackM`. The current implementation applies these
    momentum updates stochastically during the scan-position loop.

    The default mPIE parameters are `betaObject = 0.25`,
    `betaProbe = 0.25`, `alphaObject = 0.1`, `alphaProbe = 0.1`,
    `feedbackM = 0.3`, and `frictionM = 0.7`.

    [^maiden2017]: A. M. Maiden, D. Johnson, and P. Li,
            "Further improvements to the ptychographical iterative engine,"
            Optica 4, 736-745 (2017).
            https://doi.org/10.1364/OPTICA.4.000736

    Attributes:
        keepPatches (bool):
            If enabled, store the reconstructed object patch associated with each
            scan position for debugging or detailed analysis. This option can
            require substantial additional memory.
    See Also:
        `ePIE`
            Baseline ePIE reconstruction without rPIE regularization or
            momentum acceleration.
    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("mPIE")
        self.logger.info("Successfully created mPIE engine")
        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        # initialize mPIE Params
        self.initializeReconstructionParams()
        self.params.momentumAcceleration = True
        self.name = "mPIE"

    @property
    def keepPatches(self):
        """
        Whether to store the reconstructed object patch for every scan position.

        Enable with `engine.keepPatches = True` and disable with `engine.keepPatches = False`.

        This option is intended for debugging or detailed analysis and may require a large amount of additional memory.
        """
        return hasattr(self, "patches")

    @keepPatches.setter
    def keepPatches(self, keep_them):

        if keep_them:
            self.logger.info("Keeping patches!")
            self.patches = np.zeros(
                (
                    self.experimentalData.ptychogram.shape[0],
                    *self.reconstruction.shape_O,
                ),
                np.complex64,
            )
        else:
            self.logger.info("Not keeping patches")
            if hasattr(self, "patches"):
                del self.patches

    def initializeReconstructionParams(self):
        """
        Initialize mPIE-specific reconstruction parameters and momentum state.

        The default mPIE parameters are:

        - `betaObject = 0.25`: object update step size.
        - `betaProbe = 0.25`: probe update step size.
        - `alphaObject = 0.1`: object-update regularization parameter.
        - `alphaProbe = 0.1`: probe-update regularization parameter.
        - `feedbackM = 0.3`: momentum feedback strength.
        - `frictionM = 0.7`: momentum memory coefficient.
        - `numIterations = 50`: number of reconstruction iterations.

        Object and probe momentum arrays are initialized together with corresponding
        buffers that store the reconstruction state used by the momentum updates.
        """
        # self.eswUpdate = self.reconstruction.esw.copy()
        self.betaProbe = 0.25
        self.betaObject = 0.25
        self.alphaProbe = 0.1  # probe regularization
        self.alphaObject = 0.1  # object regularization
        self.feedbackM = 0.3  # feedback
        self.frictionM = 0.7  # friction
        self.numIterations = 50

        # initialize momentum
        self.reconstruction.initializeObjectMomentum()
        self.reconstruction.initializeProbeMomentum()
        # set object and probe buffers
        self.reconstruction.objectBuffer = self.reconstruction.object.copy()
        self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

        self.reconstruction.probeWindow = np.abs(self.reconstruction.probe)

    def reconstruct(
        self, experimentalData=None, reconstruction=None, vis_after_each_iteration=None
    ):
        r"""
        Run the mPIE reconstruction to completion.

        The reconstruction follows the standard ptychographic position loop.
        At each scan position $j$, the current object patch and probe form the
        exit surface wave

        $$
        \Psi_j = O_j P
        $$

        which is propagated to the detector plane and constrained by the measured
        diffraction intensity through `intensityProjection()`. The corresponding
        exit-wave correction is

        $$
        \Delta\Psi_j = \Psi'_j - \Psi_j
        $$

        The object and probe are then updated using the mPIE/rPIE update rules
        implemented by `objectPatchUpdate()` and `probeUpdate()`.

        If `params.objectTVregSwitch` is enabled, the TV-regularized object update
        `objectPatchUpdate_TV()` is used every `params.objectTVfreq` iterations.
        The native mPIE object update is retained and an additional TV
        regularization term is added with strength controlled by
        `params.objectTVregStepSize`.

        If `params.weigh_probe_updates_by_intensity` is enabled, the probe update
        is scaled by the relative intensity of the current diffraction frame.

        If `params.positionCorrectionSwitch` is enabled, scan-position correction
        is applied after the object and probe updates.

        Momentum acceleration is applied stochastically during the scan-position
        loop. In the current implementation, each position update has
        approximately a 5% probability of triggering `objectMomentumUpdate()` and
        `probeMomentumUpdate()`.

        If `keepPatches` is enabled, the reconstructed patch associated with each
        scan position is additionally stored in `self.patches` for diagnostics or
        further analysis.

        After all scan positions in an iteration have been processed,
        `getErrorMetrics()` evaluates the reconstruction error,
        `applyConstraints()` applies the enabled reconstruction constraints, and
        `showReconstruction()` updates the reconstruction monitor.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use for the reconstruction. If provided,
                it replaces the currently attached experimental data.
            reconstruction (Reconstruction, optional):
                Reconstruction state to optimize. If provided, it replaces the
                currently attached reconstruction object.
            vis_after_each_iteration (callable, optional):
                Callback executed after each reconstruction iteration as
                `vis_after_each_iteration(loop, reconstruction)`.

        Notes:
            The object and probe momentum buffers are reset after
            `_prepareReconstruction()` so that they remain synchronized with any
            initialization changes applied before reconstruction starts.
        """
        self.changeExperimentalData(experimentalData)
        self.changeOptimizable(reconstruction)

        self._prepareReconstruction()
        # set object and probe buffers, in case object and probe are changed in the _prepareReconstruction() step
        self.reconstruction.objectBuffer = self.reconstruction.object.copy()
        self.reconstruction.probeBuffer = self.reconstruction.probe.copy()
        # actual reconstruction MPIE_engine
        self.pbar = trange(self.numIterations, desc="mPIE", file=sys.stdout, leave=True)
        for loop in self.pbar:
            # set position order
            self.setPositionOrder()
            self.pbar_pos = tqdm(
                self.positionIndices, leave=False, desc="ptychogram", file=sys.stdout
            )
            for positionLoop, positionIndex in enumerate(self.pbar_pos):
                # get object patch, stored as self.probe
                # self.reconstruction.make_probe(positionIndex)

                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw
                # self.viewer.layers['update'].data[positionIndex] = abs(DELTA ** 2).get()
                # import pyqtgraph as pg
                # pg.QtGui.QGuiApplication.processEvents()

                # object update
                if (
                    self.params.objectTVregSwitch
                    and loop % self.params.objectTVfreq == 0
                ):
                    object_patch = self.objectPatchUpdate_TV(objectPatch, DELTA)
                else:
                    object_patch = self.objectPatchUpdate(objectPatch, DELTA)

                self.reconstruction.object[..., sy, sx] = object_patch
                if self.keepPatches:
                    self.patches[positionIndex, ..., sy, sx] = asNumpyArray(
                        abs(object_patch) ** 2
                    )

                # probe update
                weight = 1
                if self.params.weigh_probe_updates_by_intensity:
                    weight = self.experimentalData.relative_intensity(positionIndex)
                    # print(f'for position {positionIndex}, using weight {weight}')

                self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA, weight)
                # self.reconstruction.push_probe_update(self.reconstruction.probe, positionIndex, self.experimentalData.ptychogram.shape[0])

                if self.params.positionCorrectionSwitch:
                    self.positionCorrection(objectPatch, positionIndex, sy, sx)
                    # self.pbar_pos.write(f'Corr: {shifter[0]*1e6:.2f} um x {shifter[1]*1e6:.2f} um')

                # momentum updates
                if np.random.rand(1) > 0.95:
                    self.objectMomentumUpdate()
                    self.probeMomentumUpdate()
                # yield positionLoop, positionIndex

            # get error metric
            self.getErrorMetrics()
            # yield 1,1

            # apply Constraints
            self.applyConstraints(loop)
            # yield 1, 1

            # show reconstruction
            self.showReconstruction(loop)

            if callable(vis_after_each_iteration):
                vis_after_each_iteration(loop, self.reconstruction)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

            # todo clearMemory implementation

    def objectMomentumUpdate(self):
        r"""
        Apply the mPIE momentum update to the reconstructed object.

        The change in the object since the previous momentum update is estimated
        from the stored object buffer:

        $$
        G_O^{(n)} = O_{\mathrm{buf}}^{(n)} - O^{(n)}
        $$

        The object momentum is updated according to

        $$
        M_O^{(n)} = G_O^{(n)} + \eta M_O^{(n-1)}
        $$

        where $\eta$ is `frictionM`.

        The accumulated momentum is then fed back into the object estimate:

        $$
        O^{(n+1)} = O^{(n)} - \gamma M_O^{(n)}
        $$

        where $\gamma$ is `feedbackM`.

        After the momentum correction, `objectBuffer` is updated with the current
        object estimate for the next momentum step.

        Notes:
            This update is triggered stochastically from `reconstruct()` rather
            than after every scan-position update.
        """
        gradient = self.reconstruction.objectBuffer - self.reconstruction.object
        self.reconstruction.objectMomentum = (
            gradient + self.frictionM * self.reconstruction.objectMomentum
        )
        self.reconstruction.object = (
            self.reconstruction.object
            - self.feedbackM * self.reconstruction.objectMomentum
        )
        self.reconstruction.objectBuffer = self.reconstruction.object.copy()

    def probeMomentumUpdate(self):
        r"""
        Apply the mPIE momentum update to the reconstructed probe. Similar to `objectMomentumUpdate()`.

        See Also:
            `objectMomentumUpdate`
                Equivalent momentum update applied to the reconstructed object.
        """
        gradient = self.reconstruction.probeBuffer - self.reconstruction.probe
        self.reconstruction.probeMomentum = (
            gradient + self.frictionM * self.reconstruction.probeMomentum
        )
        self.reconstruction.probe = (
            self.reconstruction.probe
            - self.feedbackM * self.reconstruction.probeMomentum
        )
        self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the object patch using the regularized mPIE/rPIE object-update rule.

        The probe intensity is first evaluated and its maximum value is used as a
        global normalization scale:

        $$
        P_{\max} = \max_{x,y}\sum |P(x,y)|^2
        $$

        For conventional ptychography, the probe weighting is

        $$
        W_P =\frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2}
        $$

        and the object patch is updated according to

        $$
        O'_j =O_j + \beta_O \sum W_P\Delta\Psi_j
        $$

        where $\Delta\Psi_j$ is the exit-wave correction, $\beta_O$ is
        `betaObject`, and $\alpha_O$ is `alphaObject`.

        The parameter `alphaObject` controls the balance between global
        normalization by the maximum probe intensity and local normalization by
        the spatially varying probe intensity.

        For Fourier ptychography (`operationMode == "FPM"`), an additional
        probe-amplitude weighting is applied:

        $$
        W_P^{\mathrm{FPM}} =\frac{|P|}{P_{\max}}\frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2}
        $$

        In the multidimensional PtyLab representation, the object correction is
        summed over the probe-mode axis before being added to the current object
        patch.

        Args:
            objectPatch (ndarray):
                Current object patch at the active scan position.
            DELTA (ndarray):
                Exit-wave correction
                `reconstruction.eswUpdate - reconstruction.esw`.

        Returns:
            ndarray:
                Updated object patch.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        absP2 = xp.abs(self.reconstruction.probe) ** 2
        Pmax = xp.max(xp.sum(absP2, axis=(0, 1, 2, 3)), axis=(-1, -2))
        if self.experimentalData.operationMode == "FPM":
            frac = (
                abs(self.reconstruction.probe)
                / Pmax
                * self.reconstruction.probe.conj()
                / (self.alphaObject * Pmax + (1 - self.alphaObject) * absP2)
            )
        else:
            frac = self.reconstruction.probe.conj() / (
                self.alphaObject * Pmax + (1 - self.alphaObject) * absP2
            )

        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=2, keepdims=True
        )

    def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray, weight: float):
        r"""
        Update the probe using the regularized mPIE/rPIE probe-update rule.

        The object intensity is first evaluated and its maximum value is used as
        a global normalization scale:

        $$
        O_{\max} = \max_{x,y}\sum |O_j(x,y)|^2
        $$

        The object weighting is then calculated as

        $$
        W_O = \frac{O_j^*}{\alpha_P O_{\max} + (1-\alpha_P)|O_j|^2}
        $$

        and the probe is updated according to

        $$
        P' = P + w\beta_P\sum W_O\Delta\Psi_j
        $$

        where $\Delta\Psi_j$ is the exit-wave correction, $\beta_P$ is
        `betaProbe`, $\alpha_P$ is `alphaProbe`, and $w$ is the optional
        intensity-dependent update weight.

        The parameter `alphaProbe` controls the balance between global
        normalization by the maximum object intensity and local normalization by
        the spatially varying object intensity.

        By default, $w=1$. If `params.weigh_probe_updates_by_intensity` is
        enabled in `reconstruct()`, $w$ is set to the relative intensity of the
        current diffraction frame.

        In the current multidimensional PtyLab representation, the probe
        correction is summed over axis `1` before being added to the current
        probe estimate.

        Args:
            objectPatch (ndarray):
                Current object patch at the active scan position.
            DELTA (ndarray):
                Exit-wave correction
                `reconstruction.eswUpdate - reconstruction.esw`.
            weight (float):
                Multiplicative weight applied to the probe update. Typically `1`,
                or the relative intensity of the current diffraction frame when
                intensity-weighted probe updates are enabled.

        Returns:
            ndarray:
                Updated probe.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        absO2 = xp.abs(objectPatch) ** 2
        Omax = xp.max(xp.sum(absO2, axis=(0, 1, 2, 3)), axis=(-1, -2))
        frac = objectPatch.conj() / (
            self.alphaProbe * Omax + (1 - self.alphaProbe) * absO2
        )
        r = self.reconstruction.probe + weight * self.betaProbe * xp.sum(
            frac * DELTA, axis=1, keepdims=True
        )
        return r

keepPatches property writable

Whether to store the reconstructed object patch for every scan position.

Enable with engine.keepPatches = True and disable with engine.keepPatches = False.

This option is intended for debugging or detailed analysis and may require a large amount of additional memory.

initializeReconstructionParams()

Initialize mPIE-specific reconstruction parameters and momentum state.

The default mPIE parameters are:

  • betaObject = 0.25: object update step size.
  • betaProbe = 0.25: probe update step size.
  • alphaObject = 0.1: object-update regularization parameter.
  • alphaProbe = 0.1: probe-update regularization parameter.
  • feedbackM = 0.3: momentum feedback strength.
  • frictionM = 0.7: momentum memory coefficient.
  • numIterations = 50: number of reconstruction iterations.

Object and probe momentum arrays are initialized together with corresponding buffers that store the reconstruction state used by the momentum updates.

Source code in PtyLab/Engines/mPIE.py
def initializeReconstructionParams(self):
    """
    Initialize mPIE-specific reconstruction parameters and momentum state.

    The default mPIE parameters are:

    - `betaObject = 0.25`: object update step size.
    - `betaProbe = 0.25`: probe update step size.
    - `alphaObject = 0.1`: object-update regularization parameter.
    - `alphaProbe = 0.1`: probe-update regularization parameter.
    - `feedbackM = 0.3`: momentum feedback strength.
    - `frictionM = 0.7`: momentum memory coefficient.
    - `numIterations = 50`: number of reconstruction iterations.

    Object and probe momentum arrays are initialized together with corresponding
    buffers that store the reconstruction state used by the momentum updates.
    """
    # self.eswUpdate = self.reconstruction.esw.copy()
    self.betaProbe = 0.25
    self.betaObject = 0.25
    self.alphaProbe = 0.1  # probe regularization
    self.alphaObject = 0.1  # object regularization
    self.feedbackM = 0.3  # feedback
    self.frictionM = 0.7  # friction
    self.numIterations = 50

    # initialize momentum
    self.reconstruction.initializeObjectMomentum()
    self.reconstruction.initializeProbeMomentum()
    # set object and probe buffers
    self.reconstruction.objectBuffer = self.reconstruction.object.copy()
    self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

    self.reconstruction.probeWindow = np.abs(self.reconstruction.probe)

reconstruct(experimentalData=None, reconstruction=None, vis_after_each_iteration=None)

Run the mPIE reconstruction to completion.

The reconstruction follows the standard ptychographic position loop. At each scan position \(j\), the current object patch and probe form the exit surface wave

\[ \Psi_j = O_j P \]

which is propagated to the detector plane and constrained by the measured diffraction intensity through intensityProjection(). The corresponding exit-wave correction is

\[ \Delta\Psi_j = \Psi'_j - \Psi_j \]

The object and probe are then updated using the mPIE/rPIE update rules implemented by objectPatchUpdate() and probeUpdate().

If params.objectTVregSwitch is enabled, the TV-regularized object update objectPatchUpdate_TV() is used every params.objectTVfreq iterations. The native mPIE object update is retained and an additional TV regularization term is added with strength controlled by params.objectTVregStepSize.

If params.weigh_probe_updates_by_intensity is enabled, the probe update is scaled by the relative intensity of the current diffraction frame.

If params.positionCorrectionSwitch is enabled, scan-position correction is applied after the object and probe updates.

Momentum acceleration is applied stochastically during the scan-position loop. In the current implementation, each position update has approximately a 5% probability of triggering objectMomentumUpdate() and probeMomentumUpdate().

If keepPatches is enabled, the reconstructed patch associated with each scan position is additionally stored in self.patches for diagnostics or further analysis.

After all scan positions in an iteration have been processed, getErrorMetrics() evaluates the reconstruction error, applyConstraints() applies the enabled reconstruction constraints, and showReconstruction() updates the reconstruction monitor.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for the reconstruction. If provided, it replaces the currently attached experimental data.

None
reconstruction Reconstruction

Reconstruction state to optimize. If provided, it replaces the currently attached reconstruction object.

None
vis_after_each_iteration callable

Callback executed after each reconstruction iteration as vis_after_each_iteration(loop, reconstruction).

None
Notes

The object and probe momentum buffers are reset after _prepareReconstruction() so that they remain synchronized with any initialization changes applied before reconstruction starts.

Source code in PtyLab/Engines/mPIE.py
def reconstruct(
    self, experimentalData=None, reconstruction=None, vis_after_each_iteration=None
):
    r"""
    Run the mPIE reconstruction to completion.

    The reconstruction follows the standard ptychographic position loop.
    At each scan position $j$, the current object patch and probe form the
    exit surface wave

    $$
    \Psi_j = O_j P
    $$

    which is propagated to the detector plane and constrained by the measured
    diffraction intensity through `intensityProjection()`. The corresponding
    exit-wave correction is

    $$
    \Delta\Psi_j = \Psi'_j - \Psi_j
    $$

    The object and probe are then updated using the mPIE/rPIE update rules
    implemented by `objectPatchUpdate()` and `probeUpdate()`.

    If `params.objectTVregSwitch` is enabled, the TV-regularized object update
    `objectPatchUpdate_TV()` is used every `params.objectTVfreq` iterations.
    The native mPIE object update is retained and an additional TV
    regularization term is added with strength controlled by
    `params.objectTVregStepSize`.

    If `params.weigh_probe_updates_by_intensity` is enabled, the probe update
    is scaled by the relative intensity of the current diffraction frame.

    If `params.positionCorrectionSwitch` is enabled, scan-position correction
    is applied after the object and probe updates.

    Momentum acceleration is applied stochastically during the scan-position
    loop. In the current implementation, each position update has
    approximately a 5% probability of triggering `objectMomentumUpdate()` and
    `probeMomentumUpdate()`.

    If `keepPatches` is enabled, the reconstructed patch associated with each
    scan position is additionally stored in `self.patches` for diagnostics or
    further analysis.

    After all scan positions in an iteration have been processed,
    `getErrorMetrics()` evaluates the reconstruction error,
    `applyConstraints()` applies the enabled reconstruction constraints, and
    `showReconstruction()` updates the reconstruction monitor.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use for the reconstruction. If provided,
            it replaces the currently attached experimental data.
        reconstruction (Reconstruction, optional):
            Reconstruction state to optimize. If provided, it replaces the
            currently attached reconstruction object.
        vis_after_each_iteration (callable, optional):
            Callback executed after each reconstruction iteration as
            `vis_after_each_iteration(loop, reconstruction)`.

    Notes:
        The object and probe momentum buffers are reset after
        `_prepareReconstruction()` so that they remain synchronized with any
        initialization changes applied before reconstruction starts.
    """
    self.changeExperimentalData(experimentalData)
    self.changeOptimizable(reconstruction)

    self._prepareReconstruction()
    # set object and probe buffers, in case object and probe are changed in the _prepareReconstruction() step
    self.reconstruction.objectBuffer = self.reconstruction.object.copy()
    self.reconstruction.probeBuffer = self.reconstruction.probe.copy()
    # actual reconstruction MPIE_engine
    self.pbar = trange(self.numIterations, desc="mPIE", file=sys.stdout, leave=True)
    for loop in self.pbar:
        # set position order
        self.setPositionOrder()
        self.pbar_pos = tqdm(
            self.positionIndices, leave=False, desc="ptychogram", file=sys.stdout
        )
        for positionLoop, positionIndex in enumerate(self.pbar_pos):
            # get object patch, stored as self.probe
            # self.reconstruction.make_probe(positionIndex)

            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()

            # make exit surface wave
            self.reconstruction.esw = objectPatch * self.reconstruction.probe

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw
            # self.viewer.layers['update'].data[positionIndex] = abs(DELTA ** 2).get()
            # import pyqtgraph as pg
            # pg.QtGui.QGuiApplication.processEvents()

            # object update
            if (
                self.params.objectTVregSwitch
                and loop % self.params.objectTVfreq == 0
            ):
                object_patch = self.objectPatchUpdate_TV(objectPatch, DELTA)
            else:
                object_patch = self.objectPatchUpdate(objectPatch, DELTA)

            self.reconstruction.object[..., sy, sx] = object_patch
            if self.keepPatches:
                self.patches[positionIndex, ..., sy, sx] = asNumpyArray(
                    abs(object_patch) ** 2
                )

            # probe update
            weight = 1
            if self.params.weigh_probe_updates_by_intensity:
                weight = self.experimentalData.relative_intensity(positionIndex)
                # print(f'for position {positionIndex}, using weight {weight}')

            self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA, weight)
            # self.reconstruction.push_probe_update(self.reconstruction.probe, positionIndex, self.experimentalData.ptychogram.shape[0])

            if self.params.positionCorrectionSwitch:
                self.positionCorrection(objectPatch, positionIndex, sy, sx)
                # self.pbar_pos.write(f'Corr: {shifter[0]*1e6:.2f} um x {shifter[1]*1e6:.2f} um')

            # momentum updates
            if np.random.rand(1) > 0.95:
                self.objectMomentumUpdate()
                self.probeMomentumUpdate()
            # yield positionLoop, positionIndex

        # get error metric
        self.getErrorMetrics()
        # yield 1,1

        # apply Constraints
        self.applyConstraints(loop)
        # yield 1, 1

        # show reconstruction
        self.showReconstruction(loop)

        if callable(vis_after_each_iteration):
            vis_after_each_iteration(loop, self.reconstruction)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

objectMomentumUpdate()

Apply the mPIE momentum update to the reconstructed object.

The change in the object since the previous momentum update is estimated from the stored object buffer:

\[ G_O^{(n)} = O_{\mathrm{buf}}^{(n)} - O^{(n)} \]

The object momentum is updated according to

\[ M_O^{(n)} = G_O^{(n)} + \eta M_O^{(n-1)} \]

where \(\eta\) is frictionM.

The accumulated momentum is then fed back into the object estimate:

\[ O^{(n+1)} = O^{(n)} - \gamma M_O^{(n)} \]

where \(\gamma\) is feedbackM.

After the momentum correction, objectBuffer is updated with the current object estimate for the next momentum step.

Notes

This update is triggered stochastically from reconstruct() rather than after every scan-position update.

Source code in PtyLab/Engines/mPIE.py
def objectMomentumUpdate(self):
    r"""
    Apply the mPIE momentum update to the reconstructed object.

    The change in the object since the previous momentum update is estimated
    from the stored object buffer:

    $$
    G_O^{(n)} = O_{\mathrm{buf}}^{(n)} - O^{(n)}
    $$

    The object momentum is updated according to

    $$
    M_O^{(n)} = G_O^{(n)} + \eta M_O^{(n-1)}
    $$

    where $\eta$ is `frictionM`.

    The accumulated momentum is then fed back into the object estimate:

    $$
    O^{(n+1)} = O^{(n)} - \gamma M_O^{(n)}
    $$

    where $\gamma$ is `feedbackM`.

    After the momentum correction, `objectBuffer` is updated with the current
    object estimate for the next momentum step.

    Notes:
        This update is triggered stochastically from `reconstruct()` rather
        than after every scan-position update.
    """
    gradient = self.reconstruction.objectBuffer - self.reconstruction.object
    self.reconstruction.objectMomentum = (
        gradient + self.frictionM * self.reconstruction.objectMomentum
    )
    self.reconstruction.object = (
        self.reconstruction.object
        - self.feedbackM * self.reconstruction.objectMomentum
    )
    self.reconstruction.objectBuffer = self.reconstruction.object.copy()

probeMomentumUpdate()

Apply the mPIE momentum update to the reconstructed probe. Similar to objectMomentumUpdate().

See Also

objectMomentumUpdate Equivalent momentum update applied to the reconstructed object.

Source code in PtyLab/Engines/mPIE.py
def probeMomentumUpdate(self):
    r"""
    Apply the mPIE momentum update to the reconstructed probe. Similar to `objectMomentumUpdate()`.

    See Also:
        `objectMomentumUpdate`
            Equivalent momentum update applied to the reconstructed object.
    """
    gradient = self.reconstruction.probeBuffer - self.reconstruction.probe
    self.reconstruction.probeMomentum = (
        gradient + self.frictionM * self.reconstruction.probeMomentum
    )
    self.reconstruction.probe = (
        self.reconstruction.probe
        - self.feedbackM * self.reconstruction.probeMomentum
    )
    self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the regularized mPIE/rPIE object-update rule.

The probe intensity is first evaluated and its maximum value is used as a global normalization scale:

\[ P_{\max} = \max_{x,y}\sum |P(x,y)|^2 \]

For conventional ptychography, the probe weighting is

\[ W_P =\frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2} \]

and the object patch is updated according to

\[ O'_j =O_j + \beta_O \sum W_P\Delta\Psi_j \]

where \(\Delta\Psi_j\) is the exit-wave correction, \(\beta_O\) is betaObject, and \(\alpha_O\) is alphaObject.

The parameter alphaObject controls the balance between global normalization by the maximum probe intensity and local normalization by the spatially varying probe intensity.

For Fourier ptychography (operationMode == "FPM"), an additional probe-amplitude weighting is applied:

\[ W_P^{\mathrm{FPM}} =\frac{|P|}{P_{\max}}\frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2} \]

In the multidimensional PtyLab representation, the object correction is summed over the probe-mode axis before being added to the current object patch.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the active scan position.

required
DELTA ndarray

Exit-wave correction reconstruction.eswUpdate - reconstruction.esw.

required

Returns:

Type Description
ndarray

Updated object patch.

Source code in PtyLab/Engines/mPIE.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the object patch using the regularized mPIE/rPIE object-update rule.

    The probe intensity is first evaluated and its maximum value is used as a
    global normalization scale:

    $$
    P_{\max} = \max_{x,y}\sum |P(x,y)|^2
    $$

    For conventional ptychography, the probe weighting is

    $$
    W_P =\frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2}
    $$

    and the object patch is updated according to

    $$
    O'_j =O_j + \beta_O \sum W_P\Delta\Psi_j
    $$

    where $\Delta\Psi_j$ is the exit-wave correction, $\beta_O$ is
    `betaObject`, and $\alpha_O$ is `alphaObject`.

    The parameter `alphaObject` controls the balance between global
    normalization by the maximum probe intensity and local normalization by
    the spatially varying probe intensity.

    For Fourier ptychography (`operationMode == "FPM"`), an additional
    probe-amplitude weighting is applied:

    $$
    W_P^{\mathrm{FPM}} =\frac{|P|}{P_{\max}}\frac{P^*}{\alpha_O P_{\max} + (1-\alpha_O)|P|^2}
    $$

    In the multidimensional PtyLab representation, the object correction is
    summed over the probe-mode axis before being added to the current object
    patch.

    Args:
        objectPatch (ndarray):
            Current object patch at the active scan position.
        DELTA (ndarray):
            Exit-wave correction
            `reconstruction.eswUpdate - reconstruction.esw`.

    Returns:
        ndarray:
            Updated object patch.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    absP2 = xp.abs(self.reconstruction.probe) ** 2
    Pmax = xp.max(xp.sum(absP2, axis=(0, 1, 2, 3)), axis=(-1, -2))
    if self.experimentalData.operationMode == "FPM":
        frac = (
            abs(self.reconstruction.probe)
            / Pmax
            * self.reconstruction.probe.conj()
            / (self.alphaObject * Pmax + (1 - self.alphaObject) * absP2)
        )
    else:
        frac = self.reconstruction.probe.conj() / (
            self.alphaObject * Pmax + (1 - self.alphaObject) * absP2
        )

    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=2, keepdims=True
    )

probeUpdate(objectPatch, DELTA, weight)

Update the probe using the regularized mPIE/rPIE probe-update rule.

The object intensity is first evaluated and its maximum value is used as a global normalization scale:

\[ O_{\max} = \max_{x,y}\sum |O_j(x,y)|^2 \]

The object weighting is then calculated as

\[ W_O = \frac{O_j^*}{\alpha_P O_{\max} + (1-\alpha_P)|O_j|^2} \]

and the probe is updated according to

\[ P' = P + w\beta_P\sum W_O\Delta\Psi_j \]

where \(\Delta\Psi_j\) is the exit-wave correction, \(\beta_P\) is betaProbe, \(\alpha_P\) is alphaProbe, and \(w\) is the optional intensity-dependent update weight.

The parameter alphaProbe controls the balance between global normalization by the maximum object intensity and local normalization by the spatially varying object intensity.

By default, \(w=1\). If params.weigh_probe_updates_by_intensity is enabled in reconstruct(), \(w\) is set to the relative intensity of the current diffraction frame.

In the current multidimensional PtyLab representation, the probe correction is summed over axis 1 before being added to the current probe estimate.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the active scan position.

required
DELTA ndarray

Exit-wave correction reconstruction.eswUpdate - reconstruction.esw.

required
weight float

Multiplicative weight applied to the probe update. Typically 1, or the relative intensity of the current diffraction frame when intensity-weighted probe updates are enabled.

required

Returns:

Type Description
ndarray

Updated probe.

Source code in PtyLab/Engines/mPIE.py
def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray, weight: float):
    r"""
    Update the probe using the regularized mPIE/rPIE probe-update rule.

    The object intensity is first evaluated and its maximum value is used as
    a global normalization scale:

    $$
    O_{\max} = \max_{x,y}\sum |O_j(x,y)|^2
    $$

    The object weighting is then calculated as

    $$
    W_O = \frac{O_j^*}{\alpha_P O_{\max} + (1-\alpha_P)|O_j|^2}
    $$

    and the probe is updated according to

    $$
    P' = P + w\beta_P\sum W_O\Delta\Psi_j
    $$

    where $\Delta\Psi_j$ is the exit-wave correction, $\beta_P$ is
    `betaProbe`, $\alpha_P$ is `alphaProbe`, and $w$ is the optional
    intensity-dependent update weight.

    The parameter `alphaProbe` controls the balance between global
    normalization by the maximum object intensity and local normalization by
    the spatially varying object intensity.

    By default, $w=1$. If `params.weigh_probe_updates_by_intensity` is
    enabled in `reconstruct()`, $w$ is set to the relative intensity of the
    current diffraction frame.

    In the current multidimensional PtyLab representation, the probe
    correction is summed over axis `1` before being added to the current
    probe estimate.

    Args:
        objectPatch (ndarray):
            Current object patch at the active scan position.
        DELTA (ndarray):
            Exit-wave correction
            `reconstruction.eswUpdate - reconstruction.esw`.
        weight (float):
            Multiplicative weight applied to the probe update. Typically `1`,
            or the relative intensity of the current diffraction frame when
            intensity-weighted probe updates are enabled.

    Returns:
        ndarray:
            Updated probe.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    absO2 = xp.abs(objectPatch) ** 2
    Omax = xp.max(xp.sum(absO2, axis=(0, 1, 2, 3)), axis=(-1, -2))
    frac = objectPatch.conj() / (
        self.alphaProbe * Omax + (1 - self.alphaProbe) * absO2
    )
    r = self.reconstruction.probe + weight * self.betaProbe * xp.sum(
        frac * DELTA, axis=1, keepdims=True
    )
    return r

pcPIE

Bases: mPIE

Backward-compatible wrapper for mPIE.

Position correction is now provided by mPIE through params.positionCorrectionSwitch. This class is retained only for compatibility with existing code using Engines.pcPIE.

Source code in PtyLab/Engines/mPIE.py
class pcPIE(mPIE):
    """
    Backward-compatible wrapper for `mPIE`.

    Position correction is now provided by `mPIE` through
    `params.positionCorrectionSwitch`. This class is retained only for
    compatibility with existing code using `Engines.pcPIE`.
    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        warnings.warn(
            "`pcPIE` is deprecated. Use `mPIE` with "
            "`params.positionCorrectionSwitch = True` instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        super().__init__(
            reconstruction,
            experimentalData,
            params,
            monitor,
        )

        self.name = "pcPIE"
        self.logger = logging.getLogger("pcPIE")

    @property
    def betaM(self):
        """Deprecated alias for `feedbackM`."""
        return self.feedbackM

    @betaM.setter
    def betaM(self, value):
        self.feedbackM = value

    @property
    def stepM(self):
        """Deprecated alias for `frictionM`."""
        return self.frictionM

    @stepM.setter
    def stepM(self, value):
        self.frictionM = value

betaM property writable

Deprecated alias for feedbackM.

stepM property writable

Deprecated alias for frictionM.

purityPIE

Bases: mPIE

Purity-based axial-distance and wavelength self-calibration for ptychographic reconstruction.

purityPIE extends mPIE by estimating either the sample-to-detector axial distance or the illumination wavelength from the reconstructed probe purity.1

In mixed-state ptychography, the measured diffraction intensity at scan position \(j\) is modeled as an incoherent sum over multiple probe modes:

\[ I_j(\mathbf{q}) = \sum_m \left| \mathcal{F}\left[P_m(\mathbf{r}) O(\mathbf{r}-\mathbf{r}_j)\right] \right|^2 \]

where \(P_m\) denotes probe mode \(m\), \(O\) is the object transmission function, and \(\mathcal{F}\) denotes propagation to the detector plane.

The mutual intensity of the reconstructed probe is

\[ J(\mathbf{r}_1,\mathbf{r}_2) = \sum_m P_m^*(\mathbf{r}_1)P_m(\mathbf{r}_2) \]

and can be decomposed into orthonormal coherent modes as

\[ J(\mathbf{r}_1,\mathbf{r}_2) = \sum_m \lambda_m \phi_m^*(\mathbf{r}_1)\phi_m(\mathbf{r}_2) \]

where \(\lambda_m\) represents the power contribution of the corresponding orthonormal mode.

The probe purity is defined as

$$ \mu = \frac{\sqrt{\sum_m \lambda_m^2}}{\sum_m \lambda_m} $$ with \(\mu \in [0,1]\).

An incorrect axial distance or illumination wavelength introduces a mismatch in the diffraction geometry connecting the object and detector planes. This mismatch can produce geometric deformation and resolution degradation in the reconstructed object and probe and is reflected by a reduction in the reconstructed probe purity.

The calibrated parameter is therefore obtained by maximizing the reconstructed probe purity.

For each candidate value, purityPIE creates an independent reconstruction with the corresponding geometry, performs an mPIE reconstruction, orthogonalizes the reconstructed probe modes, and evaluates the resulting probe purity. The candidate yielding the highest purity is retained as the calibrated reconstruction.

Two calibration targets are supported:

  • Axial-distance calibration: optimizes the sample-to-detector distance z.

  • Wavelength calibration: optimizes the illumination wavelength λ.

The calibration target is selected through params.purityCalibrationTarget, which can be set to "z" or "wavelength".

For either calibration target, two search strategies are available:

  • Fixed-grid search: evaluates uniformly spaced candidate values over a predefined range. Axial-distance scans are controlled by params.purityZScanRange and params.purityZScanPoints, while wavelength scans are controlled by params.purityWavelengthScanRange and params.purityWavelengthScanPoints.

  • Adaptive search: starts from the current parameter estimate, determines the direction of increasing probe purity, expands the search step while the purity continues to improve, and then refines the search around the best candidate using progressively smaller steps. Adaptive search is enabled with params.purityAdaptive = True.

Purity-based calibration requires at least two reconstructed probe modes, i.e. reconstruction.npsm >= 2.


  1. C. Liu, W. Eschen, D. S. Penagos Molina, L. Licht, M. Abdelaal, and J. Rothhardt, "Purity-based self-calibration in ptychography," Opt. Lett. 50, 1581-1584 (2025). https://doi.org/10.1364/OL.543865 ↩

See Also

mPIE Momentum-accelerated reconstruction engine used for each candidate calibration value.

Source code in PtyLab/Engines/purityPIE.py
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
class purityPIE(mPIE):
    r"""
    Purity-based axial-distance and wavelength self-calibration for
    ptychographic reconstruction.

    `purityPIE` extends `mPIE` by estimating either the sample-to-detector
    axial distance or the illumination wavelength from the reconstructed
    probe purity.[^liu2025]

    In mixed-state ptychography, the measured diffraction intensity at scan
    position $j$ is modeled as an incoherent sum over multiple probe modes:

    $$
    I_j(\mathbf{q}) = \sum_m \left| \mathcal{F}\left[P_m(\mathbf{r}) O(\mathbf{r}-\mathbf{r}_j)\right] \right|^2
    $$

    where $P_m$ denotes probe mode $m$, $O$ is the object transmission
    function, and $\mathcal{F}$ denotes propagation to the detector plane.

    The mutual intensity of the reconstructed probe is

    $$
    J(\mathbf{r}_1,\mathbf{r}_2) = \sum_m P_m^*(\mathbf{r}_1)P_m(\mathbf{r}_2)
    $$

    and can be decomposed into orthonormal coherent modes as

    $$
    J(\mathbf{r}_1,\mathbf{r}_2) = \sum_m \lambda_m \phi_m^*(\mathbf{r}_1)\phi_m(\mathbf{r}_2)
    $$

    where $\lambda_m$ represents the power contribution of the corresponding
    orthonormal mode.

    The probe purity is defined as

    $$
    \mu = \frac{\sqrt{\sum_m \lambda_m^2}}{\sum_m \lambda_m}
    $$
    with $\mu \in [0,1]$.

    An incorrect axial distance or illumination wavelength introduces a
    mismatch in the diffraction geometry connecting the object and detector
    planes. This mismatch can produce geometric deformation and resolution
    degradation in the reconstructed object and probe and is reflected by a
    reduction in the reconstructed probe purity.

    The calibrated parameter is therefore obtained by maximizing the
    reconstructed probe purity.

    For each candidate value, `purityPIE` creates an independent
    reconstruction with the corresponding geometry, performs an `mPIE`
    reconstruction, orthogonalizes the reconstructed probe modes, and
    evaluates the resulting probe purity. The candidate yielding the highest
    purity is retained as the calibrated reconstruction.

    Two calibration targets are supported:

    - Axial-distance calibration: optimizes the sample-to-detector
    distance `z`.

    - Wavelength calibration: optimizes the illumination wavelength
    `λ`.

    The calibration target is selected through
    `params.purityCalibrationTarget`, which can be set to `"z"` or
    `"wavelength"`.

    For either calibration target, two search strategies are available:

    - Fixed-grid search: evaluates uniformly spaced candidate values over
    a predefined range. Axial-distance scans are controlled by
    `params.purityZScanRange` and `params.purityZScanPoints`, while
    wavelength scans are controlled by `params.purityWavelengthScanRange`
    and `params.purityWavelengthScanPoints`.

    - Adaptive search: starts from the current parameter estimate,
    determines the direction of increasing probe purity, expands the search
    step while the purity continues to improve, and then refines the search
    around the best candidate using progressively smaller steps. Adaptive
    search is enabled with `params.purityAdaptive = True`.

    Purity-based calibration requires at least two reconstructed probe modes,
    i.e. `reconstruction.npsm >= 2`.

    [^liu2025]: C. Liu, W. Eschen, D. S. Penagos Molina,
            L. Licht, M. Abdelaal, and J. Rothhardt,
            "Purity-based self-calibration in ptychography,"
            Opt. Lett. 50, 1581-1584 (2025).
            https://doi.org/10.1364/OL.543865

    See Also:
        `mPIE`
            Momentum-accelerated reconstruction engine used for each
            candidate calibration value.
    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        super().__init__(
            reconstruction,
            experimentalData,
            params,
            monitor,
        )

        self.logger = logging.getLogger("purityPIE")
        self.logger.info("Successfully created purityPIE engine")
        self.logger.info(
            "Wavelength attribute: %s",
            self.reconstruction.wavelength,
        )

        self.name = "purityPIE"

        # showReconstruction writes its verboseLevel = "high" summary through
        # self.pbar.write; purityPIE has no iteration bar of its own, so use
        # tqdm's class-level write, which prints without breaking other bars
        self.pbar = tqdm.tqdm

        # live purity-vs-parameter plot, set up by reconstruct()
        self._scanPlot = None

    def reconstruct(
        self,
        experimentalData=None,
        reconstruction=None,
    ):
        """
        Run purity-based self-calibration.

        The reconstruction first prepares the current object, probe, geometry,
        constraints, and optional GPU state using the standard `mPIE` setup.

        Each candidate parameter value is evaluated using an independent `mPIE`
        reconstruction. The reconstructed probe modes are orthogonalized, the
        corresponding probe purity is evaluated, and the candidate yielding the
        highest purity is retained.

        After calibration, the reconstruction state corresponding to the optimal
        candidate is restored to the original `Reconstruction` object.

        With the matplotlib `Monitor`, purity and reconstruction error vs the
        calibrated parameter are plotted live during the scan, and the final plot
        shades the scan resolution around the maximum. A warning is logged if the
        maximum lies at the edge of the scanned range.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use for calibration. If provided, it
                replaces the dataset currently attached to the engine.

            reconstruction (Reconstruction, optional):
                Reconstruction state to calibrate. If provided, it replaces the
                reconstruction currently attached to the engine.

        Returns:
            tuple:
                `(best_value, best_purity)`, where `best_value` is the calibrated
                axial distance in meters for `purityCalibrationTarget = "z"` or the
                calibrated wavelength in meters for
                `purityCalibrationTarget = "wavelength"`, and `best_purity` is the
                corresponding reconstructed probe purity.

        Raises:
            ValueError:
                If `params.purityCalibrationTarget` is neither `"z"` nor
                `"wavelength"`.
        """

        self.changeExperimentalData(experimentalData)
        self.changeOptimizable(reconstruction)

        hidden_history = self._setupScanMonitor()

        self._prepareReconstruction()

        # Reset momentum buffers after preparation
        self.reconstruction.objectBuffer = self.reconstruction.object.copy()

        self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

        target = self.params.purityCalibrationTarget.lower()

        # ------------------------------------------------------------------
        # Axial-distance calibration
        # ------------------------------------------------------------------

        if target == "z":
            if self.params.purityAdaptive:
                best_value, best_purity = self.adaptivePurityZScan()
            else:
                best_value, best_purity = self.purityZScan()

        # ------------------------------------------------------------------
        # Wavelength calibration
        # ------------------------------------------------------------------

        elif target == "wavelength":
            if self.params.purityAdaptive:
                best_value, best_purity = self.adaptivePurityWavelengthScan()
            else:
                best_value, best_purity = self.purityWavelengthScan()

        # ------------------------------------------------------------------
        # Unsupported target
        # ------------------------------------------------------------------

        else:
            raise ValueError(
                "Unsupported purity calibration target: "
                f"{self.params.purityCalibrationTarget!r}. "
                "Supported targets are 'z' and 'wavelength'."
            )

        self._finishScan(target)

        # ------------------------------------------------------------------
        # Return reconstruction data to CPU
        # ------------------------------------------------------------------

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

        # give the parameter-history window back to later engines, e.g. an mPIE
        # run that continues from the calibrated state
        if hidden_history is not None:
            self.monitor.showParameterHistory = hidden_history

        return best_value, best_purity

    def _createCandidateReconstruction(
        self,
        target,
        value,
    ):
        """
        Create an independent reconstruction for one calibration candidate.

        The requested calibration parameter is applied to a deep copy of the
        experimental data before a new `Reconstruction` object is created.
        Relevant reconstruction settings and initial object/probe definitions are
        then copied from the current reconstruction.

        Args:
            target (str):
                Calibration target. Supported values are `"z"` and `"wavelength"`.

            value (float):
                Candidate axial distance or wavelength in meters.

        Returns:
            tuple:
                `(candidate_data, candidate_reconstruction, candidate_params)`,
                containing the copied experimental data, newly initialized
                reconstruction, and copied parameter set for the candidate.

        Raises:
            ValueError:
                If `target` is neither `"z"` nor `"wavelength"`.
        """

        candidate_data = deepcopy(self.experimentalData)

        candidate_params = deepcopy(self.params)

        # --------------------------------------------------------------
        # Set candidate parameter before creating Reconstruction
        # --------------------------------------------------------------

        if target == "z":
            candidate_data.zo = value

        elif target == "wavelength":
            candidate_data.wavelength = value

            if self.reconstruction.nlambda == 1:
                candidate_data.spectralDensity = np.atleast_1d(value)
        else:
            raise ValueError(f"Unsupported purity calibration target: {target!r}")

        # Fresh geometry for this candidate
        candidate_reconstruction = Reconstruction(
            candidate_data,
            candidate_params,
        )

        # --------------------------------------------------------------
        # Copy reconstruction settings
        # --------------------------------------------------------------

        candidate_reconstruction.npsm = self.reconstruction.npsm

        candidate_reconstruction.nosm = self.reconstruction.nosm

        candidate_reconstruction.nlambda = self.reconstruction.nlambda

        candidate_reconstruction.nslice = self.reconstruction.nslice

        candidate_reconstruction.initialProbe = self.reconstruction.initialProbe

        candidate_reconstruction.initialObject = self.reconstruction.initialObject

        if hasattr(
            self.reconstruction,
            "initialProbe_filename",
        ):
            candidate_reconstruction.initialProbe_filename = (
                self.reconstruction.initialProbe_filename
            )

        if hasattr(
            self.reconstruction,
            "initialObject_filename",
        ):
            candidate_reconstruction.initialObject_filename = (
                self.reconstruction.initialObject_filename
            )

        candidate_reconstruction.initializeObjectProbe()

        return (
            candidate_data,
            candidate_reconstruction,
            candidate_params,
        )

    def _evaluatePurityAtZ(self, z):
        return self._evaluatePurityAtParameter(
            "z",
            z,
        )

    def _evaluatePurityAtWavelength(
        self,
        wavelength,
    ):
        return self._evaluatePurityAtParameter(
            "wavelength",
            wavelength,
        )

    def _evaluatePurityAtParameter(
        self,
        target,
        value,
    ):
        """
        Evaluate probe purity for one calibration candidate.

        An independent candidate reconstruction is created for the specified
        axial distance or wavelength and reconstructed using `mPIE`. The resulting
        probe modes are orthogonalized before the reconstructed probe purity is
        evaluated.

        Args:
            target (str):
                Calibration target. Supported values are `"z"` and `"wavelength"`.

            value (float):
                Candidate axial distance or wavelength in meters.

        Returns:
            tuple:
                `(purity, candidate_reconstruction)`, where `purity` is the
                reconstructed probe purity and `candidate_reconstruction` contains
                the reconstruction state obtained for the candidate.
        """

        # every candidate starts from the same random state (initial-guess noise,
        # shuffled scan order, mPIE's random momentum steps), so differences in
        # purity come from the candidate value; the caller's state is restored
        seed = self.params.puritySeed
        random_state = np.random.get_state() if seed is not None else None
        if seed is not None:
            np.random.seed(seed)

        try:
            (
                candidate_data,
                candidate_reconstruction,
                candidate_params,
            ) = self._createCandidateReconstruction(
                target,
                value,
            )

            candidate_monitor = DummyMonitor()

            candidate_engine = mPIE(
                candidate_reconstruction,
                candidate_data,
                candidate_params,
                candidate_monitor,
            )

            candidate_engine.numIterations = self.numIterations

            candidate_engine.betaProbe = self.betaProbe

            candidate_engine.betaObject = self.betaObject

            candidate_engine.alphaProbe = self.alphaProbe

            candidate_engine.alphaObject = self.alphaObject

            candidate_engine.feedbackM = self.feedbackM

            candidate_engine.frictionM = self.frictionM

            candidate_engine.reconstruct()

            candidate_engine.orthogonalization()
        finally:
            if random_state is not None:
                np.random.set_state(random_state)

        purity = float(
            np.asarray(asNumpyArray(candidate_reconstruction.purityProbe)).squeeze()
        )

        return (
            purity,
            candidate_reconstruction,
        )

    def _finishScan(self, target):
        """
        Check the scan result and draw the final purity-scan plot.

        Stores the scanned values, purities and errors in
        `reconstruction.extraResults["purityScan"]`, which
        `Reconstruction.saveResults()` writes to the HDF5 file. Logs a warning if the purity maximum lies at the edge of
        the scanned range, since the optimum may then lie outside it.

        Args:
            target (str): Calibration target, `"z"` or `"wavelength"`.
        """
        if target == "z":
            values, purities, errors = (
                self.purityZValues,
                self.purityZMetrics,
                self.purityZErrors,
            )
            scale, unit = 1e3, "mm"
        else:
            values, purities, errors = (
                self.purityWavelengthValues,
                self.purityWavelengthMetrics,
                self.purityWavelengthErrors,
            )
            scale, unit = 1e9, "nm"

        # saveResults() writes this as a "purityScan" group in the HDF5 file, next
        # to the calibrated object and probe
        self.reconstruction.extraResults["purityScan"] = {
            "target": target,
            "units": "values in m",
            "values": np.asarray(values, dtype=float),
            "purity": np.asarray(purities, dtype=float),
            "error": np.asarray(errors, dtype=float),
        }

        best, _, _, at_edge = _resolutionInterval(values, purities)
        if at_edge:
            self.logger.warning(
                "The purity maximum lies at the edge of the scanned range "
                f"({target} = {scale * best:.4g} {unit}); the optimum may lie "
                "outside it. Extend the scan range or move the initial guess."
            )

        if self._scanPlot is not None and self._scanValues:
            self._scanPlot.draw(
                self._scanValues,
                self._scanPurities,
                self._scanErrors,
                self._scanInitial,
                final=True,
            )

    def _setupScanMonitor(self):
        """
        Set up the monitor for a new scan.

        Clears the per-candidate values, purities and errors collected during
        the scan. For the matplotlib `Monitor`, its parameter-history window is
        switched off for the scan and replaced by a `_PurityScanLivePlot`. Other
        monitors are left unchanged and get no live plot.

        Returns:
            bool or None:
                The monitor's previous `showParameterHistory` setting, to restore
                after the scan, or `None` if the monitor was not changed.
        """
        self._scanValues, self._scanPurities, self._scanErrors = [], [], []
        self._scanPlot = None

        if not isinstance(self.monitor, Monitor):
            return None

        target = self.params.purityCalibrationTarget.lower()
        if target == "z":
            self._scanInitial = self.reconstruction.zo
            self._scanPlot = _PurityScanLivePlot("z (mm)", 1e3, "mm")
        else:
            self._scanInitial = float(np.squeeze(self.reconstruction.wavelength))
            self._scanPlot = _PurityScanLivePlot("wavelength (nm)", 1e9, "nm")

        hidden_history = self.monitor.showParameterHistory
        self.monitor.showParameterHistory = False
        # a window left over from an earlier engine would keep recording
        self.monitor.parameterHistoryMonitor = None
        # saved with the other monitor windows by
        # reconstruction.saveResults(..., snapshot=monitor)
        self.monitor.extraFigures["purity_scan"] = self._scanPlot
        return hidden_history

    def _showCandidate(self, candidate_reconstruction, purity):
        """
        Show one evaluated candidate in the main monitor.

        The candidate's calibrated parameter, object, probe, purity, error and
        detector intensities are copied to the main reconstruction, which is what
        `showReconstruction()` displays. The scans restore the best candidate
        afterwards, so this only affects what is shown during the scan.

        Args:
            candidate_reconstruction (Reconstruction):
                Reconstruction state returned by `_evaluatePurityAtParameter()`.
            purity (float):
                Reconstructed probe purity of the candidate.
        """
        target = self.params.purityCalibrationTarget.lower()

        if target == "z":
            self.reconstruction.zo = candidate_reconstruction.zo
        else:
            self.reconstruction.wavelength = candidate_reconstruction.wavelength
            self.reconstruction.dxp = candidate_reconstruction.dxp

        self.reconstruction.object = asNumpyArray(
            candidate_reconstruction.object
        ).copy()

        self.reconstruction.probe = asNumpyArray(candidate_reconstruction.probe).copy()

        self.reconstruction.purityProbe = purity

        if hasattr(candidate_reconstruction, "error"):
            self.reconstruction.error = np.asarray(
                asNumpyArray(candidate_reconstruction.error)
            ).copy()

        # read by showReconstruction for monitor.verboseLevel = "high"; the main
        # reconstruction never runs a forward model of its own
        for name in ("Iestimated", "Imeasured"):
            if hasattr(candidate_reconstruction, name):
                setattr(
                    self.reconstruction, name, getattr(candidate_reconstruction, name)
                )

        self.showReconstruction(
            self.numIterations - 1,
            force=True,
        )

        if self._scanPlot is not None:
            target = self.params.purityCalibrationTarget.lower()
            value = (
                candidate_reconstruction.zo
                if target == "z"
                else candidate_reconstruction.wavelength
            )
            self._scanValues.append(float(np.squeeze(value)))
            self._scanPurities.append(purity)
            self._scanErrors.append(
                float(
                    np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(
                        -1
                    )[-1]
                )
            )
            self._scanPlot.draw(
                self._scanValues,
                self._scanPurities,
                self._scanErrors,
                self._scanInitial,
            )

    def purityZScan(self):
        """
        Perform a fixed-grid purity-based axial calibration.

        The scan evaluates a uniformly spaced set of candidate sample-to-detector
        distances centered on the current value `reconstruction.zo`. The scan range
        and number of candidate positions are defined by
        `params.purityZScanRange` and `params.purityZScanPoints`.

        Each candidate distance is evaluated using an independent `mPIE`
        reconstruction. The reconstructed probe modes are orthogonalized, and the
        candidate yielding the highest probe purity is retained as the calibrated
        axial distance.

        The reconstruction error for each candidate is recorded together with the
        purity metric. After the scan, the reconstruction state corresponding to
        the highest-purity candidate is restored to the original `Reconstruction`
        object.

        The evaluated distances, purity values, and reconstruction errors are stored
        in `purityZValues`, `purityZMetrics`, and `purityZErrors`, respectively.

        Returns:
            tuple:
                `(best_z, best_purity)`, where `best_z` is the calibrated
                sample-to-detector distance in meters and `best_purity` is the
                corresponding reconstructed probe purity.

        Raises:
            ValueError:
                If fewer than two probe modes are reconstructed
                (`reconstruction.npsm < 2`).

            RuntimeError:
                If no valid candidate reconstruction produces a purity value.
        """

        if self.reconstruction.npsm < 2:
            raise ValueError(
                "Purity-based z scanning requires at least two probe modes "
                "(reconstruction.npsm >= 2)."
            )

        # ------------------------------------------------------------------
        # Scan grid
        # ------------------------------------------------------------------

        z0 = self.reconstruction.zo
        self.purityZInitialGuess = z0

        z_values = np.linspace(
            z0 - self.params.purityZScanRange,
            z0 + self.params.purityZScanRange,
            self.params.purityZScanPoints,
        )

        purity_values = []
        error_values = []

        best_purity = -np.inf
        best_z = z0
        best_state = None

        # ------------------------------------------------------------------
        # Scan information
        # ------------------------------------------------------------------

        tqdm.tqdm.write("")
        tqdm.tqdm.write("Starting purity-based z scan")
        tqdm.tqdm.write(
            f"Initial z = {z0 * 1e3:.6f} mm | "
            f"range = ±{self.params.purityZScanRange * 1e6:.1f} µm | "
            f"points = {len(z_values)} | "
            f"iterations/z = {self.numIterations}"
        )
        tqdm.tqdm.write("")

        # ------------------------------------------------------------------
        # Candidate-z loop
        # ------------------------------------------------------------------

        for z_index, z in enumerate(z_values):
            dz_um = (z - z0) * 1e6

            tqdm.tqdm.write(
                f"[{z_index + 1}/{len(z_values)}] "
                f"Reconstructing z = {z * 1e3:.6f} mm "
                f"(Δz = {dz_um:+.2f} µm)"
            )

            # --------------------------------------------------------------
            # Evaluate candidate
            # --------------------------------------------------------------

            purity, candidate_reconstruction = self._evaluatePurityAtZ(z)

            candidate_error = float(
                np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
            )

            purity_values.append(purity)
            error_values.append(candidate_error)

            tqdm.tqdm.write(
                f"    Probe purity = {purity:.6f} | "
                f"reconstruction error = {candidate_error:.6e}"
            )

            # --------------------------------------------------------------
            # Update main monitor with completed candidate
            # --------------------------------------------------------------

            self._showCandidate(candidate_reconstruction, purity)

            # --------------------------------------------------------------
            # Keep only the state required from the best candidate
            # --------------------------------------------------------------

            if purity > best_purity:
                best_purity = purity
                best_z = z

                best_state = {
                    "object": asNumpyArray(candidate_reconstruction.object).copy(),
                    "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                    "purityProbe": purity,
                    # object grid of this candidate; see restore below
                    "No": candidate_reconstruction.No,
                    "shape_O": candidate_reconstruction.shape_O,
                    "initialGuessObject": asNumpyArray(
                        candidate_reconstruction.initialGuessObject
                    ).copy(),
                }

                if hasattr(
                    candidate_reconstruction,
                    "encoder_corrected",
                ):
                    best_state["encoder_corrected"] = asNumpyArray(
                        candidate_reconstruction.encoder_corrected
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectMomentum",
                ):
                    best_state["objectMomentum"] = asNumpyArray(
                        candidate_reconstruction.objectMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeMomentum",
                ):
                    best_state["probeMomentum"] = asNumpyArray(
                        candidate_reconstruction.probeMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectBuffer",
                ):
                    best_state["objectBuffer"] = asNumpyArray(
                        candidate_reconstruction.objectBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeBuffer",
                ):
                    best_state["probeBuffer"] = asNumpyArray(
                        candidate_reconstruction.probeBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "error",
                ):
                    best_state["error"] = np.asarray(
                        asNumpyArray(candidate_reconstruction.error)
                    ).copy()

                tqdm.tqdm.write(
                    f"    NEW BEST: z = {best_z * 1e3:.6f} mm, "
                    f"purity = {best_purity:.6f}"
                )

            tqdm.tqdm.write("")

        # ------------------------------------------------------------------
        # Safety check
        # ------------------------------------------------------------------

        if best_state is None:
            raise RuntimeError("Purity z scan did not produce a valid purity value.")

        # ------------------------------------------------------------------
        # Restore best candidate state
        # ------------------------------------------------------------------

        self.reconstruction.zo = best_z

        # each candidate is a new Reconstruction whose object grid was sized for
        # its own z / wavelength; restore that grid with the object, or positions
        # are centred for a different No and later engines size their momentum
        # arrays from the old initialGuessObject
        self.reconstruction.No = best_state["No"]
        self.reconstruction.shape_O = best_state["shape_O"]
        self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
        self.reconstruction.object = best_state["object"]

        self.reconstruction.probe = best_state["probe"]

        self.reconstruction.purityProbe = best_state["purityProbe"]

        if "encoder_corrected" in best_state:
            self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

        if "objectMomentum" in best_state:
            self.reconstruction.objectMomentum = best_state["objectMomentum"]

        if "probeMomentum" in best_state:
            self.reconstruction.probeMomentum = best_state["probeMomentum"]

        if "objectBuffer" in best_state:
            self.reconstruction.objectBuffer = best_state["objectBuffer"]

        if "probeBuffer" in best_state:
            self.reconstruction.probeBuffer = best_state["probeBuffer"]

        if "error" in best_state:
            self.reconstruction.error = best_state["error"]

        # ------------------------------------------------------------------
        # Store scan results
        # ------------------------------------------------------------------

        self.purityZValues = np.asarray(z_values)

        self.purityZMetrics = np.asarray(purity_values)

        self.purityZErrors = np.asarray(error_values)

        self.purityBestZ = best_z
        self.purityBestValue = best_purity

        # Final monitor update
        self.showReconstruction(
            self.numIterations - 1,
            force=True,
        )

        # ------------------------------------------------------------------
        # Summary
        # ------------------------------------------------------------------

        tqdm.tqdm.write("=" * 60)
        tqdm.tqdm.write("Purity-based z scan finished")

        tqdm.tqdm.write(f"Best z      = {best_z * 1e3:.6f} mm")

        tqdm.tqdm.write(f"Best Δz     = {(best_z - z0) * 1e6:+.2f} µm")

        tqdm.tqdm.write(f"Best purity = {best_purity:.6f}")

        tqdm.tqdm.write("=" * 60)

        return best_z, best_purity

    def adaptivePurityZScan(self):
        r"""
        Perform an adaptive purity-based axial calibration.

        The search starts from the current sample-to-detector distance
        `reconstruction.zo` and evaluates the initial position together with two
        neighboring candidates separated by `params.purityZInitialStep`.

        If the reconstructed probe purity increases toward either side, the search
        continues in that direction while progressively increasing the step size
        according to

        $$
        \Delta z_{k+1} = g\,\Delta z_k
        $$

        where `g = params.purityZStepGrowth`.

        Once the purity no longer improves significantly, the search switches to a
        local refinement around the best candidate. The step size is progressively
        reduced according to

        $$
        \Delta z_{k+1} = s\,\Delta z_k
        $$

        where `s = params.purityZStepShrink`.

        Refinement continues until the step size falls below
        `params.purityZMinStep` or the maximum number of candidate evaluations
        defined by `params.purityMaxEvaluations` is reached. Previously evaluated
        axial positions are cached and reused.

        Each candidate distance is evaluated using an independent `mPIE`
        reconstruction. The candidate yielding the highest reconstructed probe
        purity is retained, and its reconstruction state is restored to the original
        `Reconstruction` object.

        The evaluated distances, purity values, and reconstruction errors are stored
        in `purityZValues`, `purityZMetrics`, and `purityZErrors`, respectively.

        Returns:
            tuple:
                `(best_z, best_purity)`, where `best_z` is the calibrated
                sample-to-detector distance in meters and `best_purity` is the
                corresponding reconstructed probe purity.

        Raises:
            ValueError:
                If fewer than two probe modes are reconstructed
                (`reconstruction.npsm < 2`).

            RuntimeError:
                If no valid candidate reconstruction produces a purity value.
        """
        if self.reconstruction.npsm < 2:
            raise ValueError(
                "Purity-based z scanning requires at least two probe modes "
                "(reconstruction.npsm >= 2)."
            )

        z0 = self.reconstruction.zo
        self.purityZInitialGuess = z0

        step = self.params.purityZInitialStep
        growth = self.params.purityZStepGrowth
        shrink = self.params.purityZStepShrink
        min_step = self.params.purityZMinStep
        purity_tol = self.params.purityZPurityTolerance
        max_evaluations = self.params.purityMaxEvaluations

        evaluated = {}

        best_z = None
        best_purity = -np.inf
        best_state = None

        z_history = []
        purity_history = []
        error_history = []

        def evaluate(z):
            nonlocal best_z
            nonlocal best_purity
            nonlocal best_state

            # Reuse already evaluated points
            key = float(z)

            if key in evaluated:
                return evaluated[key]

            purity, candidate_reconstruction = self._evaluatePurityAtZ(z)
            candidate_error = float(
                np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
            )

            evaluated[key] = purity

            z_history.append(z)
            purity_history.append(purity)
            error_history.append(candidate_error)
            tqdm.tqdm.write(
                f"z = {z * 1e3:.6f} mm | "
                f"purity = {purity:.6f} | "
                f"error = {candidate_error:.6e}"
            )

            # show every evaluated candidate live, as the fixed-grid scan does
            self._showCandidate(candidate_reconstruction, purity)

            # Store best candidate state
            if purity > best_purity:
                best_purity = purity
                best_z = z

                best_state = {
                    "object": asNumpyArray(candidate_reconstruction.object).copy(),
                    "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                    "purityProbe": purity,
                    # object grid of this candidate; see restore below
                    "No": candidate_reconstruction.No,
                    "shape_O": candidate_reconstruction.shape_O,
                    "initialGuessObject": asNumpyArray(
                        candidate_reconstruction.initialGuessObject
                    ).copy(),
                }

                if hasattr(
                    candidate_reconstruction,
                    "encoder_corrected",
                ):
                    best_state["encoder_corrected"] = asNumpyArray(
                        candidate_reconstruction.encoder_corrected
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectMomentum",
                ):
                    best_state["objectMomentum"] = asNumpyArray(
                        candidate_reconstruction.objectMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeMomentum",
                ):
                    best_state["probeMomentum"] = asNumpyArray(
                        candidate_reconstruction.probeMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectBuffer",
                ):
                    best_state["objectBuffer"] = asNumpyArray(
                        candidate_reconstruction.objectBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeBuffer",
                ):
                    best_state["probeBuffer"] = asNumpyArray(
                        candidate_reconstruction.probeBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "error",
                ):
                    best_state["error"] = np.asarray(
                        asNumpyArray(candidate_reconstruction.error)
                    ).copy()

                tqdm.tqdm.write(
                    f"NEW BEST: z = {best_z * 1e3:.6f} mm | purity = {best_purity:.6f}"
                )

            return purity

        tqdm.tqdm.write("")
        tqdm.tqdm.write("Starting adaptive purity-based z scan")
        tqdm.tqdm.write(
            f"Initial z = {z0 * 1e3:.6f} mm | initial step = {step * 1e6:.1f} µm"
        )
        tqdm.tqdm.write("")

        # --------------------------------------------------------------
        # 1. Initial three-point evaluation
        # --------------------------------------------------------------

        p0 = evaluate(z0)

        z_left = z0 - step
        z_right = z0 + step

        p_left = evaluate(z_left)
        p_right = evaluate(z_right)

        evaluations = len(evaluated)

        # --------------------------------------------------------------
        # 2. Determine initial uphill direction
        # --------------------------------------------------------------

        if p_left > p0 and p_left >= p_right:
            direction = -1

        elif p_right > p0 and p_right > p_left:
            direction = +1

        else:
            direction = 0

        # --------------------------------------------------------------
        # 3. Expansion phase
        # --------------------------------------------------------------

        if direction != 0:
            current_z = z0 + direction * step
            current_purity = evaluate(current_z)

            while evaluations < max_evaluations:
                step *= growth

                next_z = current_z + direction * step
                next_purity = evaluate(next_z)

                evaluations = len(evaluated)

                improvement = next_purity - current_purity

                if improvement > purity_tol:
                    current_z = next_z
                    current_purity = next_purity
                    continue

                # Purity stopped increasing:
                # maximum should now be bracketed.
                break

        # --------------------------------------------------------------
        # 4. Refinement phase
        # --------------------------------------------------------------

        step *= shrink

        while step >= min_step and len(evaluated) < max_evaluations:
            left_z = best_z - step
            right_z = best_z + step

            # evaluate() raises best_purity as soon as it sees a better point, so
            # compare against the best from before this round
            best_before = best_purity

            left_purity = evaluate(left_z)

            if len(evaluated) >= max_evaluations:
                break

            right_purity = evaluate(right_z)

            # If neither side significantly improves the best result,
            # reduce the search step.
            if (
                left_purity <= best_before + purity_tol
                and right_purity <= best_before + purity_tol
            ):
                step *= shrink
                continue

            # A better point was found. Keep the current step and
            # continue refining around the new best position.

        # --------------------------------------------------------------
        # Safety check
        # --------------------------------------------------------------

        if best_state is None:
            raise RuntimeError("Adaptive purity z scan did not produce a valid result.")

        # --------------------------------------------------------------
        # Restore best candidate
        # --------------------------------------------------------------

        self.reconstruction.zo = best_z
        # each candidate is a new Reconstruction whose object grid was sized for
        # its own z / wavelength; restore that grid with the object, or positions
        # are centred for a different No and later engines size their momentum
        # arrays from the old initialGuessObject
        self.reconstruction.No = best_state["No"]
        self.reconstruction.shape_O = best_state["shape_O"]
        self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
        self.reconstruction.object = best_state["object"]
        self.reconstruction.probe = best_state["probe"]
        self.reconstruction.purityProbe = best_state["purityProbe"]

        if "encoder_corrected" in best_state:
            self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

        if "objectMomentum" in best_state:
            self.reconstruction.objectMomentum = best_state["objectMomentum"]

        if "probeMomentum" in best_state:
            self.reconstruction.probeMomentum = best_state["probeMomentum"]

        if "objectBuffer" in best_state:
            self.reconstruction.objectBuffer = best_state["objectBuffer"]

        if "probeBuffer" in best_state:
            self.reconstruction.probeBuffer = best_state["probeBuffer"]

        if "error" in best_state:
            self.reconstruction.error = best_state["error"]

        # --------------------------------------------------------------
        # Store results
        # --------------------------------------------------------------

        order = np.argsort(z_history)

        self.purityZValues = np.asarray(z_history)[order]
        self.purityZMetrics = np.asarray(purity_history)[order]
        self.purityZErrors = np.asarray(error_history)[order]

        self.purityBestZ = best_z
        self.purityBestValue = best_purity

        self.showReconstruction(
            self.numIterations - 1,
            force=True,
        )

        # --------------------------------------------------------------
        # Summary
        # --------------------------------------------------------------

        tqdm.tqdm.write("=" * 60)
        tqdm.tqdm.write("Adaptive purity-based z scan finished")
        tqdm.tqdm.write(f"Best z      = {best_z * 1e3:.6f} mm")
        tqdm.tqdm.write(f"Best Δz     = {(best_z - z0) * 1e6:+.2f} µm")
        tqdm.tqdm.write(f"Best purity = {best_purity:.6f}")
        tqdm.tqdm.write(f"Evaluations = {len(evaluated)}")
        tqdm.tqdm.write("=" * 60)

        return best_z, best_purity

    def purityWavelengthScan(self):
        """
        Perform a fixed-grid purity-based wavelength calibration.

        Candidate wavelengths are evaluated over a uniformly spaced range defined
        by `params.purityWavelengthScanRange` and
        `params.purityWavelengthScanPoints`. The wavelength yielding the highest
        reconstructed probe purity is retained.

        Returns:
            tuple:
                `(best_wavelength, best_purity)`.

        See Also:
                    `purityZScan`
                        Fixed-grid purity-based axial calibration.
        """

        if self.reconstruction.npsm < 2:
            raise ValueError(
                "Purity-based wavelength scanning requires at least two probe modes "
                "(reconstruction.npsm >= 2)."
            )

        wavelength0 = float(self.reconstruction.wavelength)

        self.purityWavelengthInitialGuess = wavelength0

        wavelength_values = np.linspace(
            wavelength0 - self.params.purityWavelengthScanRange,
            wavelength0 + self.params.purityWavelengthScanRange,
            self.params.purityWavelengthScanPoints,
        )

        purity_values = []
        error_values = []

        best_purity = -np.inf
        best_wavelength = wavelength0
        best_state = None

        tqdm.tqdm.write("")
        tqdm.tqdm.write("Starting purity-based wavelength scan")

        tqdm.tqdm.write(
            f"Initial wavelength = "
            f"{wavelength0 * 1e9:.6f} nm | "
            f"range = ±"
            f"{self.params.purityWavelengthScanRange * 1e9:.4f} nm | "
            f"points = {len(wavelength_values)} | "
            f"iterations/wavelength = {self.numIterations}"
        )

        tqdm.tqdm.write("")

        for wavelength_index, wavelength in enumerate(wavelength_values):
            delta_wavelength_nm = (wavelength - wavelength0) * 1e9

            tqdm.tqdm.write(
                f"[{wavelength_index + 1}/"
                f"{len(wavelength_values)}] "
                f"Reconstructing wavelength = "
                f"{wavelength * 1e9:.6f} nm "
                f"(Δλ = {delta_wavelength_nm:+.4f} nm)"
            )

            (
                purity,
                candidate_reconstruction,
            ) = self._evaluatePurityAtWavelength(wavelength)

            candidate_error = float(
                np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
            )

            purity_values.append(purity)

            error_values.append(candidate_error)

            tqdm.tqdm.write(
                f"    Probe purity = {purity:.6f} | "
                f"reconstruction error = {candidate_error:.6e}"
            )

            # Update monitor with current candidate
            self._showCandidate(candidate_reconstruction, purity)

            if purity > best_purity:
                best_purity = purity
                best_wavelength = wavelength

                best_state = {
                    "object": asNumpyArray(candidate_reconstruction.object).copy(),
                    "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                    "purityProbe": purity,
                    # object grid of this candidate; see restore below
                    "No": candidate_reconstruction.No,
                    "shape_O": candidate_reconstruction.shape_O,
                    "initialGuessObject": asNumpyArray(
                        candidate_reconstruction.initialGuessObject
                    ).copy(),
                    "dxp": float(candidate_reconstruction.dxp),
                }

                if hasattr(
                    candidate_reconstruction,
                    "spectralDensity",
                ):
                    best_state["spectralDensity"] = np.asarray(
                        candidate_reconstruction.spectralDensity
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "encoder_corrected",
                ):
                    best_state["encoder_corrected"] = asNumpyArray(
                        candidate_reconstruction.encoder_corrected
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectMomentum",
                ):
                    best_state["objectMomentum"] = asNumpyArray(
                        candidate_reconstruction.objectMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeMomentum",
                ):
                    best_state["probeMomentum"] = asNumpyArray(
                        candidate_reconstruction.probeMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectBuffer",
                ):
                    best_state["objectBuffer"] = asNumpyArray(
                        candidate_reconstruction.objectBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeBuffer",
                ):
                    best_state["probeBuffer"] = asNumpyArray(
                        candidate_reconstruction.probeBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "error",
                ):
                    best_state["error"] = np.asarray(
                        asNumpyArray(candidate_reconstruction.error)
                    ).copy()

                tqdm.tqdm.write(
                    f"    NEW BEST: wavelength = "
                    f"{best_wavelength * 1e9:.6f} nm | "
                    f"purity = {best_purity:.6f}"
                )

            tqdm.tqdm.write("")

        if best_state is None:
            raise RuntimeError(
                "Purity wavelength scan did not produce a valid purity value."
            )

        # Restore best candidate
        self.reconstruction.wavelength = best_wavelength

        self.reconstruction.dxp = best_state["dxp"]

        if "spectralDensity" in best_state:
            self.reconstruction.spectralDensity = best_state["spectralDensity"]

        # each candidate is a new Reconstruction whose object grid was sized for
        # its own z / wavelength; restore that grid with the object, or positions
        # are centred for a different No and later engines size their momentum
        # arrays from the old initialGuessObject
        self.reconstruction.No = best_state["No"]
        self.reconstruction.shape_O = best_state["shape_O"]
        self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
        self.reconstruction.object = best_state["object"]

        self.reconstruction.probe = best_state["probe"]

        self.reconstruction.purityProbe = best_state["purityProbe"]

        if "encoder_corrected" in best_state:
            self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

        if "objectMomentum" in best_state:
            self.reconstruction.objectMomentum = best_state["objectMomentum"]

        if "probeMomentum" in best_state:
            self.reconstruction.probeMomentum = best_state["probeMomentum"]

        if "objectBuffer" in best_state:
            self.reconstruction.objectBuffer = best_state["objectBuffer"]

        if "probeBuffer" in best_state:
            self.reconstruction.probeBuffer = best_state["probeBuffer"]

        if "error" in best_state:
            self.reconstruction.error = best_state["error"]

        # Store scan results
        self.purityWavelengthValues = np.asarray(wavelength_values)

        self.purityWavelengthMetrics = np.asarray(purity_values)

        self.purityWavelengthErrors = np.asarray(error_values)

        self.purityBestWavelength = best_wavelength

        self.purityBestWavelengthValue = best_purity

        self.showReconstruction(
            self.numIterations - 1,
            force=True,
        )

        tqdm.tqdm.write("=" * 60)
        tqdm.tqdm.write("Purity-based wavelength scan finished")

        tqdm.tqdm.write(f"Best wavelength = {best_wavelength * 1e9:.6f} nm")

        tqdm.tqdm.write(
            f"Best Δλ         = {(best_wavelength - wavelength0) * 1e9:+.4f} nm"
        )

        tqdm.tqdm.write(f"Best purity     = {best_purity:.6f}")

        tqdm.tqdm.write("=" * 60)

        return (
            best_wavelength,
            best_purity,
        )

    def adaptivePurityWavelengthScan(self):
        """
        Perform an adaptive purity-based wavelength calibration.

        The search starts from the current wavelength, expands the step in the
        direction of increasing probe purity, and then refines around the best
        candidate using progressively smaller steps.

        Returns:
            tuple:
                `(best_wavelength, best_purity)`.

        See Also:
                    `adaptivePurityZScan`
                        adaptive stepsize purity-based axial distance calibration.
        """

        if self.reconstruction.npsm < 2:
            raise ValueError(
                "Purity-based wavelength scanning requires at least two probe modes "
                "(reconstruction.npsm >= 2)."
            )

        wavelength0 = float(self.reconstruction.wavelength)

        self.purityWavelengthInitialGuess = wavelength0

        step = self.params.purityWavelengthInitialStep
        growth = self.params.purityWavelengthStepGrowth
        shrink = self.params.purityWavelengthStepShrink
        min_step = self.params.purityWavelengthMinStep
        purity_tol = self.params.purityWavelengthPurityTolerance
        max_evaluations = self.params.purityMaxEvaluations

        evaluated = {}

        best_wavelength = None
        best_purity = -np.inf
        best_state = None

        wavelength_history = []
        purity_history = []
        error_history = []

        def evaluate(wavelength):

            nonlocal best_wavelength
            nonlocal best_purity
            nonlocal best_state

            if wavelength <= 0:
                return -np.inf

            key = float(wavelength)

            if key in evaluated:
                return evaluated[key]

            (
                purity,
                candidate_reconstruction,
            ) = self._evaluatePurityAtWavelength(wavelength)

            candidate_error = float(
                np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
            )

            evaluated[key] = purity

            wavelength_history.append(wavelength)

            purity_history.append(purity)

            error_history.append(candidate_error)

            tqdm.tqdm.write(
                f"wavelength = {wavelength * 1e9:.6f} nm | "
                f"purity = {purity:.6f} | "
                f"error = {candidate_error:.6e}"
            )

            # show every evaluated candidate live, as the fixed-grid scan does
            self._showCandidate(candidate_reconstruction, purity)

            if purity > best_purity:
                best_purity = purity
                best_wavelength = wavelength

                best_state = {
                    "object": asNumpyArray(candidate_reconstruction.object).copy(),
                    "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                    "purityProbe": purity,
                    # object grid of this candidate; see restore below
                    "No": candidate_reconstruction.No,
                    "shape_O": candidate_reconstruction.shape_O,
                    "initialGuessObject": asNumpyArray(
                        candidate_reconstruction.initialGuessObject
                    ).copy(),
                    "dxp": float(candidate_reconstruction.dxp),
                }

                if hasattr(
                    candidate_reconstruction,
                    "spectralDensity",
                ):
                    best_state["spectralDensity"] = np.asarray(
                        candidate_reconstruction.spectralDensity
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "encoder_corrected",
                ):
                    best_state["encoder_corrected"] = asNumpyArray(
                        candidate_reconstruction.encoder_corrected
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectMomentum",
                ):
                    best_state["objectMomentum"] = asNumpyArray(
                        candidate_reconstruction.objectMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeMomentum",
                ):
                    best_state["probeMomentum"] = asNumpyArray(
                        candidate_reconstruction.probeMomentum
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "objectBuffer",
                ):
                    best_state["objectBuffer"] = asNumpyArray(
                        candidate_reconstruction.objectBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "probeBuffer",
                ):
                    best_state["probeBuffer"] = asNumpyArray(
                        candidate_reconstruction.probeBuffer
                    ).copy()

                if hasattr(
                    candidate_reconstruction,
                    "error",
                ):
                    best_state["error"] = np.asarray(
                        asNumpyArray(candidate_reconstruction.error)
                    ).copy()

                tqdm.tqdm.write(
                    f"NEW BEST: wavelength = "
                    f"{best_wavelength * 1e9:.6f} nm | "
                    f"purity = {best_purity:.6f}"
                )

            return purity

        tqdm.tqdm.write("")
        tqdm.tqdm.write("Starting adaptive purity-based wavelength scan")

        tqdm.tqdm.write(
            f"Initial wavelength = "
            f"{wavelength0 * 1e9:.6f} nm | "
            f"initial step = {step * 1e9:.4f} nm"
        )

        tqdm.tqdm.write("")

        # ------------------------------------------------------------------
        # 1. Initial three-point evaluation
        # ------------------------------------------------------------------

        p0 = evaluate(wavelength0)

        wavelength_left = wavelength0 - step

        wavelength_right = wavelength0 + step

        p_left = evaluate(wavelength_left)

        p_right = evaluate(wavelength_right)

        # ------------------------------------------------------------------
        # 2. Determine uphill direction
        # ------------------------------------------------------------------

        if p_left > p0 and p_left >= p_right:
            direction = -1

        elif p_right > p0 and p_right > p_left:
            direction = +1

        else:
            direction = 0

        # ------------------------------------------------------------------
        # 3. Expansion phase
        # ------------------------------------------------------------------

        if direction != 0:
            current_wavelength = wavelength0 + direction * step

            current_purity = evaluate(current_wavelength)

            while len(evaluated) < max_evaluations:
                step *= growth

                next_wavelength = current_wavelength + direction * step

                if next_wavelength <= 0:
                    break

                next_purity = evaluate(next_wavelength)

                improvement = next_purity - current_purity

                if improvement > purity_tol:
                    current_wavelength = next_wavelength

                    current_purity = next_purity

                    continue

                break

        # ------------------------------------------------------------------
        # 4. Refinement phase
        # ------------------------------------------------------------------

        step *= shrink

        while step >= min_step and len(evaluated) < max_evaluations:
            left_wavelength = best_wavelength - step

            right_wavelength = best_wavelength + step

            # evaluate() raises best_purity as soon as it sees a better point, so
            # compare against the best from before this round
            best_before = best_purity

            if left_wavelength > 0:
                left_purity = evaluate(left_wavelength)
            else:
                left_purity = -np.inf

            if len(evaluated) >= max_evaluations:
                break

            right_purity = evaluate(right_wavelength)

            if (
                left_purity <= best_before + purity_tol
                and right_purity <= best_before + purity_tol
            ):
                step *= shrink
                continue

        if best_state is None:
            raise RuntimeError(
                "Adaptive purity wavelength scan did not produce a valid result."
            )

        # ------------------------------------------------------------------
        # Restore best candidate
        # ------------------------------------------------------------------

        self.reconstruction.wavelength = best_wavelength

        self.reconstruction.dxp = best_state["dxp"]

        if "spectralDensity" in best_state:
            self.reconstruction.spectralDensity = best_state["spectralDensity"]

        # each candidate is a new Reconstruction whose object grid was sized for
        # its own z / wavelength; restore that grid with the object, or positions
        # are centred for a different No and later engines size their momentum
        # arrays from the old initialGuessObject
        self.reconstruction.No = best_state["No"]
        self.reconstruction.shape_O = best_state["shape_O"]
        self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
        self.reconstruction.object = best_state["object"]

        self.reconstruction.probe = best_state["probe"]

        self.reconstruction.purityProbe = best_state["purityProbe"]

        if "encoder_corrected" in best_state:
            self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

        if "objectMomentum" in best_state:
            self.reconstruction.objectMomentum = best_state["objectMomentum"]

        if "probeMomentum" in best_state:
            self.reconstruction.probeMomentum = best_state["probeMomentum"]

        if "objectBuffer" in best_state:
            self.reconstruction.objectBuffer = best_state["objectBuffer"]

        if "probeBuffer" in best_state:
            self.reconstruction.probeBuffer = best_state["probeBuffer"]

        if "error" in best_state:
            self.reconstruction.error = best_state["error"]

        # ------------------------------------------------------------------
        # Store results
        # ------------------------------------------------------------------

        order = np.argsort(wavelength_history)

        self.purityWavelengthValues = np.asarray(wavelength_history)[order]

        self.purityWavelengthMetrics = np.asarray(purity_history)[order]

        self.purityWavelengthErrors = np.asarray(error_history)[order]

        self.purityBestWavelength = best_wavelength

        self.purityBestWavelengthValue = best_purity

        self.showReconstruction(
            self.numIterations - 1,
            force=True,
        )

        tqdm.tqdm.write("=" * 60)
        tqdm.tqdm.write("Adaptive purity-based wavelength scan finished")

        tqdm.tqdm.write(f"Best wavelength = {best_wavelength * 1e9:.6f} nm")

        tqdm.tqdm.write(
            f"Best Δλ         = {(best_wavelength - wavelength0) * 1e9:+.4f} nm"
        )

        tqdm.tqdm.write(f"Best purity     = {best_purity:.6f}")

        tqdm.tqdm.write(f"Evaluations     = {len(evaluated)}")

        tqdm.tqdm.write("=" * 60)

        return (
            best_wavelength,
            best_purity,
        )

reconstruct(experimentalData=None, reconstruction=None)

Run purity-based self-calibration.

The reconstruction first prepares the current object, probe, geometry, constraints, and optional GPU state using the standard mPIE setup.

Each candidate parameter value is evaluated using an independent mPIE reconstruction. The reconstructed probe modes are orthogonalized, the corresponding probe purity is evaluated, and the candidate yielding the highest purity is retained.

After calibration, the reconstruction state corresponding to the optimal candidate is restored to the original Reconstruction object.

With the matplotlib Monitor, purity and reconstruction error vs the calibrated parameter are plotted live during the scan, and the final plot shades the scan resolution around the maximum. A warning is logged if the maximum lies at the edge of the scanned range.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for calibration. If provided, it replaces the dataset currently attached to the engine.

None
reconstruction Reconstruction

Reconstruction state to calibrate. If provided, it replaces the reconstruction currently attached to the engine.

None

Returns:

Type Description
tuple

(best_value, best_purity), where best_value is the calibrated axial distance in meters for purityCalibrationTarget = "z" or the calibrated wavelength in meters for purityCalibrationTarget = "wavelength", and best_purity is the corresponding reconstructed probe purity.

Raises:

Type Description
ValueError

If params.purityCalibrationTarget is neither "z" nor "wavelength".

Source code in PtyLab/Engines/purityPIE.py
def reconstruct(
    self,
    experimentalData=None,
    reconstruction=None,
):
    """
    Run purity-based self-calibration.

    The reconstruction first prepares the current object, probe, geometry,
    constraints, and optional GPU state using the standard `mPIE` setup.

    Each candidate parameter value is evaluated using an independent `mPIE`
    reconstruction. The reconstructed probe modes are orthogonalized, the
    corresponding probe purity is evaluated, and the candidate yielding the
    highest purity is retained.

    After calibration, the reconstruction state corresponding to the optimal
    candidate is restored to the original `Reconstruction` object.

    With the matplotlib `Monitor`, purity and reconstruction error vs the
    calibrated parameter are plotted live during the scan, and the final plot
    shades the scan resolution around the maximum. A warning is logged if the
    maximum lies at the edge of the scanned range.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use for calibration. If provided, it
            replaces the dataset currently attached to the engine.

        reconstruction (Reconstruction, optional):
            Reconstruction state to calibrate. If provided, it replaces the
            reconstruction currently attached to the engine.

    Returns:
        tuple:
            `(best_value, best_purity)`, where `best_value` is the calibrated
            axial distance in meters for `purityCalibrationTarget = "z"` or the
            calibrated wavelength in meters for
            `purityCalibrationTarget = "wavelength"`, and `best_purity` is the
            corresponding reconstructed probe purity.

    Raises:
        ValueError:
            If `params.purityCalibrationTarget` is neither `"z"` nor
            `"wavelength"`.
    """

    self.changeExperimentalData(experimentalData)
    self.changeOptimizable(reconstruction)

    hidden_history = self._setupScanMonitor()

    self._prepareReconstruction()

    # Reset momentum buffers after preparation
    self.reconstruction.objectBuffer = self.reconstruction.object.copy()

    self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

    target = self.params.purityCalibrationTarget.lower()

    # ------------------------------------------------------------------
    # Axial-distance calibration
    # ------------------------------------------------------------------

    if target == "z":
        if self.params.purityAdaptive:
            best_value, best_purity = self.adaptivePurityZScan()
        else:
            best_value, best_purity = self.purityZScan()

    # ------------------------------------------------------------------
    # Wavelength calibration
    # ------------------------------------------------------------------

    elif target == "wavelength":
        if self.params.purityAdaptive:
            best_value, best_purity = self.adaptivePurityWavelengthScan()
        else:
            best_value, best_purity = self.purityWavelengthScan()

    # ------------------------------------------------------------------
    # Unsupported target
    # ------------------------------------------------------------------

    else:
        raise ValueError(
            "Unsupported purity calibration target: "
            f"{self.params.purityCalibrationTarget!r}. "
            "Supported targets are 'z' and 'wavelength'."
        )

    self._finishScan(target)

    # ------------------------------------------------------------------
    # Return reconstruction data to CPU
    # ------------------------------------------------------------------

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

    # give the parameter-history window back to later engines, e.g. an mPIE
    # run that continues from the calibrated state
    if hidden_history is not None:
        self.monitor.showParameterHistory = hidden_history

    return best_value, best_purity

purityZScan()

Perform a fixed-grid purity-based axial calibration.

The scan evaluates a uniformly spaced set of candidate sample-to-detector distances centered on the current value reconstruction.zo. The scan range and number of candidate positions are defined by params.purityZScanRange and params.purityZScanPoints.

Each candidate distance is evaluated using an independent mPIE reconstruction. The reconstructed probe modes are orthogonalized, and the candidate yielding the highest probe purity is retained as the calibrated axial distance.

The reconstruction error for each candidate is recorded together with the purity metric. After the scan, the reconstruction state corresponding to the highest-purity candidate is restored to the original Reconstruction object.

The evaluated distances, purity values, and reconstruction errors are stored in purityZValues, purityZMetrics, and purityZErrors, respectively.

Returns:

Type Description
tuple

(best_z, best_purity), where best_z is the calibrated sample-to-detector distance in meters and best_purity is the corresponding reconstructed probe purity.

Raises:

Type Description
ValueError

If fewer than two probe modes are reconstructed (reconstruction.npsm < 2).

RuntimeError

If no valid candidate reconstruction produces a purity value.

Source code in PtyLab/Engines/purityPIE.py
def purityZScan(self):
    """
    Perform a fixed-grid purity-based axial calibration.

    The scan evaluates a uniformly spaced set of candidate sample-to-detector
    distances centered on the current value `reconstruction.zo`. The scan range
    and number of candidate positions are defined by
    `params.purityZScanRange` and `params.purityZScanPoints`.

    Each candidate distance is evaluated using an independent `mPIE`
    reconstruction. The reconstructed probe modes are orthogonalized, and the
    candidate yielding the highest probe purity is retained as the calibrated
    axial distance.

    The reconstruction error for each candidate is recorded together with the
    purity metric. After the scan, the reconstruction state corresponding to
    the highest-purity candidate is restored to the original `Reconstruction`
    object.

    The evaluated distances, purity values, and reconstruction errors are stored
    in `purityZValues`, `purityZMetrics`, and `purityZErrors`, respectively.

    Returns:
        tuple:
            `(best_z, best_purity)`, where `best_z` is the calibrated
            sample-to-detector distance in meters and `best_purity` is the
            corresponding reconstructed probe purity.

    Raises:
        ValueError:
            If fewer than two probe modes are reconstructed
            (`reconstruction.npsm < 2`).

        RuntimeError:
            If no valid candidate reconstruction produces a purity value.
    """

    if self.reconstruction.npsm < 2:
        raise ValueError(
            "Purity-based z scanning requires at least two probe modes "
            "(reconstruction.npsm >= 2)."
        )

    # ------------------------------------------------------------------
    # Scan grid
    # ------------------------------------------------------------------

    z0 = self.reconstruction.zo
    self.purityZInitialGuess = z0

    z_values = np.linspace(
        z0 - self.params.purityZScanRange,
        z0 + self.params.purityZScanRange,
        self.params.purityZScanPoints,
    )

    purity_values = []
    error_values = []

    best_purity = -np.inf
    best_z = z0
    best_state = None

    # ------------------------------------------------------------------
    # Scan information
    # ------------------------------------------------------------------

    tqdm.tqdm.write("")
    tqdm.tqdm.write("Starting purity-based z scan")
    tqdm.tqdm.write(
        f"Initial z = {z0 * 1e3:.6f} mm | "
        f"range = ±{self.params.purityZScanRange * 1e6:.1f} µm | "
        f"points = {len(z_values)} | "
        f"iterations/z = {self.numIterations}"
    )
    tqdm.tqdm.write("")

    # ------------------------------------------------------------------
    # Candidate-z loop
    # ------------------------------------------------------------------

    for z_index, z in enumerate(z_values):
        dz_um = (z - z0) * 1e6

        tqdm.tqdm.write(
            f"[{z_index + 1}/{len(z_values)}] "
            f"Reconstructing z = {z * 1e3:.6f} mm "
            f"(Δz = {dz_um:+.2f} µm)"
        )

        # --------------------------------------------------------------
        # Evaluate candidate
        # --------------------------------------------------------------

        purity, candidate_reconstruction = self._evaluatePurityAtZ(z)

        candidate_error = float(
            np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
        )

        purity_values.append(purity)
        error_values.append(candidate_error)

        tqdm.tqdm.write(
            f"    Probe purity = {purity:.6f} | "
            f"reconstruction error = {candidate_error:.6e}"
        )

        # --------------------------------------------------------------
        # Update main monitor with completed candidate
        # --------------------------------------------------------------

        self._showCandidate(candidate_reconstruction, purity)

        # --------------------------------------------------------------
        # Keep only the state required from the best candidate
        # --------------------------------------------------------------

        if purity > best_purity:
            best_purity = purity
            best_z = z

            best_state = {
                "object": asNumpyArray(candidate_reconstruction.object).copy(),
                "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                "purityProbe": purity,
                # object grid of this candidate; see restore below
                "No": candidate_reconstruction.No,
                "shape_O": candidate_reconstruction.shape_O,
                "initialGuessObject": asNumpyArray(
                    candidate_reconstruction.initialGuessObject
                ).copy(),
            }

            if hasattr(
                candidate_reconstruction,
                "encoder_corrected",
            ):
                best_state["encoder_corrected"] = asNumpyArray(
                    candidate_reconstruction.encoder_corrected
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectMomentum",
            ):
                best_state["objectMomentum"] = asNumpyArray(
                    candidate_reconstruction.objectMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeMomentum",
            ):
                best_state["probeMomentum"] = asNumpyArray(
                    candidate_reconstruction.probeMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectBuffer",
            ):
                best_state["objectBuffer"] = asNumpyArray(
                    candidate_reconstruction.objectBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeBuffer",
            ):
                best_state["probeBuffer"] = asNumpyArray(
                    candidate_reconstruction.probeBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "error",
            ):
                best_state["error"] = np.asarray(
                    asNumpyArray(candidate_reconstruction.error)
                ).copy()

            tqdm.tqdm.write(
                f"    NEW BEST: z = {best_z * 1e3:.6f} mm, "
                f"purity = {best_purity:.6f}"
            )

        tqdm.tqdm.write("")

    # ------------------------------------------------------------------
    # Safety check
    # ------------------------------------------------------------------

    if best_state is None:
        raise RuntimeError("Purity z scan did not produce a valid purity value.")

    # ------------------------------------------------------------------
    # Restore best candidate state
    # ------------------------------------------------------------------

    self.reconstruction.zo = best_z

    # each candidate is a new Reconstruction whose object grid was sized for
    # its own z / wavelength; restore that grid with the object, or positions
    # are centred for a different No and later engines size their momentum
    # arrays from the old initialGuessObject
    self.reconstruction.No = best_state["No"]
    self.reconstruction.shape_O = best_state["shape_O"]
    self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
    self.reconstruction.object = best_state["object"]

    self.reconstruction.probe = best_state["probe"]

    self.reconstruction.purityProbe = best_state["purityProbe"]

    if "encoder_corrected" in best_state:
        self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

    if "objectMomentum" in best_state:
        self.reconstruction.objectMomentum = best_state["objectMomentum"]

    if "probeMomentum" in best_state:
        self.reconstruction.probeMomentum = best_state["probeMomentum"]

    if "objectBuffer" in best_state:
        self.reconstruction.objectBuffer = best_state["objectBuffer"]

    if "probeBuffer" in best_state:
        self.reconstruction.probeBuffer = best_state["probeBuffer"]

    if "error" in best_state:
        self.reconstruction.error = best_state["error"]

    # ------------------------------------------------------------------
    # Store scan results
    # ------------------------------------------------------------------

    self.purityZValues = np.asarray(z_values)

    self.purityZMetrics = np.asarray(purity_values)

    self.purityZErrors = np.asarray(error_values)

    self.purityBestZ = best_z
    self.purityBestValue = best_purity

    # Final monitor update
    self.showReconstruction(
        self.numIterations - 1,
        force=True,
    )

    # ------------------------------------------------------------------
    # Summary
    # ------------------------------------------------------------------

    tqdm.tqdm.write("=" * 60)
    tqdm.tqdm.write("Purity-based z scan finished")

    tqdm.tqdm.write(f"Best z      = {best_z * 1e3:.6f} mm")

    tqdm.tqdm.write(f"Best Δz     = {(best_z - z0) * 1e6:+.2f} µm")

    tqdm.tqdm.write(f"Best purity = {best_purity:.6f}")

    tqdm.tqdm.write("=" * 60)

    return best_z, best_purity

adaptivePurityZScan()

Perform an adaptive purity-based axial calibration.

The search starts from the current sample-to-detector distance reconstruction.zo and evaluates the initial position together with two neighboring candidates separated by params.purityZInitialStep.

If the reconstructed probe purity increases toward either side, the search continues in that direction while progressively increasing the step size according to

\[ \Delta z_{k+1} = g\,\Delta z_k \]

where g = params.purityZStepGrowth.

Once the purity no longer improves significantly, the search switches to a local refinement around the best candidate. The step size is progressively reduced according to

\[ \Delta z_{k+1} = s\,\Delta z_k \]

where s = params.purityZStepShrink.

Refinement continues until the step size falls below params.purityZMinStep or the maximum number of candidate evaluations defined by params.purityMaxEvaluations is reached. Previously evaluated axial positions are cached and reused.

Each candidate distance is evaluated using an independent mPIE reconstruction. The candidate yielding the highest reconstructed probe purity is retained, and its reconstruction state is restored to the original Reconstruction object.

The evaluated distances, purity values, and reconstruction errors are stored in purityZValues, purityZMetrics, and purityZErrors, respectively.

Returns:

Type Description
tuple

(best_z, best_purity), where best_z is the calibrated sample-to-detector distance in meters and best_purity is the corresponding reconstructed probe purity.

Raises:

Type Description
ValueError

If fewer than two probe modes are reconstructed (reconstruction.npsm < 2).

RuntimeError

If no valid candidate reconstruction produces a purity value.

Source code in PtyLab/Engines/purityPIE.py
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
def adaptivePurityZScan(self):
    r"""
    Perform an adaptive purity-based axial calibration.

    The search starts from the current sample-to-detector distance
    `reconstruction.zo` and evaluates the initial position together with two
    neighboring candidates separated by `params.purityZInitialStep`.

    If the reconstructed probe purity increases toward either side, the search
    continues in that direction while progressively increasing the step size
    according to

    $$
    \Delta z_{k+1} = g\,\Delta z_k
    $$

    where `g = params.purityZStepGrowth`.

    Once the purity no longer improves significantly, the search switches to a
    local refinement around the best candidate. The step size is progressively
    reduced according to

    $$
    \Delta z_{k+1} = s\,\Delta z_k
    $$

    where `s = params.purityZStepShrink`.

    Refinement continues until the step size falls below
    `params.purityZMinStep` or the maximum number of candidate evaluations
    defined by `params.purityMaxEvaluations` is reached. Previously evaluated
    axial positions are cached and reused.

    Each candidate distance is evaluated using an independent `mPIE`
    reconstruction. The candidate yielding the highest reconstructed probe
    purity is retained, and its reconstruction state is restored to the original
    `Reconstruction` object.

    The evaluated distances, purity values, and reconstruction errors are stored
    in `purityZValues`, `purityZMetrics`, and `purityZErrors`, respectively.

    Returns:
        tuple:
            `(best_z, best_purity)`, where `best_z` is the calibrated
            sample-to-detector distance in meters and `best_purity` is the
            corresponding reconstructed probe purity.

    Raises:
        ValueError:
            If fewer than two probe modes are reconstructed
            (`reconstruction.npsm < 2`).

        RuntimeError:
            If no valid candidate reconstruction produces a purity value.
    """
    if self.reconstruction.npsm < 2:
        raise ValueError(
            "Purity-based z scanning requires at least two probe modes "
            "(reconstruction.npsm >= 2)."
        )

    z0 = self.reconstruction.zo
    self.purityZInitialGuess = z0

    step = self.params.purityZInitialStep
    growth = self.params.purityZStepGrowth
    shrink = self.params.purityZStepShrink
    min_step = self.params.purityZMinStep
    purity_tol = self.params.purityZPurityTolerance
    max_evaluations = self.params.purityMaxEvaluations

    evaluated = {}

    best_z = None
    best_purity = -np.inf
    best_state = None

    z_history = []
    purity_history = []
    error_history = []

    def evaluate(z):
        nonlocal best_z
        nonlocal best_purity
        nonlocal best_state

        # Reuse already evaluated points
        key = float(z)

        if key in evaluated:
            return evaluated[key]

        purity, candidate_reconstruction = self._evaluatePurityAtZ(z)
        candidate_error = float(
            np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
        )

        evaluated[key] = purity

        z_history.append(z)
        purity_history.append(purity)
        error_history.append(candidate_error)
        tqdm.tqdm.write(
            f"z = {z * 1e3:.6f} mm | "
            f"purity = {purity:.6f} | "
            f"error = {candidate_error:.6e}"
        )

        # show every evaluated candidate live, as the fixed-grid scan does
        self._showCandidate(candidate_reconstruction, purity)

        # Store best candidate state
        if purity > best_purity:
            best_purity = purity
            best_z = z

            best_state = {
                "object": asNumpyArray(candidate_reconstruction.object).copy(),
                "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                "purityProbe": purity,
                # object grid of this candidate; see restore below
                "No": candidate_reconstruction.No,
                "shape_O": candidate_reconstruction.shape_O,
                "initialGuessObject": asNumpyArray(
                    candidate_reconstruction.initialGuessObject
                ).copy(),
            }

            if hasattr(
                candidate_reconstruction,
                "encoder_corrected",
            ):
                best_state["encoder_corrected"] = asNumpyArray(
                    candidate_reconstruction.encoder_corrected
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectMomentum",
            ):
                best_state["objectMomentum"] = asNumpyArray(
                    candidate_reconstruction.objectMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeMomentum",
            ):
                best_state["probeMomentum"] = asNumpyArray(
                    candidate_reconstruction.probeMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectBuffer",
            ):
                best_state["objectBuffer"] = asNumpyArray(
                    candidate_reconstruction.objectBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeBuffer",
            ):
                best_state["probeBuffer"] = asNumpyArray(
                    candidate_reconstruction.probeBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "error",
            ):
                best_state["error"] = np.asarray(
                    asNumpyArray(candidate_reconstruction.error)
                ).copy()

            tqdm.tqdm.write(
                f"NEW BEST: z = {best_z * 1e3:.6f} mm | purity = {best_purity:.6f}"
            )

        return purity

    tqdm.tqdm.write("")
    tqdm.tqdm.write("Starting adaptive purity-based z scan")
    tqdm.tqdm.write(
        f"Initial z = {z0 * 1e3:.6f} mm | initial step = {step * 1e6:.1f} µm"
    )
    tqdm.tqdm.write("")

    # --------------------------------------------------------------
    # 1. Initial three-point evaluation
    # --------------------------------------------------------------

    p0 = evaluate(z0)

    z_left = z0 - step
    z_right = z0 + step

    p_left = evaluate(z_left)
    p_right = evaluate(z_right)

    evaluations = len(evaluated)

    # --------------------------------------------------------------
    # 2. Determine initial uphill direction
    # --------------------------------------------------------------

    if p_left > p0 and p_left >= p_right:
        direction = -1

    elif p_right > p0 and p_right > p_left:
        direction = +1

    else:
        direction = 0

    # --------------------------------------------------------------
    # 3. Expansion phase
    # --------------------------------------------------------------

    if direction != 0:
        current_z = z0 + direction * step
        current_purity = evaluate(current_z)

        while evaluations < max_evaluations:
            step *= growth

            next_z = current_z + direction * step
            next_purity = evaluate(next_z)

            evaluations = len(evaluated)

            improvement = next_purity - current_purity

            if improvement > purity_tol:
                current_z = next_z
                current_purity = next_purity
                continue

            # Purity stopped increasing:
            # maximum should now be bracketed.
            break

    # --------------------------------------------------------------
    # 4. Refinement phase
    # --------------------------------------------------------------

    step *= shrink

    while step >= min_step and len(evaluated) < max_evaluations:
        left_z = best_z - step
        right_z = best_z + step

        # evaluate() raises best_purity as soon as it sees a better point, so
        # compare against the best from before this round
        best_before = best_purity

        left_purity = evaluate(left_z)

        if len(evaluated) >= max_evaluations:
            break

        right_purity = evaluate(right_z)

        # If neither side significantly improves the best result,
        # reduce the search step.
        if (
            left_purity <= best_before + purity_tol
            and right_purity <= best_before + purity_tol
        ):
            step *= shrink
            continue

        # A better point was found. Keep the current step and
        # continue refining around the new best position.

    # --------------------------------------------------------------
    # Safety check
    # --------------------------------------------------------------

    if best_state is None:
        raise RuntimeError("Adaptive purity z scan did not produce a valid result.")

    # --------------------------------------------------------------
    # Restore best candidate
    # --------------------------------------------------------------

    self.reconstruction.zo = best_z
    # each candidate is a new Reconstruction whose object grid was sized for
    # its own z / wavelength; restore that grid with the object, or positions
    # are centred for a different No and later engines size their momentum
    # arrays from the old initialGuessObject
    self.reconstruction.No = best_state["No"]
    self.reconstruction.shape_O = best_state["shape_O"]
    self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
    self.reconstruction.object = best_state["object"]
    self.reconstruction.probe = best_state["probe"]
    self.reconstruction.purityProbe = best_state["purityProbe"]

    if "encoder_corrected" in best_state:
        self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

    if "objectMomentum" in best_state:
        self.reconstruction.objectMomentum = best_state["objectMomentum"]

    if "probeMomentum" in best_state:
        self.reconstruction.probeMomentum = best_state["probeMomentum"]

    if "objectBuffer" in best_state:
        self.reconstruction.objectBuffer = best_state["objectBuffer"]

    if "probeBuffer" in best_state:
        self.reconstruction.probeBuffer = best_state["probeBuffer"]

    if "error" in best_state:
        self.reconstruction.error = best_state["error"]

    # --------------------------------------------------------------
    # Store results
    # --------------------------------------------------------------

    order = np.argsort(z_history)

    self.purityZValues = np.asarray(z_history)[order]
    self.purityZMetrics = np.asarray(purity_history)[order]
    self.purityZErrors = np.asarray(error_history)[order]

    self.purityBestZ = best_z
    self.purityBestValue = best_purity

    self.showReconstruction(
        self.numIterations - 1,
        force=True,
    )

    # --------------------------------------------------------------
    # Summary
    # --------------------------------------------------------------

    tqdm.tqdm.write("=" * 60)
    tqdm.tqdm.write("Adaptive purity-based z scan finished")
    tqdm.tqdm.write(f"Best z      = {best_z * 1e3:.6f} mm")
    tqdm.tqdm.write(f"Best Δz     = {(best_z - z0) * 1e6:+.2f} µm")
    tqdm.tqdm.write(f"Best purity = {best_purity:.6f}")
    tqdm.tqdm.write(f"Evaluations = {len(evaluated)}")
    tqdm.tqdm.write("=" * 60)

    return best_z, best_purity

purityWavelengthScan()

Perform a fixed-grid purity-based wavelength calibration.

Candidate wavelengths are evaluated over a uniformly spaced range defined by params.purityWavelengthScanRange and params.purityWavelengthScanPoints. The wavelength yielding the highest reconstructed probe purity is retained.

Returns:

Type Description
tuple

(best_wavelength, best_purity).

See Also

purityZScan Fixed-grid purity-based axial calibration.

Source code in PtyLab/Engines/purityPIE.py
def purityWavelengthScan(self):
    """
    Perform a fixed-grid purity-based wavelength calibration.

    Candidate wavelengths are evaluated over a uniformly spaced range defined
    by `params.purityWavelengthScanRange` and
    `params.purityWavelengthScanPoints`. The wavelength yielding the highest
    reconstructed probe purity is retained.

    Returns:
        tuple:
            `(best_wavelength, best_purity)`.

    See Also:
                `purityZScan`
                    Fixed-grid purity-based axial calibration.
    """

    if self.reconstruction.npsm < 2:
        raise ValueError(
            "Purity-based wavelength scanning requires at least two probe modes "
            "(reconstruction.npsm >= 2)."
        )

    wavelength0 = float(self.reconstruction.wavelength)

    self.purityWavelengthInitialGuess = wavelength0

    wavelength_values = np.linspace(
        wavelength0 - self.params.purityWavelengthScanRange,
        wavelength0 + self.params.purityWavelengthScanRange,
        self.params.purityWavelengthScanPoints,
    )

    purity_values = []
    error_values = []

    best_purity = -np.inf
    best_wavelength = wavelength0
    best_state = None

    tqdm.tqdm.write("")
    tqdm.tqdm.write("Starting purity-based wavelength scan")

    tqdm.tqdm.write(
        f"Initial wavelength = "
        f"{wavelength0 * 1e9:.6f} nm | "
        f"range = ±"
        f"{self.params.purityWavelengthScanRange * 1e9:.4f} nm | "
        f"points = {len(wavelength_values)} | "
        f"iterations/wavelength = {self.numIterations}"
    )

    tqdm.tqdm.write("")

    for wavelength_index, wavelength in enumerate(wavelength_values):
        delta_wavelength_nm = (wavelength - wavelength0) * 1e9

        tqdm.tqdm.write(
            f"[{wavelength_index + 1}/"
            f"{len(wavelength_values)}] "
            f"Reconstructing wavelength = "
            f"{wavelength * 1e9:.6f} nm "
            f"(Δλ = {delta_wavelength_nm:+.4f} nm)"
        )

        (
            purity,
            candidate_reconstruction,
        ) = self._evaluatePurityAtWavelength(wavelength)

        candidate_error = float(
            np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
        )

        purity_values.append(purity)

        error_values.append(candidate_error)

        tqdm.tqdm.write(
            f"    Probe purity = {purity:.6f} | "
            f"reconstruction error = {candidate_error:.6e}"
        )

        # Update monitor with current candidate
        self._showCandidate(candidate_reconstruction, purity)

        if purity > best_purity:
            best_purity = purity
            best_wavelength = wavelength

            best_state = {
                "object": asNumpyArray(candidate_reconstruction.object).copy(),
                "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                "purityProbe": purity,
                # object grid of this candidate; see restore below
                "No": candidate_reconstruction.No,
                "shape_O": candidate_reconstruction.shape_O,
                "initialGuessObject": asNumpyArray(
                    candidate_reconstruction.initialGuessObject
                ).copy(),
                "dxp": float(candidate_reconstruction.dxp),
            }

            if hasattr(
                candidate_reconstruction,
                "spectralDensity",
            ):
                best_state["spectralDensity"] = np.asarray(
                    candidate_reconstruction.spectralDensity
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "encoder_corrected",
            ):
                best_state["encoder_corrected"] = asNumpyArray(
                    candidate_reconstruction.encoder_corrected
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectMomentum",
            ):
                best_state["objectMomentum"] = asNumpyArray(
                    candidate_reconstruction.objectMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeMomentum",
            ):
                best_state["probeMomentum"] = asNumpyArray(
                    candidate_reconstruction.probeMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectBuffer",
            ):
                best_state["objectBuffer"] = asNumpyArray(
                    candidate_reconstruction.objectBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeBuffer",
            ):
                best_state["probeBuffer"] = asNumpyArray(
                    candidate_reconstruction.probeBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "error",
            ):
                best_state["error"] = np.asarray(
                    asNumpyArray(candidate_reconstruction.error)
                ).copy()

            tqdm.tqdm.write(
                f"    NEW BEST: wavelength = "
                f"{best_wavelength * 1e9:.6f} nm | "
                f"purity = {best_purity:.6f}"
            )

        tqdm.tqdm.write("")

    if best_state is None:
        raise RuntimeError(
            "Purity wavelength scan did not produce a valid purity value."
        )

    # Restore best candidate
    self.reconstruction.wavelength = best_wavelength

    self.reconstruction.dxp = best_state["dxp"]

    if "spectralDensity" in best_state:
        self.reconstruction.spectralDensity = best_state["spectralDensity"]

    # each candidate is a new Reconstruction whose object grid was sized for
    # its own z / wavelength; restore that grid with the object, or positions
    # are centred for a different No and later engines size their momentum
    # arrays from the old initialGuessObject
    self.reconstruction.No = best_state["No"]
    self.reconstruction.shape_O = best_state["shape_O"]
    self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
    self.reconstruction.object = best_state["object"]

    self.reconstruction.probe = best_state["probe"]

    self.reconstruction.purityProbe = best_state["purityProbe"]

    if "encoder_corrected" in best_state:
        self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

    if "objectMomentum" in best_state:
        self.reconstruction.objectMomentum = best_state["objectMomentum"]

    if "probeMomentum" in best_state:
        self.reconstruction.probeMomentum = best_state["probeMomentum"]

    if "objectBuffer" in best_state:
        self.reconstruction.objectBuffer = best_state["objectBuffer"]

    if "probeBuffer" in best_state:
        self.reconstruction.probeBuffer = best_state["probeBuffer"]

    if "error" in best_state:
        self.reconstruction.error = best_state["error"]

    # Store scan results
    self.purityWavelengthValues = np.asarray(wavelength_values)

    self.purityWavelengthMetrics = np.asarray(purity_values)

    self.purityWavelengthErrors = np.asarray(error_values)

    self.purityBestWavelength = best_wavelength

    self.purityBestWavelengthValue = best_purity

    self.showReconstruction(
        self.numIterations - 1,
        force=True,
    )

    tqdm.tqdm.write("=" * 60)
    tqdm.tqdm.write("Purity-based wavelength scan finished")

    tqdm.tqdm.write(f"Best wavelength = {best_wavelength * 1e9:.6f} nm")

    tqdm.tqdm.write(
        f"Best Δλ         = {(best_wavelength - wavelength0) * 1e9:+.4f} nm"
    )

    tqdm.tqdm.write(f"Best purity     = {best_purity:.6f}")

    tqdm.tqdm.write("=" * 60)

    return (
        best_wavelength,
        best_purity,
    )

adaptivePurityWavelengthScan()

Perform an adaptive purity-based wavelength calibration.

The search starts from the current wavelength, expands the step in the direction of increasing probe purity, and then refines around the best candidate using progressively smaller steps.

Returns:

Type Description
tuple

(best_wavelength, best_purity).

See Also

adaptivePurityZScan adaptive stepsize purity-based axial distance calibration.

Source code in PtyLab/Engines/purityPIE.py
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
def adaptivePurityWavelengthScan(self):
    """
    Perform an adaptive purity-based wavelength calibration.

    The search starts from the current wavelength, expands the step in the
    direction of increasing probe purity, and then refines around the best
    candidate using progressively smaller steps.

    Returns:
        tuple:
            `(best_wavelength, best_purity)`.

    See Also:
                `adaptivePurityZScan`
                    adaptive stepsize purity-based axial distance calibration.
    """

    if self.reconstruction.npsm < 2:
        raise ValueError(
            "Purity-based wavelength scanning requires at least two probe modes "
            "(reconstruction.npsm >= 2)."
        )

    wavelength0 = float(self.reconstruction.wavelength)

    self.purityWavelengthInitialGuess = wavelength0

    step = self.params.purityWavelengthInitialStep
    growth = self.params.purityWavelengthStepGrowth
    shrink = self.params.purityWavelengthStepShrink
    min_step = self.params.purityWavelengthMinStep
    purity_tol = self.params.purityWavelengthPurityTolerance
    max_evaluations = self.params.purityMaxEvaluations

    evaluated = {}

    best_wavelength = None
    best_purity = -np.inf
    best_state = None

    wavelength_history = []
    purity_history = []
    error_history = []

    def evaluate(wavelength):

        nonlocal best_wavelength
        nonlocal best_purity
        nonlocal best_state

        if wavelength <= 0:
            return -np.inf

        key = float(wavelength)

        if key in evaluated:
            return evaluated[key]

        (
            purity,
            candidate_reconstruction,
        ) = self._evaluatePurityAtWavelength(wavelength)

        candidate_error = float(
            np.asarray(asNumpyArray(candidate_reconstruction.error)).reshape(-1)[-1]
        )

        evaluated[key] = purity

        wavelength_history.append(wavelength)

        purity_history.append(purity)

        error_history.append(candidate_error)

        tqdm.tqdm.write(
            f"wavelength = {wavelength * 1e9:.6f} nm | "
            f"purity = {purity:.6f} | "
            f"error = {candidate_error:.6e}"
        )

        # show every evaluated candidate live, as the fixed-grid scan does
        self._showCandidate(candidate_reconstruction, purity)

        if purity > best_purity:
            best_purity = purity
            best_wavelength = wavelength

            best_state = {
                "object": asNumpyArray(candidate_reconstruction.object).copy(),
                "probe": asNumpyArray(candidate_reconstruction.probe).copy(),
                "purityProbe": purity,
                # object grid of this candidate; see restore below
                "No": candidate_reconstruction.No,
                "shape_O": candidate_reconstruction.shape_O,
                "initialGuessObject": asNumpyArray(
                    candidate_reconstruction.initialGuessObject
                ).copy(),
                "dxp": float(candidate_reconstruction.dxp),
            }

            if hasattr(
                candidate_reconstruction,
                "spectralDensity",
            ):
                best_state["spectralDensity"] = np.asarray(
                    candidate_reconstruction.spectralDensity
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "encoder_corrected",
            ):
                best_state["encoder_corrected"] = asNumpyArray(
                    candidate_reconstruction.encoder_corrected
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectMomentum",
            ):
                best_state["objectMomentum"] = asNumpyArray(
                    candidate_reconstruction.objectMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeMomentum",
            ):
                best_state["probeMomentum"] = asNumpyArray(
                    candidate_reconstruction.probeMomentum
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "objectBuffer",
            ):
                best_state["objectBuffer"] = asNumpyArray(
                    candidate_reconstruction.objectBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "probeBuffer",
            ):
                best_state["probeBuffer"] = asNumpyArray(
                    candidate_reconstruction.probeBuffer
                ).copy()

            if hasattr(
                candidate_reconstruction,
                "error",
            ):
                best_state["error"] = np.asarray(
                    asNumpyArray(candidate_reconstruction.error)
                ).copy()

            tqdm.tqdm.write(
                f"NEW BEST: wavelength = "
                f"{best_wavelength * 1e9:.6f} nm | "
                f"purity = {best_purity:.6f}"
            )

        return purity

    tqdm.tqdm.write("")
    tqdm.tqdm.write("Starting adaptive purity-based wavelength scan")

    tqdm.tqdm.write(
        f"Initial wavelength = "
        f"{wavelength0 * 1e9:.6f} nm | "
        f"initial step = {step * 1e9:.4f} nm"
    )

    tqdm.tqdm.write("")

    # ------------------------------------------------------------------
    # 1. Initial three-point evaluation
    # ------------------------------------------------------------------

    p0 = evaluate(wavelength0)

    wavelength_left = wavelength0 - step

    wavelength_right = wavelength0 + step

    p_left = evaluate(wavelength_left)

    p_right = evaluate(wavelength_right)

    # ------------------------------------------------------------------
    # 2. Determine uphill direction
    # ------------------------------------------------------------------

    if p_left > p0 and p_left >= p_right:
        direction = -1

    elif p_right > p0 and p_right > p_left:
        direction = +1

    else:
        direction = 0

    # ------------------------------------------------------------------
    # 3. Expansion phase
    # ------------------------------------------------------------------

    if direction != 0:
        current_wavelength = wavelength0 + direction * step

        current_purity = evaluate(current_wavelength)

        while len(evaluated) < max_evaluations:
            step *= growth

            next_wavelength = current_wavelength + direction * step

            if next_wavelength <= 0:
                break

            next_purity = evaluate(next_wavelength)

            improvement = next_purity - current_purity

            if improvement > purity_tol:
                current_wavelength = next_wavelength

                current_purity = next_purity

                continue

            break

    # ------------------------------------------------------------------
    # 4. Refinement phase
    # ------------------------------------------------------------------

    step *= shrink

    while step >= min_step and len(evaluated) < max_evaluations:
        left_wavelength = best_wavelength - step

        right_wavelength = best_wavelength + step

        # evaluate() raises best_purity as soon as it sees a better point, so
        # compare against the best from before this round
        best_before = best_purity

        if left_wavelength > 0:
            left_purity = evaluate(left_wavelength)
        else:
            left_purity = -np.inf

        if len(evaluated) >= max_evaluations:
            break

        right_purity = evaluate(right_wavelength)

        if (
            left_purity <= best_before + purity_tol
            and right_purity <= best_before + purity_tol
        ):
            step *= shrink
            continue

    if best_state is None:
        raise RuntimeError(
            "Adaptive purity wavelength scan did not produce a valid result."
        )

    # ------------------------------------------------------------------
    # Restore best candidate
    # ------------------------------------------------------------------

    self.reconstruction.wavelength = best_wavelength

    self.reconstruction.dxp = best_state["dxp"]

    if "spectralDensity" in best_state:
        self.reconstruction.spectralDensity = best_state["spectralDensity"]

    # each candidate is a new Reconstruction whose object grid was sized for
    # its own z / wavelength; restore that grid with the object, or positions
    # are centred for a different No and later engines size their momentum
    # arrays from the old initialGuessObject
    self.reconstruction.No = best_state["No"]
    self.reconstruction.shape_O = best_state["shape_O"]
    self.reconstruction.initialGuessObject = best_state["initialGuessObject"]
    self.reconstruction.object = best_state["object"]

    self.reconstruction.probe = best_state["probe"]

    self.reconstruction.purityProbe = best_state["purityProbe"]

    if "encoder_corrected" in best_state:
        self.reconstruction.encoder_corrected = best_state["encoder_corrected"]

    if "objectMomentum" in best_state:
        self.reconstruction.objectMomentum = best_state["objectMomentum"]

    if "probeMomentum" in best_state:
        self.reconstruction.probeMomentum = best_state["probeMomentum"]

    if "objectBuffer" in best_state:
        self.reconstruction.objectBuffer = best_state["objectBuffer"]

    if "probeBuffer" in best_state:
        self.reconstruction.probeBuffer = best_state["probeBuffer"]

    if "error" in best_state:
        self.reconstruction.error = best_state["error"]

    # ------------------------------------------------------------------
    # Store results
    # ------------------------------------------------------------------

    order = np.argsort(wavelength_history)

    self.purityWavelengthValues = np.asarray(wavelength_history)[order]

    self.purityWavelengthMetrics = np.asarray(purity_history)[order]

    self.purityWavelengthErrors = np.asarray(error_history)[order]

    self.purityBestWavelength = best_wavelength

    self.purityBestWavelengthValue = best_purity

    self.showReconstruction(
        self.numIterations - 1,
        force=True,
    )

    tqdm.tqdm.write("=" * 60)
    tqdm.tqdm.write("Adaptive purity-based wavelength scan finished")

    tqdm.tqdm.write(f"Best wavelength = {best_wavelength * 1e9:.6f} nm")

    tqdm.tqdm.write(
        f"Best Δλ         = {(best_wavelength - wavelength0) * 1e9:+.4f} nm"
    )

    tqdm.tqdm.write(f"Best purity     = {best_purity:.6f}")

    tqdm.tqdm.write(f"Evaluations     = {len(evaluated)}")

    tqdm.tqdm.write("=" * 60)

    return (
        best_wavelength,
        best_purity,
    )

zPIE

Bases: BaseEngine

Ptychographic iterative engine with axial-distance refinement.

zPIE extends the standard PIE reconstruction by jointly refining the object/probe estimate and the axial propagation distance \(z\).1

During reconstruction, a set of candidate axial offsets is generated around the current propagation distance:

\[ \Delta z_k \in [-\mathrm{DoF},\, \mathrm{DoF}] \]

For each candidate offset, either the reconstructed object or probe is propagated to the corresponding defocus plane using angular-spectrum propagation. The quantity used for axial optimization is selected through focusObject.

A total-variation-based focus metric is evaluated from the propagated complex field:

\[ M_k = \sum \sqrt{|\nabla_x U_k|^2 + |\nabla_y U_k|^2 + \epsilon} \]

where \(U_k\) is the propagated field at axial offset \(\Delta z_k\) and \(\epsilon\) is a small numerical stabilization term.

The axial feedback is calculated from the merit values as

\[ f_z = \frac{\sum_k \Delta z_k M_k}{\sum_k M_k} \]

and accumulated using a momentum-like update:

\[ m_z^{(n)} = \gamma m_z^{(n-1)} + \eta f_z \]

followed by

\[ z^{(n+1)} = z^{(n)} + m_z^{(n)} \]

where \(\gamma\) is zPIEfriction and \(\eta\) is zPIEgradientStepSize.

The updated axial distance is stored in reconstruction.zo. For propagation schemes whose sampling depends explicitly on distance, the corresponding propagation coordinates are updated after each axial correction.

The object and probe are subsequently updated using the standard PIE object and probe update rules.

Parameters specific to zPIE include:

  • DoF: depth-of-field scale used to define the axial search range.
  • zPIEgradientStepSize: strength of the axial feedback update.
  • zPIEfriction: momentum retention factor for axial refinement.
  • focusObject: if True, evaluate the focus metric on the object; otherwise evaluate it on the probe.
  • zMomentun: accumulated axial momentum.

  1. L. Loetgering, M. Du, K. S. E. Eikema, and S. Witte, "zPIE: an autofocusing algorithm for ptychography," Optics Letters 45, 2030-2033 (2020). https://doi.org/10.1364/OL.389492 ↩

Source code in PtyLab/Engines/zPIE.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
class zPIE(BaseEngine):
    r"""
    Ptychographic iterative engine with axial-distance refinement.

    zPIE extends the standard PIE reconstruction by jointly refining the
    object/probe estimate and the axial propagation distance $z$.[^loetgering2020]

    During reconstruction, a set of candidate axial offsets is generated
    around the current propagation distance:

    $$
    \Delta z_k \in [-\mathrm{DoF},\, \mathrm{DoF}]
    $$

    For each candidate offset, either the reconstructed object or probe is
    propagated to the corresponding defocus plane using angular-spectrum
    propagation. The quantity used for axial optimization is selected through
    `focusObject`.

    A total-variation-based focus metric is evaluated from the propagated
    complex field:

    $$
    M_k = \sum \sqrt{|\nabla_x U_k|^2 + |\nabla_y U_k|^2 + \epsilon}
    $$

    where $U_k$ is the propagated field at axial offset $\Delta z_k$ and
    $\epsilon$ is a small numerical stabilization term.

    The axial feedback is calculated from the merit values as

    $$
    f_z = \frac{\sum_k \Delta z_k M_k}{\sum_k M_k}
    $$

    and accumulated using a momentum-like update:

    $$
    m_z^{(n)} = \gamma m_z^{(n-1)} + \eta f_z
    $$

    followed by

    $$
    z^{(n+1)} = z^{(n)} + m_z^{(n)}
    $$

    where $\gamma$ is `zPIEfriction` and $\eta$ is
    `zPIEgradientStepSize`.

    The updated axial distance is stored in `reconstruction.zo`. For
    propagation schemes whose sampling depends explicitly on distance, the
    corresponding propagation coordinates are updated after each axial
    correction.

    The object and probe are subsequently updated using the standard PIE
    object and probe update rules.

    Parameters specific to zPIE include:

    - `DoF`: depth-of-field scale used to define the axial search range.
    - `zPIEgradientStepSize`: strength of the axial feedback update.
    - `zPIEfriction`: momentum retention factor for axial refinement.
    - `focusObject`: if `True`, evaluate the focus metric on the object;
      otherwise evaluate it on the probe.
    - `zMomentun`: accumulated axial momentum.

    [^loetgering2020]: L. Loetgering, M. Du, K. S. E. Eikema, and S. Witte,
        "zPIE: an autofocusing algorithm for ptychography,"
        Optics Letters 45, 2030-2033 (2020).
        https://doi.org/10.1364/OL.389492
    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        # This contains reconstruction parameters that are specific to the reconstruction
        # but not necessarily to ePIE reconstruction
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("zPIE")
        self.logger.info("Sucesfully created zPIE zPIE_engine")
        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        self.initializeReconstructionParams()
        self.name = "zPIE"

    def initializeReconstructionParams(self):
        """
        Initialize zPIE-specific reconstruction parameters.

        The default parameters are:

        - `betaProbe = 0.25`:
        Probe update step size used during the PIE reconstruction.

        - `betaObject = 0.25`:
        Object update step size used during the PIE reconstruction.

        - `numIterations = 50`:
        Number of reconstruction iterations.

        - `DoF = reconstruction.DoF`:
        Depth-of-field scale used to define the axial search interval.

        - `zPIEgradientStepSize = 100`:
        Scaling factor applied to the axial feedback term when updating the
        sample-to-detector distance.

        - `zPIEfriction = 0.7`:
        Momentum retention factor used for axial-distance refinement.

        - `focusObject = True`:
        If `True`, evaluate the axial focus metric on the reconstructed object.
        If `False`, evaluate it on the reconstructed probe.

        - `zMomentun = 0`:
        Initial accumulated axial momentum used for iterative z refinement.

        These values can be modified after creating the zPIE engine and before
        calling `reconstruct()`.
        """
        self.betaProbe = 0.25
        self.betaObject = 0.25
        self.numIterations = 50
        self.DoF = self.reconstruction.DoF
        self.zPIEgradientStepSize = 100  # gradient step size for axial position correction (typical range [1, 100])
        self.zPIEfriction = 0.7
        self.focusObject = True
        self.zMomentun = 0

    def show_defocus(self, viewer=None, scanrange_times_dof=1000, N_points=10):
        r"""
        Visualize a defocus stack of the reconstructed object.

        A set of axial offsets is generated symmetrically around the current
        reconstruction plane:

        $$
        \Delta z_k \in [-s\,\mathrm{DoF},\; s\,\mathrm{DoF}]
        $$

        where `s` is given by `scanrange_times_dof` and `DoF` is taken from
        `reconstruction.DoF`.

        For each axial offset, the current reconstructed object is propagated
        using angular-spectrum propagation (`aspw`). The propagated intensity
        is calculated as the squared magnitude of the complex field and collected
        into a defocus stack.

        The resulting stack is displayed in a napari viewer. If no viewer is
        provided, a new napari viewer is created automatically.

        Args:
            viewer (napari.Viewer, optional):
                Existing napari viewer to which the defocus stack is added.
                If `None`, a new viewer is created.

            scanrange_times_dof (float, optional):
                Half-width of the axial scan expressed in units of the
                reconstruction depth of field. Default is `1000`.

            N_points (int, optional):
                Number of equally spaced axial positions in the defocus stack.
                Default is `10`.

        Raises:
            ImportError:
                If `viewer` is `None` and napari is not installed.

        Notes:
            This function is intended as a diagnostic visualization tool and does
            not modify the reconstructed object or the current axial distance.
        """
        z = np.linspace(-1, 1, N_points) * scanrange_times_dof * self.reconstruction.DoF

        from PtyLab.Operators.Operators import aspw

        reconstruction = self.reconstruction
        defocii = np.abs(
            np.array(
                [
                    aspw(
                        reconstruction.object,
                        dz,
                        reconstruction.wavelength,
                        reconstruction.Lo,
                        is_FT=False,
                    )[0]
                    for dz in z
                ]
            )
            ** 2
        )

        if viewer is None:
            # currently a hacky way for this, these napari implementations must
            # later be moved to an optional sub-package.
            try:
                import napari

                viewer = napari.Viewer()
            except ImportError:
                msg = "Install napari to access this `NapariMonitor` implementation"
                raise ImportError(msg)

        viewer.add_image(defocii)

    def reconstruct(self, experimentalData=None, reconstruction=None):
        r"""
        Run the zPIE reconstruction with iterative axial-distance refinement.

        The reconstruction jointly updates the object, probe, and
        sample-to-detector propagation distance. Before the iterative loop starts,
        the experimental data and reconstruction state are updated if new objects
        are supplied, followed by the standard reconstruction preparation.

        During each zPIE iteration, a set of candidate axial offsets is generated
        around the current propagation distance:

        $$
        \Delta z_k \in [-\mathrm{DoF},\;\mathrm{DoF}]
        $$

        using 11 equally spaced candidate positions.

        Depending on `focusObject`, either the reconstructed object or probe is
        propagated to each candidate defocus plane using angular-spectrum
        propagation. A total-variation-based merit value is calculated for each
        propagated field.

        The axial feedback is then obtained from the weighted candidate offsets:

        $$
        f_z = \frac{\sum_k \Delta z_k M_k}{\sum_k M_k}
        $$

        where $M_k$ is the focus merit evaluated at candidate offset
        $\Delta z_k$.

        The feedback is accumulated through the axial momentum update

        $$
        m_z^{(n)} = \gamma m_z^{(n-1)} + \eta f_z
        $$

        where $\gamma$ is `zPIEfriction` and $\eta$ is
        `zPIEgradientStepSize`. The propagation distance is then updated as

        $$
        z^{(n+1)} = z^{(n)} + m_z^{(n)}
        $$

        After the axial update, a standard PIE reconstruction loop is performed
        over all scan positions. The exit surface wave is calculated from the
        current object patch and probe, followed by the intensity constraint and
        object/probe updates.

        The current axial distance is stored during reconstruction in
        `reconstruction.zHistory`. The total-variation merit values and candidate
        axial offsets are also stored in `reconstruction.merit` and
        `reconstruction.dz` for diagnostic use.

        For propagation schemes whose object-plane sampling depends explicitly on
        the propagation distance, the sampling `reconstruction.dxp` is updated
        after each axial correction.

        At the end of each iteration, reconstruction error metrics and enabled
        constraints are evaluated, followed by an update of the reconstruction
        monitor.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use. If provided, it replaces the dataset
                currently attached to the engine.

            reconstruction (Reconstruction, optional):
                Reconstruction state to optimize. If provided, it replaces the
                reconstruction currently attached to the engine.

        See Also:
            `show_defocus`
                Visualize the reconstructed object over a range of axial defocus
                positions.

            `objectPatchUpdate`
                Update the reconstructed object patch during the PIE loop.

            `probeUpdate`
                Update the reconstructed probe during the PIE loop.
        """

        self.changeExperimentalData(experimentalData)
        self.changeOptimizable(reconstruction)
        self._prepareReconstruction()

        ###################################### actual reconstruction zPIE_engine #######################################

        xp = getArrayModule(self.reconstruction.object)
        if not hasattr(self.reconstruction, "zHistory"):
            self.reconstruction.zHistory = []

        # preallocate grids
        if self.params.propagatorType == "ASP":
            n = self.reconstruction.Np * 1
        else:
            n = 2 * self.reconstruction.Np

        if not self.focusObject:
            n = self.reconstruction.Np

        X, Y = xp.meshgrid(xp.arange(-n // 2, n // 2), xp.arange(-n // 2, n // 2))
        w = xp.exp(-((xp.sqrt(X**2 + Y**2) / self.reconstruction.Np) ** 4))

        self.pbar = trange(
            self.numIterations, desc="zPIE", file=sys.stdout, leave=True
        )  # in order to change description to the tqdm progress bar
        for loop in self.pbar:
            # set position order
            self.setPositionOrder()
            imProps = []

            # get positions
            if loop == 0:
                zNew = self.reconstruction.zo
                merit, dz = None, None
            else:
                # candidate defocus planes within one depth of field, as in PtyLab.m
                dz = np.linspace(-1, 1, 11) * self.DoF
                self.dz = dz

                merit = []
                # todo, mixed states implementation, check if more need to be put on GPU to speed up
                for k in np.arange(len(dz)):
                    imProp = None
                    if self.focusObject:
                        roi = slice(
                            self.reconstruction.No // 2 - n // 2,
                            self.reconstruction.No // 2 + n // 2,
                        )
                        # the window w fades the cropped object out towards the edges, so the
                        # periodic wrap-around of the FFT does not add edges to the TV metric
                        imProp, _ = aspw(
                            u=w * xp.squeeze(self.reconstruction.object[..., roi, roi]),
                            z=dz[k],
                            wavelength=self.reconstruction.wavelength,
                            L=self.reconstruction.dxo * n,
                            bandlimit=False,
                            is_FT=False,
                        )
                    else:
                        if self.reconstruction.nlambda == 1:
                            imProp, _ = aspw(
                                u=xp.squeeze(self.reconstruction.probe[..., :, :]),
                                z=dz[k],
                                wavelength=self.reconstruction.wavelength,
                                L=self.reconstruction.Lp,
                                is_FT=False,
                            )
                        else:
                            nlambda = self.reconstruction.nlambda // 2
                            imProp, _ = aspw(
                                xp.squeeze(
                                    self.reconstruction.probe[nlambda, ..., :, :]
                                ),
                                dz[k],
                                self.reconstruction.spectralDensity[nlambda],
                                self.reconstruction.Lp,
                                is_FT=False,
                            )
                    imProps.append(asNumpyArray(imProp))
                    # TV approach
                    aleph = 1e-2
                    gradx = xp.roll(imProp, -1, axis=-1) - xp.roll(imProp, 1, axis=-1)
                    grady = xp.roll(imProp, -1, axis=-2) - xp.roll(imProp, 1, axis=-2)
                    merit.append(
                        xp.sum(xp.sqrt(abs(gradx) ** 2 + abs(grady) ** 2 + aleph))
                    )
                    # take a tiny break, we may overask the GPU
                    # yield 0, 0

                merit = asNumpyArray(xp.array(merit))
                if not hasattr(self.reconstruction, "TV_history"):
                    self.reconstruction.TV_history = []

                self.reconstruction.TV_history.append(float(merit[len(merit) // 2]))
                feedback = np.sum(dz * merit) / np.sum(
                    merit
                )  # at optimal z, feedback term becomes 0

                self.logger.debug("Step size: %s", feedback)
                self.zMomentun = (
                    self.zPIEfriction * self.zMomentun
                    + self.zPIEgradientStepSize * feedback
                )
                zNew = self.reconstruction.zo + self.zMomentun

            self.reconstruction.zHistory.append(self.reconstruction.zo)

            # print updated z
            self.pbar.set_description(
                "zPIE: update z = %.3f mm (dz = %.1f um)"
                % (self.reconstruction.zo * 1e3, self.zMomentun * 1e6)
            )

            # reset coordinates: the zo setter also rescales dxp = wavelength * zo / Ld, and the
            # positions follow from dxp; with ASP the sampling does not depend on z, so keep it
            dxp = self.reconstruction.dxp
            self.reconstruction.zo = zNew
            if self.params.propagatorType == "ASP":
                self.reconstruction.dxp = dxp
            ##################################################################################################################

            for positionLoop, positionIndex in enumerate(self.positionIndices):
                # print('Starting normal reconstruction loop')
                ### patch1 ###
                # get object patch
                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                # object update
                self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                    objectPatch, DELTA
                )

                # probe update
                self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)
            # yield positionLoop, positionIndex

            # get error metric
            self.getErrorMetrics()

            # apply Constraints
            self.applyConstraints(loop)
            # display it
            # self.showReconstruction(loop)

            # kept for `reconstruction.make_alignment_plot()`; the first iteration has no merit yet
            self.zNew = zNew
            if merit is not None:
                self.merit = merit
                self.reconstruction.merit = merit
                self.reconstruction.dz = dz

            # show reconstruction
            if False:
                if loop == 0:
                    figure, axes = plt.subplots(
                        1, 3, num=666, squeeze=True, clear=True, figsize=(5, 5)
                    )
                    ax = axes[0]
                    ax_score = axes[1]
                    ax.set_title("Estimated distance (object-camera)")
                    ax.set_xlabel("iteration")
                    ax.set_ylabel("estimated z (mm)")
                    ax.set_xscale("symlog")

                    ax_score.set_title("TV score")
                    ax_score.set_xlabel("Distance [um]")
                    ax_score.set_ylabel("TV")
                    (score_line,) = ax_score.plot(dz * 1e6, merit)
                    (line,) = ax.plot(0, zNew, "o-")
                    plt.tight_layout()
                    plt.show(block=False)

                elif np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
                    idx = np.linspace(
                        0,
                        np.log10(len(self.reconstruction.zHistory) - 1),
                        np.minimum(len(self.reconstruction.zHistory), 100),
                    )
                    idx = np.rint(10**idx).astype("int")

                    line.set_xdata(idx)
                    line.set_ydata(np.array(self.reconstruction.zHistory)[idx] * 1e3)

                    score_line.set_ydata(merit)
                    ax_score.set_ylim(merit.min() - 1, merit.max() + 1)
                    ax.set_xlim(0, np.max(idx))
                    ax.set_ylim(
                        np.min(self.reconstruction.zHistory) * 1e3,
                        np.max(self.reconstruction.zHistory) * 1e3,
                    )

                    figure.canvas.draw()
                    figure.canvas.flush_events()
            self.showReconstruction(loop)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        """
        Update the object patch using the standard ePIE object-update rule.

        This implementation is identical to `ePIE.objectPatchUpdate()`.

        See Also:
            `ePIE.objectPatchUpdate`
                Standard ePIE object update.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)

        frac = self.reconstruction.probe.conj() / xp.max(
            xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2, 3), keepdims=True
        )

    def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        """
        Update the probe using the standard ePIE probe-update rule.

        This implementation is identical to `ePIE.probeUpdate()`.

        See Also:
            `ePIE.probeUpdate`
                Standard ePIE probe update.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        frac = objectPatch.conj() / xp.max(
            xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))
        )
        r = self.reconstruction.probe + self.betaProbe * xp.sum(
            frac * DELTA, axis=(0, 1, 3), keepdims=True
        )
        return r

initializeReconstructionParams()

Initialize zPIE-specific reconstruction parameters.

The default parameters are:

  • betaProbe = 0.25: Probe update step size used during the PIE reconstruction.

  • betaObject = 0.25: Object update step size used during the PIE reconstruction.

  • numIterations = 50: Number of reconstruction iterations.

  • DoF = reconstruction.DoF: Depth-of-field scale used to define the axial search interval.

  • zPIEgradientStepSize = 100: Scaling factor applied to the axial feedback term when updating the sample-to-detector distance.

  • zPIEfriction = 0.7: Momentum retention factor used for axial-distance refinement.

  • focusObject = True: If True, evaluate the axial focus metric on the reconstructed object. If False, evaluate it on the reconstructed probe.

  • zMomentun = 0: Initial accumulated axial momentum used for iterative z refinement.

These values can be modified after creating the zPIE engine and before calling reconstruct().

Source code in PtyLab/Engines/zPIE.py
def initializeReconstructionParams(self):
    """
    Initialize zPIE-specific reconstruction parameters.

    The default parameters are:

    - `betaProbe = 0.25`:
    Probe update step size used during the PIE reconstruction.

    - `betaObject = 0.25`:
    Object update step size used during the PIE reconstruction.

    - `numIterations = 50`:
    Number of reconstruction iterations.

    - `DoF = reconstruction.DoF`:
    Depth-of-field scale used to define the axial search interval.

    - `zPIEgradientStepSize = 100`:
    Scaling factor applied to the axial feedback term when updating the
    sample-to-detector distance.

    - `zPIEfriction = 0.7`:
    Momentum retention factor used for axial-distance refinement.

    - `focusObject = True`:
    If `True`, evaluate the axial focus metric on the reconstructed object.
    If `False`, evaluate it on the reconstructed probe.

    - `zMomentun = 0`:
    Initial accumulated axial momentum used for iterative z refinement.

    These values can be modified after creating the zPIE engine and before
    calling `reconstruct()`.
    """
    self.betaProbe = 0.25
    self.betaObject = 0.25
    self.numIterations = 50
    self.DoF = self.reconstruction.DoF
    self.zPIEgradientStepSize = 100  # gradient step size for axial position correction (typical range [1, 100])
    self.zPIEfriction = 0.7
    self.focusObject = True
    self.zMomentun = 0

show_defocus(viewer=None, scanrange_times_dof=1000, N_points=10)

Visualize a defocus stack of the reconstructed object.

A set of axial offsets is generated symmetrically around the current reconstruction plane:

\[ \Delta z_k \in [-s\,\mathrm{DoF},\; s\,\mathrm{DoF}] \]

where s is given by scanrange_times_dof and DoF is taken from reconstruction.DoF.

For each axial offset, the current reconstructed object is propagated using angular-spectrum propagation (aspw). The propagated intensity is calculated as the squared magnitude of the complex field and collected into a defocus stack.

The resulting stack is displayed in a napari viewer. If no viewer is provided, a new napari viewer is created automatically.

Parameters:

Name Type Description Default
viewer Viewer

Existing napari viewer to which the defocus stack is added. If None, a new viewer is created.

None
scanrange_times_dof float

Half-width of the axial scan expressed in units of the reconstruction depth of field. Default is 1000.

1000
N_points int

Number of equally spaced axial positions in the defocus stack. Default is 10.

10

Raises:

Type Description
ImportError

If viewer is None and napari is not installed.

Notes

This function is intended as a diagnostic visualization tool and does not modify the reconstructed object or the current axial distance.

Source code in PtyLab/Engines/zPIE.py
def show_defocus(self, viewer=None, scanrange_times_dof=1000, N_points=10):
    r"""
    Visualize a defocus stack of the reconstructed object.

    A set of axial offsets is generated symmetrically around the current
    reconstruction plane:

    $$
    \Delta z_k \in [-s\,\mathrm{DoF},\; s\,\mathrm{DoF}]
    $$

    where `s` is given by `scanrange_times_dof` and `DoF` is taken from
    `reconstruction.DoF`.

    For each axial offset, the current reconstructed object is propagated
    using angular-spectrum propagation (`aspw`). The propagated intensity
    is calculated as the squared magnitude of the complex field and collected
    into a defocus stack.

    The resulting stack is displayed in a napari viewer. If no viewer is
    provided, a new napari viewer is created automatically.

    Args:
        viewer (napari.Viewer, optional):
            Existing napari viewer to which the defocus stack is added.
            If `None`, a new viewer is created.

        scanrange_times_dof (float, optional):
            Half-width of the axial scan expressed in units of the
            reconstruction depth of field. Default is `1000`.

        N_points (int, optional):
            Number of equally spaced axial positions in the defocus stack.
            Default is `10`.

    Raises:
        ImportError:
            If `viewer` is `None` and napari is not installed.

    Notes:
        This function is intended as a diagnostic visualization tool and does
        not modify the reconstructed object or the current axial distance.
    """
    z = np.linspace(-1, 1, N_points) * scanrange_times_dof * self.reconstruction.DoF

    from PtyLab.Operators.Operators import aspw

    reconstruction = self.reconstruction
    defocii = np.abs(
        np.array(
            [
                aspw(
                    reconstruction.object,
                    dz,
                    reconstruction.wavelength,
                    reconstruction.Lo,
                    is_FT=False,
                )[0]
                for dz in z
            ]
        )
        ** 2
    )

    if viewer is None:
        # currently a hacky way for this, these napari implementations must
        # later be moved to an optional sub-package.
        try:
            import napari

            viewer = napari.Viewer()
        except ImportError:
            msg = "Install napari to access this `NapariMonitor` implementation"
            raise ImportError(msg)

    viewer.add_image(defocii)

reconstruct(experimentalData=None, reconstruction=None)

Run the zPIE reconstruction with iterative axial-distance refinement.

The reconstruction jointly updates the object, probe, and sample-to-detector propagation distance. Before the iterative loop starts, the experimental data and reconstruction state are updated if new objects are supplied, followed by the standard reconstruction preparation.

During each zPIE iteration, a set of candidate axial offsets is generated around the current propagation distance:

\[ \Delta z_k \in [-\mathrm{DoF},\;\mathrm{DoF}] \]

using 11 equally spaced candidate positions.

Depending on focusObject, either the reconstructed object or probe is propagated to each candidate defocus plane using angular-spectrum propagation. A total-variation-based merit value is calculated for each propagated field.

The axial feedback is then obtained from the weighted candidate offsets:

\[ f_z = \frac{\sum_k \Delta z_k M_k}{\sum_k M_k} \]

where \(M_k\) is the focus merit evaluated at candidate offset \(\Delta z_k\).

The feedback is accumulated through the axial momentum update

\[ m_z^{(n)} = \gamma m_z^{(n-1)} + \eta f_z \]

where \(\gamma\) is zPIEfriction and \(\eta\) is zPIEgradientStepSize. The propagation distance is then updated as

\[ z^{(n+1)} = z^{(n)} + m_z^{(n)} \]

After the axial update, a standard PIE reconstruction loop is performed over all scan positions. The exit surface wave is calculated from the current object patch and probe, followed by the intensity constraint and object/probe updates.

The current axial distance is stored during reconstruction in reconstruction.zHistory. The total-variation merit values and candidate axial offsets are also stored in reconstruction.merit and reconstruction.dz for diagnostic use.

For propagation schemes whose object-plane sampling depends explicitly on the propagation distance, the sampling reconstruction.dxp is updated after each axial correction.

At the end of each iteration, reconstruction error metrics and enabled constraints are evaluated, followed by an update of the reconstruction monitor.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use. If provided, it replaces the dataset currently attached to the engine.

None
reconstruction Reconstruction

Reconstruction state to optimize. If provided, it replaces the reconstruction currently attached to the engine.

None
See Also

show_defocus Visualize the reconstructed object over a range of axial defocus positions.

objectPatchUpdate Update the reconstructed object patch during the PIE loop.

probeUpdate Update the reconstructed probe during the PIE loop.

Source code in PtyLab/Engines/zPIE.py
def reconstruct(self, experimentalData=None, reconstruction=None):
    r"""
    Run the zPIE reconstruction with iterative axial-distance refinement.

    The reconstruction jointly updates the object, probe, and
    sample-to-detector propagation distance. Before the iterative loop starts,
    the experimental data and reconstruction state are updated if new objects
    are supplied, followed by the standard reconstruction preparation.

    During each zPIE iteration, a set of candidate axial offsets is generated
    around the current propagation distance:

    $$
    \Delta z_k \in [-\mathrm{DoF},\;\mathrm{DoF}]
    $$

    using 11 equally spaced candidate positions.

    Depending on `focusObject`, either the reconstructed object or probe is
    propagated to each candidate defocus plane using angular-spectrum
    propagation. A total-variation-based merit value is calculated for each
    propagated field.

    The axial feedback is then obtained from the weighted candidate offsets:

    $$
    f_z = \frac{\sum_k \Delta z_k M_k}{\sum_k M_k}
    $$

    where $M_k$ is the focus merit evaluated at candidate offset
    $\Delta z_k$.

    The feedback is accumulated through the axial momentum update

    $$
    m_z^{(n)} = \gamma m_z^{(n-1)} + \eta f_z
    $$

    where $\gamma$ is `zPIEfriction` and $\eta$ is
    `zPIEgradientStepSize`. The propagation distance is then updated as

    $$
    z^{(n+1)} = z^{(n)} + m_z^{(n)}
    $$

    After the axial update, a standard PIE reconstruction loop is performed
    over all scan positions. The exit surface wave is calculated from the
    current object patch and probe, followed by the intensity constraint and
    object/probe updates.

    The current axial distance is stored during reconstruction in
    `reconstruction.zHistory`. The total-variation merit values and candidate
    axial offsets are also stored in `reconstruction.merit` and
    `reconstruction.dz` for diagnostic use.

    For propagation schemes whose object-plane sampling depends explicitly on
    the propagation distance, the sampling `reconstruction.dxp` is updated
    after each axial correction.

    At the end of each iteration, reconstruction error metrics and enabled
    constraints are evaluated, followed by an update of the reconstruction
    monitor.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use. If provided, it replaces the dataset
            currently attached to the engine.

        reconstruction (Reconstruction, optional):
            Reconstruction state to optimize. If provided, it replaces the
            reconstruction currently attached to the engine.

    See Also:
        `show_defocus`
            Visualize the reconstructed object over a range of axial defocus
            positions.

        `objectPatchUpdate`
            Update the reconstructed object patch during the PIE loop.

        `probeUpdate`
            Update the reconstructed probe during the PIE loop.
    """

    self.changeExperimentalData(experimentalData)
    self.changeOptimizable(reconstruction)
    self._prepareReconstruction()

    ###################################### actual reconstruction zPIE_engine #######################################

    xp = getArrayModule(self.reconstruction.object)
    if not hasattr(self.reconstruction, "zHistory"):
        self.reconstruction.zHistory = []

    # preallocate grids
    if self.params.propagatorType == "ASP":
        n = self.reconstruction.Np * 1
    else:
        n = 2 * self.reconstruction.Np

    if not self.focusObject:
        n = self.reconstruction.Np

    X, Y = xp.meshgrid(xp.arange(-n // 2, n // 2), xp.arange(-n // 2, n // 2))
    w = xp.exp(-((xp.sqrt(X**2 + Y**2) / self.reconstruction.Np) ** 4))

    self.pbar = trange(
        self.numIterations, desc="zPIE", file=sys.stdout, leave=True
    )  # in order to change description to the tqdm progress bar
    for loop in self.pbar:
        # set position order
        self.setPositionOrder()
        imProps = []

        # get positions
        if loop == 0:
            zNew = self.reconstruction.zo
            merit, dz = None, None
        else:
            # candidate defocus planes within one depth of field, as in PtyLab.m
            dz = np.linspace(-1, 1, 11) * self.DoF
            self.dz = dz

            merit = []
            # todo, mixed states implementation, check if more need to be put on GPU to speed up
            for k in np.arange(len(dz)):
                imProp = None
                if self.focusObject:
                    roi = slice(
                        self.reconstruction.No // 2 - n // 2,
                        self.reconstruction.No // 2 + n // 2,
                    )
                    # the window w fades the cropped object out towards the edges, so the
                    # periodic wrap-around of the FFT does not add edges to the TV metric
                    imProp, _ = aspw(
                        u=w * xp.squeeze(self.reconstruction.object[..., roi, roi]),
                        z=dz[k],
                        wavelength=self.reconstruction.wavelength,
                        L=self.reconstruction.dxo * n,
                        bandlimit=False,
                        is_FT=False,
                    )
                else:
                    if self.reconstruction.nlambda == 1:
                        imProp, _ = aspw(
                            u=xp.squeeze(self.reconstruction.probe[..., :, :]),
                            z=dz[k],
                            wavelength=self.reconstruction.wavelength,
                            L=self.reconstruction.Lp,
                            is_FT=False,
                        )
                    else:
                        nlambda = self.reconstruction.nlambda // 2
                        imProp, _ = aspw(
                            xp.squeeze(
                                self.reconstruction.probe[nlambda, ..., :, :]
                            ),
                            dz[k],
                            self.reconstruction.spectralDensity[nlambda],
                            self.reconstruction.Lp,
                            is_FT=False,
                        )
                imProps.append(asNumpyArray(imProp))
                # TV approach
                aleph = 1e-2
                gradx = xp.roll(imProp, -1, axis=-1) - xp.roll(imProp, 1, axis=-1)
                grady = xp.roll(imProp, -1, axis=-2) - xp.roll(imProp, 1, axis=-2)
                merit.append(
                    xp.sum(xp.sqrt(abs(gradx) ** 2 + abs(grady) ** 2 + aleph))
                )
                # take a tiny break, we may overask the GPU
                # yield 0, 0

            merit = asNumpyArray(xp.array(merit))
            if not hasattr(self.reconstruction, "TV_history"):
                self.reconstruction.TV_history = []

            self.reconstruction.TV_history.append(float(merit[len(merit) // 2]))
            feedback = np.sum(dz * merit) / np.sum(
                merit
            )  # at optimal z, feedback term becomes 0

            self.logger.debug("Step size: %s", feedback)
            self.zMomentun = (
                self.zPIEfriction * self.zMomentun
                + self.zPIEgradientStepSize * feedback
            )
            zNew = self.reconstruction.zo + self.zMomentun

        self.reconstruction.zHistory.append(self.reconstruction.zo)

        # print updated z
        self.pbar.set_description(
            "zPIE: update z = %.3f mm (dz = %.1f um)"
            % (self.reconstruction.zo * 1e3, self.zMomentun * 1e6)
        )

        # reset coordinates: the zo setter also rescales dxp = wavelength * zo / Ld, and the
        # positions follow from dxp; with ASP the sampling does not depend on z, so keep it
        dxp = self.reconstruction.dxp
        self.reconstruction.zo = zNew
        if self.params.propagatorType == "ASP":
            self.reconstruction.dxp = dxp
        ##################################################################################################################

        for positionLoop, positionIndex in enumerate(self.positionIndices):
            # print('Starting normal reconstruction loop')
            ### patch1 ###
            # get object patch
            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()

            # make exit surface wave
            self.reconstruction.esw = objectPatch * self.reconstruction.probe

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

            # object update
            self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                objectPatch, DELTA
            )

            # probe update
            self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)
        # yield positionLoop, positionIndex

        # get error metric
        self.getErrorMetrics()

        # apply Constraints
        self.applyConstraints(loop)
        # display it
        # self.showReconstruction(loop)

        # kept for `reconstruction.make_alignment_plot()`; the first iteration has no merit yet
        self.zNew = zNew
        if merit is not None:
            self.merit = merit
            self.reconstruction.merit = merit
            self.reconstruction.dz = dz

        # show reconstruction
        if False:
            if loop == 0:
                figure, axes = plt.subplots(
                    1, 3, num=666, squeeze=True, clear=True, figsize=(5, 5)
                )
                ax = axes[0]
                ax_score = axes[1]
                ax.set_title("Estimated distance (object-camera)")
                ax.set_xlabel("iteration")
                ax.set_ylabel("estimated z (mm)")
                ax.set_xscale("symlog")

                ax_score.set_title("TV score")
                ax_score.set_xlabel("Distance [um]")
                ax_score.set_ylabel("TV")
                (score_line,) = ax_score.plot(dz * 1e6, merit)
                (line,) = ax.plot(0, zNew, "o-")
                plt.tight_layout()
                plt.show(block=False)

            elif np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
                idx = np.linspace(
                    0,
                    np.log10(len(self.reconstruction.zHistory) - 1),
                    np.minimum(len(self.reconstruction.zHistory), 100),
                )
                idx = np.rint(10**idx).astype("int")

                line.set_xdata(idx)
                line.set_ydata(np.array(self.reconstruction.zHistory)[idx] * 1e3)

                score_line.set_ydata(merit)
                ax_score.set_ylim(merit.min() - 1, merit.max() + 1)
                ax.set_xlim(0, np.max(idx))
                ax.set_ylim(
                    np.min(self.reconstruction.zHistory) * 1e3,
                    np.max(self.reconstruction.zHistory) * 1e3,
                )

                figure.canvas.draw()
                figure.canvas.flush_events()
        self.showReconstruction(loop)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the standard ePIE object-update rule.

This implementation is identical to ePIE.objectPatchUpdate().

See Also

ePIE.objectPatchUpdate Standard ePIE object update.

Source code in PtyLab/Engines/zPIE.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    """
    Update the object patch using the standard ePIE object-update rule.

    This implementation is identical to `ePIE.objectPatchUpdate()`.

    See Also:
        `ePIE.objectPatchUpdate`
            Standard ePIE object update.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)

    frac = self.reconstruction.probe.conj() / xp.max(
        xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2, 3), keepdims=True
    )

probeUpdate(objectPatch, DELTA)

Update the probe using the standard ePIE probe-update rule.

This implementation is identical to ePIE.probeUpdate().

See Also

ePIE.probeUpdate Standard ePIE probe update.

Source code in PtyLab/Engines/zPIE.py
def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    """
    Update the probe using the standard ePIE probe-update rule.

    This implementation is identical to `ePIE.probeUpdate()`.

    See Also:
        `ePIE.probeUpdate`
            Standard ePIE probe update.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    frac = objectPatch.conj() / xp.max(
        xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))
    )
    r = self.reconstruction.probe + self.betaProbe * xp.sum(
        frac * DELTA, axis=(0, 1, 3), keepdims=True
    )
    return r

aPIE

Bases: BaseEngine

Angle-corrected ptychographic iterative engine (aPIE).

aPIE extends the standard PIE reconstruction by jointly refining the object, probe, and detector tilt angle. The angular correction is based on a Luus-Jaakola-type stochastic search combined with momentum acceleration.1

The detector tilt is described by the angle reconstruction.theta. For each reconstruction iteration, two candidate angles are evaluated: the current angle and a randomly perturbed angle within the current search radius. The diffraction data are transformed into the corresponding detector coordinates for each candidate, followed by a standard PIE object/probe reconstruction.

The candidate producing the lower reconstruction error is retained. The angular update is then combined with a momentum term according to

\[ \theta_{\mathrm{mom}}^{(k+1)} = f\,\Delta\theta_k + \gamma\,\theta_{\mathrm{mom}}^{(k)} \]

where f = feedback, \gamma = aPIEfriction, and \Delta\theta_k is the accepted angular change.

The angular search radius is gradually reduced from thetaSearchRadiusMax to thetaSearchRadiusMin over the reconstruction iterations, allowing coarse angular exploration at the beginning and progressively finer correction toward convergence.

The evolution of the estimated detector angle is stored in reconstruction.thetaHistory.

Angle correction requires an initial value of reconstruction.theta.

With thetaSearch = "scan", the angle is found with thetaScan() instead: one independent reconstruction per candidate angle on a grid, refined around the best one.


  1. A. de Beurs, L. Loetgering, M. Herczog, M. Du, K. S. E. Eikema, and S. Witte, "aPIE: an angle calibration algorithm for reflection ptychography," Opt. Lett. 47, 1949-1952 (2022). https://doi.org/10.1364/OL.453655 ↩

Source code in PtyLab/Engines/aPIE.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
class aPIE(BaseEngine):
    r"""
    Angle-corrected ptychographic iterative engine (aPIE).

    `aPIE` extends the standard PIE reconstruction by jointly refining the
    object, probe, and detector tilt angle. The angular correction is based on
    a Luus-Jaakola-type stochastic search combined with momentum
    acceleration.[^debeurs2022]

    The detector tilt is described by the angle `reconstruction.theta`. For
    each reconstruction iteration, two candidate angles are evaluated: the
    current angle and a randomly perturbed angle within the current search
    radius. The diffraction data are transformed into the corresponding
    detector coordinates for each candidate, followed by a standard PIE
    object/probe reconstruction.

    The candidate producing the lower reconstruction error is retained. The
    angular update is then combined with a momentum term according to

    $$
    \theta_{\mathrm{mom}}^{(k+1)} = f\,\Delta\theta_k + \gamma\,\theta_{\mathrm{mom}}^{(k)}
    $$

    where `f = feedback`, `\gamma = aPIEfriction`, and `\Delta\theta_k` is the
    accepted angular change.

    The angular search radius is gradually reduced from
    `thetaSearchRadiusMax` to `thetaSearchRadiusMin` over the reconstruction
    iterations, allowing coarse angular exploration at the beginning and
    progressively finer correction toward convergence.

    The evolution of the estimated detector angle is stored in
    `reconstruction.thetaHistory`.

    Angle correction requires an initial value of `reconstruction.theta`.

    With `thetaSearch = "scan"`, the angle is found with `thetaScan()` instead:
    one independent reconstruction per candidate angle on a grid, refined
    around the best one.

    [^debeurs2022]: A. de Beurs, L. Loetgering, M. Herczog,
            M. Du, K. S. E. Eikema, and S. Witte,
            "aPIE: an angle calibration algorithm for reflection ptychography,"
            Opt. Lett. 47, 1949-1952 (2022).
            https://doi.org/10.1364/OL.453655
    """

    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("aPIE")
        self.logger.info("Sucesfully created aPIE aPIE_engine")
        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        self.initializeReconstructionParams()

    def initializeReconstructionParams(self):
        """
        Initialize parameters specific to the aPIE reconstruction.

        This method sets the object and probe update strengths, angular momentum
        parameters, reconstruction length, and angular search-radius limits. It
        also initializes the detector-angle momentum and history if they are not
        already present.

        A copy of the original ptychogram is stored in
        `self.ptychogramUntransformed` for repeated angle-dependent coordinate
        transformations during reconstruction.

        Raises:
            ValueError:
                If `reconstruction.theta` has not been initialized.
        """
        self.betaProbe = 0.25
        self.betaObject = 0.25
        self.aPIEfriction = 0.7
        self.feedback = 0.5
        self.numIterations = 50

        if not hasattr(self.reconstruction, "thetaMomentum"):
            self.reconstruction.thetaMomentum = 0
        if not hasattr(self.reconstruction, "thetaHistory"):
            self.reconstruction.thetaHistory = np.array([])

        self.thetaSearchRadiusMin = 0.01
        self.thetaSearchRadiusMax = 0.1

        # "stochastic" (the search of de Beurs et al.) or "scan" (see thetaScan)
        self.thetaSearch = "stochastic"
        self.thetaScanRange = 10.0  # half-width of the first grid around theta [deg]
        self.thetaScanPoints = 7
        self.thetaScanRefinements = 1
        self.thetaScanSeed = 0
        self.ptychogramUntransformed = self.experimentalData.ptychogram.copy()
        self.experimentalData.W = np.ones_like(self.reconstruction.Xd)

        if self.reconstruction.theta is None:
            raise ValueError("theta value is not given")

    def doReconstruction(self):
        """Deprecated alias of `reconstruct()`."""
        warnings.warn(
            "`aPIE.doReconstruction()` is deprecated. Use `aPIE.reconstruct()` instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.reconstruct()

    def resampleDetector(self, theta):
        """
        Resample the measured ptychogram onto the detector grid of a tilt angle.

        Each pixel $(x_d, y_d)$ of the regular grid takes the measured intensity at
        $x = T^{-1}(x_d, y_d)$ (see `T_inv`), interpolated linearly along the rows.
        Points that fall outside the detector are set to zero.

        Args:
            theta (float): Tilt angle in degrees.

        Returns:
            tuple: The resampled ptychogram `(numFrames, Nd, Nd)` and the weight
                `W` `(Nd, Nd)`, the fraction of each pixel covered by the
                measurement (set to `1e-3` outside it), both in centered order.
        """
        xp = getArrayModule(self.reconstruction.object)
        nd = ndimage if xp is np else cp_ndimage
        xd = self.reconstruction.xd
        Xq = T_inv(
            self.reconstruction.Xd,
            self.reconstruction.Yd,
            self.reconstruction.zo,
            theta,
        )
        # T_inv only moves x, so each pixel samples its own row at a fractional column;
        # NaN (no real solution) is moved off the detector, where map_coordinates returns 0
        # (rounding drops float noise, so that column Nd - 1 does not land just outside)
        columns = np.nan_to_num((Xq - xd[0]) / (xd[1] - xd[0]), nan=-2.0).round(6)
        rows = np.broadcast_to(np.arange(xd.size)[:, None], columns.shape)
        coordinates = xp.asarray(np.stack([rows, columns]))

        ptychogram = xp.stack(
            [
                nd.map_coordinates(frame, coordinates, order=1, cval=0.0)
                for frame in self.ptychogramUntransformed
            ]
        )
        ptychogram = xp.clip(ptychogram, 0, None)
        W = nd.map_coordinates(
            xp.ones_like(self.ptychogramUntransformed[0]),
            coordinates,
            order=1,
            cval=0.0,
        )
        W[W == 0] = 1e-3
        return ptychogram, W

    def reconstruct(self, experimentalData=None, reconstruction=None):
        """
        Run the aPIE reconstruction with iterative detector-angle correction.

        The reconstruction starts from the current detector angle
        `reconstruction.theta` and gradually reduces the angular search radius
        from `thetaSearchRadiusMax` to `thetaSearchRadiusMin` over the requested
        number of iterations.

        At each iteration, two candidate detector angles are evaluated: the
        current angle and a randomly perturbed angle within the current search
        radius, both including the accumulated angular momentum.

        For each candidate angle, the original diffraction data stored in
        `ptychogramUntransformed` are resampled onto the transformed detector
        coordinates with `resampleDetector()`.

        After the angle-dependent coordinate correction, a standard PIE
        reconstruction is performed over all scan positions. The scan order is
        prepared with `setPositionOrder()`. For each position, the exit surface
        wave is formed from the current object patch and probe, and
        `intensityProjection()` applies the measured-intensity constraint in the
        detector plane.

        The difference between the updated and current exit surface waves is used
        to update the object and probe through `objectPatchUpdate()` and
        `probeUpdate()`, respectively. Reconstruction errors are evaluated with
        `getErrorMetrics()`, and the reconstruction constraints are applied with
        `applyConstraints()`.

        The two candidate angles are compared using their reconstruction errors.
        The candidate producing the lower error is retained together with its
        corresponding object and probe. The accepted angular change is then used to
        update `reconstruction.thetaMomentum`.

        The accepted detector angle is stored in
        `reconstruction.thetaHistory`, while `showReconstruction()` is used to
        update the reconstruction monitor during the optimization.

        If GPU acceleration is enabled, the reconstruction data are returned to
        CPU memory after completion.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use. If provided, it replaces the dataset
                currently attached to the engine.

            reconstruction (Reconstruction, optional):
                Reconstruction state to optimize. If provided, it replaces the
                reconstruction currently attached to the engine.
        """
        if experimentalData is not None:
            self.ptychogramUntransformed = experimentalData.ptychogram.copy()
        self.changeExperimentalData(experimentalData)
        self.changeOptimizable(reconstruction)
        if self.thetaSearch == "scan":
            return self.thetaScan()
        if self.thetaSearch != "stochastic":
            raise ValueError(
                f"Unknown thetaSearch {self.thetaSearch!r}, use 'stochastic' or 'scan'."
            )
        self._prepareReconstruction()

        xp = getArrayModule(self.reconstruction.object)
        # resample on the device of the reconstruction; energy is kept by rescaling to this norm
        self.ptychogramUntransformed = xp.asarray(self.ptychogramUntransformed)
        normUntransformed = xp.linalg.norm(self.ptychogramUntransformed)

        # linear search
        thetaSearchRadiusList = np.linspace(
            self.thetaSearchRadiusMax, self.thetaSearchRadiusMin, self.numIterations
        )

        self.pbar = trange(self.numIterations, desc="aPIE", file=sys.stdout, leave=True)
        for loop in self.pbar:
            # save theta search history
            self.reconstruction.thetaHistory = np.append(
                self.reconstruction.thetaHistory,
                asNumpyArray(self.reconstruction.theta),
            )

            # select two angles (todo check if three angles behave better)
            theta = (
                np.array(
                    [
                        self.reconstruction.theta,
                        self.reconstruction.theta
                        + thetaSearchRadiusList[loop] * (-1 + 2 * np.random.rand()),
                    ]
                )
                + self.reconstruction.thetaMomentum
            )

            # save object and probe
            probeTemp = self.reconstruction.probe.copy()
            objectTemp = self.reconstruction.object.copy()

            # probe and object buffer (todo maybe there's more elegant way )
            probeBuffer = xp.zeros_like(
                probeTemp
            )  # shape=(np.array([probeTemp, probeTemp])).shape)
            probeBuffer = [probeBuffer, probeBuffer]
            objectBuffer = xp.zeros_like(
                objectTemp
            )  # , shape=(np.array([objectTemp, objectTemp])).shape)  # for polychromatic case this will need to be multimode
            objectBuffer = [objectBuffer, objectBuffer]
            # initialize error
            errorTemp = np.zeros((2, 1))

            for k in range(2):
                self.reconstruction.probe = probeTemp
                self.reconstruction.object = objectTemp
                # reset ptychogram (transform into estimate coordinates)
                ptychogram, self.experimentalData.W = self.resampleDetector(theta[k])

                # renormalization (for energy conservation)
                self.experimentalData.ptychogram = (
                    ptychogram / xp.linalg.norm(ptychogram) * normUntransformed
                )

                # the untransformed data are in centered order, the engine works in FFT order
                if self.params.fftshiftSwitch:
                    self.experimentalData.ptychogram = xp.fft.ifftshift(
                        self.experimentalData.ptychogram, axes=(-1, -2)
                    )
                    self.experimentalData.W = xp.fft.ifftshift(
                        self.experimentalData.W, axes=(-1, -2)
                    )

                # set position order
                self.setPositionOrder()

                for positionLoop, positionIndex in enumerate(self.positionIndices):
                    ### patch1 ###
                    # get object patch1
                    row1, col1 = self.reconstruction.positions[positionIndex]
                    sy = slice(row1, row1 + self.reconstruction.Np)
                    sx = slice(col1, col1 + self.reconstruction.Np)
                    # note that object patch has size of probe array
                    objectPatch = self.reconstruction.object[..., sy, sx].copy()

                    # make exit surface wave
                    self.reconstruction.esw = objectPatch * self.reconstruction.probe

                    # propagate to camera, intensityProjection, propagate back to object
                    self.intensityProjection(positionIndex)

                    # difference term1
                    DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                    # object update
                    self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                        objectPatch, DELTA
                    )

                    # probe update
                    self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)

                # get error metric
                self.getErrorMetrics()
                # remove error from error history
                errorTemp[k] = self.reconstruction.error[-1]
                self.reconstruction.error = np.delete(self.reconstruction.error, -1)

                # apply Constraints
                self.applyConstraints(loop)
                # update buffer
                probeBuffer[k] = self.reconstruction.probe
                objectBuffer[k] = self.reconstruction.object

            if errorTemp[1] < errorTemp[0]:
                dtheta = theta[1] - theta[0]
                self.reconstruction.theta = theta[1]
                self.reconstruction.probe = probeBuffer[1]
                self.reconstruction.object = objectBuffer[1]
                self.reconstruction.error = np.append(
                    self.reconstruction.error, errorTemp[1]
                )
            else:
                dtheta = 0
                self.reconstruction.theta = theta[0]
                self.reconstruction.probe = probeBuffer[0]
                self.reconstruction.object = objectBuffer[0]
                self.reconstruction.error = np.append(
                    self.reconstruction.error, errorTemp[0]
                )

            self.reconstruction.thetaMomentum = (
                self.feedback * dtheta
                + self.aPIEfriction * self.reconstruction.thetaMomentum
            )
            # print updated theta
            self.pbar.set_description(
                "aPIE: update a=%.3f deg (search radius=%.3f deg, thetaMomentum=%.3f deg)"
                % (
                    self.reconstruction.theta,
                    thetaSearchRadiusList[loop],
                    self.reconstruction.thetaMomentum,
                )
            )

            # show reconstruction
            if loop == 0:
                figure, ax = plt.subplots(
                    1, 1, num=777, squeeze=True, clear=True, figsize=(5, 5)
                )
                ax.set_title("Estimated angle")
                ax.set_xlabel("iteration")
                ax.set_ylabel("estimated theta [deg]")
                ax.set_xscale("symlog")
                line = plt.plot(0, self.reconstruction.theta, "o-")[0]
                plt.tight_layout()
                plt.show(block=False)

            elif np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
                idx = np.linspace(
                    0,
                    np.log10(len(self.reconstruction.thetaHistory) - 1),
                    np.minimum(len(self.reconstruction.thetaHistory), 100),
                )
                idx = np.rint(10**idx).astype("int")

                line.set_xdata(idx)
                line.set_ydata(np.array(self.reconstruction.thetaHistory)[idx])
                ax.set_xlim(0, np.max(idx))
                ax.set_ylim(
                    min(self.reconstruction.thetaHistory),
                    max(self.reconstruction.thetaHistory),
                )

                figure.canvas.draw()
                figure.canvas.flush_events()

            self.showReconstruction(loop)

        self.ptychogramUntransformed = asNumpyArray(self.ptychogramUntransformed)
        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

        # self.thetaSearchRadiusMax = thetaSearchRadiusList[loop]

    def thetaScan(self):
        r"""
        Find the tilt angle with a grid scan of independent reconstructions.

        Each candidate angle $\theta_k$ gets its own `mPIE` reconstruction
        (`numIterations` iterations, `betaObject`, `betaProbe`) on the data
        resampled with `resampleDetector()`. All candidates start from the same
        object, probe and random state, so they differ only in $\theta_k$.
        Each candidate is scored by `rawDetectorError()`, the error against the
        measured frames before resampling, so that the score does not depend on
        how much the resampling smooths the data.

        The first grid has `thetaScanPoints` angles in
        $\theta \pm$ `thetaScanRange`. Each of the `thetaScanRefinements`
        further grids spans one grid step on either side of the best angle so
        far, with the same number of points, so it is $(N - 1)/2$ times finer
        for $N$ = `thetaScanPoints`; use $N \ge 5$ for the refinement to help.

        Afterwards `reconstruction.theta`, the object and the probe are those of
        the best candidate, and `experimentalData.ptychogram` holds the data
        resampled at that angle, so another engine can continue from there.
        The scanned angles and errors are stored in `thetaScanValues` and
        `thetaScanErrors`, and in `reconstruction.extraResults["thetaScan"]`.

        Returns:
            tuple: `(best_theta, best_error)`, the angle in degrees and its error.
        """
        rec = self.reconstruction
        # every candidate starts from this state
        object0 = asNumpyArray(rec.object).copy()
        probe0 = asNumpyArray(rec.probe).copy()
        self.ptychogramUntransformed = asNumpyArray(self.ptychogramUntransformed)

        self.thetaScanValues, self.thetaScanErrors = [], []
        best = None
        center, halfWidth = float(rec.theta), self.thetaScanRange
        for _ in range(self.thetaScanRefinements + 1):
            grid = np.linspace(
                center - halfWidth, center + halfWidth, self.thetaScanPoints
            )
            for theta in grid:
                if np.any(np.isclose(theta, self.thetaScanValues)):
                    continue
                rec.object, rec.probe = object0.copy(), probe0.copy()
                error = self._evaluateTheta(theta)
                self.thetaScanValues.append(float(theta))
                self.thetaScanErrors.append(error)
                self.logger.info(
                    "theta = %.3f deg: raw detector error %.5f", theta, error
                )
                if best is None or error < best[1]:
                    best = (float(theta), error, rec.object.copy(), rec.probe.copy())
            # the next grid spans one step of this grid on either side of the best angle
            center, halfWidth = best[0], 2 * halfWidth / (self.thetaScanPoints - 1)

        bestTheta, bestError, rec.object, rec.probe = best
        rec.theta = bestTheta
        rec.thetaHistory = np.append(rec.thetaHistory, bestTheta)
        self._setResampledData(bestTheta)
        rec.extraResults["thetaScan"] = {
            "units": "theta in deg",
            "theta": np.asarray(self.thetaScanValues),
            "error": np.asarray(self.thetaScanErrors),
        }
        return bestTheta, bestError

    def _setResampledData(self, theta):
        """Put the data resampled at `theta` into `experimentalData`; return the scale."""
        ptychogram, _ = self.resampleDetector(theta)
        # rescale to the measured energy, as in the stochastic search
        scale = np.linalg.norm(self.ptychogramUntransformed) / np.linalg.norm(
            ptychogram
        )
        ptychogram = (ptychogram * scale).astype(self.ptychogramUntransformed.dtype)
        if self.params.fftshiftFlag:
            # earlier engines left the data in FFT order
            ptychogram = np.fft.ifftshift(ptychogram, axes=(-1, -2))
        self.experimentalData.ptychogram = ptychogram
        self.experimentalData._setData()
        return scale

    def _evaluateTheta(self, theta):
        """Reconstruct with mPIE at a fixed angle and return its `rawDetectorError()`."""
        randomState = np.random.get_state()
        np.random.seed(self.thetaScanSeed)
        try:
            scale = self._setResampledData(theta)
            engine = mPIE(
                self.reconstruction, self.experimentalData, self.params, DummyMonitor()
            )
            engine.numIterations = self.numIterations
            engine.betaObject = self.betaObject
            engine.betaProbe = self.betaProbe
            engine.reconstruct()
        finally:
            np.random.set_state(randomState)
        return self.rawDetectorError(theta, scale)

    def rawDetectorError(self, theta, scale=1.0):
        r"""
        Error of the current model against the measured, unresampled frames.

        The model intensity $I_j$ of frame $j$ lives on the corrected detector
        grid. The measured pixel at $x'$ corresponds to the corrected point
        $T(x', y')$ (see `T`), so the model is sampled there and compared with
        the measured frame $M_j$:

        $$
        e = \frac{\sum_j \sum_{x', y'} \left| I_j(T(x', y'))/s - M_j(x', y') \right|}
                 {\sum_j \sum_{x', y'} M_j(x', y')}
        $$

        with $s$ the factor the resampled data were scaled by. Only the smooth
        model is interpolated, never the noisy data.

        Args:
            theta (float): Tilt angle in degrees.
            scale (float): The scale $s$ of the resampled data.

        Returns:
            float: The normalized error $e$.
        """
        rec = self.reconstruction
        xp = getArrayModule(rec.object)
        nd = ndimage if xp is np else cp_ndimage
        xd = rec.xd
        Xt, _ = T(rec.Xd, rec.Yd, rec.zo, theta)
        columns = ((Xt - xd[0]) / (xd[1] - xd[0])).round(6)
        rows = np.broadcast_to(np.arange(xd.size)[:, None], columns.shape)
        coordinates = xp.asarray(np.stack([rows, columns]))

        total, energy = 0.0, 0.0
        for j, (row, col) in enumerate(rec.positions):
            rec.esw = (
                rec.object[..., row : row + rec.Np, col : col + rec.Np] * rec.probe
            )
            self.object2detector()
            # (nlambda, nosm, npsm, nslice, Nd, Nd) -> (Nd, Nd), summed over all modes
            I = xp.sum(xp.abs(rec.ESW) ** 2, axis=(0, 1, 2, 3))
            if self.params.backgroundModeSwitch:
                I = I + rec.background
            if self.params.fftshiftFlag:
                I = xp.fft.fftshift(I)
            measured = xp.asarray(self.ptychogramUntransformed[j])
            Iraw = nd.map_coordinates(I, coordinates, order=1, cval=0.0) / scale
            total += float(xp.sum(xp.abs(Iraw - measured)))
            energy += float(xp.sum(measured))
        return total / energy

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        """
        Update the object patch using the standard ePIE object-update rule.

        This implementation is identical to `ePIE.objectPatchUpdate()`.

        See Also:
            `ePIE.objectPatchUpdate`
                Standard ePIE object update.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)

        frac = self.reconstruction.probe.conj() / xp.max(
            xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2, 3), keepdims=True
        )

    def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        """
        Update the probe using the standard ePIE probe-update rule.

        This implementation is identical to `ePIE.probeUpdate()`.

        See Also:
            `ePIE.probeUpdate`
                Standard ePIE probe update.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        frac = objectPatch.conj() / xp.max(
            xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))
        )
        r = self.reconstruction.probe + self.betaProbe * xp.sum(
            frac * DELTA, axis=(0, 1, 3), keepdims=True
        )
        return r

initializeReconstructionParams()

Initialize parameters specific to the aPIE reconstruction.

This method sets the object and probe update strengths, angular momentum parameters, reconstruction length, and angular search-radius limits. It also initializes the detector-angle momentum and history if they are not already present.

A copy of the original ptychogram is stored in self.ptychogramUntransformed for repeated angle-dependent coordinate transformations during reconstruction.

Raises:

Type Description
ValueError

If reconstruction.theta has not been initialized.

Source code in PtyLab/Engines/aPIE.py
def initializeReconstructionParams(self):
    """
    Initialize parameters specific to the aPIE reconstruction.

    This method sets the object and probe update strengths, angular momentum
    parameters, reconstruction length, and angular search-radius limits. It
    also initializes the detector-angle momentum and history if they are not
    already present.

    A copy of the original ptychogram is stored in
    `self.ptychogramUntransformed` for repeated angle-dependent coordinate
    transformations during reconstruction.

    Raises:
        ValueError:
            If `reconstruction.theta` has not been initialized.
    """
    self.betaProbe = 0.25
    self.betaObject = 0.25
    self.aPIEfriction = 0.7
    self.feedback = 0.5
    self.numIterations = 50

    if not hasattr(self.reconstruction, "thetaMomentum"):
        self.reconstruction.thetaMomentum = 0
    if not hasattr(self.reconstruction, "thetaHistory"):
        self.reconstruction.thetaHistory = np.array([])

    self.thetaSearchRadiusMin = 0.01
    self.thetaSearchRadiusMax = 0.1

    # "stochastic" (the search of de Beurs et al.) or "scan" (see thetaScan)
    self.thetaSearch = "stochastic"
    self.thetaScanRange = 10.0  # half-width of the first grid around theta [deg]
    self.thetaScanPoints = 7
    self.thetaScanRefinements = 1
    self.thetaScanSeed = 0
    self.ptychogramUntransformed = self.experimentalData.ptychogram.copy()
    self.experimentalData.W = np.ones_like(self.reconstruction.Xd)

    if self.reconstruction.theta is None:
        raise ValueError("theta value is not given")

doReconstruction()

Deprecated alias of reconstruct().

Source code in PtyLab/Engines/aPIE.py
def doReconstruction(self):
    """Deprecated alias of `reconstruct()`."""
    warnings.warn(
        "`aPIE.doReconstruction()` is deprecated. Use `aPIE.reconstruct()` instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    self.reconstruct()

resampleDetector(theta)

Resample the measured ptychogram onto the detector grid of a tilt angle.

Each pixel \((x_d, y_d)\) of the regular grid takes the measured intensity at \(x = T^{-1}(x_d, y_d)\) (see T_inv), interpolated linearly along the rows. Points that fall outside the detector are set to zero.

Parameters:

Name Type Description Default
theta float

Tilt angle in degrees.

required

Returns:

Type Description
tuple

The resampled ptychogram (numFrames, Nd, Nd) and the weight W (Nd, Nd), the fraction of each pixel covered by the measurement (set to 1e-3 outside it), both in centered order.

Source code in PtyLab/Engines/aPIE.py
def resampleDetector(self, theta):
    """
    Resample the measured ptychogram onto the detector grid of a tilt angle.

    Each pixel $(x_d, y_d)$ of the regular grid takes the measured intensity at
    $x = T^{-1}(x_d, y_d)$ (see `T_inv`), interpolated linearly along the rows.
    Points that fall outside the detector are set to zero.

    Args:
        theta (float): Tilt angle in degrees.

    Returns:
        tuple: The resampled ptychogram `(numFrames, Nd, Nd)` and the weight
            `W` `(Nd, Nd)`, the fraction of each pixel covered by the
            measurement (set to `1e-3` outside it), both in centered order.
    """
    xp = getArrayModule(self.reconstruction.object)
    nd = ndimage if xp is np else cp_ndimage
    xd = self.reconstruction.xd
    Xq = T_inv(
        self.reconstruction.Xd,
        self.reconstruction.Yd,
        self.reconstruction.zo,
        theta,
    )
    # T_inv only moves x, so each pixel samples its own row at a fractional column;
    # NaN (no real solution) is moved off the detector, where map_coordinates returns 0
    # (rounding drops float noise, so that column Nd - 1 does not land just outside)
    columns = np.nan_to_num((Xq - xd[0]) / (xd[1] - xd[0]), nan=-2.0).round(6)
    rows = np.broadcast_to(np.arange(xd.size)[:, None], columns.shape)
    coordinates = xp.asarray(np.stack([rows, columns]))

    ptychogram = xp.stack(
        [
            nd.map_coordinates(frame, coordinates, order=1, cval=0.0)
            for frame in self.ptychogramUntransformed
        ]
    )
    ptychogram = xp.clip(ptychogram, 0, None)
    W = nd.map_coordinates(
        xp.ones_like(self.ptychogramUntransformed[0]),
        coordinates,
        order=1,
        cval=0.0,
    )
    W[W == 0] = 1e-3
    return ptychogram, W

reconstruct(experimentalData=None, reconstruction=None)

Run the aPIE reconstruction with iterative detector-angle correction.

The reconstruction starts from the current detector angle reconstruction.theta and gradually reduces the angular search radius from thetaSearchRadiusMax to thetaSearchRadiusMin over the requested number of iterations.

At each iteration, two candidate detector angles are evaluated: the current angle and a randomly perturbed angle within the current search radius, both including the accumulated angular momentum.

For each candidate angle, the original diffraction data stored in ptychogramUntransformed are resampled onto the transformed detector coordinates with resampleDetector().

After the angle-dependent coordinate correction, a standard PIE reconstruction is performed over all scan positions. The scan order is prepared with setPositionOrder(). For each position, the exit surface wave is formed from the current object patch and probe, and intensityProjection() applies the measured-intensity constraint in the detector plane.

The difference between the updated and current exit surface waves is used to update the object and probe through objectPatchUpdate() and probeUpdate(), respectively. Reconstruction errors are evaluated with getErrorMetrics(), and the reconstruction constraints are applied with applyConstraints().

The two candidate angles are compared using their reconstruction errors. The candidate producing the lower error is retained together with its corresponding object and probe. The accepted angular change is then used to update reconstruction.thetaMomentum.

The accepted detector angle is stored in reconstruction.thetaHistory, while showReconstruction() is used to update the reconstruction monitor during the optimization.

If GPU acceleration is enabled, the reconstruction data are returned to CPU memory after completion.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use. If provided, it replaces the dataset currently attached to the engine.

None
reconstruction Reconstruction

Reconstruction state to optimize. If provided, it replaces the reconstruction currently attached to the engine.

None
Source code in PtyLab/Engines/aPIE.py
def reconstruct(self, experimentalData=None, reconstruction=None):
    """
    Run the aPIE reconstruction with iterative detector-angle correction.

    The reconstruction starts from the current detector angle
    `reconstruction.theta` and gradually reduces the angular search radius
    from `thetaSearchRadiusMax` to `thetaSearchRadiusMin` over the requested
    number of iterations.

    At each iteration, two candidate detector angles are evaluated: the
    current angle and a randomly perturbed angle within the current search
    radius, both including the accumulated angular momentum.

    For each candidate angle, the original diffraction data stored in
    `ptychogramUntransformed` are resampled onto the transformed detector
    coordinates with `resampleDetector()`.

    After the angle-dependent coordinate correction, a standard PIE
    reconstruction is performed over all scan positions. The scan order is
    prepared with `setPositionOrder()`. For each position, the exit surface
    wave is formed from the current object patch and probe, and
    `intensityProjection()` applies the measured-intensity constraint in the
    detector plane.

    The difference between the updated and current exit surface waves is used
    to update the object and probe through `objectPatchUpdate()` and
    `probeUpdate()`, respectively. Reconstruction errors are evaluated with
    `getErrorMetrics()`, and the reconstruction constraints are applied with
    `applyConstraints()`.

    The two candidate angles are compared using their reconstruction errors.
    The candidate producing the lower error is retained together with its
    corresponding object and probe. The accepted angular change is then used to
    update `reconstruction.thetaMomentum`.

    The accepted detector angle is stored in
    `reconstruction.thetaHistory`, while `showReconstruction()` is used to
    update the reconstruction monitor during the optimization.

    If GPU acceleration is enabled, the reconstruction data are returned to
    CPU memory after completion.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use. If provided, it replaces the dataset
            currently attached to the engine.

        reconstruction (Reconstruction, optional):
            Reconstruction state to optimize. If provided, it replaces the
            reconstruction currently attached to the engine.
    """
    if experimentalData is not None:
        self.ptychogramUntransformed = experimentalData.ptychogram.copy()
    self.changeExperimentalData(experimentalData)
    self.changeOptimizable(reconstruction)
    if self.thetaSearch == "scan":
        return self.thetaScan()
    if self.thetaSearch != "stochastic":
        raise ValueError(
            f"Unknown thetaSearch {self.thetaSearch!r}, use 'stochastic' or 'scan'."
        )
    self._prepareReconstruction()

    xp = getArrayModule(self.reconstruction.object)
    # resample on the device of the reconstruction; energy is kept by rescaling to this norm
    self.ptychogramUntransformed = xp.asarray(self.ptychogramUntransformed)
    normUntransformed = xp.linalg.norm(self.ptychogramUntransformed)

    # linear search
    thetaSearchRadiusList = np.linspace(
        self.thetaSearchRadiusMax, self.thetaSearchRadiusMin, self.numIterations
    )

    self.pbar = trange(self.numIterations, desc="aPIE", file=sys.stdout, leave=True)
    for loop in self.pbar:
        # save theta search history
        self.reconstruction.thetaHistory = np.append(
            self.reconstruction.thetaHistory,
            asNumpyArray(self.reconstruction.theta),
        )

        # select two angles (todo check if three angles behave better)
        theta = (
            np.array(
                [
                    self.reconstruction.theta,
                    self.reconstruction.theta
                    + thetaSearchRadiusList[loop] * (-1 + 2 * np.random.rand()),
                ]
            )
            + self.reconstruction.thetaMomentum
        )

        # save object and probe
        probeTemp = self.reconstruction.probe.copy()
        objectTemp = self.reconstruction.object.copy()

        # probe and object buffer (todo maybe there's more elegant way )
        probeBuffer = xp.zeros_like(
            probeTemp
        )  # shape=(np.array([probeTemp, probeTemp])).shape)
        probeBuffer = [probeBuffer, probeBuffer]
        objectBuffer = xp.zeros_like(
            objectTemp
        )  # , shape=(np.array([objectTemp, objectTemp])).shape)  # for polychromatic case this will need to be multimode
        objectBuffer = [objectBuffer, objectBuffer]
        # initialize error
        errorTemp = np.zeros((2, 1))

        for k in range(2):
            self.reconstruction.probe = probeTemp
            self.reconstruction.object = objectTemp
            # reset ptychogram (transform into estimate coordinates)
            ptychogram, self.experimentalData.W = self.resampleDetector(theta[k])

            # renormalization (for energy conservation)
            self.experimentalData.ptychogram = (
                ptychogram / xp.linalg.norm(ptychogram) * normUntransformed
            )

            # the untransformed data are in centered order, the engine works in FFT order
            if self.params.fftshiftSwitch:
                self.experimentalData.ptychogram = xp.fft.ifftshift(
                    self.experimentalData.ptychogram, axes=(-1, -2)
                )
                self.experimentalData.W = xp.fft.ifftshift(
                    self.experimentalData.W, axes=(-1, -2)
                )

            # set position order
            self.setPositionOrder()

            for positionLoop, positionIndex in enumerate(self.positionIndices):
                ### patch1 ###
                # get object patch1
                row1, col1 = self.reconstruction.positions[positionIndex]
                sy = slice(row1, row1 + self.reconstruction.Np)
                sx = slice(col1, col1 + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term1
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                # object update
                self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                    objectPatch, DELTA
                )

                # probe update
                self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)

            # get error metric
            self.getErrorMetrics()
            # remove error from error history
            errorTemp[k] = self.reconstruction.error[-1]
            self.reconstruction.error = np.delete(self.reconstruction.error, -1)

            # apply Constraints
            self.applyConstraints(loop)
            # update buffer
            probeBuffer[k] = self.reconstruction.probe
            objectBuffer[k] = self.reconstruction.object

        if errorTemp[1] < errorTemp[0]:
            dtheta = theta[1] - theta[0]
            self.reconstruction.theta = theta[1]
            self.reconstruction.probe = probeBuffer[1]
            self.reconstruction.object = objectBuffer[1]
            self.reconstruction.error = np.append(
                self.reconstruction.error, errorTemp[1]
            )
        else:
            dtheta = 0
            self.reconstruction.theta = theta[0]
            self.reconstruction.probe = probeBuffer[0]
            self.reconstruction.object = objectBuffer[0]
            self.reconstruction.error = np.append(
                self.reconstruction.error, errorTemp[0]
            )

        self.reconstruction.thetaMomentum = (
            self.feedback * dtheta
            + self.aPIEfriction * self.reconstruction.thetaMomentum
        )
        # print updated theta
        self.pbar.set_description(
            "aPIE: update a=%.3f deg (search radius=%.3f deg, thetaMomentum=%.3f deg)"
            % (
                self.reconstruction.theta,
                thetaSearchRadiusList[loop],
                self.reconstruction.thetaMomentum,
            )
        )

        # show reconstruction
        if loop == 0:
            figure, ax = plt.subplots(
                1, 1, num=777, squeeze=True, clear=True, figsize=(5, 5)
            )
            ax.set_title("Estimated angle")
            ax.set_xlabel("iteration")
            ax.set_ylabel("estimated theta [deg]")
            ax.set_xscale("symlog")
            line = plt.plot(0, self.reconstruction.theta, "o-")[0]
            plt.tight_layout()
            plt.show(block=False)

        elif np.mod(loop, self.monitor.figureUpdateFrequency) == 0:
            idx = np.linspace(
                0,
                np.log10(len(self.reconstruction.thetaHistory) - 1),
                np.minimum(len(self.reconstruction.thetaHistory), 100),
            )
            idx = np.rint(10**idx).astype("int")

            line.set_xdata(idx)
            line.set_ydata(np.array(self.reconstruction.thetaHistory)[idx])
            ax.set_xlim(0, np.max(idx))
            ax.set_ylim(
                min(self.reconstruction.thetaHistory),
                max(self.reconstruction.thetaHistory),
            )

            figure.canvas.draw()
            figure.canvas.flush_events()

        self.showReconstruction(loop)

    self.ptychogramUntransformed = asNumpyArray(self.ptychogramUntransformed)
    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

thetaScan()

Find the tilt angle with a grid scan of independent reconstructions.

Each candidate angle \(\theta_k\) gets its own mPIE reconstruction (numIterations iterations, betaObject, betaProbe) on the data resampled with resampleDetector(). All candidates start from the same object, probe and random state, so they differ only in \(\theta_k\). Each candidate is scored by rawDetectorError(), the error against the measured frames before resampling, so that the score does not depend on how much the resampling smooths the data.

The first grid has thetaScanPoints angles in \(\theta \pm\) thetaScanRange. Each of the thetaScanRefinements further grids spans one grid step on either side of the best angle so far, with the same number of points, so it is \((N - 1)/2\) times finer for \(N\) = thetaScanPoints; use \(N \ge 5\) for the refinement to help.

Afterwards reconstruction.theta, the object and the probe are those of the best candidate, and experimentalData.ptychogram holds the data resampled at that angle, so another engine can continue from there. The scanned angles and errors are stored in thetaScanValues and thetaScanErrors, and in reconstruction.extraResults["thetaScan"].

Returns:

Type Description
tuple

(best_theta, best_error), the angle in degrees and its error.

Source code in PtyLab/Engines/aPIE.py
def thetaScan(self):
    r"""
    Find the tilt angle with a grid scan of independent reconstructions.

    Each candidate angle $\theta_k$ gets its own `mPIE` reconstruction
    (`numIterations` iterations, `betaObject`, `betaProbe`) on the data
    resampled with `resampleDetector()`. All candidates start from the same
    object, probe and random state, so they differ only in $\theta_k$.
    Each candidate is scored by `rawDetectorError()`, the error against the
    measured frames before resampling, so that the score does not depend on
    how much the resampling smooths the data.

    The first grid has `thetaScanPoints` angles in
    $\theta \pm$ `thetaScanRange`. Each of the `thetaScanRefinements`
    further grids spans one grid step on either side of the best angle so
    far, with the same number of points, so it is $(N - 1)/2$ times finer
    for $N$ = `thetaScanPoints`; use $N \ge 5$ for the refinement to help.

    Afterwards `reconstruction.theta`, the object and the probe are those of
    the best candidate, and `experimentalData.ptychogram` holds the data
    resampled at that angle, so another engine can continue from there.
    The scanned angles and errors are stored in `thetaScanValues` and
    `thetaScanErrors`, and in `reconstruction.extraResults["thetaScan"]`.

    Returns:
        tuple: `(best_theta, best_error)`, the angle in degrees and its error.
    """
    rec = self.reconstruction
    # every candidate starts from this state
    object0 = asNumpyArray(rec.object).copy()
    probe0 = asNumpyArray(rec.probe).copy()
    self.ptychogramUntransformed = asNumpyArray(self.ptychogramUntransformed)

    self.thetaScanValues, self.thetaScanErrors = [], []
    best = None
    center, halfWidth = float(rec.theta), self.thetaScanRange
    for _ in range(self.thetaScanRefinements + 1):
        grid = np.linspace(
            center - halfWidth, center + halfWidth, self.thetaScanPoints
        )
        for theta in grid:
            if np.any(np.isclose(theta, self.thetaScanValues)):
                continue
            rec.object, rec.probe = object0.copy(), probe0.copy()
            error = self._evaluateTheta(theta)
            self.thetaScanValues.append(float(theta))
            self.thetaScanErrors.append(error)
            self.logger.info(
                "theta = %.3f deg: raw detector error %.5f", theta, error
            )
            if best is None or error < best[1]:
                best = (float(theta), error, rec.object.copy(), rec.probe.copy())
        # the next grid spans one step of this grid on either side of the best angle
        center, halfWidth = best[0], 2 * halfWidth / (self.thetaScanPoints - 1)

    bestTheta, bestError, rec.object, rec.probe = best
    rec.theta = bestTheta
    rec.thetaHistory = np.append(rec.thetaHistory, bestTheta)
    self._setResampledData(bestTheta)
    rec.extraResults["thetaScan"] = {
        "units": "theta in deg",
        "theta": np.asarray(self.thetaScanValues),
        "error": np.asarray(self.thetaScanErrors),
    }
    return bestTheta, bestError

rawDetectorError(theta, scale=1.0)

Error of the current model against the measured, unresampled frames.

The model intensity \(I_j\) of frame \(j\) lives on the corrected detector grid. The measured pixel at \(x'\) corresponds to the corrected point \(T(x', y')\) (see T), so the model is sampled there and compared with the measured frame \(M_j\):

\[ e = \frac{\sum_j \sum_{x', y'} \left| I_j(T(x', y'))/s - M_j(x', y') \right|} {\sum_j \sum_{x', y'} M_j(x', y')} \]

with \(s\) the factor the resampled data were scaled by. Only the smooth model is interpolated, never the noisy data.

Parameters:

Name Type Description Default
theta float

Tilt angle in degrees.

required
scale float

The scale \(s\) of the resampled data.

1.0

Returns:

Type Description
float

The normalized error \(e\).

Source code in PtyLab/Engines/aPIE.py
def rawDetectorError(self, theta, scale=1.0):
    r"""
    Error of the current model against the measured, unresampled frames.

    The model intensity $I_j$ of frame $j$ lives on the corrected detector
    grid. The measured pixel at $x'$ corresponds to the corrected point
    $T(x', y')$ (see `T`), so the model is sampled there and compared with
    the measured frame $M_j$:

    $$
    e = \frac{\sum_j \sum_{x', y'} \left| I_j(T(x', y'))/s - M_j(x', y') \right|}
             {\sum_j \sum_{x', y'} M_j(x', y')}
    $$

    with $s$ the factor the resampled data were scaled by. Only the smooth
    model is interpolated, never the noisy data.

    Args:
        theta (float): Tilt angle in degrees.
        scale (float): The scale $s$ of the resampled data.

    Returns:
        float: The normalized error $e$.
    """
    rec = self.reconstruction
    xp = getArrayModule(rec.object)
    nd = ndimage if xp is np else cp_ndimage
    xd = rec.xd
    Xt, _ = T(rec.Xd, rec.Yd, rec.zo, theta)
    columns = ((Xt - xd[0]) / (xd[1] - xd[0])).round(6)
    rows = np.broadcast_to(np.arange(xd.size)[:, None], columns.shape)
    coordinates = xp.asarray(np.stack([rows, columns]))

    total, energy = 0.0, 0.0
    for j, (row, col) in enumerate(rec.positions):
        rec.esw = (
            rec.object[..., row : row + rec.Np, col : col + rec.Np] * rec.probe
        )
        self.object2detector()
        # (nlambda, nosm, npsm, nslice, Nd, Nd) -> (Nd, Nd), summed over all modes
        I = xp.sum(xp.abs(rec.ESW) ** 2, axis=(0, 1, 2, 3))
        if self.params.backgroundModeSwitch:
            I = I + rec.background
        if self.params.fftshiftFlag:
            I = xp.fft.fftshift(I)
        measured = xp.asarray(self.ptychogramUntransformed[j])
        Iraw = nd.map_coordinates(I, coordinates, order=1, cval=0.0) / scale
        total += float(xp.sum(xp.abs(Iraw - measured)))
        energy += float(xp.sum(measured))
    return total / energy

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the standard ePIE object-update rule.

This implementation is identical to ePIE.objectPatchUpdate().

See Also

ePIE.objectPatchUpdate Standard ePIE object update.

Source code in PtyLab/Engines/aPIE.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    """
    Update the object patch using the standard ePIE object-update rule.

    This implementation is identical to `ePIE.objectPatchUpdate()`.

    See Also:
        `ePIE.objectPatchUpdate`
            Standard ePIE object update.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)

    frac = self.reconstruction.probe.conj() / xp.max(
        xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2, 3), keepdims=True
    )

probeUpdate(objectPatch, DELTA)

Update the probe using the standard ePIE probe-update rule.

This implementation is identical to ePIE.probeUpdate().

See Also

ePIE.probeUpdate Standard ePIE probe update.

Source code in PtyLab/Engines/aPIE.py
def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    """
    Update the probe using the standard ePIE probe-update rule.

    This implementation is identical to `ePIE.probeUpdate()`.

    See Also:
        `ePIE.probeUpdate`
            Standard ePIE probe update.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    frac = objectPatch.conj() / xp.max(
        xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))
    )
    r = self.reconstruction.probe + self.betaProbe * xp.sum(
        frac * DELTA, axis=(0, 1, 3), keepdims=True
    )
    return r

e3PIE

Bases: BaseEngine

Multislice ptychographic iterative engine for thick-sample reconstruction.

e3PIE extends conventional PIE reconstruction to samples represented by multiple axial object slices. The illumination is propagated sequentially through the object slices using an angular-spectrum transfer function, allowing wave propagation within a finite-thickness sample to be included in the forward model.

For each scan position, the probe interacts with the first object slice and is then propagated through the remaining slices. At slice \(s\),

\[ \Psi_s = O_s\,\mathcal{P}_{\Delta z}\{\Psi_{s-1}\} \]

where \(O_s\) is the transmission function of slice \(s\) and \(\mathcal{P}_{\Delta z}\) denotes propagation over the inter-slice distance reconstruction.dz.

After applying the measured-intensity constraint at the detector, the resulting exit-wave correction is propagated backward through the sample. The object slices are updated sequentially from the last slice to the first, while the corresponding local probe fields are updated and back-propagated between slices.

The inter-slice propagation transfer function is precomputed using aspw() and stored in reconstruction.H. The reconstruction therefore requires reconstruction.nslice > 1 to represent a multislice object.

The product of all reconstructed object slices is stored in reconstruction.objectProd as an effective projected object.

Source code in PtyLab/Engines/e3PIE.py
class e3PIE(BaseEngine):
    r"""
    Multislice ptychographic iterative engine for thick-sample reconstruction.

    `e3PIE` extends conventional PIE reconstruction to samples represented by
    multiple axial object slices. The illumination is propagated sequentially
    through the object slices using an angular-spectrum transfer function,
    allowing wave propagation within a finite-thickness sample to be included
    in the forward model.

    For each scan position, the probe interacts with the first object slice
    and is then propagated through the remaining slices. At slice $s$,

    $$
    \Psi_s = O_s\,\mathcal{P}_{\Delta z}\{\Psi_{s-1}\}
    $$

    where $O_s$ is the transmission function of slice $s$ and
    $\mathcal{P}_{\Delta z}$ denotes propagation over the inter-slice distance
    `reconstruction.dz`.

    After applying the measured-intensity constraint at the detector, the
    resulting exit-wave correction is propagated backward through the sample.
    The object slices are updated sequentially from the last slice to the
    first, while the corresponding local probe fields are updated and
    back-propagated between slices.

    The inter-slice propagation transfer function is precomputed using
    `aspw()` and stored in `reconstruction.H`. The reconstruction therefore
    requires `reconstruction.nslice > 1` to represent a multislice object.

    The product of all reconstructed object slices is stored in
    `reconstruction.objectProd` as an effective projected object.
    """
    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):

        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("e3PIE")
        self.logger.info("Sucesfully created e3PIE e3PIE_engine")

        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)

        self.initializeReconstructionParams()

    def initializeReconstructionParams(self):
        r"""
        Initialize parameters specific to the e3PIE reconstruction.

        This method sets the object and probe update strengths and the default
        number of reconstruction iterations.

        It also precomputes the angular-spectrum transfer function used to
        propagate the wavefield between adjacent object slices. The propagation
        distance is given by `reconstruction.dz`, and the effective wavelength is
        `reconstruction.wavelength / reconstruction.refrIndex`.

        Inter-slice propagation is performed in Fourier space as

        $$
        \Psi_{s+1} = \mathcal{F}^{-1}\left\{\mathcal{F}\{\Psi_s\} H\right\}
        $$

        where $\Psi_s$ is the exit wave from slice $s$ and $H$ is the
        angular-spectrum transfer function generated by `aspw()`.

        The transfer function is stored in `reconstruction.H` and shifted with
        `ifftshift()` so that it can be applied directly during FFT-based
        propagation between object slices.
        """
        # these are read back as self.betaProbe / self.betaObject in reconstruct()
        # and objectPatchUpdate(), matching every other engine (cf. ePIE.py)
        self.betaProbe = 0.25
        self.betaObject = 0.25
        self.numIterations = 50

        # preallocate transfer function. This runs from __init__, before
        # _checkGPU has moved anything, so the probe is still on the host here;
        # H is listed in Reconstruction.possible_GPU_fields and travels with the
        # rest of the state when the engine switches to the GPU.
        xp = getArrayModule(self.reconstruction.probe)
        self.reconstruction.H = aspw(
            xp.squeeze(self.reconstruction.probe[0, 0, 0, 0, ...]),
            self.reconstruction.dz,
            self.reconstruction.wavelength / self.reconstruction.refrIndex,
            self.reconstruction.Lp,
        )[1]
        # shift transfer function to avoid fftshifts for FFTS
        self.reconstruction.H = xp.fft.ifftshift(self.reconstruction.H)

    def reconstruct(self):
        r"""
        Run the multislice e3PIE reconstruction.

        For each scan position, the corresponding object patch is extracted and
        the incident probe is propagated sequentially through all object slices.

        At the first slice, the exit wave is formed as

        $$
        \Psi_0 = O_0 P_0
        $$

        For each subsequent slice, the exit wave from the previous slice is
        propagated using the precomputed angular-spectrum transfer function
        `reconstruction.H` and multiplied by the local object transmission:

        $$
        P_s = \mathcal{F}^{-1}\left\{\mathcal{F}\{\Psi_{s-1}\}H\right\},
        $$

        where

        $$
        \Psi_s = O_s P_s
        $$

        After propagation through the full object, `intensityProjection()` applies
        the measured diffraction-intensity constraint at the detector plane and
        returns the updated exit wave.

        The resulting correction term is initialized at the final object slice as

        $$
        \Delta\Psi = \Psi' - \Psi
        $$

        The object is then updated sequentially from the last slice back to the
        first using `objectPatchUpdate()`. The corresponding local probe field is
        updated with `probeUpdate()` and the correction is back-propagated to the
        preceding slice using the conjugated transfer function `H.conj()`.

        After all scan positions have been processed, the product of all object
        slices is stored in `reconstruction.objectProd`. Reconstruction errors are
        evaluated with `getErrorMetrics()`, constraints are applied with
        `applyConstraints()`, and `showReconstruction()` updates the reconstruction
        monitor.

        If GPU acceleration is enabled, the reconstruction data are returned to
        CPU memory after completion.
        """

        self._prepareReconstruction()

        # initialize esw
        self.reconstruction.esw = self.reconstruction.probe.copy()
        # get module
        xp = getArrayModule(self.reconstruction.object)

        self.pbar = trange(
            self.numIterations, desc="e3PIE", file=sys.stdout, leave=True
        )

        # self.pbar = (1, 2)

        for loop in self.pbar:
            if loop == self.numIterations - 1:
                noreason = True
            self.setPositionOrder()
            for positionLoop, positionIndex in enumerate(self.positionIndices):
                # get object patch
                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()
                # objectPatch2 = self.reconstruction.object[..., :, :].copy()

                # form first slice esw (exit surface wave)
                self.reconstruction.esw[:, :, :, 0, ...] = (
                    objectPatch[:, :, :, 0, ...]
                    * self.reconstruction.probe[:, :, :, 0, ...]
                )

                # propagate through object
                for sliceLoop in range(1, self.reconstruction.nslice):
                    self.reconstruction.probe[:, :, :, sliceLoop, ...] = xp.fft.ifft2(
                        xp.fft.fft2(
                            self.reconstruction.esw[:, :, :, sliceLoop - 1, ...]
                        )
                        * self.reconstruction.H
                    )
                    self.reconstruction.esw[:, :, :, sliceLoop, ...] = (
                        self.reconstruction.probe[:, :, :, sliceLoop, ...]
                        * objectPatch[:, :, :, sliceLoop, ...]
                    )

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = (self.reconstruction.eswUpdate - self.reconstruction.esw)[
                    :, :, :, -1, ...
                ]
                # update object slice
                for loopTemp in range(self.reconstruction.nslice - 1):
                    sliceLoop = self.reconstruction.nslice - 1 - loopTemp

                    # temp_delta = self.reconstruction.esw[..., sliceLoop, sy, sx]

                    # compute and update current object slice
                    self.reconstruction.object[..., sliceLoop, sy, sx] = (
                        self.objectPatchUpdate(
                            objectPatch[:, :, :, sliceLoop, ...],
                            DELTA,
                            self.reconstruction.probe[:, :, :, sliceLoop, ...],
                        )
                    )
                    # eswTemp update (here probe incident on last slice)
                    beth = 0.9  # todo, why need beth, not betaProbe, changable?
                    self.reconstruction.probe[:, :, :, sliceLoop, ...] = (
                        self.probeUpdate(
                            objectPatch[:, :, :, sliceLoop, ...],
                            DELTA,
                            self.reconstruction.probe[:, :, :, sliceLoop, ...],
                            beth,
                        )
                    )

                    # back-propagate and calculate gradient term
                    DELTA = (
                        xp.fft.ifft2(
                            xp.fft.fft2(
                                self.reconstruction.probe[:, :, :, sliceLoop, ...]
                            )
                            * self.reconstruction.H.conj()
                        )
                        - self.reconstruction.esw[:, :, :, sliceLoop - 1, ...]
                    )

                # update last object slice
                self.reconstruction.object[..., 0, sy, sx] = self.objectPatchUpdate(
                    objectPatch[:, :, :, 0, ...],
                    DELTA,
                    self.reconstruction.probe[:, :, :, 0, ...],
                )
                # update probe
                self.reconstruction.probe[:, :, :, 0, ...] = self.probeUpdate(
                    objectPatch[:, :, :, 0, ...],
                    DELTA,
                    self.reconstruction.probe[:, :, :, 0, ...],
                    self.betaProbe,
                )

            # set porduct of all object slices
            self.reconstruction.objectProd = np.prod(self.reconstruction.object, 3)

            # get error metric
            self.getErrorMetrics()

            # apply Constraints todo uncomment orthogonalization? check object smootheness regularization
            self.applyConstraints(loop)

            # show reconstruction
            self.showReconstruction(loop)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

    def objectPatchUpdate(
        self, objectPatch: np.ndarray, DELTA: np.ndarray, localProbe: np.ndarray
    ):
        """
        Update one object slice using the local ePIE correction.

        The object patch is updated from the exit-wave correction `DELTA` using
        the probe field incident on the current object slice.

        Args:
            objectPatch (np.ndarray):
                Object transmission function of the current slice.

            DELTA (np.ndarray):
                Exit-wave correction propagated to the current slice.

            localProbe (np.ndarray):
                Probe field incident on the current object slice.

        Returns:
            np.ndarray:
                Updated object patch.

        See Also:
                    `ePIE.probeUpdate`
                        Standard ePIE probe update.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        frac = localProbe.conj() / xp.max(
            xp.sum(xp.abs(localProbe) ** 2, axis=(0, 1, 2))
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2), keepdims=True
        )

    def probeUpdate(
        self, objectPatch: np.ndarray, DELTA: np.ndarray, localProbe: np.ndarray, beth
    ):
        """
        Update the local probe field using the ePIE correction.

        Args:
            objectPatch (np.ndarray):
                Object transmission function of the current slice.

            DELTA (np.ndarray):
                Exit-wave correction at the current slice.

            localProbe (np.ndarray):
                Probe field incident on the current object slice.

            beth (float):
                Probe-update step size.

        Returns:
            np.ndarray:
                Updated local probe field.

        See Also:
                    `ePIE.probeUpdate`
                        Standard ePIE probe update.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        frac = objectPatch.conj() / xp.max(
            xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2))
        )
        r = localProbe + beth * xp.sum(frac * DELTA, axis=(0, 1), keepdims=True)
        return r

initializeReconstructionParams()

Initialize parameters specific to the e3PIE reconstruction.

This method sets the object and probe update strengths and the default number of reconstruction iterations.

It also precomputes the angular-spectrum transfer function used to propagate the wavefield between adjacent object slices. The propagation distance is given by reconstruction.dz, and the effective wavelength is reconstruction.wavelength / reconstruction.refrIndex.

Inter-slice propagation is performed in Fourier space as

\[ \Psi_{s+1} = \mathcal{F}^{-1}\left\{\mathcal{F}\{\Psi_s\} H\right\} \]

where \(\Psi_s\) is the exit wave from slice \(s\) and \(H\) is the angular-spectrum transfer function generated by aspw().

The transfer function is stored in reconstruction.H and shifted with ifftshift() so that it can be applied directly during FFT-based propagation between object slices.

Source code in PtyLab/Engines/e3PIE.py
def initializeReconstructionParams(self):
    r"""
    Initialize parameters specific to the e3PIE reconstruction.

    This method sets the object and probe update strengths and the default
    number of reconstruction iterations.

    It also precomputes the angular-spectrum transfer function used to
    propagate the wavefield between adjacent object slices. The propagation
    distance is given by `reconstruction.dz`, and the effective wavelength is
    `reconstruction.wavelength / reconstruction.refrIndex`.

    Inter-slice propagation is performed in Fourier space as

    $$
    \Psi_{s+1} = \mathcal{F}^{-1}\left\{\mathcal{F}\{\Psi_s\} H\right\}
    $$

    where $\Psi_s$ is the exit wave from slice $s$ and $H$ is the
    angular-spectrum transfer function generated by `aspw()`.

    The transfer function is stored in `reconstruction.H` and shifted with
    `ifftshift()` so that it can be applied directly during FFT-based
    propagation between object slices.
    """
    # these are read back as self.betaProbe / self.betaObject in reconstruct()
    # and objectPatchUpdate(), matching every other engine (cf. ePIE.py)
    self.betaProbe = 0.25
    self.betaObject = 0.25
    self.numIterations = 50

    # preallocate transfer function. This runs from __init__, before
    # _checkGPU has moved anything, so the probe is still on the host here;
    # H is listed in Reconstruction.possible_GPU_fields and travels with the
    # rest of the state when the engine switches to the GPU.
    xp = getArrayModule(self.reconstruction.probe)
    self.reconstruction.H = aspw(
        xp.squeeze(self.reconstruction.probe[0, 0, 0, 0, ...]),
        self.reconstruction.dz,
        self.reconstruction.wavelength / self.reconstruction.refrIndex,
        self.reconstruction.Lp,
    )[1]
    # shift transfer function to avoid fftshifts for FFTS
    self.reconstruction.H = xp.fft.ifftshift(self.reconstruction.H)

reconstruct()

Run the multislice e3PIE reconstruction.

For each scan position, the corresponding object patch is extracted and the incident probe is propagated sequentially through all object slices.

At the first slice, the exit wave is formed as

\[ \Psi_0 = O_0 P_0 \]

For each subsequent slice, the exit wave from the previous slice is propagated using the precomputed angular-spectrum transfer function reconstruction.H and multiplied by the local object transmission:

\[ P_s = \mathcal{F}^{-1}\left\{\mathcal{F}\{\Psi_{s-1}\}H\right\}, \]

where

\[ \Psi_s = O_s P_s \]

After propagation through the full object, intensityProjection() applies the measured diffraction-intensity constraint at the detector plane and returns the updated exit wave.

The resulting correction term is initialized at the final object slice as

\[ \Delta\Psi = \Psi' - \Psi \]

The object is then updated sequentially from the last slice back to the first using objectPatchUpdate(). The corresponding local probe field is updated with probeUpdate() and the correction is back-propagated to the preceding slice using the conjugated transfer function H.conj().

After all scan positions have been processed, the product of all object slices is stored in reconstruction.objectProd. Reconstruction errors are evaluated with getErrorMetrics(), constraints are applied with applyConstraints(), and showReconstruction() updates the reconstruction monitor.

If GPU acceleration is enabled, the reconstruction data are returned to CPU memory after completion.

Source code in PtyLab/Engines/e3PIE.py
def reconstruct(self):
    r"""
    Run the multislice e3PIE reconstruction.

    For each scan position, the corresponding object patch is extracted and
    the incident probe is propagated sequentially through all object slices.

    At the first slice, the exit wave is formed as

    $$
    \Psi_0 = O_0 P_0
    $$

    For each subsequent slice, the exit wave from the previous slice is
    propagated using the precomputed angular-spectrum transfer function
    `reconstruction.H` and multiplied by the local object transmission:

    $$
    P_s = \mathcal{F}^{-1}\left\{\mathcal{F}\{\Psi_{s-1}\}H\right\},
    $$

    where

    $$
    \Psi_s = O_s P_s
    $$

    After propagation through the full object, `intensityProjection()` applies
    the measured diffraction-intensity constraint at the detector plane and
    returns the updated exit wave.

    The resulting correction term is initialized at the final object slice as

    $$
    \Delta\Psi = \Psi' - \Psi
    $$

    The object is then updated sequentially from the last slice back to the
    first using `objectPatchUpdate()`. The corresponding local probe field is
    updated with `probeUpdate()` and the correction is back-propagated to the
    preceding slice using the conjugated transfer function `H.conj()`.

    After all scan positions have been processed, the product of all object
    slices is stored in `reconstruction.objectProd`. Reconstruction errors are
    evaluated with `getErrorMetrics()`, constraints are applied with
    `applyConstraints()`, and `showReconstruction()` updates the reconstruction
    monitor.

    If GPU acceleration is enabled, the reconstruction data are returned to
    CPU memory after completion.
    """

    self._prepareReconstruction()

    # initialize esw
    self.reconstruction.esw = self.reconstruction.probe.copy()
    # get module
    xp = getArrayModule(self.reconstruction.object)

    self.pbar = trange(
        self.numIterations, desc="e3PIE", file=sys.stdout, leave=True
    )

    # self.pbar = (1, 2)

    for loop in self.pbar:
        if loop == self.numIterations - 1:
            noreason = True
        self.setPositionOrder()
        for positionLoop, positionIndex in enumerate(self.positionIndices):
            # get object patch
            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()
            # objectPatch2 = self.reconstruction.object[..., :, :].copy()

            # form first slice esw (exit surface wave)
            self.reconstruction.esw[:, :, :, 0, ...] = (
                objectPatch[:, :, :, 0, ...]
                * self.reconstruction.probe[:, :, :, 0, ...]
            )

            # propagate through object
            for sliceLoop in range(1, self.reconstruction.nslice):
                self.reconstruction.probe[:, :, :, sliceLoop, ...] = xp.fft.ifft2(
                    xp.fft.fft2(
                        self.reconstruction.esw[:, :, :, sliceLoop - 1, ...]
                    )
                    * self.reconstruction.H
                )
                self.reconstruction.esw[:, :, :, sliceLoop, ...] = (
                    self.reconstruction.probe[:, :, :, sliceLoop, ...]
                    * objectPatch[:, :, :, sliceLoop, ...]
                )

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = (self.reconstruction.eswUpdate - self.reconstruction.esw)[
                :, :, :, -1, ...
            ]
            # update object slice
            for loopTemp in range(self.reconstruction.nslice - 1):
                sliceLoop = self.reconstruction.nslice - 1 - loopTemp

                # temp_delta = self.reconstruction.esw[..., sliceLoop, sy, sx]

                # compute and update current object slice
                self.reconstruction.object[..., sliceLoop, sy, sx] = (
                    self.objectPatchUpdate(
                        objectPatch[:, :, :, sliceLoop, ...],
                        DELTA,
                        self.reconstruction.probe[:, :, :, sliceLoop, ...],
                    )
                )
                # eswTemp update (here probe incident on last slice)
                beth = 0.9  # todo, why need beth, not betaProbe, changable?
                self.reconstruction.probe[:, :, :, sliceLoop, ...] = (
                    self.probeUpdate(
                        objectPatch[:, :, :, sliceLoop, ...],
                        DELTA,
                        self.reconstruction.probe[:, :, :, sliceLoop, ...],
                        beth,
                    )
                )

                # back-propagate and calculate gradient term
                DELTA = (
                    xp.fft.ifft2(
                        xp.fft.fft2(
                            self.reconstruction.probe[:, :, :, sliceLoop, ...]
                        )
                        * self.reconstruction.H.conj()
                    )
                    - self.reconstruction.esw[:, :, :, sliceLoop - 1, ...]
                )

            # update last object slice
            self.reconstruction.object[..., 0, sy, sx] = self.objectPatchUpdate(
                objectPatch[:, :, :, 0, ...],
                DELTA,
                self.reconstruction.probe[:, :, :, 0, ...],
            )
            # update probe
            self.reconstruction.probe[:, :, :, 0, ...] = self.probeUpdate(
                objectPatch[:, :, :, 0, ...],
                DELTA,
                self.reconstruction.probe[:, :, :, 0, ...],
                self.betaProbe,
            )

        # set porduct of all object slices
        self.reconstruction.objectProd = np.prod(self.reconstruction.object, 3)

        # get error metric
        self.getErrorMetrics()

        # apply Constraints todo uncomment orthogonalization? check object smootheness regularization
        self.applyConstraints(loop)

        # show reconstruction
        self.showReconstruction(loop)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

objectPatchUpdate(objectPatch, DELTA, localProbe)

Update one object slice using the local ePIE correction.

The object patch is updated from the exit-wave correction DELTA using the probe field incident on the current object slice.

Parameters:

Name Type Description Default
objectPatch ndarray

Object transmission function of the current slice.

required
DELTA ndarray

Exit-wave correction propagated to the current slice.

required
localProbe ndarray

Probe field incident on the current object slice.

required

Returns:

Type Description
ndarray

Updated object patch.

See Also

ePIE.probeUpdate Standard ePIE probe update.

Source code in PtyLab/Engines/e3PIE.py
def objectPatchUpdate(
    self, objectPatch: np.ndarray, DELTA: np.ndarray, localProbe: np.ndarray
):
    """
    Update one object slice using the local ePIE correction.

    The object patch is updated from the exit-wave correction `DELTA` using
    the probe field incident on the current object slice.

    Args:
        objectPatch (np.ndarray):
            Object transmission function of the current slice.

        DELTA (np.ndarray):
            Exit-wave correction propagated to the current slice.

        localProbe (np.ndarray):
            Probe field incident on the current object slice.

    Returns:
        np.ndarray:
            Updated object patch.

    See Also:
                `ePIE.probeUpdate`
                    Standard ePIE probe update.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    frac = localProbe.conj() / xp.max(
        xp.sum(xp.abs(localProbe) ** 2, axis=(0, 1, 2))
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2), keepdims=True
    )

probeUpdate(objectPatch, DELTA, localProbe, beth)

Update the local probe field using the ePIE correction.

Parameters:

Name Type Description Default
objectPatch ndarray

Object transmission function of the current slice.

required
DELTA ndarray

Exit-wave correction at the current slice.

required
localProbe ndarray

Probe field incident on the current object slice.

required
beth float

Probe-update step size.

required

Returns:

Type Description
ndarray

Updated local probe field.

See Also

ePIE.probeUpdate Standard ePIE probe update.

Source code in PtyLab/Engines/e3PIE.py
def probeUpdate(
    self, objectPatch: np.ndarray, DELTA: np.ndarray, localProbe: np.ndarray, beth
):
    """
    Update the local probe field using the ePIE correction.

    Args:
        objectPatch (np.ndarray):
            Object transmission function of the current slice.

        DELTA (np.ndarray):
            Exit-wave correction at the current slice.

        localProbe (np.ndarray):
            Probe field incident on the current object slice.

        beth (float):
            Probe-update step size.

    Returns:
        np.ndarray:
            Updated local probe field.

    See Also:
                `ePIE.probeUpdate`
                    Standard ePIE probe update.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    frac = objectPatch.conj() / xp.max(
        xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2))
    )
    r = localProbe + beth * xp.sum(frac * DELTA, axis=(0, 1), keepdims=True)
    return r

OPR

Bases: BaseEngine

Orthogonal Probe Relaxation (OPR) for position-dependent probe reconstruction.

OPR extends conventional ptychographic reconstruction by allowing the illumination probe to vary between scan positions while constraining these variations to a low-dimensional orthogonal probe subspace.1

For scan position \(j\), the exit surface wave is formed as

\[ \Psi_j(\mathbf{r}) = O_j(\mathbf{r}) P_j(\mathbf{r}) \]

where \(O_j\) is the object patch illuminated at position \(j\) and \(P_j\) is the position-dependent probe.

Instead of enforcing a single identical probe for all diffraction frames, OPR maintains a probe estimate for each scan position. The set of position-dependent probes is stored in reconstruction.probe_stack.

At initialization, the selected probe modes defined by params.OPR_modes are copied to all scan positions. During reconstruction, the probe corresponding to the current diffraction frame is loaded from the probe stack, updated by the PIE step, and written back to the same scan position.

Allowing an independent probe at every scan position introduces many additional degrees of freedom. OPR therefore constrains the probe variations to a low-dimensional subspace. For one selected probe mode, the position-dependent probes are arranged as columns of the matrix

\[ A = \begin{bmatrix} | & | & & | \\ P_1 & P_2 & \cdots & P_N \\ | & | & & | \end{bmatrix} \]

where each probe is flattened into a vector and \(N\) is the number of scan positions.

A truncated singular-value decomposition is used to approximate the probe stack as

\[ A \approx U_K S_K V_K^{\dagger} \]

where \(K =\) params.OPR_subspace is the retained subspace dimension. Equivalently, the probe at scan position \(j\) can be represented as a linear combination of a small number of orthogonal probe basis functions,

\[ P_j(\mathbf{r}) = \sum_{k=1}^{K} c_{k,j}\Phi_k(\mathbf{r}) \]

thereby allowing systematic probe variations while suppressing unconstrained frame-to-frame fluctuations.

The low-rank probe estimate is blended with the current probe stack using \(\alpha =\) params.OPR_alpha,

\[ P^{\mathrm{new}} = \alpha P^{\mathrm{old}} + (1-\alpha)P^{\mathrm{low-rank}} \]

The truncated decomposition can be computed using the method selected by params.OPR_tsvd_type. The current implementation supports standard SVD, randomized SVD, and a Gram-matrix-based truncated SVD.

OPR regularization acts at two complementary levels. Despite of a low-rank constraint on the position-dependent probe stack, if params.OPR_neighbor_constraint is enabled, the subspace coefficients \(c_{k,j}\) are additionally averaged over neighboring scan positions. This imposes smoothness along the scan sequence and suppresses abrupt changes in the contribution of each probe basis mode. The two constraints therefore regularize different aspects of the probe variation: the low-rank constraint limits which spatial variations are allowed, while the neighbor constraint limits how rapidly their coefficients may change between successive scan positions.

OPR can also be combined with mixed-state ptychography.2 Multiple mutually incoherent probe modes are used to describe partial coherence within each diffraction frame, while OPR accounts for systematic changes of these probe modes between scan positions.

These two descriptions address different probe degrees of freedom. The mixed-state model represents the illumination as an incoherent sum of probe modes,

\[ I_j(\mathbf{q}) = \sum_m \left| \mathcal{F}\left[P_{m,j}(\mathbf{r}) O_j(\mathbf{r})\right] \right|^2 \]

where \(m\) indexes the mutually incoherent probe modes. OPR additionally allows the individual probe modes \(P_{m,j}\) to vary with scan position \(j\) while constraining their position dependence to a low-dimensional orthogonal subspace.

In the current implementation, the probe modes included in OPR are selected through params.OPR_modes. If params.OPR_orthogonalize_modes is enabled, orthogonalizeIncoherentModes() orthogonalizes the incoherent probe modes independently at each scan position before the position-dependent probe stack is projected onto the OPR subspace.

If params.OPR_tv is enabled, total-variation object updates are applied at the interval specified by params.OPR_tv_freq.


  1. M. Odstrčil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, and W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation," Opt. Express 24, 8360-8369 (2016). https://doi.org/10.1364/OE.24.008360 ↩

  2. W. Eschen, L. Loetgering, V. Schuster, R. Klas, A. Kirsche, L. Berthold, M. Steinert, T. Pertsch, H. Gross, M. Krause, J. Limpert, and J. Rothhardt, "Material-specific high-resolution table-top extreme ultraviolet microscopy," Light Sci. Appl. 11, 117 (2022). https://doi.org/10.1038/s41377-022-00797-6 ↩

Implementation Notes

The current OPR implementation requires CuPy and GPU execution. Several probe-stack operations are implemented directly with CuPy rather than through the NumPy/CuPy abstraction used elsewhere in PtyLab. CPU-only execution is therefore not currently supported.

Source code in PtyLab/Engines/OPR.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
class OPR(BaseEngine):
    r"""
    Orthogonal Probe Relaxation (OPR) for position-dependent probe reconstruction.

    `OPR` extends conventional ptychographic reconstruction by allowing the
    illumination probe to vary between scan positions while constraining these
    variations to a low-dimensional orthogonal probe subspace.[^odstrcil2016]

    For scan position $j$, the exit surface wave is formed as

    $$
    \Psi_j(\mathbf{r}) = O_j(\mathbf{r}) P_j(\mathbf{r})
    $$

    where $O_j$ is the object patch illuminated at position $j$ and $P_j$ is
    the position-dependent probe.

    Instead of enforcing a single identical probe for all diffraction frames,
    OPR maintains a probe estimate for each scan position. The set of
    position-dependent probes is stored in `reconstruction.probe_stack`.

    At initialization, the selected probe modes defined by `params.OPR_modes`
    are copied to all scan positions. During reconstruction, the probe
    corresponding to the current diffraction frame is loaded from the probe
    stack, updated by the PIE step, and written back to the same scan position.

    Allowing an independent probe at every scan position introduces many
    additional degrees of freedom. OPR therefore constrains the probe
    variations to a low-dimensional subspace. For one selected probe mode,
    the position-dependent probes are arranged as columns of the matrix

    $$
    A = \begin{bmatrix} | & | & & | \\ P_1 & P_2 & \cdots & P_N \\ | & | & & | \end{bmatrix}
    $$

    where each probe is flattened into a vector and $N$ is the number of scan
    positions.

    A truncated singular-value decomposition is used to approximate the probe
    stack as

    $$
    A \approx U_K S_K V_K^{\dagger}
    $$

    where $K =$ `params.OPR_subspace` is the retained subspace
    dimension. Equivalently, the probe at scan position $j$ can be represented
    as a linear combination of a small number of orthogonal probe basis
    functions,

    $$
    P_j(\mathbf{r}) = \sum_{k=1}^{K} c_{k,j}\Phi_k(\mathbf{r})
    $$

    thereby allowing systematic probe variations while suppressing
    unconstrained frame-to-frame fluctuations.

    The low-rank probe estimate is blended with the current probe stack using
    $\alpha =$ `params.OPR_alpha`,

    $$
    P^{\mathrm{new}} = \alpha P^{\mathrm{old}} + (1-\alpha)P^{\mathrm{low-rank}}
    $$

    The truncated decomposition can be computed using the method selected by
    `params.OPR_tsvd_type`. The current implementation supports standard SVD,
    randomized SVD, and a Gram-matrix-based truncated SVD.

    OPR regularization acts at two complementary levels. Despite of a low-rank
    constraint on the position-dependent probe stack, if `params.OPR_neighbor_constraint` is enabled, the subspace
    coefficients $c_{k,j}$ are additionally averaged over neighboring scan
    positions. This imposes smoothness along the scan sequence and suppresses
    abrupt changes in the contribution of each probe basis mode. The two constraints therefore regularize different aspects of the probe
    variation: the low-rank constraint limits which spatial variations are
    allowed, while the neighbor constraint limits how rapidly their coefficients
    may change between successive scan positions.

    OPR can also be combined with mixed-state ptychography.[^eschen2022]
    Multiple mutually incoherent probe modes are used to describe partial
    coherence within each diffraction frame, while OPR accounts for systematic
    changes of these probe modes between scan positions.

    These two descriptions address different probe degrees of freedom. The
    mixed-state model represents the illumination as an incoherent sum of probe
    modes,

    $$
    I_j(\mathbf{q}) = \sum_m \left| \mathcal{F}\left[P_{m,j}(\mathbf{r}) O_j(\mathbf{r})\right] \right|^2
    $$

    where $m$ indexes the mutually incoherent probe modes. OPR additionally
    allows the individual probe modes $P_{m,j}$ to vary with scan position $j$
    while constraining their position dependence to a low-dimensional
    orthogonal subspace.

    In the current implementation, the probe modes included in OPR are selected
    through `params.OPR_modes`. If `params.OPR_orthogonalize_modes` is enabled,
    `orthogonalizeIncoherentModes()` orthogonalizes the incoherent probe modes
    independently at each scan position before the position-dependent probe stack
    is projected onto the OPR subspace.

    If `params.OPR_tv` is enabled, total-variation object updates are applied
    at the interval specified by `params.OPR_tv_freq`.

    [^odstrcil2016]: M. Odstrčil, P. Baksh, S. A. Boden,
            R. Card, J. E. Chad, J. G. Frey, and W. S. Brocklesby,
            "Ptychographic coherent diffractive imaging with orthogonal probe relaxation,"
            Opt. Express 24, 8360-8369 (2016).
            https://doi.org/10.1364/OE.24.008360

    [^eschen2022]: W. Eschen, L. Loetgering, V. Schuster, R. Klas,
            A. Kirsche, L. Berthold, M. Steinert, T. Pertsch, H. Gross,
            M. Krause, J. Limpert, and J. Rothhardt,
            "Material-specific high-resolution table-top extreme ultraviolet microscopy,"
            Light Sci. Appl. 11, 117 (2022).
            https://doi.org/10.1038/s41377-022-00797-6

    Implementation Notes:
            The current OPR implementation requires CuPy and GPU execution.
            Several probe-stack operations are implemented directly with CuPy
            rather than through the NumPy/CuPy abstraction used elsewhere in
            PtyLab. CPU-only execution is therefore not currently supported.
    """
    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        # This contains reconstruction parameters that are specific to the reconstruction
        # but not necessarily to ePIE reconstruction
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("ePIE")
        self.logger.info("Sucesfully created ePIE ePIE_engine")
        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        self.initializeReconstructionParams()

    def initializeReconstructionParams(self):
        """
        Initialize parameters specific to the OPR reconstruction.

        The OPR relaxation strength, selected probe modes, and retained
        position-dependent probe subspace dimension are read from
        `params.OPR_alpha`, `params.OPR_modes`, and `params.OPR_subspace`,
        respectively.

        This method also sets the default object and probe update strengths and
        the number of reconstruction iterations. In addition, it defines the
        working-memory budget used by the batched incoherent-mode
        orthogonalization routine.

        The main OPR parameters initialized here are:

        - `alpha`:
        Blending factor between the current probe stack and its low-rank OPR
        approximation.

        - `OPR_modes`:
        Probe-mode indices for which position-dependent probe relaxation is
        applied.

        - `n_subspace`:
        Number of dominant OPR subspace components retained during the
        truncated singular-value decomposition.
        """
        self.alpha = self.params.OPR_alpha
        self.betaProbe = 0.25
        self.betaObject = 0.25
        self.numIterations = 50
        self.OPR_modes = self.params.OPR_modes
        self.n_subspace = self.params.OPR_subspace
        # Working-set budget for the chunked batched orthogonalization. Keeps
        # the transpose scratch bounded independently of the frame count.
        self._orthogonalization_chunk_bytes = 128 * 2**20

    def reconstruct(self):
        r"""
        Run the Orthogonal Probe Relaxation reconstruction.

        For each reconstruction iteration, a position-dependent probe is loaded
        from `reconstruction.probe_stack` for the current scan position. The exit
        surface wave is then formed from the local object patch and the selected
        probe, followed by `intensityProjection()` to apply the measured
        diffraction-intensity constraint.

        The resulting exit-wave correction

        $$
        \Delta\Psi_j = \Psi'_j - \Psi_j
        $$

        is used to update the object and probe through `objectPatchUpdate()` and
        `probeUpdate()`. If `params.OPR_tv` is enabled, the object update is
        periodically replaced by `objectPatchUpdate_TV()` according to
        `params.OPR_tv_freq`.

        After each probe update, the selected probe modes are written back to
        `reconstruction.probe_stack` at the corresponding scan position.

        Once all scan positions have been processed, the position-dependent probe
        stack is regularized. If `params.OPR_orthogonalize_modes` is enabled,
        `orthogonalizeIncoherentModes()` first orthogonalizes the incoherent probe
        modes independently at each scan position.

        The complete probe stack is then projected onto a low-dimensional
        position-dependent subspace using `orthogonalizeProbeStack()`, with the
        retained subspace dimension given by `params.OPR_subspace`.

        Finally, reconstruction errors are evaluated with `getErrorMetrics()`,
        the remaining reconstruction constraints are applied with
        `applyConstraints()`, and `showReconstruction()` updates the monitor.

        If GPU acceleration is enabled, the reconstruction data are returned to
        CPU memory after completion.
        """

        self._prepareReconstruction()

        # OPR parameters
        Nmodes = self.OPR_modes.shape[0]
        Np = self.reconstruction.Np
        Nframes = self.experimentalData.numFrames
        mode_slice = self.OPR_modes
        n_subspace = self.n_subspace

        self.reconstruction.probe_stack = cp.zeros(
            (1, 1, Nmodes, 1, Np, Np, Nframes), dtype=cp.complex64
        )

        for i, mode in enumerate(self.OPR_modes):
            # fill the probe-stack with the inital guess of the probes
            self.reconstruction.probe_stack[0, 0, i, 0, :, :, :] = cp.repeat(
                self.reconstruction.probe[0, 0, mode, 0, :, :, cp.newaxis],
                Nframes,
                axis=2,
            )

        # actual reconstruction ePIE_engine
        self.pbar = trange(self.numIterations, desc="OPR", file=sys.stdout, leave=True)
        for loop in self.pbar:
            self.it = loop
            # set position order
            self.setPositionOrder()
            for positionLoop, positionIndex in enumerate(self.positionIndices):
                # get object patch
                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # Get dim reduced probe
                self.reconstruction.probe[:, :, mode_slice, :, :, :] = (
                    self.reconstruction.probe_stack[..., positionIndex]
                )

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                if loop % self.params.OPR_tv_freq == 0 and self.params.OPR_tv:
                    self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate_TV(
                        objectPatch, DELTA
                    )
                else:
                    # object update
                    self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                        objectPatch, DELTA
                    )

                # probe update
                self.reconstruction.probe = self.probeUpdate(
                    objectPatch, DELTA, weight=1
                )

                # save first, dominant probe mode
                self.reconstruction.probe_stack[..., positionIndex] = cp.copy(
                    self.reconstruction.probe[:, :, mode_slice, :, :, :]
                )

            # get error metric
            self.getErrorMetrics()

            if self.params.OPR_orthogonalize_modes:
                self.orthogonalizeIncoherentModes()

            self.reconstruction.probe_stack = self.orthogonalizeProbeStack(
                self.reconstruction.probe_stack, n_subspace
            )

            # apply Constraints
            self.applyConstraints(loop)

            # show reconstruction
            self.showReconstruction(loop)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

    def orthogonalizeIncoherentModes(self):
        r"""
        Orthogonalize the incoherent probe modes at each scan position.

        For every position in `reconstruction.probe_stack`, the selected probe
        modes are reshaped into a two-dimensional matrix with one row per
        incoherent mode and one column per probe pixel.

        An SVD is then performed,

        $$
        P = U S V^\dagger
        $$

        and the probe modes are replaced by

        $$
        S V^\dagger
        $$

        which provides an equivalent orthogonal representation of the same
        mixed-state probe subspace.

        The orthogonalization is applied independently at every scan position and
        does not alter the position-dependent OPR subspace itself.

        If `params.OPR_fast_orthogonalization` is enabled, the batched
        Gram-matrix implementation `_orthogonalizeIncoherentModes_batched()` is
        used instead of the frame-by-frame SVD. For a probe-mode matrix $P$, the left singular vectors of $P$ are also
        the eigenvectors of the much smaller Gram matrix

        $$
        G = P P^\dagger
        $$

        Since the number of incoherent probe modes is typically much smaller than
        the number of probe pixels, $G$ has shape
        `(nModes, nModes)` and can be factorized much more efficiently than the
        full probe matrix. The orthogonal modes are then obtained from

        $$
        U^\dagger P
        $$

        which is equivalent to $S V^\dagger$.

        The batched implementation performs this operation for multiple scan
        positions simultaneously and processes the probe stack in chunks to limit
        temporary memory usage.
        """
        if self.params.OPR_fast_orthogonalization:
            return self._orthogonalizeIncoherentModes_batched()

        nFrames = self.experimentalData.numFrames
        n = self.reconstruction.Np
        nModes = self.reconstruction.probe_stack.shape[2]
        for pos in range(nFrames):
            probe = self.reconstruction.probe_stack[0, 0, :, 0, :, :, pos]
            probe = probe.reshape(nModes, n * n)

            U, s, Vh = self.svd(probe)

            modes = (s[:, None] * Vh).reshape(nModes, n, n)
            self.reconstruction.probe_stack[0, 0, :, 0, :, :, pos] = modes

    def _orthogonalizeIncoherentModes_batched(self):
        """Batched Gram-matrix equivalent of :meth:`orthogonalizeIncoherentModes`.

        For each frame the loop above computes ``s[:, None] * Vh`` from the SVD
        of a ``(nModes, Np**2)`` matrix P. Since ``P = U S Vh``, that product is
        just ``U^H P``, and U is the left singular matrix of the *tiny*
        ``(nModes, nModes)`` Gram matrix ``P P^H``. So the whole thing reduces to
        a batched factorization of a handful of 4x4 matrices plus one batched
        matmul -- no large SVD, and one kernel launch per chunk instead of one
        per frame.

        Measured 4.1x faster than the loop at 364 px / 202 frames / 4 modes, and
        1.8x at 512 px / 890 frames / 6 modes. The advantage *shrinks* with size:
        the loop's cost is dominated by per-frame launch overhead at small sizes,
        which is exactly what batching removes, while at large sizes the
        factorization itself dominates and batching has less to hide.

        Caveat: eigenvectors are only defined up to a per-mode phase, and when
        two modes carry near-equal power the vectors within that subspace are
        not determined at all. The mode *powers* (singular values) and the
        spanned subspace are reproduced exactly; individual mode vectors may
        differ from LAPACK's arbitrary choice. Guarded by
        ``params.OPR_fast_orthogonalization``.
        """
        stack = self.reconstruction.probe_stack
        xp = getArrayModule(stack)
        n = self.reconstruction.Np
        nModes = stack.shape[2]
        nFrames = stack.shape[-1]

        # Transposing the whole stack at once would allocate a second (and
        # third) copy of it -- 2.4 GB for a 364 px / 202 frame / 4 mode run, on
        # top of the stack itself. Work in frame chunks so the extra allocation
        # stays bounded regardless of frame count; the batched call is already
        # wide enough at a few dozen frames to hide launch overhead.
        elements_per_frame = nModes * n * n
        chunk = int(
            max(
                1,
                self._orthogonalization_chunk_bytes
                // (elements_per_frame * stack.dtype.itemsize),
            )
        )

        flat = stack[0, 0, :, 0, :, :, :].reshape(nModes, n * n, nFrames)
        for start in range(0, nFrames, chunk):
            stop = min(start + chunk, nFrames)
            # (nModes, Np**2, chunk) -> (chunk, nModes, Np**2)
            P = xp.ascontiguousarray(xp.moveaxis(flat[:, :, start:stop], 2, 0))
            G = P @ P.conj().transpose(0, 2, 1)
            # batched SVD of the tiny Hermitian Gram matrices; see gram_tsvd for
            # why this is used in preference to eigh. Already ordered by
            # descending mode power.
            U, _w, _Vh = xp.linalg.svd(G)
            modes = U.conj().transpose(0, 2, 1) @ P
            flat[:, :, start:stop] = xp.moveaxis(modes, 0, 2)
            del P, G, U, modes

    def average(self, arr):
        r"""
        Smooth a one-dimensional array by averaging neighboring values.

        Each interior element is replaced by the average of itself and its two
        nearest neighbors,

        $$
        a_j^{\mathrm{new}} = \frac{a_{j-1} + a_j + a_{j+1}}{3}
        $$

        while the first and last elements are averaged only with their single
        available neighbor.

        In OPR, this operation is used to smooth the position-dependent subspace
        coefficients when `params.OPR_neighbor_constraint` is enabled, thereby
        suppressing abrupt probe variations between successive scan positions.

        Args:
            arr (array-like):
                One-dimensional array of position-dependent coefficients.

        Returns:
            array-like:
                Smoothed array with the same shape as the input.

        Notes:
            This implementation currently operates on CuPy arrays and therefore
            requires GPU support.
        """

        arr_start = arr[:-1]
        arr_end = arr[1:]
        arr_end = cp.append(arr_end, 0)
        arr_start = cp.append(0, arr_start)
        divider = cp.ones_like(arr) * 3
        divider[0] = 2
        divider[-1] = 2
        return (arr + arr_end + arr_start) / divider

    def svd(self, P):
        r"""
        Compute the reduced singular-value decomposition of a matrix.

        The decomposition

        $$
        P = U S V^\dagger
        $$

        is evaluated with CuPy when `P` is stored on the GPU and with NumPy
        otherwise. In both cases, `full_matrices=False` is used to return the
        reduced SVD.

        Args:
            P (array-like):
                Input matrix to decompose.

        Returns:
            tuple:
                `(U, s, Vh)`, where `U` and `Vh` contain the left and right
                singular vectors and `s` contains the singular values.
        """
        if isGpuArray(P):
            try:
                return cp.linalg.svd(P, full_matrices=False)
            except:
                print(
                    "Something is wrong with SVD on cuda. Probably an installation error"
                )
                raise
        A, v, At = np.linalg.svd(asNumpyArray(P), full_matrices=False)
        if isGpuArray(P):
            A = cp.array(A)
            v = cp.array(v)
            At = cp.array(At)
        return A, v, At

    def rsvd(self, P, n_dim):
        """
        Compute a randomized truncated singular-value decomposition.

        This method delegates to `PtyLab.utils.fsvd.rsvd()` and returns a
        low-rank approximation of the input matrix using the requested subspace
        dimension.

        Args:
            P (array-like):
                Input matrix to decompose.

            n_dim (int):
                Number of singular components to retain.

        Returns:
            tuple:
                `(U, s, Vh)`, containing the truncated left singular vectors,
                singular values, and right singular vectors.
        """
        return rsvd(P, n_dim)
        # A, v, At = self.svd(P)
        # v[n_dim:] = 0
        # return A, v, At

    @staticmethod
    def gram_tsvd(A, n_dim):
        r"""
        Compute a truncated SVD through the Gram matrix.

        For a tall matrix $A$, the method forms the smaller Gram matrix

        $$
        G = A^\dagger A
        $$

        and uses

        $$
        A^\dagger A = V S^2 V^\dagger
        $$

        to recover the truncated singular-value decomposition of `A`. The retained
        left singular vectors are reconstructed from

        $$
        U = A V S^{-1}
        $$

        using the first `n_dim` components.

        The Gram matrix is formed in double precision for improved numerical
        stability, and division by numerically zero singular values is guarded.

        Args:
            A (array-like):
                Input matrix.

            n_dim (int):
                Number of singular components to retain.

        Returns:
            tuple:
                `(U, s, Vh)` containing the truncated singular-value decomposition.
        """
        xp = getArrayModule(A)
        n_dim = int(min(n_dim, A.shape[1]))

        G = (A.conj().T @ A).astype(xp.complex128)
        # G is Hermitian positive semi-definite, so its SVD and its
        # eigendecomposition coincide: the left singular vectors are the
        # eigenvectors and the singular values are the eigenvalues, already in
        # descending order. We use svd rather than eigh because eigh routes
        # through cupyx.cusolver, which is not importable in every CuPy/CUDA
        # installation (it needs libcusolver at a version cupy-cuda12x does not
        # always ship), whereas svd works through cupy's own bindings.
        V, w, _Vh = xp.linalg.svd(G)
        w = w[:n_dim]
        V = V[:, :n_dim]

        s = xp.sqrt(xp.clip(w.real, 0.0, None))
        V = V.astype(A.dtype)
        # guard the division for numerically-zero singular values
        s_safe = xp.where(s > 0, s, 1.0)
        U = (A @ V) / s_safe.astype(A.real.dtype)[None, :]
        return U, s.astype(A.real.dtype), V.conj().T

    def orthogonalizeProbeStack(self, probe_stack, n_dim):
        r"""
        Project the position-dependent probe stack onto a low-dimensional subspace.

        For each probe mode selected by `params.OPR_modes`, the probes from all
        scan positions are reshaped into a matrix

        $$
        A \in \mathbb{C}^{N_p^2 \times N_{\mathrm{frames}}}
        $$

        whose columns contain the flattened probe estimates at individual scan
        positions.

        A truncated singular-value decomposition is then computed using the method
        selected by `params.OPR_tsvd_type`. Only `n_dim` dominant components are
        retained, yielding a low-rank approximation of the position-dependent
        probe stack.

        If `params.OPR_neighbor_constraint` is enabled, the position-dependent
        subspace coefficients are smoothed over neighboring scan positions before
        the probe stack is reconstructed.

        The low-rank approximation is blended with the current probe stack using

        $$
        P^{\mathrm{new}} = \alpha P^{\mathrm{old}} + (1-\alpha)P^{\mathrm{low-rank}}
        $$

        where `alpha = params.OPR_alpha`.

        Args:
            probe_stack (array-like):
                Position-dependent probe stack.

            n_dim (int):
                Number of OPR subspace components to retain.

        Returns:
            array-like:
                Regularized probe stack with the same shape as the input.
        """
        xp = getArrayModule(probe_stack)
        n = self.reconstruction.Np
        nFrames = self.experimentalData.numFrames

        for i, mode in enumerate(self.OPR_modes):
            A = probe_stack[:, :, i, :, :, :].reshape(n * n, nFrames)

            if self.params.OPR_tsvd_type == "randomized":
                U, s, Vh = self.rsvd(A, n_dim)
            elif self.params.OPR_tsvd_type == "gram":
                U, s, Vh = self.gram_tsvd(A, n_dim)
            elif self.params.OPR_tsvd_type == "numpy":
                U, s, Vh = xp.linalg.svd(A, full_matrices=False)
                s = s.copy()
                s[n_dim:] = 0
            else:
                raise ValueError(
                    f"unknown OPR_tsvd_type {self.params.OPR_tsvd_type!r}; "
                    f"expected 'numpy', 'gram' or 'randomized'"
                )

            if self.params.OPR_neighbor_constraint:
                # Calculate the average of neigboring singular values
                content = s[:, None] * Vh
                for j in range(min(n_dim, content.shape[0])):
                    content[j] = self.average(content[j])

                probe_stack[:, :, i, :, :, :] = self.alpha * probe_stack[
                    :, :, i, :, :, :
                ] + (1 - self.alpha) * (U @ content).reshape(n, n, nFrames)
            else:
                update = (U @ (s[:, None] * Vh)).reshape(n, n, nFrames)
                probe_stack[:, :, i, :, :, :] *= self.alpha
                probe_stack[:, :, i, :, :, :] += (1 - self.alpha) * update

        return probe_stack

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        """
        Update the object patch using the ePIE correction.

        The object update uses the current probe and exit-wave correction `DELTA`
        with normalization by the maximum probe intensity.

        Args:
            objectPatch (np.ndarray):
                Current object patch at the scan position.

            DELTA (np.ndarray):
                Exit-wave correction after the intensity projection.

        Returns:
            np.ndarray:
                Updated object patch.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)

        frac = self.reconstruction.probe.conj() / xp.max(
            xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2, 3), keepdims=True
        )

    def probeUpdate(
        self, objectPatch: np.ndarray, DELTA: np.ndarray, weight: float, gimmel=0.1
    ):
        """
        Update the probe using the ePIE correction.

        The probe update is computed from the current object patch and exit-wave
        correction `DELTA`. The normalization includes the regularization term
        `gimmel` to avoid excessively large updates when the object intensity is
        small.

        The update can additionally be scaled by `weight`. In the current OPR
        reconstruction workflow, `weight` is set to 1.

        Args:
            objectPatch (np.ndarray):
                Current object patch at the scan position.

            DELTA (np.ndarray):
                Exit-wave correction after the intensity projection.

            weight (float):
                Multiplicative weight applied to the probe update.

            gimmel (float, optional):
                Small positive regularization term added to the normalization
                denominator. Default is `0.1`.

        Returns:
            np.ndarray:
                Updated probe.
        """
        # find out which array module to use, numpy or cupy (or other...)
        xp = getArrayModule(objectPatch)
        frac = objectPatch.conj() / (
            xp.max(xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))) + gimmel
        )
        frac = frac * weight
        r = self.reconstruction.probe + self.betaProbe * xp.sum(
            frac * DELTA, axis=(0, 1, 3), keepdims=True
        )
        return r

initializeReconstructionParams()

Initialize parameters specific to the OPR reconstruction.

The OPR relaxation strength, selected probe modes, and retained position-dependent probe subspace dimension are read from params.OPR_alpha, params.OPR_modes, and params.OPR_subspace, respectively.

This method also sets the default object and probe update strengths and the number of reconstruction iterations. In addition, it defines the working-memory budget used by the batched incoherent-mode orthogonalization routine.

The main OPR parameters initialized here are:

  • alpha: Blending factor between the current probe stack and its low-rank OPR approximation.

  • OPR_modes: Probe-mode indices for which position-dependent probe relaxation is applied.

  • n_subspace: Number of dominant OPR subspace components retained during the truncated singular-value decomposition.

Source code in PtyLab/Engines/OPR.py
def initializeReconstructionParams(self):
    """
    Initialize parameters specific to the OPR reconstruction.

    The OPR relaxation strength, selected probe modes, and retained
    position-dependent probe subspace dimension are read from
    `params.OPR_alpha`, `params.OPR_modes`, and `params.OPR_subspace`,
    respectively.

    This method also sets the default object and probe update strengths and
    the number of reconstruction iterations. In addition, it defines the
    working-memory budget used by the batched incoherent-mode
    orthogonalization routine.

    The main OPR parameters initialized here are:

    - `alpha`:
    Blending factor between the current probe stack and its low-rank OPR
    approximation.

    - `OPR_modes`:
    Probe-mode indices for which position-dependent probe relaxation is
    applied.

    - `n_subspace`:
    Number of dominant OPR subspace components retained during the
    truncated singular-value decomposition.
    """
    self.alpha = self.params.OPR_alpha
    self.betaProbe = 0.25
    self.betaObject = 0.25
    self.numIterations = 50
    self.OPR_modes = self.params.OPR_modes
    self.n_subspace = self.params.OPR_subspace
    # Working-set budget for the chunked batched orthogonalization. Keeps
    # the transpose scratch bounded independently of the frame count.
    self._orthogonalization_chunk_bytes = 128 * 2**20

reconstruct()

Run the Orthogonal Probe Relaxation reconstruction.

For each reconstruction iteration, a position-dependent probe is loaded from reconstruction.probe_stack for the current scan position. The exit surface wave is then formed from the local object patch and the selected probe, followed by intensityProjection() to apply the measured diffraction-intensity constraint.

The resulting exit-wave correction

\[ \Delta\Psi_j = \Psi'_j - \Psi_j \]

is used to update the object and probe through objectPatchUpdate() and probeUpdate(). If params.OPR_tv is enabled, the object update is periodically replaced by objectPatchUpdate_TV() according to params.OPR_tv_freq.

After each probe update, the selected probe modes are written back to reconstruction.probe_stack at the corresponding scan position.

Once all scan positions have been processed, the position-dependent probe stack is regularized. If params.OPR_orthogonalize_modes is enabled, orthogonalizeIncoherentModes() first orthogonalizes the incoherent probe modes independently at each scan position.

The complete probe stack is then projected onto a low-dimensional position-dependent subspace using orthogonalizeProbeStack(), with the retained subspace dimension given by params.OPR_subspace.

Finally, reconstruction errors are evaluated with getErrorMetrics(), the remaining reconstruction constraints are applied with applyConstraints(), and showReconstruction() updates the monitor.

If GPU acceleration is enabled, the reconstruction data are returned to CPU memory after completion.

Source code in PtyLab/Engines/OPR.py
def reconstruct(self):
    r"""
    Run the Orthogonal Probe Relaxation reconstruction.

    For each reconstruction iteration, a position-dependent probe is loaded
    from `reconstruction.probe_stack` for the current scan position. The exit
    surface wave is then formed from the local object patch and the selected
    probe, followed by `intensityProjection()` to apply the measured
    diffraction-intensity constraint.

    The resulting exit-wave correction

    $$
    \Delta\Psi_j = \Psi'_j - \Psi_j
    $$

    is used to update the object and probe through `objectPatchUpdate()` and
    `probeUpdate()`. If `params.OPR_tv` is enabled, the object update is
    periodically replaced by `objectPatchUpdate_TV()` according to
    `params.OPR_tv_freq`.

    After each probe update, the selected probe modes are written back to
    `reconstruction.probe_stack` at the corresponding scan position.

    Once all scan positions have been processed, the position-dependent probe
    stack is regularized. If `params.OPR_orthogonalize_modes` is enabled,
    `orthogonalizeIncoherentModes()` first orthogonalizes the incoherent probe
    modes independently at each scan position.

    The complete probe stack is then projected onto a low-dimensional
    position-dependent subspace using `orthogonalizeProbeStack()`, with the
    retained subspace dimension given by `params.OPR_subspace`.

    Finally, reconstruction errors are evaluated with `getErrorMetrics()`,
    the remaining reconstruction constraints are applied with
    `applyConstraints()`, and `showReconstruction()` updates the monitor.

    If GPU acceleration is enabled, the reconstruction data are returned to
    CPU memory after completion.
    """

    self._prepareReconstruction()

    # OPR parameters
    Nmodes = self.OPR_modes.shape[0]
    Np = self.reconstruction.Np
    Nframes = self.experimentalData.numFrames
    mode_slice = self.OPR_modes
    n_subspace = self.n_subspace

    self.reconstruction.probe_stack = cp.zeros(
        (1, 1, Nmodes, 1, Np, Np, Nframes), dtype=cp.complex64
    )

    for i, mode in enumerate(self.OPR_modes):
        # fill the probe-stack with the inital guess of the probes
        self.reconstruction.probe_stack[0, 0, i, 0, :, :, :] = cp.repeat(
            self.reconstruction.probe[0, 0, mode, 0, :, :, cp.newaxis],
            Nframes,
            axis=2,
        )

    # actual reconstruction ePIE_engine
    self.pbar = trange(self.numIterations, desc="OPR", file=sys.stdout, leave=True)
    for loop in self.pbar:
        self.it = loop
        # set position order
        self.setPositionOrder()
        for positionLoop, positionIndex in enumerate(self.positionIndices):
            # get object patch
            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()

            # Get dim reduced probe
            self.reconstruction.probe[:, :, mode_slice, :, :, :] = (
                self.reconstruction.probe_stack[..., positionIndex]
            )

            # make exit surface wave
            self.reconstruction.esw = objectPatch * self.reconstruction.probe

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

            if loop % self.params.OPR_tv_freq == 0 and self.params.OPR_tv:
                self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate_TV(
                    objectPatch, DELTA
                )
            else:
                # object update
                self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                    objectPatch, DELTA
                )

            # probe update
            self.reconstruction.probe = self.probeUpdate(
                objectPatch, DELTA, weight=1
            )

            # save first, dominant probe mode
            self.reconstruction.probe_stack[..., positionIndex] = cp.copy(
                self.reconstruction.probe[:, :, mode_slice, :, :, :]
            )

        # get error metric
        self.getErrorMetrics()

        if self.params.OPR_orthogonalize_modes:
            self.orthogonalizeIncoherentModes()

        self.reconstruction.probe_stack = self.orthogonalizeProbeStack(
            self.reconstruction.probe_stack, n_subspace
        )

        # apply Constraints
        self.applyConstraints(loop)

        # show reconstruction
        self.showReconstruction(loop)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

orthogonalizeIncoherentModes()

Orthogonalize the incoherent probe modes at each scan position.

For every position in reconstruction.probe_stack, the selected probe modes are reshaped into a two-dimensional matrix with one row per incoherent mode and one column per probe pixel.

An SVD is then performed,

\[ P = U S V^\dagger \]

and the probe modes are replaced by

\[ S V^\dagger \]

which provides an equivalent orthogonal representation of the same mixed-state probe subspace.

The orthogonalization is applied independently at every scan position and does not alter the position-dependent OPR subspace itself.

If params.OPR_fast_orthogonalization is enabled, the batched Gram-matrix implementation _orthogonalizeIncoherentModes_batched() is used instead of the frame-by-frame SVD. For a probe-mode matrix \(P\), the left singular vectors of \(P\) are also the eigenvectors of the much smaller Gram matrix

\[ G = P P^\dagger \]

Since the number of incoherent probe modes is typically much smaller than the number of probe pixels, \(G\) has shape (nModes, nModes) and can be factorized much more efficiently than the full probe matrix. The orthogonal modes are then obtained from

\[ U^\dagger P \]

which is equivalent to \(S V^\dagger\).

The batched implementation performs this operation for multiple scan positions simultaneously and processes the probe stack in chunks to limit temporary memory usage.

Source code in PtyLab/Engines/OPR.py
def orthogonalizeIncoherentModes(self):
    r"""
    Orthogonalize the incoherent probe modes at each scan position.

    For every position in `reconstruction.probe_stack`, the selected probe
    modes are reshaped into a two-dimensional matrix with one row per
    incoherent mode and one column per probe pixel.

    An SVD is then performed,

    $$
    P = U S V^\dagger
    $$

    and the probe modes are replaced by

    $$
    S V^\dagger
    $$

    which provides an equivalent orthogonal representation of the same
    mixed-state probe subspace.

    The orthogonalization is applied independently at every scan position and
    does not alter the position-dependent OPR subspace itself.

    If `params.OPR_fast_orthogonalization` is enabled, the batched
    Gram-matrix implementation `_orthogonalizeIncoherentModes_batched()` is
    used instead of the frame-by-frame SVD. For a probe-mode matrix $P$, the left singular vectors of $P$ are also
    the eigenvectors of the much smaller Gram matrix

    $$
    G = P P^\dagger
    $$

    Since the number of incoherent probe modes is typically much smaller than
    the number of probe pixels, $G$ has shape
    `(nModes, nModes)` and can be factorized much more efficiently than the
    full probe matrix. The orthogonal modes are then obtained from

    $$
    U^\dagger P
    $$

    which is equivalent to $S V^\dagger$.

    The batched implementation performs this operation for multiple scan
    positions simultaneously and processes the probe stack in chunks to limit
    temporary memory usage.
    """
    if self.params.OPR_fast_orthogonalization:
        return self._orthogonalizeIncoherentModes_batched()

    nFrames = self.experimentalData.numFrames
    n = self.reconstruction.Np
    nModes = self.reconstruction.probe_stack.shape[2]
    for pos in range(nFrames):
        probe = self.reconstruction.probe_stack[0, 0, :, 0, :, :, pos]
        probe = probe.reshape(nModes, n * n)

        U, s, Vh = self.svd(probe)

        modes = (s[:, None] * Vh).reshape(nModes, n, n)
        self.reconstruction.probe_stack[0, 0, :, 0, :, :, pos] = modes

average(arr)

Smooth a one-dimensional array by averaging neighboring values.

Each interior element is replaced by the average of itself and its two nearest neighbors,

\[ a_j^{\mathrm{new}} = \frac{a_{j-1} + a_j + a_{j+1}}{3} \]

while the first and last elements are averaged only with their single available neighbor.

In OPR, this operation is used to smooth the position-dependent subspace coefficients when params.OPR_neighbor_constraint is enabled, thereby suppressing abrupt probe variations between successive scan positions.

Parameters:

Name Type Description Default
arr array - like

One-dimensional array of position-dependent coefficients.

required

Returns:

Type Description
array - like

Smoothed array with the same shape as the input.

Notes

This implementation currently operates on CuPy arrays and therefore requires GPU support.

Source code in PtyLab/Engines/OPR.py
def average(self, arr):
    r"""
    Smooth a one-dimensional array by averaging neighboring values.

    Each interior element is replaced by the average of itself and its two
    nearest neighbors,

    $$
    a_j^{\mathrm{new}} = \frac{a_{j-1} + a_j + a_{j+1}}{3}
    $$

    while the first and last elements are averaged only with their single
    available neighbor.

    In OPR, this operation is used to smooth the position-dependent subspace
    coefficients when `params.OPR_neighbor_constraint` is enabled, thereby
    suppressing abrupt probe variations between successive scan positions.

    Args:
        arr (array-like):
            One-dimensional array of position-dependent coefficients.

    Returns:
        array-like:
            Smoothed array with the same shape as the input.

    Notes:
        This implementation currently operates on CuPy arrays and therefore
        requires GPU support.
    """

    arr_start = arr[:-1]
    arr_end = arr[1:]
    arr_end = cp.append(arr_end, 0)
    arr_start = cp.append(0, arr_start)
    divider = cp.ones_like(arr) * 3
    divider[0] = 2
    divider[-1] = 2
    return (arr + arr_end + arr_start) / divider

svd(P)

Compute the reduced singular-value decomposition of a matrix.

The decomposition

\[ P = U S V^\dagger \]

is evaluated with CuPy when P is stored on the GPU and with NumPy otherwise. In both cases, full_matrices=False is used to return the reduced SVD.

Parameters:

Name Type Description Default
P array - like

Input matrix to decompose.

required

Returns:

Type Description
tuple

(U, s, Vh), where U and Vh contain the left and right singular vectors and s contains the singular values.

Source code in PtyLab/Engines/OPR.py
def svd(self, P):
    r"""
    Compute the reduced singular-value decomposition of a matrix.

    The decomposition

    $$
    P = U S V^\dagger
    $$

    is evaluated with CuPy when `P` is stored on the GPU and with NumPy
    otherwise. In both cases, `full_matrices=False` is used to return the
    reduced SVD.

    Args:
        P (array-like):
            Input matrix to decompose.

    Returns:
        tuple:
            `(U, s, Vh)`, where `U` and `Vh` contain the left and right
            singular vectors and `s` contains the singular values.
    """
    if isGpuArray(P):
        try:
            return cp.linalg.svd(P, full_matrices=False)
        except:
            print(
                "Something is wrong with SVD on cuda. Probably an installation error"
            )
            raise
    A, v, At = np.linalg.svd(asNumpyArray(P), full_matrices=False)
    if isGpuArray(P):
        A = cp.array(A)
        v = cp.array(v)
        At = cp.array(At)
    return A, v, At

rsvd(P, n_dim)

Compute a randomized truncated singular-value decomposition.

This method delegates to PtyLab.utils.fsvd.rsvd() and returns a low-rank approximation of the input matrix using the requested subspace dimension.

Parameters:

Name Type Description Default
P array - like

Input matrix to decompose.

required
n_dim int

Number of singular components to retain.

required

Returns:

Type Description
tuple

(U, s, Vh), containing the truncated left singular vectors, singular values, and right singular vectors.

Source code in PtyLab/Engines/OPR.py
def rsvd(self, P, n_dim):
    """
    Compute a randomized truncated singular-value decomposition.

    This method delegates to `PtyLab.utils.fsvd.rsvd()` and returns a
    low-rank approximation of the input matrix using the requested subspace
    dimension.

    Args:
        P (array-like):
            Input matrix to decompose.

        n_dim (int):
            Number of singular components to retain.

    Returns:
        tuple:
            `(U, s, Vh)`, containing the truncated left singular vectors,
            singular values, and right singular vectors.
    """
    return rsvd(P, n_dim)

gram_tsvd(A, n_dim) staticmethod

Compute a truncated SVD through the Gram matrix.

For a tall matrix \(A\), the method forms the smaller Gram matrix

\[ G = A^\dagger A \]

and uses

\[ A^\dagger A = V S^2 V^\dagger \]

to recover the truncated singular-value decomposition of A. The retained left singular vectors are reconstructed from

\[ U = A V S^{-1} \]

using the first n_dim components.

The Gram matrix is formed in double precision for improved numerical stability, and division by numerically zero singular values is guarded.

Parameters:

Name Type Description Default
A array - like

Input matrix.

required
n_dim int

Number of singular components to retain.

required

Returns:

Type Description
tuple

(U, s, Vh) containing the truncated singular-value decomposition.

Source code in PtyLab/Engines/OPR.py
@staticmethod
def gram_tsvd(A, n_dim):
    r"""
    Compute a truncated SVD through the Gram matrix.

    For a tall matrix $A$, the method forms the smaller Gram matrix

    $$
    G = A^\dagger A
    $$

    and uses

    $$
    A^\dagger A = V S^2 V^\dagger
    $$

    to recover the truncated singular-value decomposition of `A`. The retained
    left singular vectors are reconstructed from

    $$
    U = A V S^{-1}
    $$

    using the first `n_dim` components.

    The Gram matrix is formed in double precision for improved numerical
    stability, and division by numerically zero singular values is guarded.

    Args:
        A (array-like):
            Input matrix.

        n_dim (int):
            Number of singular components to retain.

    Returns:
        tuple:
            `(U, s, Vh)` containing the truncated singular-value decomposition.
    """
    xp = getArrayModule(A)
    n_dim = int(min(n_dim, A.shape[1]))

    G = (A.conj().T @ A).astype(xp.complex128)
    # G is Hermitian positive semi-definite, so its SVD and its
    # eigendecomposition coincide: the left singular vectors are the
    # eigenvectors and the singular values are the eigenvalues, already in
    # descending order. We use svd rather than eigh because eigh routes
    # through cupyx.cusolver, which is not importable in every CuPy/CUDA
    # installation (it needs libcusolver at a version cupy-cuda12x does not
    # always ship), whereas svd works through cupy's own bindings.
    V, w, _Vh = xp.linalg.svd(G)
    w = w[:n_dim]
    V = V[:, :n_dim]

    s = xp.sqrt(xp.clip(w.real, 0.0, None))
    V = V.astype(A.dtype)
    # guard the division for numerically-zero singular values
    s_safe = xp.where(s > 0, s, 1.0)
    U = (A @ V) / s_safe.astype(A.real.dtype)[None, :]
    return U, s.astype(A.real.dtype), V.conj().T

orthogonalizeProbeStack(probe_stack, n_dim)

Project the position-dependent probe stack onto a low-dimensional subspace.

For each probe mode selected by params.OPR_modes, the probes from all scan positions are reshaped into a matrix

\[ A \in \mathbb{C}^{N_p^2 \times N_{\mathrm{frames}}} \]

whose columns contain the flattened probe estimates at individual scan positions.

A truncated singular-value decomposition is then computed using the method selected by params.OPR_tsvd_type. Only n_dim dominant components are retained, yielding a low-rank approximation of the position-dependent probe stack.

If params.OPR_neighbor_constraint is enabled, the position-dependent subspace coefficients are smoothed over neighboring scan positions before the probe stack is reconstructed.

The low-rank approximation is blended with the current probe stack using

\[ P^{\mathrm{new}} = \alpha P^{\mathrm{old}} + (1-\alpha)P^{\mathrm{low-rank}} \]

where alpha = params.OPR_alpha.

Parameters:

Name Type Description Default
probe_stack array - like

Position-dependent probe stack.

required
n_dim int

Number of OPR subspace components to retain.

required

Returns:

Type Description
array - like

Regularized probe stack with the same shape as the input.

Source code in PtyLab/Engines/OPR.py
def orthogonalizeProbeStack(self, probe_stack, n_dim):
    r"""
    Project the position-dependent probe stack onto a low-dimensional subspace.

    For each probe mode selected by `params.OPR_modes`, the probes from all
    scan positions are reshaped into a matrix

    $$
    A \in \mathbb{C}^{N_p^2 \times N_{\mathrm{frames}}}
    $$

    whose columns contain the flattened probe estimates at individual scan
    positions.

    A truncated singular-value decomposition is then computed using the method
    selected by `params.OPR_tsvd_type`. Only `n_dim` dominant components are
    retained, yielding a low-rank approximation of the position-dependent
    probe stack.

    If `params.OPR_neighbor_constraint` is enabled, the position-dependent
    subspace coefficients are smoothed over neighboring scan positions before
    the probe stack is reconstructed.

    The low-rank approximation is blended with the current probe stack using

    $$
    P^{\mathrm{new}} = \alpha P^{\mathrm{old}} + (1-\alpha)P^{\mathrm{low-rank}}
    $$

    where `alpha = params.OPR_alpha`.

    Args:
        probe_stack (array-like):
            Position-dependent probe stack.

        n_dim (int):
            Number of OPR subspace components to retain.

    Returns:
        array-like:
            Regularized probe stack with the same shape as the input.
    """
    xp = getArrayModule(probe_stack)
    n = self.reconstruction.Np
    nFrames = self.experimentalData.numFrames

    for i, mode in enumerate(self.OPR_modes):
        A = probe_stack[:, :, i, :, :, :].reshape(n * n, nFrames)

        if self.params.OPR_tsvd_type == "randomized":
            U, s, Vh = self.rsvd(A, n_dim)
        elif self.params.OPR_tsvd_type == "gram":
            U, s, Vh = self.gram_tsvd(A, n_dim)
        elif self.params.OPR_tsvd_type == "numpy":
            U, s, Vh = xp.linalg.svd(A, full_matrices=False)
            s = s.copy()
            s[n_dim:] = 0
        else:
            raise ValueError(
                f"unknown OPR_tsvd_type {self.params.OPR_tsvd_type!r}; "
                f"expected 'numpy', 'gram' or 'randomized'"
            )

        if self.params.OPR_neighbor_constraint:
            # Calculate the average of neigboring singular values
            content = s[:, None] * Vh
            for j in range(min(n_dim, content.shape[0])):
                content[j] = self.average(content[j])

            probe_stack[:, :, i, :, :, :] = self.alpha * probe_stack[
                :, :, i, :, :, :
            ] + (1 - self.alpha) * (U @ content).reshape(n, n, nFrames)
        else:
            update = (U @ (s[:, None] * Vh)).reshape(n, n, nFrames)
            probe_stack[:, :, i, :, :, :] *= self.alpha
            probe_stack[:, :, i, :, :, :] += (1 - self.alpha) * update

    return probe_stack

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the ePIE correction.

The object update uses the current probe and exit-wave correction DELTA with normalization by the maximum probe intensity.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the scan position.

required
DELTA ndarray

Exit-wave correction after the intensity projection.

required

Returns:

Type Description
ndarray

Updated object patch.

Source code in PtyLab/Engines/OPR.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    """
    Update the object patch using the ePIE correction.

    The object update uses the current probe and exit-wave correction `DELTA`
    with normalization by the maximum probe intensity.

    Args:
        objectPatch (np.ndarray):
            Current object patch at the scan position.

        DELTA (np.ndarray):
            Exit-wave correction after the intensity projection.

    Returns:
        np.ndarray:
            Updated object patch.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)

    frac = self.reconstruction.probe.conj() / xp.max(
        xp.sum(xp.abs(self.reconstruction.probe) ** 2, axis=(0, 1, 2, 3))
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2, 3), keepdims=True
    )

probeUpdate(objectPatch, DELTA, weight, gimmel=0.1)

Update the probe using the ePIE correction.

The probe update is computed from the current object patch and exit-wave correction DELTA. The normalization includes the regularization term gimmel to avoid excessively large updates when the object intensity is small.

The update can additionally be scaled by weight. In the current OPR reconstruction workflow, weight is set to 1.

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the scan position.

required
DELTA ndarray

Exit-wave correction after the intensity projection.

required
weight float

Multiplicative weight applied to the probe update.

required
gimmel float

Small positive regularization term added to the normalization denominator. Default is 0.1.

0.1

Returns:

Type Description
ndarray

Updated probe.

Source code in PtyLab/Engines/OPR.py
def probeUpdate(
    self, objectPatch: np.ndarray, DELTA: np.ndarray, weight: float, gimmel=0.1
):
    """
    Update the probe using the ePIE correction.

    The probe update is computed from the current object patch and exit-wave
    correction `DELTA`. The normalization includes the regularization term
    `gimmel` to avoid excessively large updates when the object intensity is
    small.

    The update can additionally be scaled by `weight`. In the current OPR
    reconstruction workflow, `weight` is set to 1.

    Args:
        objectPatch (np.ndarray):
            Current object patch at the scan position.

        DELTA (np.ndarray):
            Exit-wave correction after the intensity projection.

        weight (float):
            Multiplicative weight applied to the probe update.

        gimmel (float, optional):
            Small positive regularization term added to the normalization
            denominator. Default is `0.1`.

    Returns:
        np.ndarray:
            Updated probe.
    """
    # find out which array module to use, numpy or cupy (or other...)
    xp = getArrayModule(objectPatch)
    frac = objectPatch.conj() / (
        xp.max(xp.sum(xp.abs(objectPatch) ** 2, axis=(0, 1, 2, 3))) + gimmel
    )
    frac = frac * weight
    r = self.reconstruction.probe + self.betaProbe * xp.sum(
        frac * DELTA, axis=(0, 1, 3), keepdims=True
    )
    return r

qNewton

Bases: BaseEngine

Experimental quasi-Newton-inspired ptychographic reconstruction engine.

qNewton provides an alternative to the standard ePIE and mPIE update rules by using locally weighted, regularized object and probe corrections. Its purpose is to adapt the update strength to the local illumination or object amplitude instead of applying the same normalization everywhere.

For the object update, the current implementation uses a factor of the form

\[ \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O} \]

while the probe update uses the corresponding object-dependent expression,

\[ \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P} \]

where regObject and regProbe provide the regularization terms.

The inverse-intensity factors reduce the update in strongly illuminated regions and prevent excessively large corrections where the local probe or object intensity becomes small. The additional amplitude weighting further modulates the contribution of weakly illuminated or weak-object regions.

This type of locally scaled update may be useful when the illumination or object amplitude varies strongly across the reconstruction and a standard globally normalized PIE update becomes poorly balanced.

The remaining reconstruction workflow follows the standard PIE structure: the exit surface wave is formed from the object and probe, intensityProjection() applies the measured diffraction constraint, and the resulting exit-wave correction is used to update the object and probe.

Notes

This engine is retained as an experimental algorithm implementation. Its normalization and theoretical formulation should be validated against the original method or reference before further development.

Source code in PtyLab/Engines/qNewton.py
class qNewton(BaseEngine):
    r"""
    Experimental quasi-Newton-inspired ptychographic reconstruction engine.

    `qNewton` provides an alternative to the standard ePIE and mPIE update
    rules by using locally weighted, regularized object and probe corrections.
    Its purpose is to adapt the update strength to the local illumination or
    object amplitude instead of applying the same normalization everywhere.

    For the object update, the current implementation uses a factor of the form

    $$
    \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O}
    $$

    while the probe update uses the corresponding object-dependent expression,

    $$
    \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P}
    $$

    where `regObject` and `regProbe` provide the regularization terms.

    The inverse-intensity factors reduce the update in strongly illuminated
    regions and prevent excessively large corrections where the local probe or
    object intensity becomes small. The additional amplitude weighting further
    modulates the contribution of weakly illuminated or weak-object regions.

    This type of locally scaled update may be useful __when the illumination or
    object amplitude varies strongly across the reconstruction__ and a standard
    globally normalized PIE update becomes poorly balanced. 

    The remaining reconstruction workflow follows the standard PIE structure:
    the exit surface wave is formed from the object and probe,
    `intensityProjection()` applies the measured diffraction constraint, and
    the resulting exit-wave correction is used to update the object and probe.

    Notes:
        This engine is retained as an experimental algorithm implementation.
        Its normalization and theoretical formulation should be validated
        against the original method or reference before further development.
    """
    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("qNewton")
        self.logger.info("Sucesfully created qNewton engine")

        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        self.initializeReconstructionParams()

    def initializeReconstructionParams(self):
        """
        Initialize parameters specific to the experimental qNewton reconstruction.

        This method sets the default object and probe update strengths,
        regularization parameters, and number of reconstruction iterations.

        The object and probe updates are controlled by `betaObject` and
        `betaProbe`, while `regObject` and `regProbe` regularize the local
        inverse-intensity factors used in the qNewton-inspired update rules.
        """
        self.betaProbe = 1
        self.betaObject = 1
        self.regObject = 1
        self.regProbe = 1
        self.numIterations = 50

    def reconstruct(self, experimentalData: ExperimentalData = None):
        """
        Run the qNewton ptychographic reconstruction.

        The reconstruction follows the standard PIE workflow: each scan position
        is processed sequentially, `intensityProjection()` applies the measured
        diffraction constraint, and the resulting exit-wave correction is used to
        update the object and probe.

        The qNewton-specific behavior is provided by `objectPatchUpdate()` and
        `probeUpdate()`, which apply the locally weighted and regularized update
        rules defined by this engine.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use for the reconstruction. If provided,
                it replaces the dataset currently attached to the engine.
        """
        if experimentalData is not None:
            self.reconstruction.data = experimentalData
            self.experimentalData = experimentalData
        self._prepareReconstruction()

        self.pbar = trange(
            self.numIterations, desc="qNewton", file=sys.stdout, leave=True
        )
        for loop in self.pbar:
            # set position order
            self.setPositionOrder()

            for positionLoop, positionIndex in enumerate(self.positionIndices):
                # get object patch
                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                # object update
                self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                    objectPatch, DELTA
                )

                # probe update
                self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)

            # get error metric
            self.getErrorMetrics()

            # apply Constraints
            self.applyConstraints(loop)

            # show reconstruction
            self.showReconstruction(loop)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0

            # todo clearMemory implementation

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the object patch using the qNewton-inspired correction.

        The update is weighted by the current probe according to

        $$
        \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O}
        $$

        where `regObject` provides the regularization term $\lambda_O$.

        Args:
            objectPatch (np.ndarray):
                Current object patch at the scan position.

            DELTA (np.ndarray):
                Exit-wave correction after the intensity projection.

        Returns:
            np.ndarray:
                Updated object patch.
        """

        xp = getArrayModule(objectPatch)
        Pmax = xp.max(xp.sum(xp.abs(self.reconstruction.probe), axis=(0, 1, 2, 3)))
        frac = (
            xp.abs(self.reconstruction.probe)
            / Pmax
            * self.reconstruction.probe.conj()
            / (xp.abs(self.reconstruction.probe) ** 2 + self.regObject)
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2, 3), keepdims=True
        )

    def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the probe using the qNewton-inspired correction.

        The update is weighted by the current object patch according to

        $$
        \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P}
        $$

        where `regProbe` provides the regularization term $\lambda_P$.

        Args:
            objectPatch (np.ndarray):
                Current object patch at the scan position.

            DELTA (np.ndarray):
                Exit-wave correction after the intensity projection.

        Returns:
            np.ndarray:
                Updated probe.
        """
        xp = getArrayModule(objectPatch)
        Omax = xp.max(xp.sum(xp.abs(self.reconstruction.object), axis=(0, 1, 2, 3)))
        frac = (
            xp.abs(objectPatch)
            / Omax
            * objectPatch.conj()
            / (xp.abs(objectPatch) ** 2 + self.regProbe)
        )
        r = self.reconstruction.probe + self.betaProbe * xp.sum(
            frac * DELTA, axis=(0, 1, 3), keepdims=True
        )
        return r

initializeReconstructionParams()

Initialize parameters specific to the experimental qNewton reconstruction.

This method sets the default object and probe update strengths, regularization parameters, and number of reconstruction iterations.

The object and probe updates are controlled by betaObject and betaProbe, while regObject and regProbe regularize the local inverse-intensity factors used in the qNewton-inspired update rules.

Source code in PtyLab/Engines/qNewton.py
def initializeReconstructionParams(self):
    """
    Initialize parameters specific to the experimental qNewton reconstruction.

    This method sets the default object and probe update strengths,
    regularization parameters, and number of reconstruction iterations.

    The object and probe updates are controlled by `betaObject` and
    `betaProbe`, while `regObject` and `regProbe` regularize the local
    inverse-intensity factors used in the qNewton-inspired update rules.
    """
    self.betaProbe = 1
    self.betaObject = 1
    self.regObject = 1
    self.regProbe = 1
    self.numIterations = 50

reconstruct(experimentalData=None)

Run the qNewton ptychographic reconstruction.

The reconstruction follows the standard PIE workflow: each scan position is processed sequentially, intensityProjection() applies the measured diffraction constraint, and the resulting exit-wave correction is used to update the object and probe.

The qNewton-specific behavior is provided by objectPatchUpdate() and probeUpdate(), which apply the locally weighted and regularized update rules defined by this engine.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for the reconstruction. If provided, it replaces the dataset currently attached to the engine.

None
Source code in PtyLab/Engines/qNewton.py
def reconstruct(self, experimentalData: ExperimentalData = None):
    """
    Run the qNewton ptychographic reconstruction.

    The reconstruction follows the standard PIE workflow: each scan position
    is processed sequentially, `intensityProjection()` applies the measured
    diffraction constraint, and the resulting exit-wave correction is used to
    update the object and probe.

    The qNewton-specific behavior is provided by `objectPatchUpdate()` and
    `probeUpdate()`, which apply the locally weighted and regularized update
    rules defined by this engine.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use for the reconstruction. If provided,
            it replaces the dataset currently attached to the engine.
    """
    if experimentalData is not None:
        self.reconstruction.data = experimentalData
        self.experimentalData = experimentalData
    self._prepareReconstruction()

    self.pbar = trange(
        self.numIterations, desc="qNewton", file=sys.stdout, leave=True
    )
    for loop in self.pbar:
        # set position order
        self.setPositionOrder()

        for positionLoop, positionIndex in enumerate(self.positionIndices):
            # get object patch
            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()

            # make exit surface wave
            self.reconstruction.esw = objectPatch * self.reconstruction.probe

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

            # object update
            self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                objectPatch, DELTA
            )

            # probe update
            self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)

        # get error metric
        self.getErrorMetrics()

        # apply Constraints
        self.applyConstraints(loop)

        # show reconstruction
        self.showReconstruction(loop)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the qNewton-inspired correction.

The update is weighted by the current probe according to

\[ \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O} \]

where regObject provides the regularization term \(\lambda_O\).

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the scan position.

required
DELTA ndarray

Exit-wave correction after the intensity projection.

required

Returns:

Type Description
ndarray

Updated object patch.

Source code in PtyLab/Engines/qNewton.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the object patch using the qNewton-inspired correction.

    The update is weighted by the current probe according to

    $$
    \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O}
    $$

    where `regObject` provides the regularization term $\lambda_O$.

    Args:
        objectPatch (np.ndarray):
            Current object patch at the scan position.

        DELTA (np.ndarray):
            Exit-wave correction after the intensity projection.

    Returns:
        np.ndarray:
            Updated object patch.
    """

    xp = getArrayModule(objectPatch)
    Pmax = xp.max(xp.sum(xp.abs(self.reconstruction.probe), axis=(0, 1, 2, 3)))
    frac = (
        xp.abs(self.reconstruction.probe)
        / Pmax
        * self.reconstruction.probe.conj()
        / (xp.abs(self.reconstruction.probe) ** 2 + self.regObject)
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2, 3), keepdims=True
    )

probeUpdate(objectPatch, DELTA)

Update the probe using the qNewton-inspired correction.

The update is weighted by the current object patch according to

\[ \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P} \]

where regProbe provides the regularization term \(\lambda_P\).

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the scan position.

required
DELTA ndarray

Exit-wave correction after the intensity projection.

required

Returns:

Type Description
ndarray

Updated probe.

Source code in PtyLab/Engines/qNewton.py
def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the probe using the qNewton-inspired correction.

    The update is weighted by the current object patch according to

    $$
    \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P}
    $$

    where `regProbe` provides the regularization term $\lambda_P$.

    Args:
        objectPatch (np.ndarray):
            Current object patch at the scan position.

        DELTA (np.ndarray):
            Exit-wave correction after the intensity projection.

    Returns:
        np.ndarray:
            Updated probe.
    """
    xp = getArrayModule(objectPatch)
    Omax = xp.max(xp.sum(xp.abs(self.reconstruction.object), axis=(0, 1, 2, 3)))
    frac = (
        xp.abs(objectPatch)
        / Omax
        * objectPatch.conj()
        / (xp.abs(objectPatch) ** 2 + self.regProbe)
    )
    r = self.reconstruction.probe + self.betaProbe * xp.sum(
        frac * DELTA, axis=(0, 1, 3), keepdims=True
    )
    return r

mqNewton

Bases: BaseEngine

Experimental momentum-accelerated quasi-Newton-inspired ptychographic reconstruction engine. mqNewton extends qNewton by combining the same locally regularized, curvature-like object and probe updates with adaptive momentum acceleration.

The current implementation supports three momentum schemes: "momentum", "ADAM", and "NADAM". Object and probe momentum updates are applied after each scan-position update. These methods should be interpreted as adaptive momentum variants unless further theoretical validation establishes a more specific correspondence.

The local object and probe updates are inherited conceptually from the qNewton formulation, while the momentum contribution is applied through objectMomentumUpdate() and probeMomentumUpdate().

Notes

This engine is retained as an experimental algorithm implementation. The qNewton normalization, momentum formulation, and theoretical basis should be validated against the original method or reference before further development.

Source code in PtyLab/Engines/mqNewton.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
class mqNewton(BaseEngine):
    r"""
    Experimental momentum-accelerated quasi-Newton-inspired ptychographic
    reconstruction engine.
    `mqNewton` extends `qNewton` by combining the same locally regularized,
    curvature-like object and probe updates with adaptive momentum
    acceleration.

    The current implementation supports three momentum schemes:
    `"momentum"`, `"ADAM"`, and `"NADAM"`. Object and probe momentum updates
    are applied after each scan-position update. These methods should  be interpreted as adaptive
    momentum variants unless further theoretical validation establishes a more
    specific correspondence.

    The local object and probe updates are inherited conceptually from the
    `qNewton` formulation, while the momentum contribution is applied through
    `objectMomentumUpdate()` and `probeMomentumUpdate()`.

    Notes:
        This engine is retained as an experimental algorithm implementation.
        The qNewton normalization, momentum formulation, and theoretical basis
        should be validated against the original method or reference before
        further development.
    """
    def __init__(
        self,
        reconstruction: Reconstruction,
        experimentalData: ExperimentalData,
        params: Params,
        monitor: Monitor,
    ):
        # This contains reconstruction parameters that are specific to the reconstruction
        # but not necessarily to ePIE reconstruction
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.logger = logging.getLogger("mqNewton")
        self.logger.info("Sucesfully created momentum accelerated qNewton mqNewton")

        self.logger.info("Wavelength attribute: %s", self.reconstruction.wavelength)
        self.initializeReconstructionParams()
        # initialize momentum
        self.reconstruction.initializeObjectMomentum()
        self.reconstruction.initializeProbeMomentum()
        # set object and probe buffers
        self.reconstruction.objectBuffer = self.reconstruction.object.copy()
        self.reconstruction.probeBuffer = self.reconstruction.probe.copy()
        self.params.momentumAcceleration = True

    def initializeReconstructionParams(self):
        """
        Initialize parameters specific to the experimental mqNewton reconstruction.

        This method sets the qNewton-style object and probe update strengths and
        regularization parameters, together with the parameters used by the
        momentum-acceleration scheme.

        `beta1` and `beta2` control the first- and second-moment estimates used by
        the adaptive momentum methods. `betaObject_m` and `betaProbe_m` determine
        the strength of the resulting momentum corrections.

        The momentum strategy is selected through `momentum_method`, with the
        current implementation supporting `"momentum"`, `"ADAM"`, and `"NADAM"`.
        """
        self.betaProbe = 1
        self.betaObject = 1
        self.regObject = 1
        self.regProbe = 1
        self.beta1 = 0.5
        self.beta2 = 0.5
        self.betaProbe_m = 0.25
        self.betaObject_m = 0.25
        self.feedbackM = 0.3  # feedback
        self.frictionM = 0.7  # friction
        self.momentum_method = "ADAM"  # which optimizer to use for momentum updates
        self.numIterations = 50

    def initializeAdaptiveMomentum(self):
        """
        Initialize the selected momentum-acceleration scheme.

        The update function is selected from `momentum`, `ADAM`, or `NADAM`
        according to `momentum_method` and stored in `momentum_engine`.

        For the adaptive `"ADAM"` and `"NADAM"` variants, additional second-moment
        buffers are initialized for both the object and probe momentum terms.
        These buffers are stored in `objectMomentum_v` and `probeMomentum_v`.

        Raises:
            AttributeError:
                If `momentum_method` does not correspond to an implemented
                momentum function.
        """
        self.momentum_engine = getattr(mqNewton, self.momentum_method)
        print("Momentum Engines implemented: momentum, ADAM, NADAM")
        print("Momentum mqNewton used: {}".format(self.momentum_method))
        if self.momentum_method in ["ADAM", "NADAM"]:
            # 2nd order momentum terms
            self.reconstruction.objectMomentum_v = (
                self.reconstruction.objectMomentum.copy()
            )
            self.reconstruction.probeMomentum_v = (
                self.reconstruction.probeMomentum.copy()
            )

    def reconstruct(self, experimentalData: ExperimentalData = None):
        """
        Run the momentum-accelerated qNewton reconstruction.

        The reconstruction follows the standard PIE workflow using the
        qNewton-specific object and probe update rules. After each scan-position
        update, additional object and probe momentum corrections are applied
        through `objectMomentumUpdate()` and `probeMomentumUpdate()`.

        The momentum update scheme is selected by `momentum_method` and may use
        standard momentum, ADAM, or NADAM. If
        `params.positionCorrectionSwitch` is enabled, position correction is also
        applied during the scan loop.

        Args:
            experimentalData (ExperimentalData, optional):
                Experimental dataset to use for the reconstruction. If provided,
                it replaces the dataset currently attached to the engine.
        """
        if experimentalData is not None:
            self.experimentalData = experimentalData
            self.reconstruction.data = experimentalData
        self._prepareReconstruction()
        self.initializeAdaptiveMomentum()

        self.pbar = trange(
            self.numIterations, desc="mqNewton", file=sys.stdout, leave=True
        )
        for loop in self.pbar:
            # set position order
            self.setPositionOrder()

            for positionLoop, positionIndex in enumerate(self.positionIndices):
                # get object patch
                row, col = self.reconstruction.positions[positionIndex]
                sy = slice(row, row + self.reconstruction.Np)
                sx = slice(col, col + self.reconstruction.Np)
                # note that object patch has size of probe array
                objectPatch = self.reconstruction.object[..., sy, sx].copy()

                # make exit surface wave
                self.reconstruction.esw = objectPatch * self.reconstruction.probe

                # propagate to camera, intensityProjection, propagate back to object
                self.intensityProjection(positionIndex)

                # difference term
                DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

                # object update
                self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                    objectPatch, DELTA
                )

                # probe update
                self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)

                # momentum updates
                self.objectMomentumUpdate(loop)
                self.probeMomentumUpdate(loop)

                if self.params.positionCorrectionSwitch:
                    self.positionCorrection(objectPatch, positionIndex, sy, sx)

            # get error metric
            self.getErrorMetrics()

            # apply Constraints
            self.applyConstraints(loop)

            # show reconstruction
            self.showReconstruction(loop)

        if self.params.gpuFlag:
            self.logger.info("switch to cpu")
            self._move_data_to_cpu()
            self.params.gpuFlag = 0
            # todo clearMemory implementation

    def ADAM(self, grad, mt, vt, itr):
        r"""
        Compute an ADAM-inspired adaptive momentum update.

        ADAM (Adaptive Moment Estimation) combines momentum with adaptive step
        scaling. It tracks both the running average of the gradient direction and
        a running estimate of the gradient magnitude, allowing the update direction
        and effective step size to adapt during optimization.

        The first-moment estimate is updated as

        $$
        m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t
        $$

        while the second-moment estimate uses the global squared L2 norm of the
        gradient,

        $$
        v_t = \beta_2 v_{t-1} + (1-\beta_2)\|g_t\|_2^2
        $$

        Bias-corrected estimates are then formed as

        $$
        \hat{m}_t = \frac{m_t}{1-\beta_1^t}
        $$

        $$
        \hat{v}_t = \frac{v_t}{1-\beta_2^t}
        $$

        and the normalized momentum update is

        $$
        u_t = \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}
        $$

        with $\epsilon = 10^{-8}$.


        Args:
            grad (array-like):
                Current object or probe gradient.

            mt (array-like):
                Previous first-moment estimate.

            vt (array-like):
                Previous second-moment estimate.

            itr (int):
                Current iteration index used for bias correction.

        Returns:
            tuple:
                `(update, mt, vt)`, containing the normalized momentum update and
                the updated first- and second-moment estimates.
        """
        xp = getArrayModule(grad)
        beta1_scale = 1 - self.beta1**itr
        beta2_scale = 1 - self.beta2**itr
        mt = self.beta1 * mt + (1 - self.beta1) * grad
        vt = (
            self.beta2 * vt
            + (1 - self.beta2) * xp.linalg.norm(grad.flatten().squeeze(), 2) ** 2
        )
        m_hat = mt / beta1_scale
        v_hat = vt / beta2_scale
        return m_hat / (v_hat**0.5 + 1e-8), mt, vt

    def NADAM(self, grad, mt, vt, itr):
        r"""
        Compute a NADAM-inspired adaptive momentum update.

        NADAM combines ADAM-style adaptive moment estimation with a
        Nesterov-type momentum correction. Compared with ADAM, the update includes
        an additional contribution from the current gradient, giving the momentum
        step a more anticipatory character.

        The first- and second-moment estimates are updated as in `ADAM()`, using the current gradient `g_t`.
        The NADAM-style update is then computed as

        $$
        u_t =\frac{\beta_1 \hat{m}_t+\frac{1-\beta_1}{1-\beta_1^t}g_t}{\sqrt{\hat{v}_t}+\epsilon}
        $$

        with $\epsilon = 10^{-8}$.

        Args:
            grad (array-like):
                Current object or probe gradient.

            mt (array-like):
                Previous first-moment estimate.

            vt (array-like):
                Previous second-moment estimate.

            itr (int):
                Current iteration index used for bias correction.

        Returns:
            tuple:
                `(update, mt, vt)`, containing the adaptive momentum update and
                the updated first- and second-moment estimates.
        """
        xp = getArrayModule(grad)

        beta1_scale = 1 - self.beta1**itr
        beta2_scale = 1 - self.beta2**itr

        norm_sq = xp.linalg.norm(grad.flatten(), 2) ** 2
        mt = self.beta1 * mt + (1 - self.beta1) * grad
        vt = self.beta2 * vt + (1 - self.beta2) * norm_sq
        m_hat = mt / beta1_scale
        v_hat = vt / beta2_scale
        update = (self.beta1 * m_hat + grad * (1 - self.beta1) / beta1_scale) / (
            v_hat**0.5 + 1e-8
        )
        return update, mt, vt

    def momentum(self, grad, mt, vt, itr):
        r"""
        Compute a standard momentum update.

        The current gradient is combined with the previous momentum according to

        $$
        m_t = g_t + \gamma m_{t-1}
        $$

        where `frictionM` defines the momentum retention factor $\gamma$.

        The resulting momentum is used directly as the update direction. The
        second-moment variable `vt` is not modified and is returned unchanged so
        that this method shares the same calling interface as `ADAM()` and
        `NADAM()`.

        Args:
            grad (array-like):
                Current object or probe gradient.

            mt (array-like):
                Previous momentum estimate.

            vt (array-like):
                Second-moment buffer. It is not used by standard momentum and is
                returned unchanged.

            itr (int):
                Iteration index. It is not used by standard momentum but is
                accepted for a common interface with the adaptive momentum methods.

        Returns:
            tuple:
                `(update, mt, vt)`, where `update` and `mt` are the updated momentum
                term and `vt` is returned unchanged.
        """
        mt = grad + self.frictionM * mt
        return mt, mt, vt

    def objectMomentumUpdate(self, loop):
        r"""
        Apply the selected momentum update to the reconstructed object.

        The momentum gradient is defined from the difference between the
        buffered object state and the current reconstruction,

        $$
        g_t = O_{\mathrm{buffer}} - O_t
        $$

        The selected momentum method (`momentum`, `ADAM`, or `NADAM`) is then
        used to compute the update direction and refresh the corresponding
        momentum buffers.

        The reconstructed object is updated according to

        $$
        O_{t+1} = O_t - \beta_{O,m} u_t
        $$

        where `betaObject_m` controls the strength of the momentum correction
        and $u_t$ is the update returned by the selected momentum method.

        After the update, the object buffer is replaced by the new object state
        for use in the next momentum step.

        Args:
            loop (int):
                Current reconstruction iteration index.
        """
        gradient = self.reconstruction.objectBuffer - self.reconstruction.object
        (
            update,
            self.reconstruction.objectMomentum,
            self.reconstruction.objectMomentum_v,
        ) = self.momentum_engine(
            self,
            gradient,
            self.reconstruction.objectMomentum,
            self.reconstruction.objectMomentum_v,
            loop + 1,
        )

        self.reconstruction.object -= self.betaObject_m * update
        self.reconstruction.objectBuffer = self.reconstruction.object.copy()

    def probeMomentumUpdate(self, loop):
        r"""
        Apply the selected momentum update to the reconstructed probe.

        The momentum gradient is defined from the difference between the
        buffered probe state and the current reconstruction,

        $$
        g_t = P_{\mathrm{buffer}} - P_t
        $$

        The selected momentum method (`momentum`, `ADAM`, or `NADAM`) is used
        to compute the probe update direction and refresh the corresponding
        momentum buffers.

        The probe is updated according to

        $$
        P_{t+1} = P_t - \beta_{P,m} u_t
        $$

        where `betaProbe_m` controls the strength of the momentum correction.

        After the update, the probe buffer is replaced by the new probe state
        for use in the next momentum step.

        Args:
            loop (int):
                Current reconstruction iteration index.
        """
        gradient = self.reconstruction.probeBuffer - self.reconstruction.probe
        (
            update,
            self.reconstruction.probeMomentum,
            self.reconstruction.probeMomentum_v,
        ) = self.momentum_engine(
            self,
            gradient,
            self.reconstruction.probeMomentum,
            self.reconstruction.probeMomentum_v,
            loop + 1,
        )

        self.reconstruction.probe -= self.betaProbe_m * update
        self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

    def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the object patch using the qNewton-inspired correction.

        The update is weighted by the current probe according to

        $$
        \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O}
        $$

        where `regObject` provides the regularization term $\lambda_O$.

        This local qNewton-style update is applied before the additional momentum
        correction performed by `objectMomentumUpdate()`.

        Args:
            objectPatch (np.ndarray):
                Current object patch at the scan position.

            DELTA (np.ndarray):
                Exit-wave correction after the intensity projection.

        Returns:
            np.ndarray:
                Updated object patch.
        """
        xp = getArrayModule(objectPatch)
        Pmax = xp.max(xp.sum(xp.abs(self.reconstruction.probe), axis=(0, 1, 2, 3)))
        frac = (
            xp.abs(self.reconstruction.probe)
            / Pmax
            * self.reconstruction.probe.conj()
            / (xp.abs(self.reconstruction.probe) ** 2 + self.regObject)
        )
        return objectPatch + self.betaObject * xp.sum(
            frac * DELTA, axis=(0, 2, 3), keepdims=True
        )

    def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
        r"""
        Update the probe using the qNewton-inspired correction.

        The update is weighted by the current object patch according to

        $$
        \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P}
        $$

        where `regProbe` provides the regularization term $\lambda_P$.

        This local qNewton-style update is applied before the additional momentum
        correction performed by `probeMomentumUpdate()`.

        Args:
            objectPatch (np.ndarray):
                Current object patch at the scan position.

            DELTA (np.ndarray):
                Exit-wave correction after the intensity projection.

        Returns:
            np.ndarray:
                Updated probe.
        """
        xp = getArrayModule(objectPatch)
        Omax = xp.max(xp.sum(xp.abs(self.reconstruction.object), axis=(0, 1, 2, 3)))
        frac = (
            xp.abs(objectPatch)
            / Omax
            * objectPatch.conj()
            / (xp.abs(objectPatch) ** 2 + self.regProbe)
        )
        r = self.reconstruction.probe + self.betaProbe * xp.sum(
            frac * DELTA, axis=(0, 1, 3), keepdims=True
        )
        return r

initializeReconstructionParams()

Initialize parameters specific to the experimental mqNewton reconstruction.

This method sets the qNewton-style object and probe update strengths and regularization parameters, together with the parameters used by the momentum-acceleration scheme.

beta1 and beta2 control the first- and second-moment estimates used by the adaptive momentum methods. betaObject_m and betaProbe_m determine the strength of the resulting momentum corrections.

The momentum strategy is selected through momentum_method, with the current implementation supporting "momentum", "ADAM", and "NADAM".

Source code in PtyLab/Engines/mqNewton.py
def initializeReconstructionParams(self):
    """
    Initialize parameters specific to the experimental mqNewton reconstruction.

    This method sets the qNewton-style object and probe update strengths and
    regularization parameters, together with the parameters used by the
    momentum-acceleration scheme.

    `beta1` and `beta2` control the first- and second-moment estimates used by
    the adaptive momentum methods. `betaObject_m` and `betaProbe_m` determine
    the strength of the resulting momentum corrections.

    The momentum strategy is selected through `momentum_method`, with the
    current implementation supporting `"momentum"`, `"ADAM"`, and `"NADAM"`.
    """
    self.betaProbe = 1
    self.betaObject = 1
    self.regObject = 1
    self.regProbe = 1
    self.beta1 = 0.5
    self.beta2 = 0.5
    self.betaProbe_m = 0.25
    self.betaObject_m = 0.25
    self.feedbackM = 0.3  # feedback
    self.frictionM = 0.7  # friction
    self.momentum_method = "ADAM"  # which optimizer to use for momentum updates
    self.numIterations = 50

initializeAdaptiveMomentum()

Initialize the selected momentum-acceleration scheme.

The update function is selected from momentum, ADAM, or NADAM according to momentum_method and stored in momentum_engine.

For the adaptive "ADAM" and "NADAM" variants, additional second-moment buffers are initialized for both the object and probe momentum terms. These buffers are stored in objectMomentum_v and probeMomentum_v.

Raises:

Type Description
AttributeError

If momentum_method does not correspond to an implemented momentum function.

Source code in PtyLab/Engines/mqNewton.py
def initializeAdaptiveMomentum(self):
    """
    Initialize the selected momentum-acceleration scheme.

    The update function is selected from `momentum`, `ADAM`, or `NADAM`
    according to `momentum_method` and stored in `momentum_engine`.

    For the adaptive `"ADAM"` and `"NADAM"` variants, additional second-moment
    buffers are initialized for both the object and probe momentum terms.
    These buffers are stored in `objectMomentum_v` and `probeMomentum_v`.

    Raises:
        AttributeError:
            If `momentum_method` does not correspond to an implemented
            momentum function.
    """
    self.momentum_engine = getattr(mqNewton, self.momentum_method)
    print("Momentum Engines implemented: momentum, ADAM, NADAM")
    print("Momentum mqNewton used: {}".format(self.momentum_method))
    if self.momentum_method in ["ADAM", "NADAM"]:
        # 2nd order momentum terms
        self.reconstruction.objectMomentum_v = (
            self.reconstruction.objectMomentum.copy()
        )
        self.reconstruction.probeMomentum_v = (
            self.reconstruction.probeMomentum.copy()
        )

reconstruct(experimentalData=None)

Run the momentum-accelerated qNewton reconstruction.

The reconstruction follows the standard PIE workflow using the qNewton-specific object and probe update rules. After each scan-position update, additional object and probe momentum corrections are applied through objectMomentumUpdate() and probeMomentumUpdate().

The momentum update scheme is selected by momentum_method and may use standard momentum, ADAM, or NADAM. If params.positionCorrectionSwitch is enabled, position correction is also applied during the scan loop.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Experimental dataset to use for the reconstruction. If provided, it replaces the dataset currently attached to the engine.

None
Source code in PtyLab/Engines/mqNewton.py
def reconstruct(self, experimentalData: ExperimentalData = None):
    """
    Run the momentum-accelerated qNewton reconstruction.

    The reconstruction follows the standard PIE workflow using the
    qNewton-specific object and probe update rules. After each scan-position
    update, additional object and probe momentum corrections are applied
    through `objectMomentumUpdate()` and `probeMomentumUpdate()`.

    The momentum update scheme is selected by `momentum_method` and may use
    standard momentum, ADAM, or NADAM. If
    `params.positionCorrectionSwitch` is enabled, position correction is also
    applied during the scan loop.

    Args:
        experimentalData (ExperimentalData, optional):
            Experimental dataset to use for the reconstruction. If provided,
            it replaces the dataset currently attached to the engine.
    """
    if experimentalData is not None:
        self.experimentalData = experimentalData
        self.reconstruction.data = experimentalData
    self._prepareReconstruction()
    self.initializeAdaptiveMomentum()

    self.pbar = trange(
        self.numIterations, desc="mqNewton", file=sys.stdout, leave=True
    )
    for loop in self.pbar:
        # set position order
        self.setPositionOrder()

        for positionLoop, positionIndex in enumerate(self.positionIndices):
            # get object patch
            row, col = self.reconstruction.positions[positionIndex]
            sy = slice(row, row + self.reconstruction.Np)
            sx = slice(col, col + self.reconstruction.Np)
            # note that object patch has size of probe array
            objectPatch = self.reconstruction.object[..., sy, sx].copy()

            # make exit surface wave
            self.reconstruction.esw = objectPatch * self.reconstruction.probe

            # propagate to camera, intensityProjection, propagate back to object
            self.intensityProjection(positionIndex)

            # difference term
            DELTA = self.reconstruction.eswUpdate - self.reconstruction.esw

            # object update
            self.reconstruction.object[..., sy, sx] = self.objectPatchUpdate(
                objectPatch, DELTA
            )

            # probe update
            self.reconstruction.probe = self.probeUpdate(objectPatch, DELTA)

            # momentum updates
            self.objectMomentumUpdate(loop)
            self.probeMomentumUpdate(loop)

            if self.params.positionCorrectionSwitch:
                self.positionCorrection(objectPatch, positionIndex, sy, sx)

        # get error metric
        self.getErrorMetrics()

        # apply Constraints
        self.applyConstraints(loop)

        # show reconstruction
        self.showReconstruction(loop)

    if self.params.gpuFlag:
        self.logger.info("switch to cpu")
        self._move_data_to_cpu()
        self.params.gpuFlag = 0

ADAM(grad, mt, vt, itr)

Compute an ADAM-inspired adaptive momentum update.

ADAM (Adaptive Moment Estimation) combines momentum with adaptive step scaling. It tracks both the running average of the gradient direction and a running estimate of the gradient magnitude, allowing the update direction and effective step size to adapt during optimization.

The first-moment estimate is updated as

\[ m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t \]

while the second-moment estimate uses the global squared L2 norm of the gradient,

\[ v_t = \beta_2 v_{t-1} + (1-\beta_2)\|g_t\|_2^2 \]

Bias-corrected estimates are then formed as

\[ \hat{m}_t = \frac{m_t}{1-\beta_1^t} \]
\[ \hat{v}_t = \frac{v_t}{1-\beta_2^t} \]

and the normalized momentum update is

\[ u_t = \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon} \]

with \(\epsilon = 10^{-8}\).

Parameters:

Name Type Description Default
grad array - like

Current object or probe gradient.

required
mt array - like

Previous first-moment estimate.

required
vt array - like

Previous second-moment estimate.

required
itr int

Current iteration index used for bias correction.

required

Returns:

Type Description
tuple

(update, mt, vt), containing the normalized momentum update and the updated first- and second-moment estimates.

Source code in PtyLab/Engines/mqNewton.py
def ADAM(self, grad, mt, vt, itr):
    r"""
    Compute an ADAM-inspired adaptive momentum update.

    ADAM (Adaptive Moment Estimation) combines momentum with adaptive step
    scaling. It tracks both the running average of the gradient direction and
    a running estimate of the gradient magnitude, allowing the update direction
    and effective step size to adapt during optimization.

    The first-moment estimate is updated as

    $$
    m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t
    $$

    while the second-moment estimate uses the global squared L2 norm of the
    gradient,

    $$
    v_t = \beta_2 v_{t-1} + (1-\beta_2)\|g_t\|_2^2
    $$

    Bias-corrected estimates are then formed as

    $$
    \hat{m}_t = \frac{m_t}{1-\beta_1^t}
    $$

    $$
    \hat{v}_t = \frac{v_t}{1-\beta_2^t}
    $$

    and the normalized momentum update is

    $$
    u_t = \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}
    $$

    with $\epsilon = 10^{-8}$.


    Args:
        grad (array-like):
            Current object or probe gradient.

        mt (array-like):
            Previous first-moment estimate.

        vt (array-like):
            Previous second-moment estimate.

        itr (int):
            Current iteration index used for bias correction.

    Returns:
        tuple:
            `(update, mt, vt)`, containing the normalized momentum update and
            the updated first- and second-moment estimates.
    """
    xp = getArrayModule(grad)
    beta1_scale = 1 - self.beta1**itr
    beta2_scale = 1 - self.beta2**itr
    mt = self.beta1 * mt + (1 - self.beta1) * grad
    vt = (
        self.beta2 * vt
        + (1 - self.beta2) * xp.linalg.norm(grad.flatten().squeeze(), 2) ** 2
    )
    m_hat = mt / beta1_scale
    v_hat = vt / beta2_scale
    return m_hat / (v_hat**0.5 + 1e-8), mt, vt

NADAM(grad, mt, vt, itr)

Compute a NADAM-inspired adaptive momentum update.

NADAM combines ADAM-style adaptive moment estimation with a Nesterov-type momentum correction. Compared with ADAM, the update includes an additional contribution from the current gradient, giving the momentum step a more anticipatory character.

The first- and second-moment estimates are updated as in ADAM(), using the current gradient g_t. The NADAM-style update is then computed as

\[ u_t =\frac{\beta_1 \hat{m}_t+\frac{1-\beta_1}{1-\beta_1^t}g_t}{\sqrt{\hat{v}_t}+\epsilon} \]

with \(\epsilon = 10^{-8}\).

Parameters:

Name Type Description Default
grad array - like

Current object or probe gradient.

required
mt array - like

Previous first-moment estimate.

required
vt array - like

Previous second-moment estimate.

required
itr int

Current iteration index used for bias correction.

required

Returns:

Type Description
tuple

(update, mt, vt), containing the adaptive momentum update and the updated first- and second-moment estimates.

Source code in PtyLab/Engines/mqNewton.py
def NADAM(self, grad, mt, vt, itr):
    r"""
    Compute a NADAM-inspired adaptive momentum update.

    NADAM combines ADAM-style adaptive moment estimation with a
    Nesterov-type momentum correction. Compared with ADAM, the update includes
    an additional contribution from the current gradient, giving the momentum
    step a more anticipatory character.

    The first- and second-moment estimates are updated as in `ADAM()`, using the current gradient `g_t`.
    The NADAM-style update is then computed as

    $$
    u_t =\frac{\beta_1 \hat{m}_t+\frac{1-\beta_1}{1-\beta_1^t}g_t}{\sqrt{\hat{v}_t}+\epsilon}
    $$

    with $\epsilon = 10^{-8}$.

    Args:
        grad (array-like):
            Current object or probe gradient.

        mt (array-like):
            Previous first-moment estimate.

        vt (array-like):
            Previous second-moment estimate.

        itr (int):
            Current iteration index used for bias correction.

    Returns:
        tuple:
            `(update, mt, vt)`, containing the adaptive momentum update and
            the updated first- and second-moment estimates.
    """
    xp = getArrayModule(grad)

    beta1_scale = 1 - self.beta1**itr
    beta2_scale = 1 - self.beta2**itr

    norm_sq = xp.linalg.norm(grad.flatten(), 2) ** 2
    mt = self.beta1 * mt + (1 - self.beta1) * grad
    vt = self.beta2 * vt + (1 - self.beta2) * norm_sq
    m_hat = mt / beta1_scale
    v_hat = vt / beta2_scale
    update = (self.beta1 * m_hat + grad * (1 - self.beta1) / beta1_scale) / (
        v_hat**0.5 + 1e-8
    )
    return update, mt, vt

momentum(grad, mt, vt, itr)

Compute a standard momentum update.

The current gradient is combined with the previous momentum according to

\[ m_t = g_t + \gamma m_{t-1} \]

where frictionM defines the momentum retention factor \(\gamma\).

The resulting momentum is used directly as the update direction. The second-moment variable vt is not modified and is returned unchanged so that this method shares the same calling interface as ADAM() and NADAM().

Parameters:

Name Type Description Default
grad array - like

Current object or probe gradient.

required
mt array - like

Previous momentum estimate.

required
vt array - like

Second-moment buffer. It is not used by standard momentum and is returned unchanged.

required
itr int

Iteration index. It is not used by standard momentum but is accepted for a common interface with the adaptive momentum methods.

required

Returns:

Type Description
tuple

(update, mt, vt), where update and mt are the updated momentum term and vt is returned unchanged.

Source code in PtyLab/Engines/mqNewton.py
def momentum(self, grad, mt, vt, itr):
    r"""
    Compute a standard momentum update.

    The current gradient is combined with the previous momentum according to

    $$
    m_t = g_t + \gamma m_{t-1}
    $$

    where `frictionM` defines the momentum retention factor $\gamma$.

    The resulting momentum is used directly as the update direction. The
    second-moment variable `vt` is not modified and is returned unchanged so
    that this method shares the same calling interface as `ADAM()` and
    `NADAM()`.

    Args:
        grad (array-like):
            Current object or probe gradient.

        mt (array-like):
            Previous momentum estimate.

        vt (array-like):
            Second-moment buffer. It is not used by standard momentum and is
            returned unchanged.

        itr (int):
            Iteration index. It is not used by standard momentum but is
            accepted for a common interface with the adaptive momentum methods.

    Returns:
        tuple:
            `(update, mt, vt)`, where `update` and `mt` are the updated momentum
            term and `vt` is returned unchanged.
    """
    mt = grad + self.frictionM * mt
    return mt, mt, vt

objectMomentumUpdate(loop)

Apply the selected momentum update to the reconstructed object.

The momentum gradient is defined from the difference between the buffered object state and the current reconstruction,

\[ g_t = O_{\mathrm{buffer}} - O_t \]

The selected momentum method (momentum, ADAM, or NADAM) is then used to compute the update direction and refresh the corresponding momentum buffers.

The reconstructed object is updated according to

\[ O_{t+1} = O_t - \beta_{O,m} u_t \]

where betaObject_m controls the strength of the momentum correction and \(u_t\) is the update returned by the selected momentum method.

After the update, the object buffer is replaced by the new object state for use in the next momentum step.

Parameters:

Name Type Description Default
loop int

Current reconstruction iteration index.

required
Source code in PtyLab/Engines/mqNewton.py
def objectMomentumUpdate(self, loop):
    r"""
    Apply the selected momentum update to the reconstructed object.

    The momentum gradient is defined from the difference between the
    buffered object state and the current reconstruction,

    $$
    g_t = O_{\mathrm{buffer}} - O_t
    $$

    The selected momentum method (`momentum`, `ADAM`, or `NADAM`) is then
    used to compute the update direction and refresh the corresponding
    momentum buffers.

    The reconstructed object is updated according to

    $$
    O_{t+1} = O_t - \beta_{O,m} u_t
    $$

    where `betaObject_m` controls the strength of the momentum correction
    and $u_t$ is the update returned by the selected momentum method.

    After the update, the object buffer is replaced by the new object state
    for use in the next momentum step.

    Args:
        loop (int):
            Current reconstruction iteration index.
    """
    gradient = self.reconstruction.objectBuffer - self.reconstruction.object
    (
        update,
        self.reconstruction.objectMomentum,
        self.reconstruction.objectMomentum_v,
    ) = self.momentum_engine(
        self,
        gradient,
        self.reconstruction.objectMomentum,
        self.reconstruction.objectMomentum_v,
        loop + 1,
    )

    self.reconstruction.object -= self.betaObject_m * update
    self.reconstruction.objectBuffer = self.reconstruction.object.copy()

probeMomentumUpdate(loop)

Apply the selected momentum update to the reconstructed probe.

The momentum gradient is defined from the difference between the buffered probe state and the current reconstruction,

\[ g_t = P_{\mathrm{buffer}} - P_t \]

The selected momentum method (momentum, ADAM, or NADAM) is used to compute the probe update direction and refresh the corresponding momentum buffers.

The probe is updated according to

\[ P_{t+1} = P_t - \beta_{P,m} u_t \]

where betaProbe_m controls the strength of the momentum correction.

After the update, the probe buffer is replaced by the new probe state for use in the next momentum step.

Parameters:

Name Type Description Default
loop int

Current reconstruction iteration index.

required
Source code in PtyLab/Engines/mqNewton.py
def probeMomentumUpdate(self, loop):
    r"""
    Apply the selected momentum update to the reconstructed probe.

    The momentum gradient is defined from the difference between the
    buffered probe state and the current reconstruction,

    $$
    g_t = P_{\mathrm{buffer}} - P_t
    $$

    The selected momentum method (`momentum`, `ADAM`, or `NADAM`) is used
    to compute the probe update direction and refresh the corresponding
    momentum buffers.

    The probe is updated according to

    $$
    P_{t+1} = P_t - \beta_{P,m} u_t
    $$

    where `betaProbe_m` controls the strength of the momentum correction.

    After the update, the probe buffer is replaced by the new probe state
    for use in the next momentum step.

    Args:
        loop (int):
            Current reconstruction iteration index.
    """
    gradient = self.reconstruction.probeBuffer - self.reconstruction.probe
    (
        update,
        self.reconstruction.probeMomentum,
        self.reconstruction.probeMomentum_v,
    ) = self.momentum_engine(
        self,
        gradient,
        self.reconstruction.probeMomentum,
        self.reconstruction.probeMomentum_v,
        loop + 1,
    )

    self.reconstruction.probe -= self.betaProbe_m * update
    self.reconstruction.probeBuffer = self.reconstruction.probe.copy()

objectPatchUpdate(objectPatch, DELTA)

Update the object patch using the qNewton-inspired correction.

The update is weighted by the current probe according to

\[ \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O} \]

where regObject provides the regularization term \(\lambda_O\).

This local qNewton-style update is applied before the additional momentum correction performed by objectMomentumUpdate().

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the scan position.

required
DELTA ndarray

Exit-wave correction after the intensity projection.

required

Returns:

Type Description
ndarray

Updated object patch.

Source code in PtyLab/Engines/mqNewton.py
def objectPatchUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the object patch using the qNewton-inspired correction.

    The update is weighted by the current probe according to

    $$
    \frac{|P|}{P_{\max}}\frac{P^*}{|P|^2+\lambda_O}
    $$

    where `regObject` provides the regularization term $\lambda_O$.

    This local qNewton-style update is applied before the additional momentum
    correction performed by `objectMomentumUpdate()`.

    Args:
        objectPatch (np.ndarray):
            Current object patch at the scan position.

        DELTA (np.ndarray):
            Exit-wave correction after the intensity projection.

    Returns:
        np.ndarray:
            Updated object patch.
    """
    xp = getArrayModule(objectPatch)
    Pmax = xp.max(xp.sum(xp.abs(self.reconstruction.probe), axis=(0, 1, 2, 3)))
    frac = (
        xp.abs(self.reconstruction.probe)
        / Pmax
        * self.reconstruction.probe.conj()
        / (xp.abs(self.reconstruction.probe) ** 2 + self.regObject)
    )
    return objectPatch + self.betaObject * xp.sum(
        frac * DELTA, axis=(0, 2, 3), keepdims=True
    )

probeUpdate(objectPatch, DELTA)

Update the probe using the qNewton-inspired correction.

The update is weighted by the current object patch according to

\[ \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P} \]

where regProbe provides the regularization term \(\lambda_P\).

This local qNewton-style update is applied before the additional momentum correction performed by probeMomentumUpdate().

Parameters:

Name Type Description Default
objectPatch ndarray

Current object patch at the scan position.

required
DELTA ndarray

Exit-wave correction after the intensity projection.

required

Returns:

Type Description
ndarray

Updated probe.

Source code in PtyLab/Engines/mqNewton.py
def probeUpdate(self, objectPatch: np.ndarray, DELTA: np.ndarray):
    r"""
    Update the probe using the qNewton-inspired correction.

    The update is weighted by the current object patch according to

    $$
    \frac{|O|}{O_{\max}}\frac{O^*}{|O|^2+\lambda_P}
    $$

    where `regProbe` provides the regularization term $\lambda_P$.

    This local qNewton-style update is applied before the additional momentum
    correction performed by `probeMomentumUpdate()`.

    Args:
        objectPatch (np.ndarray):
            Current object patch at the scan position.

        DELTA (np.ndarray):
            Exit-wave correction after the intensity projection.

    Returns:
        np.ndarray:
            Updated probe.
    """
    xp = getArrayModule(objectPatch)
    Omax = xp.max(xp.sum(xp.abs(self.reconstruction.object), axis=(0, 1, 2, 3)))
    frac = (
        xp.abs(objectPatch)
        / Omax
        * objectPatch.conj()
        / (xp.abs(objectPatch) ** 2 + self.regProbe)
    )
    r = self.reconstruction.probe + self.betaProbe * xp.sum(
        frac * DELTA, axis=(0, 1, 3), keepdims=True
    )
    return r