Skip to content

Gradient Engine

PyTorch engine for differentiable ptychography. It needs the torch extra (ptylab[torch]); see Differentiable Ptychography for usage.

Engine

GradientEngine

Bases: BaseEngine

Estimate selected physical parameters from a full ptychographic scan by automatic differentiation.

The constructor and reconstruct() entry point are the same as for the classic engines. The model predicts the detector intensity of every frame,

\[ I_j = \left|\mathcal{D}\left\lbrace O(\mathbf{r} + \mathbf{x}_j)\, P(\mathbf{r})\right\rbrace \right|^2 + b, \]

and an optimizer minimizes lossFunction between \(I_j\) and the measured frames, summed over the scan, plus any regularizers.

Set parameters to a mapping from model parameter names to optimizer options:

engine.parameters = {
    "object": {"lr": 0.03},
    "probe": {"lr": 0.1},
}

Omitted parameters remain fixed. parameters = None selects object and probe with learningRateObject and learningRateProbe.

The probe is optimized scale-free: the "probe" parameter (the model's probe.field) stores \(F = P/s\), with \(s\) set from the measured photons per frame at every preparation and reset() (see models.probe_scale). Probe learning rates are therefore dimensionless, like the object's; an older Adam rate lr for the physical probe corresponds to lr / s. snapshot(), reconstruction.probe and model.probe(indices) stay in physical units.

Every reconstruction call creates a fresh optimizer while retaining the component values from the previous call. reset() explicitly imports the detached arrays currently stored on the Reconstruction. reconstruct(phases=...) runs a sequence of Phase settings, each with a fresh optimizer; plain reconstruct() is a single phase with the engine's current settings.

NumPy is used only at the boundaries: reading ExperimentalData and Reconstruction arrays, building propagation kernels, and publishing detached results. Measurements, backgrounds and all per-iteration work are tensors on device.

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. Switches the engine does not support are listed in unsupportedSettings and rejected.

required
monitor Monitor

Monitor used to visualize and report reconstruction progress.

required

Attributes:

Name Type Description
numIterations int

Full-scan iterations per reconstruct() call. Initialized to 100.

parameters Mapping or None

Estimated parameters and their optimizer options, as {name: {"lr": rate}}; parameters not listed stay fixed. Names are "object", "probe" (scale-free, the model's probe.field) and "background" (when background is set); a custom model adds its own named_parameters() names. None estimates object and probe with learningRateObject and learningRateProbe. Initialized to None.

learningRateObject float

Object learning rate when parameters is None. Initialized to 0.03.

learningRateProbe float

Scale-free probe learning rate when parameters is None. Initialized to 0.1.

lossFunction callable

Data objective from losses, optionally wrapped in functools.partial. Initialized to amplitude_loss.

regularizers list

Penalties called with the model, added once per full scan. Initialized to an empty list.

optimizerType str

"adam", or "preconditioned" for PIE-style gradient descent: each gradient is divided by the regularized curvature map from model.gradient_preconditioners before a plain step. Its learning rates are dimensionless; about 0.3 suits the amplitude loss. Initialized to "adam".

preconditionerAlpha float

Regularization \(\alpha\) of the preconditioner, see preconditionGradients. Initialized to 0.1.

updatePerBatch bool

Take one optimizer step per batch instead of one per full scan. With it, params.positionOrder = "random" reshuffles the frames every iteration, so each batch samples the whole scan. Initialized to False.

constraints list

In-place operations applied after every optimizer step, each with its own schedule (see constraints), for example [ProbeCentering(), ObjectAmplitudeClamp(1.0)]. afterStep still runs after them for subclasses. Initialized to an empty list.

batchSize int or None

Frames forwarded per batch. None forwards the whole scan as one tensor; set an integer only to bound memory. The step stays one per full scan, with gradients accumulated over batches, so the result does not depend on it. Initialized to None.

memoryBudget float or None

CUDA only: bytes of allocated CUDA memory of the process (other tensors included) that one iteration may use. The largest batch within it is picked, see suggestBatchSize. Initialized to None.

dataDevice str or None

Where the measurements live. None keeps them on device unless they would take more than half of the free GPU memory; "cpu" keeps them in pinned host memory and copies each batch over while the previous one is computed. Initialized to None.

background float or array_like or None

Incoherent detector background \(b\) that the model adds to every predicted frame, so the data are compared with \(|\mathcal{D}\lbrace \psi\rbrace |^2 + b\) instead of being background-subtracted. The noise-model losses count \(b\) as photons, with shot-noise variance \(g\,b\), so \(b\) is for Poisson backgrounds such as stray light. A noise-free offset (electronic bias, the mean of dark frames) does not belong in \(b\): subtract it from the frames, without clipping. A nonnegative scalar or one frame-shaped image in centered order (as fft2c), as a NumPy array or tensor. It becomes the model parameter "background": fixed by default, estimated (and kept nonnegative) when selected in parameters. Assigning it or calling reset() imports it again; otherwise a learned value is retained between runs. Initialized to None.

readoutSigma float or array_like or None

Readout noise \(\sigma\) handed to the loss as read_out_sigma, in detector units. A nonnegative scalar, used for every detector pixel, or one \((N_p, N_p)\) map \(\sigma(\mathbf q)\) in centered order (as fft2c), for example the temporal standard deviation of tens of dark frames whose mean is subtracted from the data (it then also holds the dark-current shot noise). None leaves the loss's own read_out_sigma. Initialized to None.

compile bool

Compile the loss with torch.compile. Only the real-valued loss is compiled, not the complex forward model. Helps most with large frames; the first iteration of each loss is slower while it compiles. Initialized to False.

device str

Torch device of the model. Initialized to "cuda" when available, else "cpu". params.gpuSwitch (CuPy, classic engines) is ignored.

Examples:

import PtyLab
from PtyLab.Engines.GradientEngine import GradientEngine

experimentalData, reconstruction, params, monitor, _ = PtyLab.easyInitialize(
    "example:simulation_cpm", operationMode="CPM"
)
engine = GradientEngine(reconstruction, experimentalData, params, monitor)
engine.numIterations = 200
engine.reconstruct()  # results in reconstruction.object / .probe / .error
Source code in PtyLab/Engines/GradientEngine/engine.py
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
class GradientEngine(BaseEngine):
    r"""
    Estimate selected physical parameters from a full ptychographic scan by
    automatic differentiation.

    The constructor and `reconstruct()` entry point are the same as for the
    classic engines. The model predicts the detector intensity of every frame,

    $$
    I_j = \left|\mathcal{D}\left\lbrace O(\mathbf{r} + \mathbf{x}_j)\, P(\mathbf{r})\right\rbrace \right|^2 + b,
    $$

    and an optimizer minimizes `lossFunction` between $I_j$ and the measured
    frames, summed over the scan, plus any `regularizers`.

    Set `parameters` to a mapping from model parameter names to optimizer
    options:

    ```python
    engine.parameters = {
        "object": {"lr": 0.03},
        "probe": {"lr": 0.1},
    }
    ```

    Omitted parameters remain fixed. `parameters = None` selects object and
    probe with `learningRateObject` and `learningRateProbe`.

    The probe is optimized scale-free: the `"probe"` parameter (the model's
    `probe.field`) stores $F = P/s$, with $s$
    set from the measured photons per frame at every preparation and `reset()`
    (see `models.probe_scale`). Probe learning rates are therefore
    dimensionless, like the object's; an older Adam rate `lr` for the physical
    probe corresponds to `lr / s`. `snapshot()`, `reconstruction.probe` and
    `model.probe(indices)` stay in physical units.

    Every reconstruction call creates a fresh optimizer while retaining the
    component values from the previous call. `reset()` explicitly imports the
    detached arrays currently stored on the `Reconstruction`.
    `reconstruct(phases=...)` runs a sequence of `Phase` settings, each with a
    fresh optimizer; plain `reconstruct()` is a single phase with the engine's
    current settings.

    NumPy is used only at the boundaries: reading `ExperimentalData` and
    `Reconstruction` arrays, building propagation kernels, and publishing
    detached results. Measurements, backgrounds and all per-iteration work are
    tensors on `device`.

    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. Switches the engine does not support
            are listed in `unsupportedSettings` and rejected.

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

    Attributes:
        numIterations (int):
            Full-scan iterations per `reconstruct()` call. Initialized to 100.

        parameters (Mapping or None):
            Estimated parameters and their optimizer options, as
            `{name: {"lr": rate}}`; parameters not listed stay fixed. Names are
            `"object"`, `"probe"` (scale-free, the model's `probe.field`) and
            `"background"` (when `background` is set); a custom model adds its
            own `named_parameters()` names. None estimates object and probe
            with `learningRateObject` and `learningRateProbe`. Initialized to
            None.

        learningRateObject (float):
            Object learning rate when `parameters` is None. Initialized to
            0.03.

        learningRateProbe (float):
            Scale-free probe learning rate when `parameters` is None.
            Initialized to 0.1.

        lossFunction (callable):
            Data objective from `losses`, optionally wrapped in
            `functools.partial`. Initialized to `amplitude_loss`.

        regularizers (list):
            Penalties called with the model, added once per full scan.
            Initialized to an empty list.

        optimizerType (str):
            `"adam"`, or `"preconditioned"` for PIE-style gradient descent:
            each gradient is divided by the regularized curvature map from
            `model.gradient_preconditioners` before a plain step. Its learning
            rates are dimensionless; about 0.3 suits the amplitude loss.
            Initialized to `"adam"`.

        preconditionerAlpha (float):
            Regularization $\alpha$ of the preconditioner, see
            `preconditionGradients`. Initialized to 0.1.

        updatePerBatch (bool):
            Take one optimizer step per batch instead of one per full scan.
            With it, `params.positionOrder = "random"` reshuffles the frames
            every iteration, so each batch samples the whole scan. Initialized
            to False.

        constraints (list):
            In-place operations applied after every optimizer step, each with
            its own schedule (see `constraints`), for example
            `[ProbeCentering(), ObjectAmplitudeClamp(1.0)]`. `afterStep` still
            runs after them for subclasses. Initialized to an empty list.

        batchSize (int or None):
            Frames forwarded per batch. None forwards the whole scan as one
            tensor; set an integer only to bound memory. The step stays one
            per full scan, with gradients accumulated over batches, so the
            result does not depend on it. Initialized to None.

        memoryBudget (float or None):
            CUDA only: bytes of allocated CUDA memory of the process (other
            tensors included) that one iteration may use. The largest batch
            within it is picked, see `suggestBatchSize`. Initialized to None.

        dataDevice (str or None):
            Where the measurements live. None keeps them on `device` unless
            they would take more than half of the free GPU memory; `"cpu"`
            keeps them in pinned host memory and copies each batch over while
            the previous one is computed. Initialized to None.

        background (float or array_like or None):
            Incoherent detector background $b$ that the model adds to every
            predicted frame, so the data are compared with
            $|\mathcal{D}\lbrace \psi\rbrace |^2 + b$ instead of being
            background-subtracted. The noise-model losses count $b$ as
            photons, with shot-noise variance $g\,b$, so $b$ is for Poisson
            backgrounds such as stray light. A noise-free offset (electronic
            bias, the mean of dark frames) does not belong in $b$: subtract it
            from the frames, without clipping. A nonnegative scalar or one frame-shaped image in centered order
            (as `fft2c`), as a NumPy array or tensor. It becomes the model parameter
            `"background"`: fixed by default, estimated (and kept nonnegative)
            when selected in `parameters`. Assigning it or calling `reset()`
            imports it again; otherwise a learned value is retained between runs.
            Initialized to None.

        readoutSigma (float or array_like or None):
            Readout noise $\sigma$ handed to the loss as `read_out_sigma`, in
            detector units. A nonnegative scalar, used for every detector
            pixel, or one $(N_p, N_p)$ map
            $\sigma(\mathbf q)$ in centered order (as `fft2c`), for example the
            temporal standard deviation of tens of dark frames whose mean is
            subtracted from the data (it then also holds the
            dark-current shot noise). None leaves the loss's own
            `read_out_sigma`. Initialized to None.

        compile (bool):
            Compile the loss with `torch.compile`. Only the real-valued loss
            is compiled, not the complex forward model. Helps most with large
            frames; the first iteration of each loss is slower while it
            compiles. Initialized to False.

        device (str):
            Torch device of the model. Initialized to `"cuda"` when available,
            else `"cpu"`. `params.gpuSwitch` (CuPy, classic engines) is ignored.

    Examples:
        ```python
        import PtyLab
        from PtyLab.Engines.GradientEngine import GradientEngine

        experimentalData, reconstruction, params, monitor, _ = PtyLab.easyInitialize(
            "example:simulation_cpm", operationMode="CPM"
        )
        engine = GradientEngine(reconstruction, experimentalData, params, monitor)
        engine.numIterations = 200
        engine.reconstruct()  # results in reconstruction.object / .probe / .error
        ```
    """

    unsupportedSettings = (
        "objectTVregSwitch",
        "FourierMaskSwitch",
        "CPSCswitch",
        "orthogonalizationSwitch",
        "objectSmoothenessSwitch",
        "absObjectSwitch",
        "objectContrastSwitch",
        "probeSmoothenessSwitch",
        "probeBoundary",
        "absorbingProbeBoundary",
        "probePowerCorrectionSwitch",
        "probeSpectralPowerCorrectionSwitch",
        "modulusEnforcedProbeSwitch",
        "absProbeSwitch",
        "couplingSwitch",
        "binaryProbeSwitch",
        "backgroundModeSwitch",
        "comStabilizationSwitch",
        "PSDestimationSwitch",
        "positionCorrectionSwitch",
        "adaptiveDenoisingSwitch",
        "l2reg",
        "TV_autofocus",
        "OPRP",
        "SHG_probe",
        "momentumAcceleration",
        "adaptiveMomentumAcceleration",
        "weigh_probe_updates_by_intensity",
    )
    supportedPropagators = ("Fraunhofer", "Fresnel", "ASP", "scaledASP")

    def __init__(self, reconstruction, experimentalData, params, monitor):
        super().__init__(reconstruction, experimentalData, params, monitor)
        self.numIterations = 100
        self.batchSize = None
        self.memoryBudget = None
        self.dataDevice = None
        self.compile = False
        self.learningRateObject = 0.03
        self.learningRateProbe = 0.1  # scale-free, see probe_scale
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.parameters = None
        self.model = None
        self.lossFunction = amplitude_loss
        self.regularizers = []
        self.optimizerType = "adam"
        self.preconditionerAlpha = 0.1
        self.updatePerBatch = False
        self.constraints = []
        self.background = None
        self.readoutSigma = None

    @property
    def background(self):
        """Detector background imported into the model at the next run."""
        return self._background

    @background.setter
    def background(self, value):
        self._background = value
        self._backgroundPending = True

    def validateSettings(self):
        """
        Reject inputs outside the supported CPM contract.

        Raises:
            ValueError:
                If a setting is unsupported or inconsistent.

            NotImplementedError:
                If the data, the propagator or the state counts are not supported
                in this version.
        """
        if self.batchSize is not None and (
            not _is_number(self.batchSize, Integral) or self.batchSize < 1
        ):
            raise ValueError("batchSize must be a positive integer or None.")
        if self.memoryBudget is not None and (
            not _is_number(self.memoryBudget) or not self.memoryBudget > 0
        ):
            raise ValueError("memoryBudget must be a positive number of bytes or None.")
        if self.dataDevice is not None and torch.device(self.dataDevice).type not in (
            "cpu",
            torch.device(self.device).type,
        ):
            raise ValueError('dataDevice must be None, "cpu" or the engine device.')
        if not isinstance(self.compile, (bool, np.bool_)):
            raise ValueError("compile must be True or False.")
        r, p = self.reconstruction, self.params
        if self.experimentalData.operationMode != "CPM":
            raise NotImplementedError("GradientEngine currently supports CPM only.")
        if p.propagatorType.lower() not in {
            name.lower() for name in self.supportedPropagators
        }:
            raise NotImplementedError(
                f"Supported propagators: {self.supportedPropagators}"
            )
        validator = (
            self.model.validate
            if self.model is not None
            else PtychographyModel.validate
        )
        validator(r)
        probe = getattr(self.model, "probe", None)
        if isinstance(probe, OPRProbe) and len(probe.field) != len(r.positions):
            # One probe per frame: new data with another frame count would
            # index past the stack, or pair frames with the wrong probes.
            raise ValueError(
                f"The probe stack has {len(probe.field)} frames but the data have "
                f"{len(r.positions)}; create a new engine for these data."
            )
        if p.fftshiftSwitch or p.fftshiftFlag:
            raise NotImplementedError(
                "GradientEngine requires centered data and fftshiftSwitch = False."
            )
        if p.intensityConstraint != "standard":
            raise NotImplementedError(
                "GradientEngine requires the standard detector constraint setting."
            )
        if p.objectUpdateStart != 1 or p.probeUpdateStart != 1:
            raise NotImplementedError(
                "Use engine.parameters to select object and probe estimation."
            )
        enabled = [name for name in self.unsupportedSettings if getattr(p, name, False)]
        if enabled:
            raise NotImplementedError(
                "GradientEngine does not support: " + ", ".join(enabled)
            )
        # functools.partial keeps bound arguments in .keywords; the engine's
        # read_out_sigma would silently override the loss's.
        if self.readoutSigma is not None and "read_out_sigma" in getattr(
            self.lossFunction, "keywords", {}
        ):
            raise ValueError(
                "Set read_out_sigma in the loss or engine.readoutSigma, not both."
            )
        if self.numIterations < 1:
            raise ValueError("numIterations must be positive.")
        if self.optimizerType not in ("adam", "preconditioned"):
            raise ValueError('optimizerType must be "adam" or "preconditioned".')
        if isinstance(self.constraints, (str, bytes)) or not all(
            callable(constraint) for constraint in self.constraints
        ):
            raise TypeError("constraints must be a list of callables.")
        alpha = self.preconditionerAlpha
        if not _is_number(alpha) or not 0 < alpha <= 1:
            raise ValueError("preconditionerAlpha must lie in (0, 1].")

    fft2c = staticmethod(KernelPropagator.fft2c)
    ifft2c = staticmethod(KernelPropagator.ifft2c)

    def preparePropagation(self):
        """Create fixed propagation kernels on the selected Torch device."""
        self.propagation = KernelPropagator(
            self.reconstruction, self.params.propagatorType, self.device
        )

    def propagate(self, exit_wave):
        """
        Propagate an exit wave while preserving all leading dimensions.

        Args:
            exit_wave (torch.Tensor):
                Complex exit wave with spatial axes last.

        Returns:
            torch.Tensor:
                Complex detector field.
        """
        return self.propagation(exit_wave)

    def createModel(self):
        """Create the default object and shared-probe component model."""
        r = self.reconstruction
        return PtychographyModel(r.object, SharedProbe(r.probe), r.positions)

    def initializeParameters(self):
        """Create components once, or move retained components to the run device."""
        if self.model is None:
            self.model = self.createModel()
        self.model.to(self.device)
        self.model.set_positions(self.positions)
        self.model.set_propagation(self.propagation)

    def reset(self):
        """
        Import the current `Reconstruction` object and probe, and `background`.

        The probe scale is set again from the measured photons per frame. With an `OPRProbe`, `reconstruction.probe_stack` is imported if
        present. A run exports both the stack and its dominant probe
        `reconstruction.probe`; if that probe was changed since, the changed
        probe is copied to every frame instead.

        Examples:
            ```python
            reconstruction.object = previous_object  # an external edit, same shape
            engine.reset()  # import it; without reset() the model keeps its estimate
            engine.reconstruct()
            ```
        """
        PtychographyModel.validate(self.reconstruction)
        if self.model is None:
            self.model = self.createModel()
        else:
            if not hasattr(self.model, "reset_from_reconstruction"):
                raise TypeError(
                    "A custom model must implement reset_from_reconstruction()."
                )
            self.model.to(self.device)
            self.model.reset_from_reconstruction(self.reconstruction)
            exported = getattr(self, "_exportedProbe", None)
            if (
                isinstance(self.model.probe, OPRProbe)
                and exported is not None
                and not np.array_equal(self.reconstruction.probe, exported)
            ):
                # The exported stack is stale; the edited probe wins.
                self.model.probe.reset_from_array(self.reconstruction.probe)
        self.model.to(self.device)
        frames = np.asarray(self.experimentalData.ptychogram)
        self._set_probe_scale(frames.sum(dtype=np.float64) / len(frames))
        self._backgroundPending = True
        return self

    def relaxProbe(self):
        """
        Give every scan frame its own probe (orthogonal probe relaxation).

        The shared probe is replaced by an `OPRProbe` in which every frame
        starts as the current probe; the next `reconstruct()` estimates it
        with a fresh optimizer, under the same `"probe"` name. Add
        `OPRProjection` to the constraints to keep the stack low rank. To
        start from a stack instead, set `reconstruction.probe_stack` (classic
        `OPR` layout) and call `reset()` afterwards. Calling it again keeps
        the stack.

        Returns:
            GradientEngine:
                The engine, for chaining.

        Examples:
            ```python
            from PtyLab.Engines.GradientEngine import OPRProjection

            engine.reconstruct()  # fit a shared probe first
            engine.relaxProbe()
            engine.constraints = [OPRProjection(rank=4, relax=0.05)]
            engine.reconstruct()
            reconstruction.probe_stack.shape  # (nlambda, 1, npsm, 1, Np, Np, frames)
            ```
        """
        if self.model is None:
            self.model = self.createModel()
        if not isinstance(self.model.probe, OPRProbe):
            self.model.to(self.device)
            frames = len(self.reconstruction.positions)
            self.model.probe = OPRProbe.from_probe(self.model.probe, frames)
        return self

    def _set_probe_scale(self, photons_per_frame):
        """Rescale a scale-free probe for the data, keeping the physical probe."""
        probe = getattr(self.model, "probe", None)
        if hasattr(probe, "set_scale"):
            probe.set_scale(probe_scale(photons_per_frame, self.reconstruction.Np**2))

    def _physical_probe(self):
        probe = self.model.probe
        if isinstance(probe, OPRProbe):
            return probe.shared_estimate()  # one six-axis probe for the stack
        if hasattr(probe, "physical_field"):
            return probe.physical_field()
        return probe.field

    def snapshot(self, stack=True):
        """
        Return detached CPU NumPy copies of the current physical parameters.

        Args:
            stack (bool, optional):
                With an `OPRProbe`, also return the per-frame stack as
                `"probe_stack"`. Defaults to True. During iterations only the
                six-axis probe is copied, since the stack can be gigabytes.

        Returns:
            dict:
                Arrays keyed like the `Reconstruction` attributes. `"probe"` is the physical
                probe, not the scale-free parameter; with an `OPRProbe` it is
                the dominant component (`OPRProbe.shared_estimate`) and
                `"probe_stack"` the frame probes in the classic `OPR` layout
                `(nlambda, 1, npsm, 1, Np, Np, frames)`. A model background is
                included as `"background"` in centered order.

        Examples:
            ```python
            state = engine.snapshot()
            state["object"].shape  # (nlambda, nosm, 1, nslice, No, No)
            state["probe"]  # physical probe, not the scale-free parameter
            ```
        """
        if self.model is None:
            return {
                "object": np.array(self.reconstruction.object, copy=True),
                "probe": np.array(self.reconstruction.probe, copy=True),
            }
        state = {
            "object": self.model.object.detach().cpu().numpy().copy(),
            "probe": self._physical_probe().detach().cpu().numpy().copy(),
        }
        if stack and isinstance(self.model.probe, OPRProbe):
            # (frames, ...) -> (..., frames), the classic OPR engine's layout
            physical = self.model.probe.physical_field().detach().movedim(0, -1)
            state["probe_stack"] = physical.cpu().numpy()
        if getattr(self.model, "background", None) is not None:
            state["background"] = self.model.background.detach().cpu().numpy().copy()
        return state

    def _sync_reconstruction(self, stack=False, probe=True):
        """
        Publish detached object and probe snapshots for monitoring and saving.

        With `probe=False` and an `OPRProbe`, only the object is published and
        `reconstruction.probe` keeps its last export: the shared estimate is a
        $J \times J$ eigendecomposition, 34-50 ms at 1600 frames against a
        7 ms iteration.
        """
        if not probe and isinstance(self.model.probe, OPRProbe):
            self.reconstruction.object = self.model.object.detach().cpu().numpy().copy()
            return
        state = self.snapshot(stack=stack)
        self.reconstruction.object = state["object"]
        self.reconstruction.probe = state["probe"]
        if "probe_stack" in state:
            self.reconstruction.probe_stack = state["probe_stack"]
            # A private copy: reset() compares with it to see whether
            # reconstruction.probe was changed after this export.
            self._exportedProbe = state["probe"].copy()

    def _selection(self):
        if self.parameters is None:
            return {
                "object": {"lr": self.learningRateObject},
                "probe.field": {"lr": self.learningRateProbe},
            }
        if not isinstance(self.parameters, Mapping):
            raise TypeError("parameters must be a mapping or None.")
        if not self.parameters:
            raise ValueError("parameters must select at least one model parameter.")
        # "probe" is the public name of the scale-free probe parameter probe.field.
        selection = {}
        for name, options in self.parameters.items():
            key = _PARAMETER_NAMES.get(name, name)
            if key in selection:
                raise ValueError(f"{name!r} and {key!r} refer to the same tensor.")
            selection[key] = options
        return selection

    def parameterGroups(self):
        """
        Validate the public parameter selection and return optimizer groups.

        Returns:
            list:
                One optimizer parameter group per selected parameter.

        Raises:
            KeyError:
                If the selection names unknown parameters or options, or lacks
                an `"lr"`.

            TypeError:
                If the options of a parameter are not a mapping.

            ValueError:
                If a learning rate is not positive and finite, or two names
                refer to the same tensor.
        """
        named_items = list(self.model.named_parameters(remove_duplicate=False))
        named = dict(named_items)
        selection = self._selection()
        unknown = sorted(set(selection) - set(named))
        if unknown:
            available = ", ".join(named)
            raise KeyError(
                f"Unknown parameter name(s): {', '.join(unknown)}. Available: {available}."
            )

        for parameter in self.model.parameters():
            parameter.requires_grad_(False)

        groups = []
        owners = {}
        for name, options in selection.items():
            if not isinstance(options, Mapping):
                raise TypeError(f"Configuration for {name!r} must be a mapping.")
            extra = set(options) - {"lr"}
            if extra:
                raise KeyError(
                    f"Unsupported option(s) for {name!r}: {', '.join(sorted(extra))}."
                )
            if "lr" not in options:
                raise KeyError(f"Parameter {name!r} requires an 'lr' value.")
            rate = options["lr"]
            if not _is_number(rate) or not np.isfinite(rate) or rate <= 0:
                raise ValueError(
                    f"Learning rate for {name!r} must be positive and finite."
                )
            parameter = named[name]
            owner = owners.get(id(parameter))
            if owner is not None:
                raise ValueError(
                    f"Parameters {owner!r} and {name!r} refer to the same tensor."
                )
            owners[id(parameter)] = name
            parameter.requires_grad_(True)
            groups.append({"params": [parameter], "lr": float(rate), "name": name})
        return groups

    def createOptimizer(self):
        """Create a fresh optimizer of `optimizerType` for the selected parameters."""
        if self.optimizerType == "preconditioned":
            return torch.optim.SGD(self.parameterGroups(), foreach=False)
        return torch.optim.Adam(self.parameterGroups(), foreach=False)

    def preconditionGradients(self, indices):
        r"""
        Divide gradients by regularized curvature maps of the stepped frames.

        With the curvature map $D$ from `model.gradient_preconditioners`, each
        gradient is divided by

        $$
        \frac{(1 - \alpha)\,D + \alpha\max D}{P},
        $$

        with $\alpha$ = `preconditionerAlpha`, as in rPIE, and $P$ the
        full-scan power that normalizes every loss. $D$ is summed over
        `batchIndices(indices)`, so `batchSize` bounds its memory as it does
        the loss's.

        Args:
            indices (torch.Tensor):
                Frame indices of the step.

        Raises:
            KeyError:
                If the model has no curvature map for a selected parameter.
        """
        curvature = {}
        for batch in self.batchIndices(indices):
            for name, values in self.model.gradient_preconditioners(batch).items():
                total = curvature.get(name)
                curvature[name] = values if total is None else total + values
        alpha = self.preconditionerAlpha
        for group in self.optimizer.param_groups:
            (parameter,) = group["params"]
            if parameter.grad is None:
                continue
            if group["name"] not in curvature:
                raise KeyError(
                    f"No preconditioner for parameter {group['name']!r}; "
                    "extend model.gradient_preconditioners."
                )
            values = curvature[group["name"]]
            denominator = (1 - alpha) * values + alpha * values.max()
            parameter.grad.div_(denominator / self.totalPower)

    def _validate_data(self):
        r"""
        Return the measurements as a tensor after checking them where they live.

        Negative values are allowed: raw offset-subtracted frames with readout
        noise contain them, and losses that need $y \geq 0$ clamp internally.
        """
        r = self.reconstruction
        self.positions = np.asarray(r.positions)
        # A copy, so the engine never aliases ExperimentalData's array.
        frames = np.asarray(self.experimentalData.ptychogram)
        intensity = torch.tensor(
            frames,
            dtype=torch.float32,
            device=data_device(self.device, self.dataDevice, frames.size * 4),
        )
        if intensity.shape != (len(self.positions), r.Np, r.Np) or not len(
            self.positions
        ):
            raise ValueError(
                "Expected one probe-sized diffraction frame per scan position."
            )
        if not torch.isfinite(intensity).all() or not intensity.sum() > 0:
            raise ValueError(
                "Diffraction intensities must be finite and have positive total power."
            )
        if np.any(self.positions < 0) or np.any(self.positions + r.Np > r.No):
            raise ValueError("Scan positions place a probe patch outside the object.")
        return intensity

    def _background_tensor(self):
        """Return `background` as a device tensor."""
        background = torch.as_tensor(self.background, device=self.device)
        if background.dtype == torch.bool or background.is_complex():
            raise TypeError("background must be a real scalar or image.")
        background = background.to(torch.float32)
        frame_shape = self.measuredIntensities.shape[-2:]
        if background.ndim not in (0, 2) or (
            background.ndim == 2 and background.shape != frame_shape
        ):
            raise ValueError(
                f"background must be a scalar or an image of shape {tuple(frame_shape)}."
            )
        if not torch.isfinite(background).all() or (background < 0).any():
            raise ValueError("background must be finite and nonnegative.")
        return background

    def _import_background(self):
        """Copy a newly assigned `background` into the model."""
        if not self._backgroundPending:
            return
        if self.background is None:
            if getattr(self.model, "background", None) is not None:
                self.model.set_background(None)
        elif not hasattr(self.model, "set_background"):
            raise TypeError("A custom model must implement set_background().")
        else:
            self.model.set_background(self._background_tensor())
        self._backgroundPending = False

    def _readout_sigma_tensor(self):
        """Return `readoutSigma` as None, a float, or an `(Np, Np)` device map."""
        sigma = self.readoutSigma
        if sigma is None or np.ndim(sigma) == 0:
            # A scalar stays a Python float, exactly as if bound in the loss.
            return None if sigma is None else float(sigma)
        sigma = torch.as_tensor(sigma, dtype=torch.float32, device=self.device)
        # One value per detector pixel; it broadcasts against (batch, Np, Np).
        if sigma.shape != self.measuredIntensities.shape[-2:]:
            raise ValueError("readoutSigma must be a scalar or an (Np, Np) map.")
        if not torch.isfinite(sigma).all() or (sigma < 0).any():
            raise ValueError("readoutSigma must be finite and nonnegative.")
        return sigma

    def prepareReconstruction(self):
        """Prepare data, retained components, propagation and a fresh optimizer."""
        # params.gpuSwitch is the classic engines' CuPy switch and is ignored here;
        # Torch uses engine.device. Data a classic run left on the GPU (CuPy) are
        # brought back to NumPy, which is what classic engines do after a run.
        if getattr(self.params, "gpuFlag", 0):
            self._move_data_to_cpu()
            self.params.gpuFlag = 0
        self.validateSettings()
        # Drop the previous run's copy first, so a later phase never holds
        # two copies of the data or places them by the memory the old one used.
        self.measuredIntensities = self._loader = None
        self.measuredIntensities = self._validate_data()
        self.preparePropagation()
        self._loader = MeasurementLoader(self.measuredIntensities, self.device)
        self.measuredIntensities = data = self._loader.data
        # Summed in double precision, so it is the same wherever the data live.
        self.totalPower = data.sum(dtype=torch.float64).to(self.device, torch.float32)
        self.initializeParameters()
        self._set_probe_scale(self.totalPower.item() / len(self.measuredIntensities))
        self._import_background()
        self._readoutSigma = self._readout_sigma_tensor()
        self.optimizer = self.createOptimizer()
        # reconstruction.error keeps growing over runs, as in the classic engines:
        # the monitor counts iterations as len(error), so a reset would restart them.
        if not hasattr(self.reconstruction, "error"):
            self.reconstruction.error = []
        self.effectiveBatchSize = self.batchSize
        if self.memoryBudget is not None and torch.device(self.device).type == "cuda":
            self.effectiveBatchSize = self.suggestBatchSize(self.memoryBudget)[
                "batch size"
            ]
        self._sync_reconstruction()
        self._setObjectProbeROI(update=True)
        self._showInitialGuesses()

    def measuredBatch(self, indices):
        """
        Return the measured frames of a batch on `device`.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Measured frames, centered.
        """
        return next(self.measuredBatches([indices]))

    def measuredBatches(self, batches):
        """
        Yield the measured frames of each index batch on `device`, in order.

        Host-resident data for a CUDA run are copied while the previous batch
        is computed, see `batching.MeasurementLoader`.

        Args:
            batches (Sequence):
                Index tensors, one per batch.

        Returns:
            Iterator:
                Measured frames of each batch.
        """
        return self._loader(batches)

    def batchIndices(self, indices):
        """
        Split device indices into consecutive batches of `effectiveBatchSize`.

        Args:
            indices (torch.Tensor):
                Frame indices of the scan.

        Returns:
            tuple:
                Index tensors, one per batch.
        """
        return split_indices(indices, self.effectiveBatchSize)

    def suggestBatchSize(self, budget):
        """
        Return the largest batch whose measured iteration peak fits a memory budget.

        The peak of `torch.cuda.max_memory_allocated` over one iteration (data,
        parameters, gradients, optimizer state and temporaries) is measured by
        `batching.iteration_peak` at the sizes `batching.largest_batch_within`
        tries: doubling, then bisection.

        Args:
            budget (float):
                Memory budget in bytes.

        Returns:
            dict:
                `"batch size"`, its `"peak bytes"`, and `"measurements"`, the
                peak of every size tried.

        Raises:
            RuntimeError:
                If `device` is not CUDA.

            MemoryError:
                If one frame per batch already exceeds the budget.

        Notes:
            Each measurement runs two iterations and restores parameters and
            optimizer state. Constraints and `afterStep` do run, and a random
            position order draws from NumPy's global generator.

        Examples:
            ```python
            engine.device = "cuda"
            result = engine.suggestBatchSize(8 * 2**30)  # 8 GiB
            engine.batchSize = result["batch size"]
            ```
        """
        if torch.device(self.device).type != "cuda":
            raise RuntimeError(
                "suggestBatchSize measures CUDA memory; device is not CUDA."
            )
        return largest_batch_within(
            budget, len(self.positions), lambda size: iteration_peak(self, size)
        )

    def forward(self, indices):
        """
        Predict the detector intensities of one batch.

        Args:
            indices (torch.Tensor):
                Device-resident frame indices.

        Returns:
            torch.Tensor:
                Predicted intensity of shape `(batch, Np, Np)`.
        """
        return self.model(indices)

    def computeLoss(self, predictedIntensity, measuredIntensity):
        """
        Evaluate the configured data objective, normalized by the full-scan power.

        With `readoutSigma` set, the loss also gets it as `read_out_sigma`:
        the scalar, or the `(Np, Np)` map.

        Args:
            predictedIntensity (torch.Tensor):
                Predicted intensity of a batch.

            measuredIntensity (torch.Tensor):
                Measured intensity of the same batch.

        Returns:
            torch.Tensor:
                Real scalar loss.
        """
        loss = self.lossFunction
        if self.compile:
            cache = self.__dict__.setdefault("_compiledLosses", {})
            if loss not in cache:
                cache[loss] = torch.compile(loss)
            loss = cache[loss]
        sigma = getattr(self, "_readoutSigma", None)
        if sigma is None:
            return loss(predictedIntensity, measuredIntensity, self.totalPower)
        return loss(
            predictedIntensity, measuredIntensity, self.totalPower, read_out_sigma=sigma
        )

    def regularizationLoss(self):
        """
        Return the sum of the regularization penalties of the current model.

        Returns:
            torch.Tensor or None:
                Sum of the `regularizers`, or None if there are none.
        """
        if not self.regularizers:
            return None
        return sum(penalty(self.model) for penalty in self.regularizers)

    def afterStep(self, iteration):
        """
        Hook for subclasses, called after every optimizer step and constraint.

        Args:
            iteration (int):
                Iteration index from 0 within the current run of
                `numIterations`, that is within the current phase.
        """
        pass

    def runIteration(self, iteration):
        """
        Accumulate the full-scan objective and take one optimizer step.

        With `updatePerBatch` every batch takes its own step, and each step
        carries the regularization penalty weighted by its share of the frames.
        Constraints and `afterStep` run after every step.

        Args:
            iteration (int):
                Iteration index from 0 within the current run of
                `numIterations`, that is within the current phase.

        Returns:
            float:
                Full-scan loss of the iteration.
        """
        self.setPositionOrder()
        total_loss = torch.zeros((), device=self.device)
        indices = torch.as_tensor(
            self.positionIndices, dtype=torch.long, device=self.device
        )
        batches = self.batchIndices(indices)
        steps = [[batch] for batch in batches] if self.updatePerBatch else [batches]
        measured_batches = self.measuredBatches(batches)
        for step in steps:
            self.optimizer.zero_grad(set_to_none=True)
            for batch in step:
                predicted = self.forward(batch)
                measured = next(measured_batches)
                loss = self.computeLoss(predicted, measured)
                loss.backward()
                total_loss += loss.detach()
                if batch is batches[-1]:
                    last_intensity = predicted[-1].detach().clone()
                del loss, predicted, measured

            step_indices = torch.cat(step)
            penalty = self.regularizationLoss()
            if penalty is not None:
                if len(step_indices) != len(indices):
                    penalty = penalty * (len(step_indices) / len(indices))
                penalty.backward()
                total_loss += penalty.detach()

            if self.optimizerType == "preconditioned":
                self.preconditionGradients(step_indices)
            self.optimizer.step()
            with torch.no_grad():
                background = getattr(self.model, "background", None)
                if background is not None and background.requires_grad:
                    background.clamp_(min=0)
                for constraint in self.constraints:
                    constraint(self, iteration)
                self.afterStep(iteration)

        # NumPy copies of the last frame for the monitor (centered order)
        last_measured = self.measuredIntensities[self.positionIndices[-1]]
        self.reconstruction.Iestimated = last_intensity.detach().cpu().numpy().copy()
        self.reconstruction.Imeasured = last_measured.detach().cpu().numpy().copy()
        return total_loss.item()

    def _replace_experimental_data(self, experimentalData):
        """
        Replace measurements and positions after checking grid compatibility.

        Raises:
            ValueError:
                If the new data change the acquisition geometry.
        """
        previous = self.reconstruction.data
        geometry_fields = (
            "operationMode",
            "wavelength",
            "dxd",
            "zo",
            "theta",
            "spectralDensity",
            "entrancePupilDiameter",
        )
        changed = [
            name
            for name in geometry_fields
            if not np.array_equal(
                getattr(previous, name), getattr(experimentalData, name)
            )
        ]
        if previous.ptychogram.shape[1:] != experimentalData.ptychogram.shape[1:]:
            changed.append("detector shape")
        if changed:
            raise ValueError(
                "Replacement data changes acquisition geometry ("
                + ", ".join(changed)
                + "); create a new Reconstruction."
            )
        self.experimentalData = experimentalData
        self.reconstruction.data = experimentalData
        self.reconstruction.reset_positioncorrection()

    def reconstruct(self, experimentalData=None, phases=None):
        """
        Run the reconstruction from the retained estimates with a fresh optimizer.

        Without `phases`, it runs `numIterations` with the engine's own
        settings. With `phases`, it runs each `Phase` in order, each with a
        fresh optimizer and starting from the estimates the previous phase
        left. A phase sets its non-None fields on the engine for its own
        iterations; its None fields take the engine's own settings, not those
        of an earlier phase. The engine's settings are restored afterwards. The
        errors of every iteration are appended to `reconstruction.error`, which
        keeps those of earlier runs, as in the classic engines.

        Args:
            experimentalData (ExperimentalData, optional):
                Replacement data with the same acquisition geometry. If None,
                the current data are used.
            phases (Sequence, optional):
                Nonempty sequence of `Phase` records, for example from
                `blind_recipe`. If None, one run with the engine's settings.

        Returns:
            list or None:
                With `phases`, one dict per phase with its `"name"` and
                `"error"` history; otherwise None.

        Raises:
            TypeError:
                If `phases` is empty or contains anything but `Phase` records.

        Examples:
            ```python
            from PtyLab.Engines.GradientEngine import Phase, blind_recipe

            engine.reconstruct()  # numIterations with the engine's settings
            engine.reconstruct(phases=blind_recipe(iterations=1000))
            history = engine.reconstruct(
                phases=[
                    Phase(200, {"object": {"lr": 0.03}}, name="object only"),
                    Phase(800, {"object": {"lr": 0.03}, "probe": {"lr": 0.1}}),
                ]
            )
            history[0]["error"]  # errors of the first phase
            ```
        """
        if phases is None and isinstance(experimentalData, (list, tuple)):
            raise TypeError("Pass phases by keyword: engine.reconstruct(phases=...).")
        if experimentalData is not None:
            self._replace_experimental_data(experimentalData)
        if phases is None:
            self._run_iterations()
            return None
        return self._run_phases(phases)

    def _run_iterations(self):
        """Run `numIterations` with the current settings and a fresh optimizer."""
        try:
            self.prepareReconstruction()
            with trange(self.numIterations, desc=type(self).__name__) as self.pbar:
                for iteration in self.pbar:
                    loss = self.runIteration(iteration)
                    self.reconstruction.error.append(loss)
                    # The monitor draws every figureUpdateFrequency iterations
                    # and at the last one; only then is an OPR probe exported.
                    last = iteration == self.numIterations - 1
                    draws = last or iteration % self.monitor.figureUpdateFrequency == 0
                    self._sync_reconstruction(probe=draws)
                    self.showReconstruction(iteration, force=last)
                    self.pbar.set_postfix(loss=loss)
        finally:
            if self.model is not None:
                self._sync_reconstruction(stack=True)

    def _run_phases(self, phases):
        """Run `phases` in order and restore the engine's settings; see `reconstruct`."""
        phases = list(phases)
        if not phases or not all(isinstance(phase, Phase) for phase in phases):
            raise TypeError("phases must be a nonempty sequence of Phase records.")
        # Every attribute a phase can set, so the engine's own values come back.
        names = (*_SETTINGS.values(), "numIterations")
        saved = {name: getattr(self, name) for name in names}
        history = []
        try:
            for phase in phases:
                # A field left at None means the engine's own value, not the
                # value an earlier phase set.
                for name, value in {**saved, **phase.settings()}.items():
                    setattr(self, name, value)
                self.numIterations = phase.iterations
                start = len(getattr(self.reconstruction, "error", []))
                try:
                    self._run_iterations()
                finally:
                    # Also keeps the errors of an interrupted phase.
                    history.append(
                        {
                            "name": phase.name,
                            "error": list(self.reconstruction.error[start:]),
                        }
                    )
        finally:
            for name, value in saved.items():
                setattr(self, name, value)
        return history

background property writable

Detector background imported into the model at the next run.

validateSettings()

Reject inputs outside the supported CPM contract.

Raises:

Type Description
ValueError

If a setting is unsupported or inconsistent.

NotImplementedError

If the data, the propagator or the state counts are not supported in this version.

Source code in PtyLab/Engines/GradientEngine/engine.py
def validateSettings(self):
    """
    Reject inputs outside the supported CPM contract.

    Raises:
        ValueError:
            If a setting is unsupported or inconsistent.

        NotImplementedError:
            If the data, the propagator or the state counts are not supported
            in this version.
    """
    if self.batchSize is not None and (
        not _is_number(self.batchSize, Integral) or self.batchSize < 1
    ):
        raise ValueError("batchSize must be a positive integer or None.")
    if self.memoryBudget is not None and (
        not _is_number(self.memoryBudget) or not self.memoryBudget > 0
    ):
        raise ValueError("memoryBudget must be a positive number of bytes or None.")
    if self.dataDevice is not None and torch.device(self.dataDevice).type not in (
        "cpu",
        torch.device(self.device).type,
    ):
        raise ValueError('dataDevice must be None, "cpu" or the engine device.')
    if not isinstance(self.compile, (bool, np.bool_)):
        raise ValueError("compile must be True or False.")
    r, p = self.reconstruction, self.params
    if self.experimentalData.operationMode != "CPM":
        raise NotImplementedError("GradientEngine currently supports CPM only.")
    if p.propagatorType.lower() not in {
        name.lower() for name in self.supportedPropagators
    }:
        raise NotImplementedError(
            f"Supported propagators: {self.supportedPropagators}"
        )
    validator = (
        self.model.validate
        if self.model is not None
        else PtychographyModel.validate
    )
    validator(r)
    probe = getattr(self.model, "probe", None)
    if isinstance(probe, OPRProbe) and len(probe.field) != len(r.positions):
        # One probe per frame: new data with another frame count would
        # index past the stack, or pair frames with the wrong probes.
        raise ValueError(
            f"The probe stack has {len(probe.field)} frames but the data have "
            f"{len(r.positions)}; create a new engine for these data."
        )
    if p.fftshiftSwitch or p.fftshiftFlag:
        raise NotImplementedError(
            "GradientEngine requires centered data and fftshiftSwitch = False."
        )
    if p.intensityConstraint != "standard":
        raise NotImplementedError(
            "GradientEngine requires the standard detector constraint setting."
        )
    if p.objectUpdateStart != 1 or p.probeUpdateStart != 1:
        raise NotImplementedError(
            "Use engine.parameters to select object and probe estimation."
        )
    enabled = [name for name in self.unsupportedSettings if getattr(p, name, False)]
    if enabled:
        raise NotImplementedError(
            "GradientEngine does not support: " + ", ".join(enabled)
        )
    # functools.partial keeps bound arguments in .keywords; the engine's
    # read_out_sigma would silently override the loss's.
    if self.readoutSigma is not None and "read_out_sigma" in getattr(
        self.lossFunction, "keywords", {}
    ):
        raise ValueError(
            "Set read_out_sigma in the loss or engine.readoutSigma, not both."
        )
    if self.numIterations < 1:
        raise ValueError("numIterations must be positive.")
    if self.optimizerType not in ("adam", "preconditioned"):
        raise ValueError('optimizerType must be "adam" or "preconditioned".')
    if isinstance(self.constraints, (str, bytes)) or not all(
        callable(constraint) for constraint in self.constraints
    ):
        raise TypeError("constraints must be a list of callables.")
    alpha = self.preconditionerAlpha
    if not _is_number(alpha) or not 0 < alpha <= 1:
        raise ValueError("preconditionerAlpha must lie in (0, 1].")

preparePropagation()

Create fixed propagation kernels on the selected Torch device.

Source code in PtyLab/Engines/GradientEngine/engine.py
def preparePropagation(self):
    """Create fixed propagation kernels on the selected Torch device."""
    self.propagation = KernelPropagator(
        self.reconstruction, self.params.propagatorType, self.device
    )

propagate(exit_wave)

Propagate an exit wave while preserving all leading dimensions.

Parameters:

Name Type Description Default
exit_wave Tensor

Complex exit wave with spatial axes last.

required

Returns:

Type Description
Tensor

Complex detector field.

Source code in PtyLab/Engines/GradientEngine/engine.py
def propagate(self, exit_wave):
    """
    Propagate an exit wave while preserving all leading dimensions.

    Args:
        exit_wave (torch.Tensor):
            Complex exit wave with spatial axes last.

    Returns:
        torch.Tensor:
            Complex detector field.
    """
    return self.propagation(exit_wave)

createModel()

Create the default object and shared-probe component model.

Source code in PtyLab/Engines/GradientEngine/engine.py
def createModel(self):
    """Create the default object and shared-probe component model."""
    r = self.reconstruction
    return PtychographyModel(r.object, SharedProbe(r.probe), r.positions)

initializeParameters()

Create components once, or move retained components to the run device.

Source code in PtyLab/Engines/GradientEngine/engine.py
def initializeParameters(self):
    """Create components once, or move retained components to the run device."""
    if self.model is None:
        self.model = self.createModel()
    self.model.to(self.device)
    self.model.set_positions(self.positions)
    self.model.set_propagation(self.propagation)

reset()

Import the current Reconstruction object and probe, and background.

The probe scale is set again from the measured photons per frame. With an OPRProbe, reconstruction.probe_stack is imported if present. A run exports both the stack and its dominant probe reconstruction.probe; if that probe was changed since, the changed probe is copied to every frame instead.

Examples:

reconstruction.object = previous_object  # an external edit, same shape
engine.reset()  # import it; without reset() the model keeps its estimate
engine.reconstruct()
Source code in PtyLab/Engines/GradientEngine/engine.py
def reset(self):
    """
    Import the current `Reconstruction` object and probe, and `background`.

    The probe scale is set again from the measured photons per frame. With an `OPRProbe`, `reconstruction.probe_stack` is imported if
    present. A run exports both the stack and its dominant probe
    `reconstruction.probe`; if that probe was changed since, the changed
    probe is copied to every frame instead.

    Examples:
        ```python
        reconstruction.object = previous_object  # an external edit, same shape
        engine.reset()  # import it; without reset() the model keeps its estimate
        engine.reconstruct()
        ```
    """
    PtychographyModel.validate(self.reconstruction)
    if self.model is None:
        self.model = self.createModel()
    else:
        if not hasattr(self.model, "reset_from_reconstruction"):
            raise TypeError(
                "A custom model must implement reset_from_reconstruction()."
            )
        self.model.to(self.device)
        self.model.reset_from_reconstruction(self.reconstruction)
        exported = getattr(self, "_exportedProbe", None)
        if (
            isinstance(self.model.probe, OPRProbe)
            and exported is not None
            and not np.array_equal(self.reconstruction.probe, exported)
        ):
            # The exported stack is stale; the edited probe wins.
            self.model.probe.reset_from_array(self.reconstruction.probe)
    self.model.to(self.device)
    frames = np.asarray(self.experimentalData.ptychogram)
    self._set_probe_scale(frames.sum(dtype=np.float64) / len(frames))
    self._backgroundPending = True
    return self

relaxProbe()

Give every scan frame its own probe (orthogonal probe relaxation).

The shared probe is replaced by an OPRProbe in which every frame starts as the current probe; the next reconstruct() estimates it with a fresh optimizer, under the same "probe" name. Add OPRProjection to the constraints to keep the stack low rank. To start from a stack instead, set reconstruction.probe_stack (classic OPR layout) and call reset() afterwards. Calling it again keeps the stack.

Returns:

Type Description
GradientEngine

The engine, for chaining.

Examples:

from PtyLab.Engines.GradientEngine import OPRProjection

engine.reconstruct()  # fit a shared probe first
engine.relaxProbe()
engine.constraints = [OPRProjection(rank=4, relax=0.05)]
engine.reconstruct()
reconstruction.probe_stack.shape  # (nlambda, 1, npsm, 1, Np, Np, frames)
Source code in PtyLab/Engines/GradientEngine/engine.py
def relaxProbe(self):
    """
    Give every scan frame its own probe (orthogonal probe relaxation).

    The shared probe is replaced by an `OPRProbe` in which every frame
    starts as the current probe; the next `reconstruct()` estimates it
    with a fresh optimizer, under the same `"probe"` name. Add
    `OPRProjection` to the constraints to keep the stack low rank. To
    start from a stack instead, set `reconstruction.probe_stack` (classic
    `OPR` layout) and call `reset()` afterwards. Calling it again keeps
    the stack.

    Returns:
        GradientEngine:
            The engine, for chaining.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import OPRProjection

        engine.reconstruct()  # fit a shared probe first
        engine.relaxProbe()
        engine.constraints = [OPRProjection(rank=4, relax=0.05)]
        engine.reconstruct()
        reconstruction.probe_stack.shape  # (nlambda, 1, npsm, 1, Np, Np, frames)
        ```
    """
    if self.model is None:
        self.model = self.createModel()
    if not isinstance(self.model.probe, OPRProbe):
        self.model.to(self.device)
        frames = len(self.reconstruction.positions)
        self.model.probe = OPRProbe.from_probe(self.model.probe, frames)
    return self

snapshot(stack=True)

Return detached CPU NumPy copies of the current physical parameters.

Parameters:

Name Type Description Default
stack bool

With an OPRProbe, also return the per-frame stack as "probe_stack". Defaults to True. During iterations only the six-axis probe is copied, since the stack can be gigabytes.

True

Returns:

Type Description
dict

Arrays keyed like the Reconstruction attributes. "probe" is the physical probe, not the scale-free parameter; with an OPRProbe it is the dominant component (OPRProbe.shared_estimate) and "probe_stack" the frame probes in the classic OPR layout (nlambda, 1, npsm, 1, Np, Np, frames). A model background is included as "background" in centered order.

Examples:

state = engine.snapshot()
state["object"].shape  # (nlambda, nosm, 1, nslice, No, No)
state["probe"]  # physical probe, not the scale-free parameter
Source code in PtyLab/Engines/GradientEngine/engine.py
def snapshot(self, stack=True):
    """
    Return detached CPU NumPy copies of the current physical parameters.

    Args:
        stack (bool, optional):
            With an `OPRProbe`, also return the per-frame stack as
            `"probe_stack"`. Defaults to True. During iterations only the
            six-axis probe is copied, since the stack can be gigabytes.

    Returns:
        dict:
            Arrays keyed like the `Reconstruction` attributes. `"probe"` is the physical
            probe, not the scale-free parameter; with an `OPRProbe` it is
            the dominant component (`OPRProbe.shared_estimate`) and
            `"probe_stack"` the frame probes in the classic `OPR` layout
            `(nlambda, 1, npsm, 1, Np, Np, frames)`. A model background is
            included as `"background"` in centered order.

    Examples:
        ```python
        state = engine.snapshot()
        state["object"].shape  # (nlambda, nosm, 1, nslice, No, No)
        state["probe"]  # physical probe, not the scale-free parameter
        ```
    """
    if self.model is None:
        return {
            "object": np.array(self.reconstruction.object, copy=True),
            "probe": np.array(self.reconstruction.probe, copy=True),
        }
    state = {
        "object": self.model.object.detach().cpu().numpy().copy(),
        "probe": self._physical_probe().detach().cpu().numpy().copy(),
    }
    if stack and isinstance(self.model.probe, OPRProbe):
        # (frames, ...) -> (..., frames), the classic OPR engine's layout
        physical = self.model.probe.physical_field().detach().movedim(0, -1)
        state["probe_stack"] = physical.cpu().numpy()
    if getattr(self.model, "background", None) is not None:
        state["background"] = self.model.background.detach().cpu().numpy().copy()
    return state

parameterGroups()

Validate the public parameter selection and return optimizer groups.

Returns:

Type Description
list

One optimizer parameter group per selected parameter.

Raises:

Type Description
KeyError

If the selection names unknown parameters or options, or lacks an "lr".

TypeError

If the options of a parameter are not a mapping.

ValueError

If a learning rate is not positive and finite, or two names refer to the same tensor.

Source code in PtyLab/Engines/GradientEngine/engine.py
def parameterGroups(self):
    """
    Validate the public parameter selection and return optimizer groups.

    Returns:
        list:
            One optimizer parameter group per selected parameter.

    Raises:
        KeyError:
            If the selection names unknown parameters or options, or lacks
            an `"lr"`.

        TypeError:
            If the options of a parameter are not a mapping.

        ValueError:
            If a learning rate is not positive and finite, or two names
            refer to the same tensor.
    """
    named_items = list(self.model.named_parameters(remove_duplicate=False))
    named = dict(named_items)
    selection = self._selection()
    unknown = sorted(set(selection) - set(named))
    if unknown:
        available = ", ".join(named)
        raise KeyError(
            f"Unknown parameter name(s): {', '.join(unknown)}. Available: {available}."
        )

    for parameter in self.model.parameters():
        parameter.requires_grad_(False)

    groups = []
    owners = {}
    for name, options in selection.items():
        if not isinstance(options, Mapping):
            raise TypeError(f"Configuration for {name!r} must be a mapping.")
        extra = set(options) - {"lr"}
        if extra:
            raise KeyError(
                f"Unsupported option(s) for {name!r}: {', '.join(sorted(extra))}."
            )
        if "lr" not in options:
            raise KeyError(f"Parameter {name!r} requires an 'lr' value.")
        rate = options["lr"]
        if not _is_number(rate) or not np.isfinite(rate) or rate <= 0:
            raise ValueError(
                f"Learning rate for {name!r} must be positive and finite."
            )
        parameter = named[name]
        owner = owners.get(id(parameter))
        if owner is not None:
            raise ValueError(
                f"Parameters {owner!r} and {name!r} refer to the same tensor."
            )
        owners[id(parameter)] = name
        parameter.requires_grad_(True)
        groups.append({"params": [parameter], "lr": float(rate), "name": name})
    return groups

createOptimizer()

Create a fresh optimizer of optimizerType for the selected parameters.

Source code in PtyLab/Engines/GradientEngine/engine.py
def createOptimizer(self):
    """Create a fresh optimizer of `optimizerType` for the selected parameters."""
    if self.optimizerType == "preconditioned":
        return torch.optim.SGD(self.parameterGroups(), foreach=False)
    return torch.optim.Adam(self.parameterGroups(), foreach=False)

preconditionGradients(indices)

Divide gradients by regularized curvature maps of the stepped frames.

With the curvature map \(D\) from model.gradient_preconditioners, each gradient is divided by

\[ \frac{(1 - \alpha)\,D + \alpha\max D}{P}, \]

with \(\alpha\) = preconditionerAlpha, as in rPIE, and \(P\) the full-scan power that normalizes every loss. \(D\) is summed over batchIndices(indices), so batchSize bounds its memory as it does the loss's.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the step.

required

Raises:

Type Description
KeyError

If the model has no curvature map for a selected parameter.

Source code in PtyLab/Engines/GradientEngine/engine.py
def preconditionGradients(self, indices):
    r"""
    Divide gradients by regularized curvature maps of the stepped frames.

    With the curvature map $D$ from `model.gradient_preconditioners`, each
    gradient is divided by

    $$
    \frac{(1 - \alpha)\,D + \alpha\max D}{P},
    $$

    with $\alpha$ = `preconditionerAlpha`, as in rPIE, and $P$ the
    full-scan power that normalizes every loss. $D$ is summed over
    `batchIndices(indices)`, so `batchSize` bounds its memory as it does
    the loss's.

    Args:
        indices (torch.Tensor):
            Frame indices of the step.

    Raises:
        KeyError:
            If the model has no curvature map for a selected parameter.
    """
    curvature = {}
    for batch in self.batchIndices(indices):
        for name, values in self.model.gradient_preconditioners(batch).items():
            total = curvature.get(name)
            curvature[name] = values if total is None else total + values
    alpha = self.preconditionerAlpha
    for group in self.optimizer.param_groups:
        (parameter,) = group["params"]
        if parameter.grad is None:
            continue
        if group["name"] not in curvature:
            raise KeyError(
                f"No preconditioner for parameter {group['name']!r}; "
                "extend model.gradient_preconditioners."
            )
        values = curvature[group["name"]]
        denominator = (1 - alpha) * values + alpha * values.max()
        parameter.grad.div_(denominator / self.totalPower)

prepareReconstruction()

Prepare data, retained components, propagation and a fresh optimizer.

Source code in PtyLab/Engines/GradientEngine/engine.py
def prepareReconstruction(self):
    """Prepare data, retained components, propagation and a fresh optimizer."""
    # params.gpuSwitch is the classic engines' CuPy switch and is ignored here;
    # Torch uses engine.device. Data a classic run left on the GPU (CuPy) are
    # brought back to NumPy, which is what classic engines do after a run.
    if getattr(self.params, "gpuFlag", 0):
        self._move_data_to_cpu()
        self.params.gpuFlag = 0
    self.validateSettings()
    # Drop the previous run's copy first, so a later phase never holds
    # two copies of the data or places them by the memory the old one used.
    self.measuredIntensities = self._loader = None
    self.measuredIntensities = self._validate_data()
    self.preparePropagation()
    self._loader = MeasurementLoader(self.measuredIntensities, self.device)
    self.measuredIntensities = data = self._loader.data
    # Summed in double precision, so it is the same wherever the data live.
    self.totalPower = data.sum(dtype=torch.float64).to(self.device, torch.float32)
    self.initializeParameters()
    self._set_probe_scale(self.totalPower.item() / len(self.measuredIntensities))
    self._import_background()
    self._readoutSigma = self._readout_sigma_tensor()
    self.optimizer = self.createOptimizer()
    # reconstruction.error keeps growing over runs, as in the classic engines:
    # the monitor counts iterations as len(error), so a reset would restart them.
    if not hasattr(self.reconstruction, "error"):
        self.reconstruction.error = []
    self.effectiveBatchSize = self.batchSize
    if self.memoryBudget is not None and torch.device(self.device).type == "cuda":
        self.effectiveBatchSize = self.suggestBatchSize(self.memoryBudget)[
            "batch size"
        ]
    self._sync_reconstruction()
    self._setObjectProbeROI(update=True)
    self._showInitialGuesses()

measuredBatch(indices)

Return the measured frames of a batch on device.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Measured frames, centered.

Source code in PtyLab/Engines/GradientEngine/engine.py
def measuredBatch(self, indices):
    """
    Return the measured frames of a batch on `device`.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Measured frames, centered.
    """
    return next(self.measuredBatches([indices]))

measuredBatches(batches)

Yield the measured frames of each index batch on device, in order.

Host-resident data for a CUDA run are copied while the previous batch is computed, see batching.MeasurementLoader.

Parameters:

Name Type Description Default
batches Sequence

Index tensors, one per batch.

required

Returns:

Type Description
Iterator

Measured frames of each batch.

Source code in PtyLab/Engines/GradientEngine/engine.py
def measuredBatches(self, batches):
    """
    Yield the measured frames of each index batch on `device`, in order.

    Host-resident data for a CUDA run are copied while the previous batch
    is computed, see `batching.MeasurementLoader`.

    Args:
        batches (Sequence):
            Index tensors, one per batch.

    Returns:
        Iterator:
            Measured frames of each batch.
    """
    return self._loader(batches)

batchIndices(indices)

Split device indices into consecutive batches of effectiveBatchSize.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the scan.

required

Returns:

Type Description
tuple

Index tensors, one per batch.

Source code in PtyLab/Engines/GradientEngine/engine.py
def batchIndices(self, indices):
    """
    Split device indices into consecutive batches of `effectiveBatchSize`.

    Args:
        indices (torch.Tensor):
            Frame indices of the scan.

    Returns:
        tuple:
            Index tensors, one per batch.
    """
    return split_indices(indices, self.effectiveBatchSize)

suggestBatchSize(budget)

Return the largest batch whose measured iteration peak fits a memory budget.

The peak of torch.cuda.max_memory_allocated over one iteration (data, parameters, gradients, optimizer state and temporaries) is measured by batching.iteration_peak at the sizes batching.largest_batch_within tries: doubling, then bisection.

Parameters:

Name Type Description Default
budget float

Memory budget in bytes.

required

Returns:

Type Description
dict

"batch size", its "peak bytes", and "measurements", the peak of every size tried.

Raises:

Type Description
RuntimeError

If device is not CUDA.

MemoryError

If one frame per batch already exceeds the budget.

Notes

Each measurement runs two iterations and restores parameters and optimizer state. Constraints and afterStep do run, and a random position order draws from NumPy's global generator.

Examples:

engine.device = "cuda"
result = engine.suggestBatchSize(8 * 2**30)  # 8 GiB
engine.batchSize = result["batch size"]
Source code in PtyLab/Engines/GradientEngine/engine.py
def suggestBatchSize(self, budget):
    """
    Return the largest batch whose measured iteration peak fits a memory budget.

    The peak of `torch.cuda.max_memory_allocated` over one iteration (data,
    parameters, gradients, optimizer state and temporaries) is measured by
    `batching.iteration_peak` at the sizes `batching.largest_batch_within`
    tries: doubling, then bisection.

    Args:
        budget (float):
            Memory budget in bytes.

    Returns:
        dict:
            `"batch size"`, its `"peak bytes"`, and `"measurements"`, the
            peak of every size tried.

    Raises:
        RuntimeError:
            If `device` is not CUDA.

        MemoryError:
            If one frame per batch already exceeds the budget.

    Notes:
        Each measurement runs two iterations and restores parameters and
        optimizer state. Constraints and `afterStep` do run, and a random
        position order draws from NumPy's global generator.

    Examples:
        ```python
        engine.device = "cuda"
        result = engine.suggestBatchSize(8 * 2**30)  # 8 GiB
        engine.batchSize = result["batch size"]
        ```
    """
    if torch.device(self.device).type != "cuda":
        raise RuntimeError(
            "suggestBatchSize measures CUDA memory; device is not CUDA."
        )
    return largest_batch_within(
        budget, len(self.positions), lambda size: iteration_peak(self, size)
    )

forward(indices)

Predict the detector intensities of one batch.

Parameters:

Name Type Description Default
indices Tensor

Device-resident frame indices.

required

Returns:

Type Description
Tensor

Predicted intensity of shape (batch, Np, Np).

Source code in PtyLab/Engines/GradientEngine/engine.py
def forward(self, indices):
    """
    Predict the detector intensities of one batch.

    Args:
        indices (torch.Tensor):
            Device-resident frame indices.

    Returns:
        torch.Tensor:
            Predicted intensity of shape `(batch, Np, Np)`.
    """
    return self.model(indices)

computeLoss(predictedIntensity, measuredIntensity)

Evaluate the configured data objective, normalized by the full-scan power.

With readoutSigma set, the loss also gets it as read_out_sigma: the scalar, or the (Np, Np) map.

Parameters:

Name Type Description Default
predictedIntensity Tensor

Predicted intensity of a batch.

required
measuredIntensity Tensor

Measured intensity of the same batch.

required

Returns:

Type Description
Tensor

Real scalar loss.

Source code in PtyLab/Engines/GradientEngine/engine.py
def computeLoss(self, predictedIntensity, measuredIntensity):
    """
    Evaluate the configured data objective, normalized by the full-scan power.

    With `readoutSigma` set, the loss also gets it as `read_out_sigma`:
    the scalar, or the `(Np, Np)` map.

    Args:
        predictedIntensity (torch.Tensor):
            Predicted intensity of a batch.

        measuredIntensity (torch.Tensor):
            Measured intensity of the same batch.

    Returns:
        torch.Tensor:
            Real scalar loss.
    """
    loss = self.lossFunction
    if self.compile:
        cache = self.__dict__.setdefault("_compiledLosses", {})
        if loss not in cache:
            cache[loss] = torch.compile(loss)
        loss = cache[loss]
    sigma = getattr(self, "_readoutSigma", None)
    if sigma is None:
        return loss(predictedIntensity, measuredIntensity, self.totalPower)
    return loss(
        predictedIntensity, measuredIntensity, self.totalPower, read_out_sigma=sigma
    )

regularizationLoss()

Return the sum of the regularization penalties of the current model.

Returns:

Type Description
Tensor or None

Sum of the regularizers, or None if there are none.

Source code in PtyLab/Engines/GradientEngine/engine.py
def regularizationLoss(self):
    """
    Return the sum of the regularization penalties of the current model.

    Returns:
        torch.Tensor or None:
            Sum of the `regularizers`, or None if there are none.
    """
    if not self.regularizers:
        return None
    return sum(penalty(self.model) for penalty in self.regularizers)

afterStep(iteration)

Hook for subclasses, called after every optimizer step and constraint.

Parameters:

Name Type Description Default
iteration int

Iteration index from 0 within the current run of numIterations, that is within the current phase.

required
Source code in PtyLab/Engines/GradientEngine/engine.py
def afterStep(self, iteration):
    """
    Hook for subclasses, called after every optimizer step and constraint.

    Args:
        iteration (int):
            Iteration index from 0 within the current run of
            `numIterations`, that is within the current phase.
    """
    pass

runIteration(iteration)

Accumulate the full-scan objective and take one optimizer step.

With updatePerBatch every batch takes its own step, and each step carries the regularization penalty weighted by its share of the frames. Constraints and afterStep run after every step.

Parameters:

Name Type Description Default
iteration int

Iteration index from 0 within the current run of numIterations, that is within the current phase.

required

Returns:

Type Description
float

Full-scan loss of the iteration.

Source code in PtyLab/Engines/GradientEngine/engine.py
def runIteration(self, iteration):
    """
    Accumulate the full-scan objective and take one optimizer step.

    With `updatePerBatch` every batch takes its own step, and each step
    carries the regularization penalty weighted by its share of the frames.
    Constraints and `afterStep` run after every step.

    Args:
        iteration (int):
            Iteration index from 0 within the current run of
            `numIterations`, that is within the current phase.

    Returns:
        float:
            Full-scan loss of the iteration.
    """
    self.setPositionOrder()
    total_loss = torch.zeros((), device=self.device)
    indices = torch.as_tensor(
        self.positionIndices, dtype=torch.long, device=self.device
    )
    batches = self.batchIndices(indices)
    steps = [[batch] for batch in batches] if self.updatePerBatch else [batches]
    measured_batches = self.measuredBatches(batches)
    for step in steps:
        self.optimizer.zero_grad(set_to_none=True)
        for batch in step:
            predicted = self.forward(batch)
            measured = next(measured_batches)
            loss = self.computeLoss(predicted, measured)
            loss.backward()
            total_loss += loss.detach()
            if batch is batches[-1]:
                last_intensity = predicted[-1].detach().clone()
            del loss, predicted, measured

        step_indices = torch.cat(step)
        penalty = self.regularizationLoss()
        if penalty is not None:
            if len(step_indices) != len(indices):
                penalty = penalty * (len(step_indices) / len(indices))
            penalty.backward()
            total_loss += penalty.detach()

        if self.optimizerType == "preconditioned":
            self.preconditionGradients(step_indices)
        self.optimizer.step()
        with torch.no_grad():
            background = getattr(self.model, "background", None)
            if background is not None and background.requires_grad:
                background.clamp_(min=0)
            for constraint in self.constraints:
                constraint(self, iteration)
            self.afterStep(iteration)

    # NumPy copies of the last frame for the monitor (centered order)
    last_measured = self.measuredIntensities[self.positionIndices[-1]]
    self.reconstruction.Iestimated = last_intensity.detach().cpu().numpy().copy()
    self.reconstruction.Imeasured = last_measured.detach().cpu().numpy().copy()
    return total_loss.item()

reconstruct(experimentalData=None, phases=None)

Run the reconstruction from the retained estimates with a fresh optimizer.

Without phases, it runs numIterations with the engine's own settings. With phases, it runs each Phase in order, each with a fresh optimizer and starting from the estimates the previous phase left. A phase sets its non-None fields on the engine for its own iterations; its None fields take the engine's own settings, not those of an earlier phase. The engine's settings are restored afterwards. The errors of every iteration are appended to reconstruction.error, which keeps those of earlier runs, as in the classic engines.

Parameters:

Name Type Description Default
experimentalData ExperimentalData

Replacement data with the same acquisition geometry. If None, the current data are used.

None
phases Sequence

Nonempty sequence of Phase records, for example from blind_recipe. If None, one run with the engine's settings.

None

Returns:

Type Description
list or None

With phases, one dict per phase with its "name" and "error" history; otherwise None.

Raises:

Type Description
TypeError

If phases is empty or contains anything but Phase records.

Examples:

from PtyLab.Engines.GradientEngine import Phase, blind_recipe

engine.reconstruct()  # numIterations with the engine's settings
engine.reconstruct(phases=blind_recipe(iterations=1000))
history = engine.reconstruct(
    phases=[
        Phase(200, {"object": {"lr": 0.03}}, name="object only"),
        Phase(800, {"object": {"lr": 0.03}, "probe": {"lr": 0.1}}),
    ]
)
history[0]["error"]  # errors of the first phase
Source code in PtyLab/Engines/GradientEngine/engine.py
def reconstruct(self, experimentalData=None, phases=None):
    """
    Run the reconstruction from the retained estimates with a fresh optimizer.

    Without `phases`, it runs `numIterations` with the engine's own
    settings. With `phases`, it runs each `Phase` in order, each with a
    fresh optimizer and starting from the estimates the previous phase
    left. A phase sets its non-None fields on the engine for its own
    iterations; its None fields take the engine's own settings, not those
    of an earlier phase. The engine's settings are restored afterwards. The
    errors of every iteration are appended to `reconstruction.error`, which
    keeps those of earlier runs, as in the classic engines.

    Args:
        experimentalData (ExperimentalData, optional):
            Replacement data with the same acquisition geometry. If None,
            the current data are used.
        phases (Sequence, optional):
            Nonempty sequence of `Phase` records, for example from
            `blind_recipe`. If None, one run with the engine's settings.

    Returns:
        list or None:
            With `phases`, one dict per phase with its `"name"` and
            `"error"` history; otherwise None.

    Raises:
        TypeError:
            If `phases` is empty or contains anything but `Phase` records.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import Phase, blind_recipe

        engine.reconstruct()  # numIterations with the engine's settings
        engine.reconstruct(phases=blind_recipe(iterations=1000))
        history = engine.reconstruct(
            phases=[
                Phase(200, {"object": {"lr": 0.03}}, name="object only"),
                Phase(800, {"object": {"lr": 0.03}, "probe": {"lr": 0.1}}),
            ]
        )
        history[0]["error"]  # errors of the first phase
        ```
    """
    if phases is None and isinstance(experimentalData, (list, tuple)):
        raise TypeError("Pass phases by keyword: engine.reconstruct(phases=...).")
    if experimentalData is not None:
        self._replace_experimental_data(experimentalData)
    if phases is None:
        self._run_iterations()
        return None
    return self._run_phases(phases)

Models

Torch components for the ptychographic forward model.

SharedProbe

Bases: Module

Entrance probe shared by every scan frame, stored scale-free.

The physical probe is

\[ P = s\,F, \]

where the field \(F\) (field) is the optimized parameter and the scale \(s\) (scale) a fixed real buffer, which GradientEngine sets from the measured photons per frame (see probe_scale). \(F\) is then of order one at every photon count, so one Adam learning rate fits all data: Adam steps are about lr in the parameter's own units.

Parameters:

Name Type Description Default
field array_like

Physical probe of shape (nlambda, 1, npsm, 1, Np, Np).

required
scale float

Probe scale \(s\), rounded to a power of two. Defaults to 1.0.

1.0
Notes

\(s\) is kept a power of two, so converting between \(F\) and the physical probe is exact in floating point.

Examples:

probe = engine.model.probe  # a SharedProbe after the first reconstruct()
probe.scale  # power of two s, set from the photons per frame
probe.physical_field()  # P = s F, differentiable
probe.mode_powers()  # (nlambda, npsm)
Source code in PtyLab/Engines/GradientEngine/models.py
class SharedProbe(torch.nn.Module):
    r"""
    Entrance probe shared by every scan frame, stored scale-free.

    The physical probe is

    $$
    P = s\,F,
    $$

    where the field $F$ (`field`) is the optimized parameter and the scale $s$
    (`scale`) a fixed real buffer, which `GradientEngine` sets from the
    measured photons per frame (see `probe_scale`). $F$ is then of order one
    at every photon count, so one Adam learning rate fits all data: Adam steps
    are about `lr` in the parameter's own units.

    Args:
        field (array_like):
            Physical probe of shape `(nlambda, 1, npsm, 1, Np, Np)`.

        scale (float, optional):
            Probe scale $s$, rounded to a power of two. Defaults to 1.0.

    Notes:
        $s$ is kept a power of two, so converting between $F$ and the physical
        probe is exact in floating point.

    Examples:
        ```python
        probe = engine.model.probe  # a SharedProbe after the first reconstruct()
        probe.scale  # power of two s, set from the photons per frame
        probe.physical_field()  # P = s F, differentiable
        probe.mode_powers()  # (nlambda, npsm)
        ```
    """

    def __init__(self, field, scale=1.0):
        super().__init__()
        self.register_buffer("scale", torch.tensor(_power_of_two(scale)))
        self.field = torch.nn.Parameter(
            torch.as_tensor(field, dtype=torch.complex64) / self.scale
        )

    def physical_field(self):
        r"""
        Return the physical probe $P = sF$.

        Returns:
            torch.Tensor:
                Differentiable physical probe.
        """
        return self.scale * self.field

    def forward(self, indices):
        """
        Return one broadcast view of the six-axis physical probe per frame.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Probe of shape `(batch, nlambda, 1, npsm, 1, Np, Np)`.
        """
        field = self.physical_field()
        return field.unsqueeze(0).expand(len(indices), *field.shape)

    def mode_powers(self):
        r"""
        Return the power of each probe mode.

        $$
        s_m = \sum_{\mathbf{r}} |P_m(\mathbf{r})|^2,
        $$

        in physical units, so $\sum_m s_m$ is the total probe power.

        Returns:
            torch.Tensor:
                Detached real powers of shape `(nlambda, npsm)`.
        """
        with torch.no_grad():
            power = squared_modulus(self.physical_field()).sum(dim=(-2, -1))
        # (nlambda, 1, npsm, 1) -> (nlambda, npsm)
        return power[:, 0, :, 0]

    def set_scale(self, scale):
        r"""
        Change the scale $s$ while keeping the physical probe unchanged.

        Args:
            scale (float):
                New scale, rounded to a power of two.
        """
        scale = _power_of_two(scale)
        with torch.no_grad():
            self.field.mul_(self.scale / scale)
            self.scale.fill_(scale)

    def reset_from_array(self, field):
        """
        Copy a physical probe into the existing parameter.

        Args:
            field (array_like):
                Physical probe with the shape of `field`.

        Raises:
            ValueError:
                If the shape differs from the parameter's.
        """
        value = torch.as_tensor(field, dtype=self.field.dtype, device=self.field.device)
        if value.shape != self.field.shape:
            raise ValueError(
                f"Probe shape changed from {tuple(self.field.shape)} to {tuple(value.shape)}."
            )
        with torch.no_grad():
            self.field.copy_(value / self.scale)

physical_field()

Return the physical probe \(P = sF\).

Returns:

Type Description
Tensor

Differentiable physical probe.

Source code in PtyLab/Engines/GradientEngine/models.py
def physical_field(self):
    r"""
    Return the physical probe $P = sF$.

    Returns:
        torch.Tensor:
            Differentiable physical probe.
    """
    return self.scale * self.field

forward(indices)

Return one broadcast view of the six-axis physical probe per frame.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Probe of shape (batch, nlambda, 1, npsm, 1, Np, Np).

Source code in PtyLab/Engines/GradientEngine/models.py
def forward(self, indices):
    """
    Return one broadcast view of the six-axis physical probe per frame.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Probe of shape `(batch, nlambda, 1, npsm, 1, Np, Np)`.
    """
    field = self.physical_field()
    return field.unsqueeze(0).expand(len(indices), *field.shape)

mode_powers()

Return the power of each probe mode.

\[ s_m = \sum_{\mathbf{r}} |P_m(\mathbf{r})|^2, \]

in physical units, so \(\sum_m s_m\) is the total probe power.

Returns:

Type Description
Tensor

Detached real powers of shape (nlambda, npsm).

Source code in PtyLab/Engines/GradientEngine/models.py
def mode_powers(self):
    r"""
    Return the power of each probe mode.

    $$
    s_m = \sum_{\mathbf{r}} |P_m(\mathbf{r})|^2,
    $$

    in physical units, so $\sum_m s_m$ is the total probe power.

    Returns:
        torch.Tensor:
            Detached real powers of shape `(nlambda, npsm)`.
    """
    with torch.no_grad():
        power = squared_modulus(self.physical_field()).sum(dim=(-2, -1))
    # (nlambda, 1, npsm, 1) -> (nlambda, npsm)
    return power[:, 0, :, 0]

set_scale(scale)

Change the scale \(s\) while keeping the physical probe unchanged.

Parameters:

Name Type Description Default
scale float

New scale, rounded to a power of two.

required
Source code in PtyLab/Engines/GradientEngine/models.py
def set_scale(self, scale):
    r"""
    Change the scale $s$ while keeping the physical probe unchanged.

    Args:
        scale (float):
            New scale, rounded to a power of two.
    """
    scale = _power_of_two(scale)
    with torch.no_grad():
        self.field.mul_(self.scale / scale)
        self.scale.fill_(scale)

reset_from_array(field)

Copy a physical probe into the existing parameter.

Parameters:

Name Type Description Default
field array_like

Physical probe with the shape of field.

required

Raises:

Type Description
ValueError

If the shape differs from the parameter's.

Source code in PtyLab/Engines/GradientEngine/models.py
def reset_from_array(self, field):
    """
    Copy a physical probe into the existing parameter.

    Args:
        field (array_like):
            Physical probe with the shape of `field`.

    Raises:
        ValueError:
            If the shape differs from the parameter's.
    """
    value = torch.as_tensor(field, dtype=self.field.dtype, device=self.field.device)
    if value.shape != self.field.shape:
        raise ValueError(
            f"Probe shape changed from {tuple(self.field.shape)} to {tuple(value.shape)}."
        )
    with torch.no_grad():
        self.field.copy_(value / self.scale)

OPRProbe

Bases: SharedProbe

One entrance probe per scan frame, for orthogonal probe relaxation (OPR).

Frame \(j\) has its own probe \(P_j = s\,F_j\), so pulse-to-pulse changes of the source (flux, pointing, wavefront) can be fitted. On its own a free probe per frame is far too flexible; OPRProjection keeps the stack in a low-dimensional subspace after each step,

\[ P_j(\mathbf{r}) \approx \sum_{k=1}^{K} c_{jk}\,B_k(\mathbf{r}), \]

as the classic OPR engine does. Every probe mode varies between frames; the modes still add incoherently within a frame.

The parameter keeps the name "probe.field" (selected as "probe"), so parameters, learning rates and phases work unchanged. Create it from a shared probe with from_probe or GradientEngine.relaxProbe.

Parameters:

Name Type Description Default
field array_like

Physical probe stack of shape (frames, nlambda, 1, npsm, 1, Np, Np).

required
scale float

Probe scale \(s\), rounded to a power of two. Defaults to 1.0.

1.0

Examples:

engine.relaxProbe()  # engine.model.probe becomes an OPRProbe
engine.reconstruct()
engine.model.probe.frame_powers()  # (frames, nlambda, npsm)
Source code in PtyLab/Engines/GradientEngine/models.py
class OPRProbe(SharedProbe):
    r"""
    One entrance probe per scan frame, for orthogonal probe relaxation (OPR).

    Frame $j$ has its own probe $P_j = s\,F_j$, so pulse-to-pulse changes of
    the source (flux, pointing, wavefront) can be fitted. On its own a free
    probe per frame is far too flexible; `OPRProjection` keeps the stack in a
    low-dimensional subspace after each step,

    $$
    P_j(\mathbf{r}) \approx \sum_{k=1}^{K} c_{jk}\,B_k(\mathbf{r}),
    $$

    as the classic `OPR` engine does. Every probe mode varies between frames;
    the modes still add incoherently within a frame.

    The parameter keeps the name `"probe.field"` (selected as `"probe"`), so
    `parameters`, learning rates and phases work unchanged. Create it from a shared probe with
    `from_probe` or `GradientEngine.relaxProbe`.

    Args:
        field (array_like):
            Physical probe stack of shape
            `(frames, nlambda, 1, npsm, 1, Np, Np)`.

        scale (float, optional):
            Probe scale $s$, rounded to a power of two. Defaults to 1.0.

    Examples:
        ```python
        engine.relaxProbe()  # engine.model.probe becomes an OPRProbe
        engine.reconstruct()
        engine.model.probe.frame_powers()  # (frames, nlambda, npsm)
        ```
    """

    @classmethod
    def from_probe(cls, probe, frames):
        """
        Start every frame from the same shared probe.

        Args:
            probe (SharedProbe):
                Shared probe; its scale is kept.

            frames (int):
                Number of scan frames.

        Returns:
            OPRProbe:
                Stack on the device of `probe`.
        """
        field = probe.physical_field().detach()
        stack = cls(field.expand(frames, *field.shape).clone(), probe.scale.item())
        return stack.to(field.device)

    def forward(self, indices):
        """
        Return the physical probes of the frames of a batch.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Probes of shape `(batch, nlambda, 1, npsm, 1, Np, Np)`.
        """
        # Scale only the gathered frames, not the whole stack.
        return self.scale * self.field[indices]

    def frame_powers(self):
        r"""
        Return the power $\sum_{\mathbf{r}} |P_{jm}(\mathbf{r})|^2$ of every frame and mode.

        Returns:
            torch.Tensor:
                Detached real powers of shape `(frames, nlambda, npsm)`.
        """
        with torch.no_grad():
            power = squared_modulus(self.field).sum(dim=(-2, -1)) * self.scale**2
        # (frames, nlambda, 1, npsm, 1) -> (frames, nlambda, npsm)
        return power[:, :, 0, :, 0]

    def mode_powers(self):
        """
        Return the power of each probe mode, averaged over the frames.

        Returns:
            torch.Tensor:
                Detached real powers of shape `(nlambda, npsm)`.
        """
        return self.frame_powers().mean(dim=0)

    def shared_estimate(self):
        r"""
        Return one six-axis probe that best represents the stack.

        For each wavelength and mode, with the frames as rows of $A$
        ($A_{j\mathbf{r}} = P_j(\mathbf{r})$) and $v_1$ the leading
        eigenvector of $G = AA^\dagger$,

        $$
        \bar P = \frac{v_1^\dagger A}{\sqrt{J}},
        $$

        the dominant OPR component, with $\sum|\bar P|^2 = \lambda_1 / J$
        (the mean frame power when one component dominates). If all frames
        are equal, $\bar P$ is that probe. It is exported as
        `reconstruction.probe` for monitoring and as a start for a shared run.

        Returns:
            torch.Tensor:
                Detached probe of shape `(nlambda, 1, npsm, 1, Np, Np)`.
        """
        with torch.no_grad():
            field = self.field
            estimate = torch.empty_like(field[0])
            for wavelength in range(field.shape[1]):
                for mode in range(field.shape[3]):
                    rows = field[:, wavelength, 0, mode, 0].flatten(-2)  # (J, N)
                    _, V = frame_modes(rows)
                    v = V[:, 0]
                    # Eigenvector phase is free; pick it so the frames add in phase.
                    phase = torch.sgn(v.sum())
                    v = v * (phase.conj() if phase != 0 else 1)
                    estimate[wavelength, 0, mode, 0] = (v.conj() @ rows).view(
                        field.shape[-2:]
                    ) / math.sqrt(len(rows))
            return self.scale * estimate

    def reset_from_array(self, field):
        """
        Copy a physical probe stack, or one shared probe for every frame.

        Args:
            field (array_like):
                Stack with the shape of `field`, or a six-axis probe
                `(nlambda, 1, npsm, 1, Np, Np)` copied to all frames.
        """
        value = torch.as_tensor(field, dtype=self.field.dtype, device=self.field.device)
        if value.shape == self.field.shape[1:]:
            value = value.expand_as(self.field)
        super().reset_from_array(value)

from_probe(probe, frames) classmethod

Start every frame from the same shared probe.

Parameters:

Name Type Description Default
probe SharedProbe

Shared probe; its scale is kept.

required
frames int

Number of scan frames.

required

Returns:

Type Description
OPRProbe

Stack on the device of probe.

Source code in PtyLab/Engines/GradientEngine/models.py
@classmethod
def from_probe(cls, probe, frames):
    """
    Start every frame from the same shared probe.

    Args:
        probe (SharedProbe):
            Shared probe; its scale is kept.

        frames (int):
            Number of scan frames.

    Returns:
        OPRProbe:
            Stack on the device of `probe`.
    """
    field = probe.physical_field().detach()
    stack = cls(field.expand(frames, *field.shape).clone(), probe.scale.item())
    return stack.to(field.device)

forward(indices)

Return the physical probes of the frames of a batch.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Probes of shape (batch, nlambda, 1, npsm, 1, Np, Np).

Source code in PtyLab/Engines/GradientEngine/models.py
def forward(self, indices):
    """
    Return the physical probes of the frames of a batch.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Probes of shape `(batch, nlambda, 1, npsm, 1, Np, Np)`.
    """
    # Scale only the gathered frames, not the whole stack.
    return self.scale * self.field[indices]

frame_powers()

Return the power \(\sum_{\mathbf{r}} |P_{jm}(\mathbf{r})|^2\) of every frame and mode.

Returns:

Type Description
Tensor

Detached real powers of shape (frames, nlambda, npsm).

Source code in PtyLab/Engines/GradientEngine/models.py
def frame_powers(self):
    r"""
    Return the power $\sum_{\mathbf{r}} |P_{jm}(\mathbf{r})|^2$ of every frame and mode.

    Returns:
        torch.Tensor:
            Detached real powers of shape `(frames, nlambda, npsm)`.
    """
    with torch.no_grad():
        power = squared_modulus(self.field).sum(dim=(-2, -1)) * self.scale**2
    # (frames, nlambda, 1, npsm, 1) -> (frames, nlambda, npsm)
    return power[:, :, 0, :, 0]

mode_powers()

Return the power of each probe mode, averaged over the frames.

Returns:

Type Description
Tensor

Detached real powers of shape (nlambda, npsm).

Source code in PtyLab/Engines/GradientEngine/models.py
def mode_powers(self):
    """
    Return the power of each probe mode, averaged over the frames.

    Returns:
        torch.Tensor:
            Detached real powers of shape `(nlambda, npsm)`.
    """
    return self.frame_powers().mean(dim=0)

shared_estimate()

Return one six-axis probe that best represents the stack.

For each wavelength and mode, with the frames as rows of \(A\) (\(A_{j\mathbf{r}} = P_j(\mathbf{r})\)) and \(v_1\) the leading eigenvector of \(G = AA^\dagger\),

\[ \bar P = \frac{v_1^\dagger A}{\sqrt{J}}, \]

the dominant OPR component, with \(\sum|\bar P|^2 = \lambda_1 / J\) (the mean frame power when one component dominates). If all frames are equal, \(\bar P\) is that probe. It is exported as reconstruction.probe for monitoring and as a start for a shared run.

Returns:

Type Description
Tensor

Detached probe of shape (nlambda, 1, npsm, 1, Np, Np).

Source code in PtyLab/Engines/GradientEngine/models.py
def shared_estimate(self):
    r"""
    Return one six-axis probe that best represents the stack.

    For each wavelength and mode, with the frames as rows of $A$
    ($A_{j\mathbf{r}} = P_j(\mathbf{r})$) and $v_1$ the leading
    eigenvector of $G = AA^\dagger$,

    $$
    \bar P = \frac{v_1^\dagger A}{\sqrt{J}},
    $$

    the dominant OPR component, with $\sum|\bar P|^2 = \lambda_1 / J$
    (the mean frame power when one component dominates). If all frames
    are equal, $\bar P$ is that probe. It is exported as
    `reconstruction.probe` for monitoring and as a start for a shared run.

    Returns:
        torch.Tensor:
            Detached probe of shape `(nlambda, 1, npsm, 1, Np, Np)`.
    """
    with torch.no_grad():
        field = self.field
        estimate = torch.empty_like(field[0])
        for wavelength in range(field.shape[1]):
            for mode in range(field.shape[3]):
                rows = field[:, wavelength, 0, mode, 0].flatten(-2)  # (J, N)
                _, V = frame_modes(rows)
                v = V[:, 0]
                # Eigenvector phase is free; pick it so the frames add in phase.
                phase = torch.sgn(v.sum())
                v = v * (phase.conj() if phase != 0 else 1)
                estimate[wavelength, 0, mode, 0] = (v.conj() @ rows).view(
                    field.shape[-2:]
                ) / math.sqrt(len(rows))
        return self.scale * estimate

reset_from_array(field)

Copy a physical probe stack, or one shared probe for every frame.

Parameters:

Name Type Description Default
field array_like

Stack with the shape of field, or a six-axis probe (nlambda, 1, npsm, 1, Np, Np) copied to all frames.

required
Source code in PtyLab/Engines/GradientEngine/models.py
def reset_from_array(self, field):
    """
    Copy a physical probe stack, or one shared probe for every frame.

    Args:
        field (array_like):
            Stack with the shape of `field`, or a six-axis probe
            `(nlambda, 1, npsm, 1, Np, Np)` copied to all frames.
    """
    value = torch.as_tensor(field, dtype=self.field.dtype, device=self.field.device)
    if value.shape == self.field.shape[1:]:
        value = value.expand_as(self.field)
    super().reset_from_array(value)

PtychographyModel

Bases: Module

Single-slice CPM forward model with six-axis object and probe storage.

For scan frame \(j\) with patch origin \(\mathbf{x}_j\), the predicted intensity is

\[ I_j = \sum_{a=1}^{n_{\mathrm{osm}}} \sum_{m=1}^{n_{\mathrm{psm}}} \left|\mathcal{D}\left\lbrace O_a(\mathbf{r} + \mathbf{x}_j)\,P_m(\mathbf{r})\right\rbrace \right|^2 + b, \]

where \(O_a\) are the object states, \(P_m\) the probe states, \(\mathcal{D}\) the propagation and \(b\) the optional detector background. Every pair \((a, m)\) is a mutually incoherent channel: intensities add, fields do not.

The object has shape (nlambda, nosm, 1, nslice, No, No) and the shared probe has shape (nlambda, 1, npsm, 1, Np, Np). Their singleton axes broadcast, so the detector fields hold all pairs, with shape (batch, nlambda, nosm, npsm, nslice, Np, Np). Any number of object and probe states is supported; wavelengths and slices are still restricted to one.

background is an optional incoherent detector background added to every predicted frame, a scalar or one (Np, Np) image in centered pixel order, like forward's output. It is an ordinary parameter, so it stays fixed unless selected for estimation.

Parameters:

Name Type Description Default
object_field array_like

Complex six-axis object.

required
probe SharedProbe

Probe module.

required
positions array_like

Integer patch origins of shape (frames, 2) in object pixels.

required

Examples:

import torch

indices = torch.arange(4, device=engine.device)
engine.model(indices)  # (4, Np, Np) predicted intensity, centered order

# Custom physics: subclass the model and return it from createModel().
from PtyLab.Engines.GradientEngine import PtychographyModel, SharedProbe


class MyModel(PtychographyModel):
    def forward(self, indices):
        return 0.9 * super().forward(indices)  # detector efficiency


class MyEngine(GradientEngine):
    def createModel(self):
        r = self.reconstruction
        return MyModel(r.object, SharedProbe(r.probe), r.positions)
Source code in PtyLab/Engines/GradientEngine/models.py
class PtychographyModel(torch.nn.Module):
    r"""
    Single-slice CPM forward model with six-axis object and probe storage.

    For scan frame $j$ with patch origin $\mathbf{x}_j$, the predicted
    intensity is

    $$
    I_j = \sum_{a=1}^{n_{\mathrm{osm}}} \sum_{m=1}^{n_{\mathrm{psm}}} \left|\mathcal{D}\left\lbrace O_a(\mathbf{r} + \mathbf{x}_j)\,P_m(\mathbf{r})\right\rbrace \right|^2 + b,
    $$

    where $O_a$ are the object states, $P_m$ the probe states, $\mathcal{D}$
    the propagation and $b$ the optional detector background. Every pair
    $(a, m)$ is a mutually incoherent channel: intensities add, fields do not.

    The object has shape `(nlambda, nosm, 1, nslice, No, No)` and the shared
    probe has shape `(nlambda, 1, npsm, 1, Np, Np)`. Their singleton axes
    broadcast, so the detector fields hold all pairs, with shape
    `(batch, nlambda, nosm, npsm, nslice, Np, Np)`. Any number of object and
    probe states is supported; wavelengths and slices are still restricted
    to one.

    `background` is an optional incoherent detector background added to every
    predicted frame, a scalar or one `(Np, Np)` image in centered pixel
    order, like `forward`'s output. It is an ordinary parameter, so it stays fixed unless
    selected for estimation.

    Args:
        object_field (array_like):
            Complex six-axis object.

        probe (SharedProbe):
            Probe module.

        positions (array_like):
            Integer patch origins of shape `(frames, 2)` in object pixels.

    Examples:
        ```python
        import torch

        indices = torch.arange(4, device=engine.device)
        engine.model(indices)  # (4, Np, Np) predicted intensity, centered order

        # Custom physics: subclass the model and return it from createModel().
        from PtyLab.Engines.GradientEngine import PtychographyModel, SharedProbe


        class MyModel(PtychographyModel):
            def forward(self, indices):
                return 0.9 * super().forward(indices)  # detector efficiency


        class MyEngine(GradientEngine):
            def createModel(self):
                r = self.reconstruction
                return MyModel(r.object, SharedProbe(r.probe), r.positions)
        ```
    """

    def __init__(self, object_field, probe, positions):
        super().__init__()
        self.object = torch.nn.Parameter(
            torch.as_tensor(object_field, dtype=torch.complex64)
        )
        self.probe = probe
        # Flat object offsets of one probe-sized patch, fixed by the two grids.
        height, width = probe.field.shape[-2:]
        offsets = (
            torch.arange(height)[:, None] * self.object.shape[-1]
            + torch.arange(width)[None, :]
        )
        self.register_buffer("patch_offsets", offsets, persistent=False)
        self.register_buffer("positions", None, persistent=False)
        self.register_buffer("patch_origins", None, persistent=False)
        self.register_parameter("background", None)
        self.set_positions(positions)
        self.propagation = None

    @staticmethod
    def validate(reconstruction):
        """
        Validate the supported counts and the canonical six-axis array shapes.

        Args:
            reconstruction (Reconstruction):
                Reconstruction state to check.

        Raises:
            NotImplementedError:
                If there is more than one wavelength or slice.

            ValueError:
                If the object or probe is not a six-axis array.
        """
        recon = reconstruction
        if recon.nlambda != 1 or recon.nslice != 1:
            raise NotImplementedError(
                "PtychographyModel currently requires one wavelength and one slice."
            )
        object_shape = (1, recon.nosm, 1, 1, recon.No, recon.No)
        probe_shape = (1, 1, recon.npsm, 1, recon.Np, recon.Np)
        if recon.object.shape != object_shape or recon.probe.shape != probe_shape:
            raise ValueError(
                "Initialize six-axis object and probe arrays with initializeObjectProbe()."
            )

    def set_positions(self, positions):
        """
        Replace the integer patch origins without changing model parameters.

        Args:
            positions (array_like):
                Patch origins of shape `(frames, 2)` in object pixels.
        """
        self.positions = torch.as_tensor(
            positions, dtype=torch.long, device=self.object.device
        )
        # Flat index of each patch's top-left pixel, cached for every gather.
        self.patch_origins = (
            self.positions[:, 0] * self.object.shape[-1] + self.positions[:, 1]
        )

    def set_propagation(self, propagation):
        """
        Set the callable that maps exit waves to detector fields.

        Args:
            propagation (callable):
                Maps exit waves to complex detector fields in centered pixel
                order, like `KernelPropagator`.
        """
        self.propagation = propagation

    def set_background(self, background):
        """
        Replace the detector background, or remove it.

        Args:
            background (float or array_like or None):
                Real scalar or one-frame image in centered pixel order,
                copied to the object's device as float32. None removes it.
        """
        if background is None:
            self.background = None
            return
        self.background = torch.nn.Parameter(
            torch.as_tensor(background, dtype=torch.float32, device=self.object.device)
            .detach()
            .clone()
        )

    def reset_from_reconstruction(self, reconstruction):
        """
        Import object, probe and positions while preserving parameter identity.

        For an `OPRProbe`, a `reconstruction.probe_stack` in the classic `OPR`
        layout `(nlambda, 1, npsm, 1, Np, Np, frames)` is imported if present;
        otherwise `reconstruction.probe` is copied to every frame.

        Args:
            reconstruction (Reconstruction):
                Source of the object, probe and positions.

        Raises:
            ValueError:
                If the object or probe shape changed.
        """
        obj = torch.as_tensor(
            reconstruction.object, dtype=self.object.dtype, device=self.object.device
        )
        if obj.shape != self.object.shape:
            raise ValueError(
                f"Object shape changed from {tuple(self.object.shape)} to {tuple(obj.shape)}."
            )
        with torch.no_grad():
            self.object.copy_(obj)
        stack = getattr(reconstruction, "probe_stack", None)
        if isinstance(self.probe, OPRProbe) and stack is not None:
            # PtyLab layout (nlambda, 1, npsm, 1, Np, Np, frames) -> frames first.
            stack = torch.as_tensor(np.asarray(stack)).movedim(-1, 0)
            self.probe.reset_from_array(stack)
        else:
            self.probe.reset_from_array(reconstruction.probe)
        self.set_positions(reconstruction.positions)

    def patch_indices(self, indices):
        """
        Return the flat object indices of the patches of a batch.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Flat indices of shape `(batch, Np, Np)`.
        """
        return self.patch_origins[indices, None, None] + self.patch_offsets

    def object_patches(self, indices):
        """
        Gather the object patches of a batch.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Patches with the batch axis followed by the six physical axes.
        """
        flat = self.patch_indices(indices)
        patches = self.object.flatten(-2).index_select(-1, flat.reshape(-1))
        return patches.unflatten(-1, flat.shape).movedim(-3, 0)

    def illumination(self, indices):
        r"""
        Return the probe power that the frames of a batch put on the object.

        $$
        D_O(\mathbf{x}) = \sum_{j} \sum_m |P_m(\mathbf{x} - \mathbf{x}_j)|^2,
        $$

        summed over the frames $j$ in `indices` and the probe states $m$.
        Maps of disjoint batches add up to the map of their union.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Detached real map of shape `(No, No)`.
        """
        with torch.no_grad():
            # sum_m |P_m|^2: (1 or batch, Np, Np), broadcast to (batch, Np, Np).
            probe = _one_frame_if_shared(self.probe(indices))
            probe_intensity = squared_modulus(probe).sum(dim=(1, 2, 3, 4))
            probe_intensity = probe_intensity.expand(len(indices), -1, -1)
            illumination = torch.zeros(
                self.object.shape[-2:].numel(),
                dtype=probe_intensity.dtype,
                device=self.object.device,
            )
            illumination.index_add_(
                0, self.patch_indices(indices).reshape(-1), probe_intensity.reshape(-1)
            )
        return illumination.view(self.object.shape[-2:])

    def gradient_preconditioners(self, indices):
        r"""
        Return diagonal curvature maps for PIE-style preconditioning.

        $$
        D_O(\mathbf{x}) = \sum_{j} \sum_m |P_m(\mathbf{x} - \mathbf{x}_j)|^2,\qquad D_F(\mathbf{r}) = s^2 \sum_{j} \sum_a |O_a(\mathbf{r} + \mathbf{x}_j)|^2,
        $$

        summed over the frames $j$ in `indices` and over the probe states $m$
        and object states $a$: every object state meets every probe state, so
        each sees the illumination of all the others. One map is shared by all
        states of a tensor. These are the Gauss-Newton
        diagonals for a loss with constant curvature in the detector field, as
        used by PIE-type updates. Both are for the stored parameters: the probe
        map carries the $s^2$ of a scale-free probe, so a preconditioned step
        moves the physical probe independently of $s$. The maps of disjoint
        batches add up to the map of their union, so the engine builds them
        batch by batch.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            dict:
                `"object"`: $D_O$ with the object's shape, and
                `"probe.field"`: $D_F$.
        """
        illumination = self.illumination(indices)
        with torch.no_grad():
            # (batch, nlambda, nosm, 1, nslice, Np, Np): sum object states
            # -> (batch, nlambda, 1, 1, nslice, Np, Np), broadcast over probe states.
            coverage = squared_modulus(self.object_patches(indices))
            coverage = coverage.sum(dim=2, keepdim=True)
            coverage = coverage * getattr(self.probe, "scale", 1.0) ** 2
            field = self.probe.field
            if isinstance(self.probe, OPRProbe):
                # One probe per frame: frame j's map is its own patch,
                # D_F,j = s^2 sum_a |O_a(r + x_j)|^2; frames not in the batch get 0.
                probe_map = torch.zeros(
                    field.shape, dtype=coverage.dtype, device=field.device
                )
                probe_map[indices] = coverage.expand(len(indices), *field.shape[1:])
            else:
                # Shared probe: the maps of all frames add up.
                probe_map = coverage.sum(dim=0).expand(field.shape)
        return {
            "object": illumination.expand(self.object.shape),
            "probe.field": probe_map,
        }

    def detector_fields(self, indices):
        """
        Return the complex detector fields of a batch.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Detector fields with all state axes retained.

        Raises:
            RuntimeError:
                If no propagation is set.
        """
        if self.propagation is None:
            raise RuntimeError("Set model propagation before forwarding data.")
        patches = self.object_patches(indices)
        entrance_probe = self.probe(indices)
        return self.propagation(patches * entrance_probe)

    def forward(self, indices):
        r"""
        Return the predicted detector intensity of a batch, plus any background.

        Args:
            indices (torch.Tensor):
                Frame indices of the batch.

        Returns:
            torch.Tensor:
                Intensity of shape `(batch, Np, Np)`, in centered pixel order.

        Notes:
            For a propagation built on centered FFTs (`KernelPropagator` with
            `centered`), the shifts are moved to smaller tensors. With
            $S$ = `fftshift` and $K$ = `KernelPropagator.unshifted`,

            $$
            I_j = S\Big(\sum_{a,m} \big|K\lbrace S^{-1}O_a(\mathbf{r} + \mathbf{x}_j)\; S^{-1}P_m(\mathbf{r})\rbrace\big|^2\Big),
            $$

            using $S^{-1}(OP) = S^{-1}O\,S^{-1}P$ and $|Su|^2 = S|u|^2$. The
            values are the same, but fewer and smaller tensors are shifted,
            which is faster with several probe modes. `detector_fields` keeps
            the centered fields; to change the physics, override `forward`
            and call `super().forward`.
        """
        if getattr(self.propagation, "centered", False):
            # S^{-1}(O P) = S^{-1}O S^{-1}P; a shared probe is shifted once, not per frame.
            patches = torch.fft.ifftshift(self.object_patches(indices), dim=(-2, -1))
            probe = _one_frame_if_shared(self.probe(indices))
            probe = torch.fft.ifftshift(probe, dim=(-2, -1))
            fields = self.propagation.unshifted(patches * probe)
            # |S u|^2 = S |u|^2: shift the mode-summed real intensity, (batch, Np, Np).
            intensity = squared_modulus(fields).sum(dim=(1, 2, 3, 4))
            intensity = torch.fft.fftshift(intensity, dim=(-2, -1))
        else:
            fields = self.detector_fields(indices)
            intensity = squared_modulus(fields).sum(dim=(1, 2, 3, 4))
        if self.background is not None:
            intensity = intensity + self.background
        return intensity

validate(reconstruction) staticmethod

Validate the supported counts and the canonical six-axis array shapes.

Parameters:

Name Type Description Default
reconstruction Reconstruction

Reconstruction state to check.

required

Raises:

Type Description
NotImplementedError

If there is more than one wavelength or slice.

ValueError

If the object or probe is not a six-axis array.

Source code in PtyLab/Engines/GradientEngine/models.py
@staticmethod
def validate(reconstruction):
    """
    Validate the supported counts and the canonical six-axis array shapes.

    Args:
        reconstruction (Reconstruction):
            Reconstruction state to check.

    Raises:
        NotImplementedError:
            If there is more than one wavelength or slice.

        ValueError:
            If the object or probe is not a six-axis array.
    """
    recon = reconstruction
    if recon.nlambda != 1 or recon.nslice != 1:
        raise NotImplementedError(
            "PtychographyModel currently requires one wavelength and one slice."
        )
    object_shape = (1, recon.nosm, 1, 1, recon.No, recon.No)
    probe_shape = (1, 1, recon.npsm, 1, recon.Np, recon.Np)
    if recon.object.shape != object_shape or recon.probe.shape != probe_shape:
        raise ValueError(
            "Initialize six-axis object and probe arrays with initializeObjectProbe()."
        )

set_positions(positions)

Replace the integer patch origins without changing model parameters.

Parameters:

Name Type Description Default
positions array_like

Patch origins of shape (frames, 2) in object pixels.

required
Source code in PtyLab/Engines/GradientEngine/models.py
def set_positions(self, positions):
    """
    Replace the integer patch origins without changing model parameters.

    Args:
        positions (array_like):
            Patch origins of shape `(frames, 2)` in object pixels.
    """
    self.positions = torch.as_tensor(
        positions, dtype=torch.long, device=self.object.device
    )
    # Flat index of each patch's top-left pixel, cached for every gather.
    self.patch_origins = (
        self.positions[:, 0] * self.object.shape[-1] + self.positions[:, 1]
    )

set_propagation(propagation)

Set the callable that maps exit waves to detector fields.

Parameters:

Name Type Description Default
propagation callable

Maps exit waves to complex detector fields in centered pixel order, like KernelPropagator.

required
Source code in PtyLab/Engines/GradientEngine/models.py
def set_propagation(self, propagation):
    """
    Set the callable that maps exit waves to detector fields.

    Args:
        propagation (callable):
            Maps exit waves to complex detector fields in centered pixel
            order, like `KernelPropagator`.
    """
    self.propagation = propagation

set_background(background)

Replace the detector background, or remove it.

Parameters:

Name Type Description Default
background float or array_like or None

Real scalar or one-frame image in centered pixel order, copied to the object's device as float32. None removes it.

required
Source code in PtyLab/Engines/GradientEngine/models.py
def set_background(self, background):
    """
    Replace the detector background, or remove it.

    Args:
        background (float or array_like or None):
            Real scalar or one-frame image in centered pixel order,
            copied to the object's device as float32. None removes it.
    """
    if background is None:
        self.background = None
        return
    self.background = torch.nn.Parameter(
        torch.as_tensor(background, dtype=torch.float32, device=self.object.device)
        .detach()
        .clone()
    )

reset_from_reconstruction(reconstruction)

Import object, probe and positions while preserving parameter identity.

For an OPRProbe, a reconstruction.probe_stack in the classic OPR layout (nlambda, 1, npsm, 1, Np, Np, frames) is imported if present; otherwise reconstruction.probe is copied to every frame.

Parameters:

Name Type Description Default
reconstruction Reconstruction

Source of the object, probe and positions.

required

Raises:

Type Description
ValueError

If the object or probe shape changed.

Source code in PtyLab/Engines/GradientEngine/models.py
def reset_from_reconstruction(self, reconstruction):
    """
    Import object, probe and positions while preserving parameter identity.

    For an `OPRProbe`, a `reconstruction.probe_stack` in the classic `OPR`
    layout `(nlambda, 1, npsm, 1, Np, Np, frames)` is imported if present;
    otherwise `reconstruction.probe` is copied to every frame.

    Args:
        reconstruction (Reconstruction):
            Source of the object, probe and positions.

    Raises:
        ValueError:
            If the object or probe shape changed.
    """
    obj = torch.as_tensor(
        reconstruction.object, dtype=self.object.dtype, device=self.object.device
    )
    if obj.shape != self.object.shape:
        raise ValueError(
            f"Object shape changed from {tuple(self.object.shape)} to {tuple(obj.shape)}."
        )
    with torch.no_grad():
        self.object.copy_(obj)
    stack = getattr(reconstruction, "probe_stack", None)
    if isinstance(self.probe, OPRProbe) and stack is not None:
        # PtyLab layout (nlambda, 1, npsm, 1, Np, Np, frames) -> frames first.
        stack = torch.as_tensor(np.asarray(stack)).movedim(-1, 0)
        self.probe.reset_from_array(stack)
    else:
        self.probe.reset_from_array(reconstruction.probe)
    self.set_positions(reconstruction.positions)

patch_indices(indices)

Return the flat object indices of the patches of a batch.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Flat indices of shape (batch, Np, Np).

Source code in PtyLab/Engines/GradientEngine/models.py
def patch_indices(self, indices):
    """
    Return the flat object indices of the patches of a batch.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Flat indices of shape `(batch, Np, Np)`.
    """
    return self.patch_origins[indices, None, None] + self.patch_offsets

object_patches(indices)

Gather the object patches of a batch.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Patches with the batch axis followed by the six physical axes.

Source code in PtyLab/Engines/GradientEngine/models.py
def object_patches(self, indices):
    """
    Gather the object patches of a batch.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Patches with the batch axis followed by the six physical axes.
    """
    flat = self.patch_indices(indices)
    patches = self.object.flatten(-2).index_select(-1, flat.reshape(-1))
    return patches.unflatten(-1, flat.shape).movedim(-3, 0)

illumination(indices)

Return the probe power that the frames of a batch put on the object.

\[ D_O(\mathbf{x}) = \sum_{j} \sum_m |P_m(\mathbf{x} - \mathbf{x}_j)|^2, \]

summed over the frames \(j\) in indices and the probe states \(m\). Maps of disjoint batches add up to the map of their union.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Detached real map of shape (No, No).

Source code in PtyLab/Engines/GradientEngine/models.py
def illumination(self, indices):
    r"""
    Return the probe power that the frames of a batch put on the object.

    $$
    D_O(\mathbf{x}) = \sum_{j} \sum_m |P_m(\mathbf{x} - \mathbf{x}_j)|^2,
    $$

    summed over the frames $j$ in `indices` and the probe states $m$.
    Maps of disjoint batches add up to the map of their union.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Detached real map of shape `(No, No)`.
    """
    with torch.no_grad():
        # sum_m |P_m|^2: (1 or batch, Np, Np), broadcast to (batch, Np, Np).
        probe = _one_frame_if_shared(self.probe(indices))
        probe_intensity = squared_modulus(probe).sum(dim=(1, 2, 3, 4))
        probe_intensity = probe_intensity.expand(len(indices), -1, -1)
        illumination = torch.zeros(
            self.object.shape[-2:].numel(),
            dtype=probe_intensity.dtype,
            device=self.object.device,
        )
        illumination.index_add_(
            0, self.patch_indices(indices).reshape(-1), probe_intensity.reshape(-1)
        )
    return illumination.view(self.object.shape[-2:])

gradient_preconditioners(indices)

Return diagonal curvature maps for PIE-style preconditioning.

\[ D_O(\mathbf{x}) = \sum_{j} \sum_m |P_m(\mathbf{x} - \mathbf{x}_j)|^2,\qquad D_F(\mathbf{r}) = s^2 \sum_{j} \sum_a |O_a(\mathbf{r} + \mathbf{x}_j)|^2, \]

summed over the frames \(j\) in indices and over the probe states \(m\) and object states \(a\): every object state meets every probe state, so each sees the illumination of all the others. One map is shared by all states of a tensor. These are the Gauss-Newton diagonals for a loss with constant curvature in the detector field, as used by PIE-type updates. Both are for the stored parameters: the probe map carries the \(s^2\) of a scale-free probe, so a preconditioned step moves the physical probe independently of \(s\). The maps of disjoint batches add up to the map of their union, so the engine builds them batch by batch.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
dict

"object": \(D_O\) with the object's shape, and "probe.field": \(D_F\).

Source code in PtyLab/Engines/GradientEngine/models.py
def gradient_preconditioners(self, indices):
    r"""
    Return diagonal curvature maps for PIE-style preconditioning.

    $$
    D_O(\mathbf{x}) = \sum_{j} \sum_m |P_m(\mathbf{x} - \mathbf{x}_j)|^2,\qquad D_F(\mathbf{r}) = s^2 \sum_{j} \sum_a |O_a(\mathbf{r} + \mathbf{x}_j)|^2,
    $$

    summed over the frames $j$ in `indices` and over the probe states $m$
    and object states $a$: every object state meets every probe state, so
    each sees the illumination of all the others. One map is shared by all
    states of a tensor. These are the Gauss-Newton
    diagonals for a loss with constant curvature in the detector field, as
    used by PIE-type updates. Both are for the stored parameters: the probe
    map carries the $s^2$ of a scale-free probe, so a preconditioned step
    moves the physical probe independently of $s$. The maps of disjoint
    batches add up to the map of their union, so the engine builds them
    batch by batch.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        dict:
            `"object"`: $D_O$ with the object's shape, and
            `"probe.field"`: $D_F$.
    """
    illumination = self.illumination(indices)
    with torch.no_grad():
        # (batch, nlambda, nosm, 1, nslice, Np, Np): sum object states
        # -> (batch, nlambda, 1, 1, nslice, Np, Np), broadcast over probe states.
        coverage = squared_modulus(self.object_patches(indices))
        coverage = coverage.sum(dim=2, keepdim=True)
        coverage = coverage * getattr(self.probe, "scale", 1.0) ** 2
        field = self.probe.field
        if isinstance(self.probe, OPRProbe):
            # One probe per frame: frame j's map is its own patch,
            # D_F,j = s^2 sum_a |O_a(r + x_j)|^2; frames not in the batch get 0.
            probe_map = torch.zeros(
                field.shape, dtype=coverage.dtype, device=field.device
            )
            probe_map[indices] = coverage.expand(len(indices), *field.shape[1:])
        else:
            # Shared probe: the maps of all frames add up.
            probe_map = coverage.sum(dim=0).expand(field.shape)
    return {
        "object": illumination.expand(self.object.shape),
        "probe.field": probe_map,
    }

detector_fields(indices)

Return the complex detector fields of a batch.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Detector fields with all state axes retained.

Raises:

Type Description
RuntimeError

If no propagation is set.

Source code in PtyLab/Engines/GradientEngine/models.py
def detector_fields(self, indices):
    """
    Return the complex detector fields of a batch.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Detector fields with all state axes retained.

    Raises:
        RuntimeError:
            If no propagation is set.
    """
    if self.propagation is None:
        raise RuntimeError("Set model propagation before forwarding data.")
    patches = self.object_patches(indices)
    entrance_probe = self.probe(indices)
    return self.propagation(patches * entrance_probe)

forward(indices)

Return the predicted detector intensity of a batch, plus any background.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the batch.

required

Returns:

Type Description
Tensor

Intensity of shape (batch, Np, Np), in centered pixel order.

Notes

For a propagation built on centered FFTs (KernelPropagator with centered), the shifts are moved to smaller tensors. With \(S\) = fftshift and \(K\) = KernelPropagator.unshifted,

\[ I_j = S\Big(\sum_{a,m} \big|K\lbrace S^{-1}O_a(\mathbf{r} + \mathbf{x}_j)\; S^{-1}P_m(\mathbf{r})\rbrace\big|^2\Big), \]

using \(S^{-1}(OP) = S^{-1}O\,S^{-1}P\) and \(|Su|^2 = S|u|^2\). The values are the same, but fewer and smaller tensors are shifted, which is faster with several probe modes. detector_fields keeps the centered fields; to change the physics, override forward and call super().forward.

Source code in PtyLab/Engines/GradientEngine/models.py
def forward(self, indices):
    r"""
    Return the predicted detector intensity of a batch, plus any background.

    Args:
        indices (torch.Tensor):
            Frame indices of the batch.

    Returns:
        torch.Tensor:
            Intensity of shape `(batch, Np, Np)`, in centered pixel order.

    Notes:
        For a propagation built on centered FFTs (`KernelPropagator` with
        `centered`), the shifts are moved to smaller tensors. With
        $S$ = `fftshift` and $K$ = `KernelPropagator.unshifted`,

        $$
        I_j = S\Big(\sum_{a,m} \big|K\lbrace S^{-1}O_a(\mathbf{r} + \mathbf{x}_j)\; S^{-1}P_m(\mathbf{r})\rbrace\big|^2\Big),
        $$

        using $S^{-1}(OP) = S^{-1}O\,S^{-1}P$ and $|Su|^2 = S|u|^2$. The
        values are the same, but fewer and smaller tensors are shifted,
        which is faster with several probe modes. `detector_fields` keeps
        the centered fields; to change the physics, override `forward`
        and call `super().forward`.
    """
    if getattr(self.propagation, "centered", False):
        # S^{-1}(O P) = S^{-1}O S^{-1}P; a shared probe is shifted once, not per frame.
        patches = torch.fft.ifftshift(self.object_patches(indices), dim=(-2, -1))
        probe = _one_frame_if_shared(self.probe(indices))
        probe = torch.fft.ifftshift(probe, dim=(-2, -1))
        fields = self.propagation.unshifted(patches * probe)
        # |S u|^2 = S |u|^2: shift the mode-summed real intensity, (batch, Np, Np).
        intensity = squared_modulus(fields).sum(dim=(1, 2, 3, 4))
        intensity = torch.fft.fftshift(intensity, dim=(-2, -1))
    else:
        fields = self.detector_fields(indices)
        intensity = squared_modulus(fields).sum(dim=(1, 2, 3, 4))
    if self.background is not None:
        intensity = intensity + self.background
    return intensity

frame_modes(rows)

Return the eigenvalues and eigenvectors of the frame Gram matrix.

With the frames as rows of \(A\) (shape (J, N)), \(G = AA^\dagger\) is only \(J \times J\). Its eigenvectors \(V\) give the SVD \(A = V\Sigma U^\dagger\) without forming the large \(U\): \(\lambda_k = \sigma_k^2\), and the best rank-\(K\) approximation is \(V_K V_K^\dagger A\).

Parameters:

Name Type Description Default
rows Tensor

Complex matrix of shape (J, N).

required

Returns:

Type Description
tuple

(eigenvalues, V): real (J,) in descending order and the eigenvectors as the columns of (J, J), in the dtype of rows.

Source code in PtyLab/Engines/GradientEngine/models.py
def frame_modes(rows):
    r"""
    Return the eigenvalues and eigenvectors of the frame Gram matrix.

    With the frames as rows of $A$ (shape `(J, N)`), $G = AA^\dagger$ is only
    $J \times J$. Its eigenvectors $V$ give the SVD $A = V\Sigma U^\dagger$
    without forming the large $U$: $\lambda_k = \sigma_k^2$, and the best
    rank-$K$ approximation is $V_K V_K^\dagger A$.

    Args:
        rows (torch.Tensor):
            Complex matrix of shape `(J, N)`.

    Returns:
        tuple:
            `(eigenvalues, V)`: real `(J,)` in descending order and the
            eigenvectors as the columns of `(J, J)`, in the dtype of `rows`.
    """
    # Gram in the data precision, eigh in double: weak components lie many
    # orders of magnitude below the strongest.
    gram = (rows @ rows.conj().T).to(torch.complex128)
    eigenvalues, V = torch.linalg.eigh(gram)  # ascending
    return eigenvalues.flip(-1), V.flip(-1).to(rows.dtype)

probe_scale(photons_per_frame, frame_pixels)

Return the probe scale for a mean frame power, rounded to a power of two.

\[ s = \sqrt{\frac{N_{\mathrm{frame}}}{N_{\mathrm{pix}}}} \]

is the amplitude of a probe spreading the frame's \(N_{\mathrm{frame}}\) photons evenly over the \(N_{\mathrm{pix}}\) pixels of the probe window. A unitary propagator conserves power, so \(\sum |P|^2\) is about the photons per frame for a transmission near one, and \(|F|^2\) then averages about one over the window.

Parameters:

Name Type Description Default
photons_per_frame float

Mean measured photons per frame \(N_{\mathrm{frame}}\).

required
frame_pixels int

Number of pixels \(N_{\mathrm{pix}}\) in the probe window.

required

Returns:

Type Description
float

Probe scale \(s\), rounded to a power of two.

Raises:

Type Description
ValueError

If the scale is not positive and finite.

Examples:

from PtyLab.Engines.GradientEngine.models import probe_scale

probe_scale(1e6, 128**2)  # sqrt(1e6 / 128**2) = 7.8, rounded to 8.0
Source code in PtyLab/Engines/GradientEngine/models.py
def probe_scale(photons_per_frame, frame_pixels):
    r"""
    Return the probe scale for a mean frame power, rounded to a power of two.

    $$
    s = \sqrt{\frac{N_{\mathrm{frame}}}{N_{\mathrm{pix}}}}
    $$

    is the amplitude of a probe spreading the frame's $N_{\mathrm{frame}}$
    photons evenly over the $N_{\mathrm{pix}}$ pixels of the probe window. A
    unitary propagator conserves power, so $\sum |P|^2$ is about the photons
    per frame for a transmission near one, and $|F|^2$ then averages about one
    over the window.

    Args:
        photons_per_frame (float):
            Mean measured photons per frame $N_{\mathrm{frame}}$.

        frame_pixels (int):
            Number of pixels $N_{\mathrm{pix}}$ in the probe window.

    Returns:
        float:
            Probe scale $s$, rounded to a power of two.

    Raises:
        ValueError:
            If the scale is not positive and finite.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine.models import probe_scale

        probe_scale(1e6, 128**2)  # sqrt(1e6 / 128**2) = 7.8, rounded to 8.0
        ```
    """
    return _power_of_two((float(photons_per_frame) / frame_pixels) ** 0.5)

squared_modulus(field)

Return \(|u|^2\) computed as \(\mathrm{Re}(u)^2 + \mathrm{Im}(u)^2\).

Parameters:

Name Type Description Default
field Tensor

Complex field \(u\).

required

Returns:

Type Description
Tensor

Real squared modulus with the shape of field.

Notes

field.abs().square() takes a square root only to square it again. On the 512/128 CPM fixture this form makes a full-scan CUDA iteration about 30% faster, with the same values and gradients up to rounding.

Source code in PtyLab/Engines/GradientEngine/models.py
def squared_modulus(field):
    r"""
    Return $|u|^2$ computed as $\mathrm{Re}(u)^2 + \mathrm{Im}(u)^2$.

    Args:
        field (torch.Tensor):
            Complex field $u$.

    Returns:
        torch.Tensor:
            Real squared modulus with the shape of `field`.

    Notes:
        `field.abs().square()` takes a square root only to square it again. On
        the 512/128 CPM fixture this form makes a full-scan CUDA iteration
        about 30% faster, with the same values and gradients up to rounding.
    """
    return torch.view_as_real(field).square().sum(dim=-1)

Propagation

Propagation of a Torch field, independent of optimization and monitoring.

KernelPropagator

Propagate exit waves to the detector with fixed geometry.

Construct once per reconstruction, then call with a complex Torch exit wave. All leading field dimensions are preserved, and the kernels follow the conventions of PtyLab.Operators.Operators.

Examples:

import torch
from PtyLab.Engines.GradientEngine.propagation import KernelPropagator

propagate = KernelPropagator(reconstruction, "Fresnel", device="cpu")
N = reconstruction.Np
exit_wave = torch.ones(N, N, dtype=torch.complex64)
propagate(exit_wave)  # detector field, same shape, centered order
Source code in PtyLab/Engines/GradientEngine/propagation.py
class KernelPropagator:
    """
    Propagate exit waves to the detector with fixed geometry.

    Construct once per reconstruction, then call with a complex Torch exit wave.
    All leading field dimensions are preserved, and the kernels follow the
    conventions of `PtyLab.Operators.Operators`.

    Examples:
        ```python
        import torch
        from PtyLab.Engines.GradientEngine.propagation import KernelPropagator

        propagate = KernelPropagator(reconstruction, "Fresnel", device="cpu")
        N = reconstruction.Np
        exit_wave = torch.ones(N, N, dtype=torch.complex64)
        propagate(exit_wave)  # detector field, same shape, centered order
        ```
    """

    @staticmethod
    def fft2c(field):
        r"""
        Apply a centered, unitary 2D FFT over the last two dimensions.

        $$
        \mathcal{F}_c\lbrace u\rbrace = \frac{1}{\sqrt{HW}}\, \mathrm{fftshift}\left(\mathrm{fft2}\left(\mathrm{ifftshift}(u)\right)\right)
        $$

        where $H$ and $W$ are the spatial sizes. Leading batch and mode axes are
        preserved.

        Args:
            field (torch.Tensor):
                Complex field with spatial axes last.

        Returns:
            torch.Tensor:
                Centered spectrum with the shape of `field`.
        """
        field = torch.fft.ifftshift(field, dim=(-2, -1))
        field = torch.fft.fft2(field, norm="ortho")
        return torch.fft.fftshift(field, dim=(-2, -1))

    @staticmethod
    def ifft2c(field):
        r"""
        Invert `fft2c` over the last two dimensions.

        $$
        \mathcal{F}_c^{-1}\lbrace U\rbrace = \sqrt{HW}\, \mathrm{fftshift}\left(\mathrm{ifft2}\left(\mathrm{ifftshift}(U)\right)\right)
        $$

        where $H$ and $W$ are the spatial sizes and $\mathrm{ifft2}$ has its
        default normalization. Leading axes are preserved.

        Args:
            field (torch.Tensor):
                Complex centered spectrum with spatial axes last.

        Returns:
            torch.Tensor:
                Field with the shape of `field`.
        """
        field = torch.fft.ifftshift(field, dim=(-2, -1))
        field = torch.fft.ifft2(field, norm="ortho")
        return torch.fft.fftshift(field, dim=(-2, -1))

    def __init__(self, reconstruction, propagator, device="cpu"):
        """
        Build the fixed geometry kernels once per run.

        No optimizable fields enter NumPy here. Subclasses that learn the
        geometry should instead build their kernels in Torch inside
        `__call__()`, on each forward pass, so those kernels remain part of the
        current autograd graph.

        Args:
            reconstruction (Reconstruction):
                Reconstruction state providing the geometry (`Np`, `dxp`,
                `dxd`, `dxo`, `zo`, `wavelength`, `Lp`).

            propagator (str):
                `"Fraunhofer"`, `"Fresnel"`, `"ASP"` or `"scaledASP"`, in any
                case.

            device (str or torch.device, optional):
                Device of the kernels. Defaults to `"cpu"`.

        Raises:
            ValueError:
                If Fresnel or scaledASP has zero propagation distance, or ASP
                has different object and detector pixel sizes.

            NotImplementedError:
                For any other propagator.
        """
        r = reconstruction
        self.propagator = propagator.lower()
        # Fraunhofer, Fresnel and scaledASP are built on the centered fft2c, so
        # their shifts can move to smaller tensors (see `unshifted`); ASP has none.
        self.centered = self.propagator != "asp"
        self.propagationKernels = self.unshiftedKernels = ()
        if self.propagator == "fraunhofer":
            return
        if self.propagator in ("fresnel", "scaledasp") and r.zo == 0:
            raise ValueError(
                "Fresnel and scaledASP require nonzero propagation distance."
            )
        if self.propagator == "asp" and not np.isclose(r.dxp, r.dxd, rtol=1e-6, atol=0):
            raise ValueError(
                "ASP requires reconstruction.dxp == reconstruction.dxd; use scaledASP for different pixel spacings."
            )

        dummy = np.zeros((r.Np, r.Np), dtype=np.complex64)
        if self.propagator == "fresnel":
            kernels = (make_quad_phase(r.zo, r.wavelength, r.Np, r.dxp, False),)
        elif self.propagator == "asp":
            _, transfer = aspw(dummy, r.zo, r.wavelength, r.Lp)
            # Match propagate_ASP's unshifted FFT implementation, including odd grids.
            kernels = (np.fft.ifftshift(transfer.astype(np.complex64)),)
        elif self.propagator == "scaledasp":
            _, source_phase, transfer = scaledASP(
                dummy, r.zo, r.wavelength, r.dxo, r.dxd
            )
            kernels = (source_phase.astype(np.complex64), transfer.astype(np.complex64))
        else:
            raise NotImplementedError(
                "Provide a custom propagation callable for this propagator."
            )
        self.propagationKernels = tuple(
            torch.tensor(kernel, device=device) for kernel in kernels
        )
        # The same kernels in unshifted FFT order, for `unshifted`. ASP's
        # transfer function is already in that order.
        self.unshiftedKernels = self.propagationKernels
        if self.centered:
            self.unshiftedKernels = tuple(
                torch.fft.ifftshift(kernel, dim=(-2, -1))
                for kernel in self.propagationKernels
            )

    def __call__(self, exit_wave):
        r"""
        Propagate an exit wave $\psi$ to the detector.

        With $\mathcal{F}_c$ the centered and $\mathcal{F}$ the unshifted
        unitary FFT, the detector field is

        - Fraunhofer: $u = \mathcal{F}_c\lbrace \psi\rbrace$,
        - Fresnel: $u = \mathcal{F}_c\lbrace \psi Q\rbrace$, with the quadratic phase $Q$,
        - ASP: $u = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace \psi\rbrace H\rbrace$, with the
          angular-spectrum transfer function $H$,
        - scaledASP:
          $u = \mathcal{F}_c^{-1}\lbrace \mathcal{F}_c\lbrace \psi Q_s\rbrace H_s\rbrace$,
          with the source phase $Q_s$ and scaled transfer function $H_s$.

        Fixed kernels are cast to the field's dtype; gradients flow through
        the field.

        Args:
            exit_wave (torch.Tensor):
                Complex exit wave with spatial axes last, on the kernel device.

        Returns:
            torch.Tensor:
                Complex detector field with the shape of `exit_wave`.
        """
        kernels = [
            kernel.to(dtype=exit_wave.dtype) for kernel in self.propagationKernels
        ]
        if self.propagator == "fraunhofer":
            # u = F_c(psi), with psi the exit wave.
            return self.fft2c(exit_wave)
        if self.propagator == "fresnel":
            # u = F_c(psi * Q), using the prepared quadratic phase Q.
            return self.fft2c(exit_wave * kernels[0])
        if self.propagator == "asp":
            # u = F^{-1}(F(psi) * H), with H the angular-spectrum transfer.
            spectrum = torch.fft.fft2(exit_wave, norm="ortho")
            return torch.fft.ifft2(spectrum * kernels[0], norm="ortho")
        if self.propagator == "scaledasp":
            # u = F_c^{-1}(F_c(psi * Q_source) * H_scaled).
            source_phase, transfer = kernels
            return self.ifft2c(self.fft2c(exit_wave * source_phase) * transfer)
        raise NotImplementedError(f"Unsupported propagator: {self.propagator}")

    def unshifted(self, exit_wave):
        r"""
        Propagate an exit wave given in unshifted FFT order, without the centering shifts.

        With $S$ = `fftshift` and $S^{-1}$ = `ifftshift` over the last two
        axes, this computes $K$ in

        $$
        \mathcal{D}\lbrace\psi\rbrace = S\,K\lbrace S^{-1}\psi\rbrace,
        $$

        where $\mathcal{D}$ is `__call__`. With $\mathcal{F}$ the unshifted
        unitary FFT and $\tilde k = S^{-1}k$ a kernel in unshifted order,

        - Fraunhofer: $K\lbrace x\rbrace = \mathcal{F}\lbrace x\rbrace$,
        - Fresnel: $K\lbrace x\rbrace = \mathcal{F}\lbrace x\tilde Q\rbrace$,
        - ASP: $K\lbrace x\rbrace = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace x\rbrace H\rbrace$,
          a circular convolution, which commutes with the shifts,
        - scaledASP:
          $K\lbrace x\rbrace = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace x\tilde Q_s\rbrace \tilde H_s\rbrace$;
          the inner shifts of $\mathcal{F}_c^{-1}\mathcal{F}_c$ cancel.

        A shift only reorders pixels, so these identities are exact for even
        and odd grids. `PtychographyModel.forward` uses them to shift the
        object patches, the probe and the mode-summed intensity instead of
        every mode's exit wave and detector field.

        Args:
            exit_wave (torch.Tensor):
                Complex exit wave $S^{-1}\psi$ with spatial axes last.

        Returns:
            torch.Tensor:
                Detector field $S^{-1}\mathcal{D}\lbrace\psi\rbrace$ with the shape
                of `exit_wave`.
        """
        kernels = [kernel.to(dtype=exit_wave.dtype) for kernel in self.unshiftedKernels]
        if self.propagator == "fraunhofer":
            return torch.fft.fft2(exit_wave, norm="ortho")
        if self.propagator == "fresnel":
            return torch.fft.fft2(exit_wave * kernels[0], norm="ortho")
        if self.propagator == "asp":
            spectrum = torch.fft.fft2(exit_wave, norm="ortho")
            return torch.fft.ifft2(spectrum * kernels[0], norm="ortho")
        if self.propagator == "scaledasp":
            source_phase, transfer = kernels
            spectrum = torch.fft.fft2(exit_wave * source_phase, norm="ortho")
            return torch.fft.ifft2(spectrum * transfer, norm="ortho")
        raise NotImplementedError(f"Unsupported propagator: {self.propagator}")

fft2c(field) staticmethod

Apply a centered, unitary 2D FFT over the last two dimensions.

\[ \mathcal{F}_c\lbrace u\rbrace = \frac{1}{\sqrt{HW}}\, \mathrm{fftshift}\left(\mathrm{fft2}\left(\mathrm{ifftshift}(u)\right)\right) \]

where \(H\) and \(W\) are the spatial sizes. Leading batch and mode axes are preserved.

Parameters:

Name Type Description Default
field Tensor

Complex field with spatial axes last.

required

Returns:

Type Description
Tensor

Centered spectrum with the shape of field.

Source code in PtyLab/Engines/GradientEngine/propagation.py
@staticmethod
def fft2c(field):
    r"""
    Apply a centered, unitary 2D FFT over the last two dimensions.

    $$
    \mathcal{F}_c\lbrace u\rbrace = \frac{1}{\sqrt{HW}}\, \mathrm{fftshift}\left(\mathrm{fft2}\left(\mathrm{ifftshift}(u)\right)\right)
    $$

    where $H$ and $W$ are the spatial sizes. Leading batch and mode axes are
    preserved.

    Args:
        field (torch.Tensor):
            Complex field with spatial axes last.

    Returns:
        torch.Tensor:
            Centered spectrum with the shape of `field`.
    """
    field = torch.fft.ifftshift(field, dim=(-2, -1))
    field = torch.fft.fft2(field, norm="ortho")
    return torch.fft.fftshift(field, dim=(-2, -1))

ifft2c(field) staticmethod

Invert fft2c over the last two dimensions.

\[ \mathcal{F}_c^{-1}\lbrace U\rbrace = \sqrt{HW}\, \mathrm{fftshift}\left(\mathrm{ifft2}\left(\mathrm{ifftshift}(U)\right)\right) \]

where \(H\) and \(W\) are the spatial sizes and \(\mathrm{ifft2}\) has its default normalization. Leading axes are preserved.

Parameters:

Name Type Description Default
field Tensor

Complex centered spectrum with spatial axes last.

required

Returns:

Type Description
Tensor

Field with the shape of field.

Source code in PtyLab/Engines/GradientEngine/propagation.py
@staticmethod
def ifft2c(field):
    r"""
    Invert `fft2c` over the last two dimensions.

    $$
    \mathcal{F}_c^{-1}\lbrace U\rbrace = \sqrt{HW}\, \mathrm{fftshift}\left(\mathrm{ifft2}\left(\mathrm{ifftshift}(U)\right)\right)
    $$

    where $H$ and $W$ are the spatial sizes and $\mathrm{ifft2}$ has its
    default normalization. Leading axes are preserved.

    Args:
        field (torch.Tensor):
            Complex centered spectrum with spatial axes last.

    Returns:
        torch.Tensor:
            Field with the shape of `field`.
    """
    field = torch.fft.ifftshift(field, dim=(-2, -1))
    field = torch.fft.ifft2(field, norm="ortho")
    return torch.fft.fftshift(field, dim=(-2, -1))

__init__(reconstruction, propagator, device='cpu')

Build the fixed geometry kernels once per run.

No optimizable fields enter NumPy here. Subclasses that learn the geometry should instead build their kernels in Torch inside __call__(), on each forward pass, so those kernels remain part of the current autograd graph.

Parameters:

Name Type Description Default
reconstruction Reconstruction

Reconstruction state providing the geometry (Np, dxp, dxd, dxo, zo, wavelength, Lp).

required
propagator str

"Fraunhofer", "Fresnel", "ASP" or "scaledASP", in any case.

required
device str or device

Device of the kernels. Defaults to "cpu".

'cpu'

Raises:

Type Description
ValueError

If Fresnel or scaledASP has zero propagation distance, or ASP has different object and detector pixel sizes.

NotImplementedError

For any other propagator.

Source code in PtyLab/Engines/GradientEngine/propagation.py
def __init__(self, reconstruction, propagator, device="cpu"):
    """
    Build the fixed geometry kernels once per run.

    No optimizable fields enter NumPy here. Subclasses that learn the
    geometry should instead build their kernels in Torch inside
    `__call__()`, on each forward pass, so those kernels remain part of the
    current autograd graph.

    Args:
        reconstruction (Reconstruction):
            Reconstruction state providing the geometry (`Np`, `dxp`,
            `dxd`, `dxo`, `zo`, `wavelength`, `Lp`).

        propagator (str):
            `"Fraunhofer"`, `"Fresnel"`, `"ASP"` or `"scaledASP"`, in any
            case.

        device (str or torch.device, optional):
            Device of the kernels. Defaults to `"cpu"`.

    Raises:
        ValueError:
            If Fresnel or scaledASP has zero propagation distance, or ASP
            has different object and detector pixel sizes.

        NotImplementedError:
            For any other propagator.
    """
    r = reconstruction
    self.propagator = propagator.lower()
    # Fraunhofer, Fresnel and scaledASP are built on the centered fft2c, so
    # their shifts can move to smaller tensors (see `unshifted`); ASP has none.
    self.centered = self.propagator != "asp"
    self.propagationKernels = self.unshiftedKernels = ()
    if self.propagator == "fraunhofer":
        return
    if self.propagator in ("fresnel", "scaledasp") and r.zo == 0:
        raise ValueError(
            "Fresnel and scaledASP require nonzero propagation distance."
        )
    if self.propagator == "asp" and not np.isclose(r.dxp, r.dxd, rtol=1e-6, atol=0):
        raise ValueError(
            "ASP requires reconstruction.dxp == reconstruction.dxd; use scaledASP for different pixel spacings."
        )

    dummy = np.zeros((r.Np, r.Np), dtype=np.complex64)
    if self.propagator == "fresnel":
        kernels = (make_quad_phase(r.zo, r.wavelength, r.Np, r.dxp, False),)
    elif self.propagator == "asp":
        _, transfer = aspw(dummy, r.zo, r.wavelength, r.Lp)
        # Match propagate_ASP's unshifted FFT implementation, including odd grids.
        kernels = (np.fft.ifftshift(transfer.astype(np.complex64)),)
    elif self.propagator == "scaledasp":
        _, source_phase, transfer = scaledASP(
            dummy, r.zo, r.wavelength, r.dxo, r.dxd
        )
        kernels = (source_phase.astype(np.complex64), transfer.astype(np.complex64))
    else:
        raise NotImplementedError(
            "Provide a custom propagation callable for this propagator."
        )
    self.propagationKernels = tuple(
        torch.tensor(kernel, device=device) for kernel in kernels
    )
    # The same kernels in unshifted FFT order, for `unshifted`. ASP's
    # transfer function is already in that order.
    self.unshiftedKernels = self.propagationKernels
    if self.centered:
        self.unshiftedKernels = tuple(
            torch.fft.ifftshift(kernel, dim=(-2, -1))
            for kernel in self.propagationKernels
        )

__call__(exit_wave)

Propagate an exit wave \(\psi\) to the detector.

With \(\mathcal{F}_c\) the centered and \(\mathcal{F}\) the unshifted unitary FFT, the detector field is

  • Fraunhofer: \(u = \mathcal{F}_c\lbrace \psi\rbrace\),
  • Fresnel: \(u = \mathcal{F}_c\lbrace \psi Q\rbrace\), with the quadratic phase \(Q\),
  • ASP: \(u = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace \psi\rbrace H\rbrace\), with the angular-spectrum transfer function \(H\),
  • scaledASP: \(u = \mathcal{F}_c^{-1}\lbrace \mathcal{F}_c\lbrace \psi Q_s\rbrace H_s\rbrace\), with the source phase \(Q_s\) and scaled transfer function \(H_s\).

Fixed kernels are cast to the field's dtype; gradients flow through the field.

Parameters:

Name Type Description Default
exit_wave Tensor

Complex exit wave with spatial axes last, on the kernel device.

required

Returns:

Type Description
Tensor

Complex detector field with the shape of exit_wave.

Source code in PtyLab/Engines/GradientEngine/propagation.py
def __call__(self, exit_wave):
    r"""
    Propagate an exit wave $\psi$ to the detector.

    With $\mathcal{F}_c$ the centered and $\mathcal{F}$ the unshifted
    unitary FFT, the detector field is

    - Fraunhofer: $u = \mathcal{F}_c\lbrace \psi\rbrace$,
    - Fresnel: $u = \mathcal{F}_c\lbrace \psi Q\rbrace$, with the quadratic phase $Q$,
    - ASP: $u = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace \psi\rbrace H\rbrace$, with the
      angular-spectrum transfer function $H$,
    - scaledASP:
      $u = \mathcal{F}_c^{-1}\lbrace \mathcal{F}_c\lbrace \psi Q_s\rbrace H_s\rbrace$,
      with the source phase $Q_s$ and scaled transfer function $H_s$.

    Fixed kernels are cast to the field's dtype; gradients flow through
    the field.

    Args:
        exit_wave (torch.Tensor):
            Complex exit wave with spatial axes last, on the kernel device.

    Returns:
        torch.Tensor:
            Complex detector field with the shape of `exit_wave`.
    """
    kernels = [
        kernel.to(dtype=exit_wave.dtype) for kernel in self.propagationKernels
    ]
    if self.propagator == "fraunhofer":
        # u = F_c(psi), with psi the exit wave.
        return self.fft2c(exit_wave)
    if self.propagator == "fresnel":
        # u = F_c(psi * Q), using the prepared quadratic phase Q.
        return self.fft2c(exit_wave * kernels[0])
    if self.propagator == "asp":
        # u = F^{-1}(F(psi) * H), with H the angular-spectrum transfer.
        spectrum = torch.fft.fft2(exit_wave, norm="ortho")
        return torch.fft.ifft2(spectrum * kernels[0], norm="ortho")
    if self.propagator == "scaledasp":
        # u = F_c^{-1}(F_c(psi * Q_source) * H_scaled).
        source_phase, transfer = kernels
        return self.ifft2c(self.fft2c(exit_wave * source_phase) * transfer)
    raise NotImplementedError(f"Unsupported propagator: {self.propagator}")

unshifted(exit_wave)

Propagate an exit wave given in unshifted FFT order, without the centering shifts.

With \(S\) = fftshift and \(S^{-1}\) = ifftshift over the last two axes, this computes \(K\) in

\[ \mathcal{D}\lbrace\psi\rbrace = S\,K\lbrace S^{-1}\psi\rbrace, \]

where \(\mathcal{D}\) is __call__. With \(\mathcal{F}\) the unshifted unitary FFT and \(\tilde k = S^{-1}k\) a kernel in unshifted order,

  • Fraunhofer: \(K\lbrace x\rbrace = \mathcal{F}\lbrace x\rbrace\),
  • Fresnel: \(K\lbrace x\rbrace = \mathcal{F}\lbrace x\tilde Q\rbrace\),
  • ASP: \(K\lbrace x\rbrace = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace x\rbrace H\rbrace\), a circular convolution, which commutes with the shifts,
  • scaledASP: \(K\lbrace x\rbrace = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace x\tilde Q_s\rbrace \tilde H_s\rbrace\); the inner shifts of \(\mathcal{F}_c^{-1}\mathcal{F}_c\) cancel.

A shift only reorders pixels, so these identities are exact for even and odd grids. PtychographyModel.forward uses them to shift the object patches, the probe and the mode-summed intensity instead of every mode's exit wave and detector field.

Parameters:

Name Type Description Default
exit_wave Tensor

Complex exit wave \(S^{-1}\psi\) with spatial axes last.

required

Returns:

Type Description
Tensor

Detector field \(S^{-1}\mathcal{D}\lbrace\psi\rbrace\) with the shape of exit_wave.

Source code in PtyLab/Engines/GradientEngine/propagation.py
def unshifted(self, exit_wave):
    r"""
    Propagate an exit wave given in unshifted FFT order, without the centering shifts.

    With $S$ = `fftshift` and $S^{-1}$ = `ifftshift` over the last two
    axes, this computes $K$ in

    $$
    \mathcal{D}\lbrace\psi\rbrace = S\,K\lbrace S^{-1}\psi\rbrace,
    $$

    where $\mathcal{D}$ is `__call__`. With $\mathcal{F}$ the unshifted
    unitary FFT and $\tilde k = S^{-1}k$ a kernel in unshifted order,

    - Fraunhofer: $K\lbrace x\rbrace = \mathcal{F}\lbrace x\rbrace$,
    - Fresnel: $K\lbrace x\rbrace = \mathcal{F}\lbrace x\tilde Q\rbrace$,
    - ASP: $K\lbrace x\rbrace = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace x\rbrace H\rbrace$,
      a circular convolution, which commutes with the shifts,
    - scaledASP:
      $K\lbrace x\rbrace = \mathcal{F}^{-1}\lbrace \mathcal{F}\lbrace x\tilde Q_s\rbrace \tilde H_s\rbrace$;
      the inner shifts of $\mathcal{F}_c^{-1}\mathcal{F}_c$ cancel.

    A shift only reorders pixels, so these identities are exact for even
    and odd grids. `PtychographyModel.forward` uses them to shift the
    object patches, the probe and the mode-summed intensity instead of
    every mode's exit wave and detector field.

    Args:
        exit_wave (torch.Tensor):
            Complex exit wave $S^{-1}\psi$ with spatial axes last.

    Returns:
        torch.Tensor:
            Detector field $S^{-1}\mathcal{D}\lbrace\psi\rbrace$ with the shape
            of `exit_wave`.
    """
    kernels = [kernel.to(dtype=exit_wave.dtype) for kernel in self.unshiftedKernels]
    if self.propagator == "fraunhofer":
        return torch.fft.fft2(exit_wave, norm="ortho")
    if self.propagator == "fresnel":
        return torch.fft.fft2(exit_wave * kernels[0], norm="ortho")
    if self.propagator == "asp":
        spectrum = torch.fft.fft2(exit_wave, norm="ortho")
        return torch.fft.ifft2(spectrum * kernels[0], norm="ortho")
    if self.propagator == "scaledasp":
        source_phase, transfer = kernels
        spectrum = torch.fft.fft2(exit_wave * source_phase, norm="ortho")
        return torch.fft.ifft2(spectrum * transfer, norm="ortho")
    raise NotImplementedError(f"Unsupported propagator: {self.propagator}")

Losses

Losses comparing the predicted intensity \(I\) with the measured intensity \(y\).

Each loss returns a real scalar, summed over all pixels and frames and normalized by the total measured power \(P\) of the scan. Notation:

  • \(\lVert\cdot\rVert\): Euclidean norm over all pixels and frames.
  • \(\sqrt{\cdot}\), \(\log\), products and quotients act per pixel.
  • \(g\): detector gain, the signal one photon produces in detector units (camera counts, ADU). A pixel that receives \(\bar N\) photons on average has the predicted intensity \(I = g\bar N\). For a photon-counting detector, \(g = 1\) and \(I\) is in photons.
  • \(\sigma\): readout noise standard deviation (read_out_sigma), a scalar or a tensor that broadcasts against the intensities, e.g. a per-pixel map (N, N) in centered order.

\(y\) may be negative (offset-subtracted raw data); only the plain amplitude_loss clamps it to zero. See Detector background for where background and dark frames belong.

intensity_loss(predicted_intensity, measured_intensity, total_power)

Squared intensity error, for Gaussian noise with constant variance.

\[ \mathcal{L} = \frac{\lVert I - y \rVert^2}{P^2} \]

Parameters:

Name Type Description Default
predicted_intensity Tensor

Predicted intensity \(I\).

required
measured_intensity Tensor

Measured intensity \(y\), same shape.

required
total_power Tensor

Total measured power \(P\) of the scan.

required

Returns:

Type Description
Tensor

Real scalar loss.

Examples:

from PtyLab.Engines.GradientEngine import intensity_loss

engine.lossFunction = intensity_loss
Source code in PtyLab/Engines/GradientEngine/losses.py
def intensity_loss(
    predicted_intensity,
    measured_intensity,
    total_power,
):
    r"""
    Squared intensity error, for Gaussian noise with constant variance.

    $$
    \mathcal{L} = \frac{\lVert I - y \rVert^2}{P^2}
    $$

    Args:
        predicted_intensity (torch.Tensor): Predicted intensity $I$.
        measured_intensity (torch.Tensor): Measured intensity $y$, same shape.
        total_power (torch.Tensor): Total measured power $P$ of the scan.

    Returns:
        torch.Tensor: Real scalar loss.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import intensity_loss

        engine.lossFunction = intensity_loss
        ```
    """
    residual = predicted_intensity - measured_intensity
    return residual.square().sum() / total_power.square()

poisson_loss(predicted_intensity, measured_intensity, total_power, gain=1.0, read_out_sigma=0.0, eps=1e-10)

Poisson negative log-likelihood, optionally with Gaussian readout noise.

\[ \mathcal{L} = \frac{1}{P}\sum \left(\tilde I - \tilde y \log \tilde I\right), \qquad \tilde I = \frac{I}{g} + s^2,\quad \tilde y = \frac{y}{g} + s^2,\quad s = \frac{\sigma}{g}. \]

With \(\sigma = 0\) this is the plain Poisson likelihood. With \(\sigma > 0\), \(\tilde y\) has the mean and variance of \(\mathrm{Poisson}(\tilde I)\) (Snyder et al.), so the loss models raw negative \(y\) directly. The minimum is at \(I = y\) for any gain.

Parameters:

Name Type Description Default
predicted_intensity Tensor

Predicted intensity \(I\), detector units.

required
measured_intensity Tensor

Measured intensity \(y\), detector units, same shape.

required
total_power Tensor

Total measured power \(P\) of the scan.

required
gain float

Detector gain \(g\).

1.0
read_out_sigma float or Tensor

Readout noise \(\sigma\), detector units.

0.0
eps float

Lower bound on \(\tilde I\) inside the log.

1e-10

Returns:

Type Description
Tensor

Real scalar loss (can be negative).

Raises:

Type Description
ValueError

If gain or eps is outside \((0, \infty)\), or a scalar read_out_sigma is outside \([0, \infty)\).

Examples:

from functools import partial
from PtyLab.Engines.GradientEngine import poisson_loss

engine.lossFunction = partial(poisson_loss, gain=1.0, read_out_sigma=2.0)
Source code in PtyLab/Engines/GradientEngine/losses.py
def poisson_loss(
    predicted_intensity,
    measured_intensity,
    total_power,
    gain=1.0,
    read_out_sigma=0.0,
    eps=1e-10,
):
    r"""
    Poisson negative log-likelihood, optionally with Gaussian readout noise.

    $$
    \mathcal{L} = \frac{1}{P}\sum \left(\tilde I - \tilde y \log \tilde I\right),
    \qquad \tilde I = \frac{I}{g} + s^2,\quad \tilde y = \frac{y}{g} + s^2,\quad s = \frac{\sigma}{g}.
    $$

    With $\sigma = 0$ this is the plain Poisson likelihood. With $\sigma > 0$,
    $\tilde y$ has the mean and variance of $\mathrm{Poisson}(\tilde I)$
    (Snyder et al.), so the loss models raw negative $y$ directly. The minimum
    is at $I = y$ for any gain.

    Args:
        predicted_intensity (torch.Tensor): Predicted intensity $I$, detector units.
        measured_intensity (torch.Tensor): Measured intensity $y$, detector units, same shape.
        total_power (torch.Tensor): Total measured power $P$ of the scan.
        gain (float, optional): Detector gain $g$.
        read_out_sigma (float or torch.Tensor, optional): Readout noise
            $\sigma$, detector units.
        eps (float, optional): Lower bound on $\tilde I$ inside the log.

    Returns:
        torch.Tensor: Real scalar loss (can be negative).

    Raises:
        ValueError: If `gain` or `eps` is outside $(0, \infty)$, or a scalar
            `read_out_sigma` is outside $[0, \infty)$.

    Examples:
        ```python
        from functools import partial
        from PtyLab.Engines.GradientEngine import poisson_loss

        engine.lossFunction = partial(poisson_loss, gain=1.0, read_out_sigma=2.0)
        ```
    """
    if not isfinite(gain) or gain <= 0:
        raise ValueError("gain must be a positive finite scalar.")
    _check_read_out_sigma(read_out_sigma)
    if not isfinite(eps) or eps <= 0:
        raise ValueError("eps must be a positive finite scalar.")
    # s^2 per pixel: a scalar, or a map that broadcasts against the batch.
    shift = (read_out_sigma / gain) ** 2
    counts = predicted_intensity / gain + shift
    return (
        counts - (measured_intensity / gain + shift) * counts.clamp_min(eps).log()
    ).sum() / total_power

amplitude_loss(predicted_intensity, measured_intensity, total_power, anscombe_offset_switch=False, gain=1.0, read_out_sigma=0.0, eps=1e-12)

Squared amplitude error, optionally with the generalized Anscombe shift.

\[ \mathcal{L} = \frac{\lVert \sqrt{I} - \sqrt{y} \rVert^2}{P} \]

This is the default ptychographic objective. Negative \(I\) and \(y\) are clamped to zero, which biases dark pixels upward.

With anscombe_offset_switch=True, both sides are shifted first:

\[ \mathcal{L} = \frac{\lVert \sqrt{I + c} - \sqrt{y + c} \rVert^2}{P}, \qquad c = \frac{3}{8}\,g + \frac{\sigma^2}{g}. \]

\(\sqrt{y + c}\) is the generalized Anscombe transform (Mäkitalo and Foi, 2013) up to the constant factor \(2/\sqrt{g}\). It gives Poisson plus readout noise the same variance at every intensity, and the shift lifts almost all raw negative \(y\) above zero, so they enter the loss as measured. For \(g = 1\) and \(\sigma = 0\) it is the classic Anscombe transform with \(c = 3/8\).

Parameters:

Name Type Description Default
predicted_intensity Tensor

Predicted intensity \(I\), detector units.

required
measured_intensity Tensor

Measured intensity \(y\), detector units, same shape.

required
total_power Tensor

Total measured power \(P\) of the scan.

required
anscombe_offset_switch bool

Apply the shift \(c\).

False
gain float

Detector gain \(g\). Only used with the shift.

1.0
read_out_sigma float or Tensor

Readout noise \(\sigma\), detector units. Only used with the shift.

0.0
eps float

Added to \(I\) under the square root when the shift is off, to keep gradients finite at \(I = 0\).

1e-12

Returns:

Type Description
Tensor

Real scalar loss.

Raises:

Type Description
ValueError

If gain or eps is outside \((0, \infty)\), a scalar read_out_sigma is outside \([0, \infty)\), or gain or read_out_sigma is set while anscombe_offset_switch=False.

Examples:

from functools import partial
from PtyLab.Engines.GradientEngine import amplitude_loss

engine.lossFunction = amplitude_loss  # the default
engine.lossFunction = partial(
    amplitude_loss, anscombe_offset_switch=True, gain=2.0, read_out_sigma=1.5
)
Source code in PtyLab/Engines/GradientEngine/losses.py
def amplitude_loss(
    predicted_intensity,
    measured_intensity,
    total_power,
    anscombe_offset_switch=False,
    gain=1.0,
    read_out_sigma=0.0,
    eps=1e-12,
):
    r"""
    Squared amplitude error, optionally with the generalized Anscombe shift.

    $$
    \mathcal{L} = \frac{\lVert \sqrt{I} - \sqrt{y} \rVert^2}{P}
    $$

    This is the default ptychographic objective. Negative $I$ and $y$ are
    clamped to zero, which biases dark pixels upward.

    With `anscombe_offset_switch=True`, both sides are shifted first:

    $$
    \mathcal{L} = \frac{\lVert \sqrt{I + c} - \sqrt{y + c} \rVert^2}{P},
    \qquad c = \frac{3}{8}\,g + \frac{\sigma^2}{g}.
    $$

    $\sqrt{y + c}$ is the generalized Anscombe transform (Mäkitalo and Foi,
    2013) up to the constant factor $2/\sqrt{g}$. It gives Poisson plus
    readout noise the same variance at every intensity, and the shift lifts
    almost all raw negative $y$ above zero, so they enter the loss as
    measured. For $g = 1$ and $\sigma = 0$ it is the classic Anscombe
    transform with $c = 3/8$.

    Args:
        predicted_intensity (torch.Tensor): Predicted intensity $I$, detector units.
        measured_intensity (torch.Tensor): Measured intensity $y$, detector units, same shape.
        total_power (torch.Tensor): Total measured power $P$ of the scan.
        anscombe_offset_switch (bool, optional): Apply the shift $c$.
        gain (float, optional): Detector gain $g$. Only used with the shift.
        read_out_sigma (float or torch.Tensor, optional): Readout noise
            $\sigma$, detector units. Only used with the shift.
        eps (float, optional): Added to $I$ under the square root when the
            shift is off, to keep gradients finite at $I = 0$.

    Returns:
        torch.Tensor: Real scalar loss.

    Raises:
        ValueError: If `gain` or `eps` is outside $(0, \infty)$, a scalar
            `read_out_sigma` is outside $[0, \infty)$, or `gain` or
            `read_out_sigma` is set while `anscombe_offset_switch=False`.

    Examples:
        ```python
        from functools import partial
        from PtyLab.Engines.GradientEngine import amplitude_loss

        engine.lossFunction = amplitude_loss  # the default
        engine.lossFunction = partial(
            amplitude_loss, anscombe_offset_switch=True, gain=2.0, read_out_sigma=1.5
        )
        ```
    """
    if not isfinite(gain) or gain <= 0:
        raise ValueError("gain must be a positive finite scalar.")
    _check_read_out_sigma(read_out_sigma)
    if not isfinite(eps) or eps <= 0:
        raise ValueError("eps must be a positive finite scalar.")
    if anscombe_offset_switch:
        # c = 3g/8 + σ²/g, per pixel when σ is a map.
        offset = 0.375 * gain + read_out_sigma**2 / gain
        predicted_amplitude = torch.sqrt(predicted_intensity.clamp_min(0.0) + offset)
        measured_amplitude = torch.sqrt((measured_intensity + offset).clamp_min(0.0))
    else:
        if gain != 1:
            raise ValueError("gain requires anscombe_offset_switch=True.")
        # A map is refused whatever its values: checking them would need a sync.
        if torch.is_tensor(read_out_sigma) or read_out_sigma != 0:
            raise ValueError("read_out_sigma requires anscombe_offset_switch=True.")
        predicted_amplitude = torch.sqrt(predicted_intensity.clamp_min(0.0) + eps)
        measured_amplitude = measured_intensity.clamp_min(0.0).sqrt()
    residual = predicted_amplitude - measured_amplitude
    return residual.square().sum() / total_power

mixed_poisson_gaussian_loss(predicted_intensity, measured_intensity, total_power, gain=1.0, read_out_sigma=0.0, eps=1e-08)

Gaussian approximation of Poisson plus readout noise.

\[ \mathcal{L} = \frac{1}{2P}\left(\left\lVert \frac{I - y}{\sqrt{v}} \right\rVert^2 + \sum \log v\right), \qquad v = gI + \sigma^2. \]

\(v\) is the variance of \(y\) for Poisson photons plus Gaussian readout noise. The loss approximates the exact Poisson-Gaussian likelihood and loses accuracy at low counts.

Parameters:

Name Type Description Default
predicted_intensity Tensor

Predicted intensity \(I\), detector units.

required
measured_intensity Tensor

Measured intensity \(y\), detector units, same shape.

required
total_power Tensor

Total measured power \(P\) of the scan.

required
gain float

Detector gain \(g\).

1.0
read_out_sigma float or Tensor

Readout noise \(\sigma\), detector units.

0.0
eps float

Added to \(v\) to keep it positive.

1e-08

Returns:

Type Description
Tensor

Real scalar loss (can be negative).

Raises:

Type Description
ValueError

If gain or a scalar read_out_sigma is outside \([0, \infty)\), or eps is outside \((0, \infty)\).

Examples:

from functools import partial
from PtyLab.Engines.GradientEngine import mixed_poisson_gaussian_loss

engine.lossFunction = partial(
    mixed_poisson_gaussian_loss, gain=1.0, read_out_sigma=2.0
)
Source code in PtyLab/Engines/GradientEngine/losses.py
def mixed_poisson_gaussian_loss(
    predicted_intensity,
    measured_intensity,
    total_power,
    gain=1.0,
    read_out_sigma=0.0,
    eps=1e-8,
):
    r"""
    Gaussian approximation of Poisson plus readout noise.

    $$
    \mathcal{L} = \frac{1}{2P}\left(\left\lVert \frac{I - y}{\sqrt{v}} \right\rVert^2 + \sum \log v\right),
    \qquad v = gI + \sigma^2.
    $$

    $v$ is the variance of $y$ for Poisson photons plus Gaussian readout
    noise. The loss approximates the exact Poisson-Gaussian likelihood and
    loses accuracy at low counts.

    Args:
        predicted_intensity (torch.Tensor): Predicted intensity $I$, detector units.
        measured_intensity (torch.Tensor): Measured intensity $y$, detector units, same shape.
        total_power (torch.Tensor): Total measured power $P$ of the scan.
        gain (float, optional): Detector gain $g$.
        read_out_sigma (float or torch.Tensor, optional): Readout noise
            $\sigma$, detector units.
        eps (float, optional): Added to $v$ to keep it positive.

    Returns:
        torch.Tensor: Real scalar loss (can be negative).

    Raises:
        ValueError: If `gain` or a scalar `read_out_sigma` is outside
            $[0, \infty)$, or `eps` is outside $(0, \infty)$.

    Examples:
        ```python
        from functools import partial
        from PtyLab.Engines.GradientEngine import mixed_poisson_gaussian_loss

        engine.lossFunction = partial(
            mixed_poisson_gaussian_loss, gain=1.0, read_out_sigma=2.0
        )
        ```
    """
    if not isfinite(gain) or gain < 0:
        raise ValueError("gain must be a nonnegative finite scalar.")
    _check_read_out_sigma(read_out_sigma)
    if not isfinite(eps) or eps <= 0:
        raise ValueError("eps must be a positive finite scalar.")

    # v = g I + σ² + ε, with σ² per pixel when σ is a map.
    variance = gain * predicted_intensity.clamp_min(0.0) + (read_out_sigma**2) + eps
    residual_sq = (predicted_intensity - measured_intensity).square()

    nll = 0.5 * ((residual_sq / variance) + variance.log())
    return nll.sum() / total_power

Regularizers

Optional penalties on a PtychographyModel state.

object_smoothness(model, weight=0.0001)

Penalize squared differences between neighbouring object pixels.

\[ \mathcal{R} = w\left(\left\langle |O_{y+1,x} - O_{y,x}|^2 \right\rangle + \left\langle |O_{y,x+1} - O_{y,x}|^2 \right\rangle\right) \]

where \(\langle\cdot\rangle\) is the mean over all pixel pairs (and modes) of the complex object \(O\). This quadratic smoothness penalty (an L2 penalty on the object gradient) suppresses strong gradients and smooths a noisy reconstruction, edges included. object_tv keeps edges sharper.

Parameters:

Name Type Description Default
model PtychographyModel

Model whose object is penalized.

required
weight float

Weight \(w\) of the penalty. Defaults to 1e-4.

0.0001

Returns:

Type Description
Tensor

Real scalar penalty.

Examples:

from functools import partial
from PtyLab.Engines.GradientEngine import object_smoothness

engine.regularizers = [partial(object_smoothness, weight=1e-4)]
Source code in PtyLab/Engines/GradientEngine/regularizers.py
def object_smoothness(model, weight=1e-4):
    r"""
    Penalize squared differences between neighbouring object pixels.

    $$
    \mathcal{R} = w\left(\left\langle |O_{y+1,x} - O_{y,x}|^2 \right\rangle + \left\langle |O_{y,x+1} - O_{y,x}|^2 \right\rangle\right)
    $$

    where $\langle\cdot\rangle$ is the mean over all pixel pairs (and modes) of
    the complex object $O$. This quadratic smoothness penalty (an L2 penalty on
    the object gradient) suppresses strong gradients and smooths a noisy
    reconstruction, edges included. `object_tv` keeps edges sharper.

    Args:
        model (PtychographyModel):
            Model whose `object` is penalized.

        weight (float, optional):
            Weight $w$ of the penalty. Defaults to 1e-4.

    Returns:
        torch.Tensor:
            Real scalar penalty.

    Examples:
        ```python
        from functools import partial
        from PtyLab.Engines.GradientEngine import object_smoothness

        engine.regularizers = [partial(object_smoothness, weight=1e-4)]
        ```
    """
    obj = model.object
    dy = obj[..., 1:, :] - obj[..., :-1, :]
    dx = obj[..., :, 1:] - obj[..., :, :-1]
    return weight * (dy.abs().square().mean() + dx.abs().square().mean())

object_tv(model, weight=0.0001, epsilon=1e-06)

Penalize the isotropic total variation (TV) of the object.

\[ \mathcal{R} = w\left\langle \sqrt{|O_{y+1,x} - O_{y,x}|^2 + |O_{y,x+1} - O_{y,x}|^2 + \epsilon} \right\rangle \]

where \(\langle\cdot\rangle\) is the mean over all pixels (and modes) of the complex object \(O\). Unlike object_smoothness, which squares the differences, TV grows only linearly with them: it removes small noisy variations but lets a few large jumps, such as sharp edges, stay. The offset \(\epsilon\) keeps the gradient finite where the object is flat.

Parameters:

Name Type Description Default
model PtychographyModel

Model whose object is penalized.

required
weight float

Weight \(w\) of the penalty. Defaults to 1e-4.

0.0001
epsilon float

Offset \(\epsilon\) under the square root, in squared object units. Differences much smaller than \(\sqrt{\epsilon}\) are penalized quadratically, as in object_smoothness. Defaults to 1e-6.

1e-06

Returns:

Type Description
Tensor

Real scalar penalty.

Examples:

from functools import partial
from PtyLab.Engines.GradientEngine import object_tv

engine.regularizers = [partial(object_tv, weight=1e-3)]
Source code in PtyLab/Engines/GradientEngine/regularizers.py
def object_tv(model, weight=1e-4, epsilon=1e-6):
    r"""
    Penalize the isotropic total variation (TV) of the object.

    $$
    \mathcal{R} = w\left\langle \sqrt{|O_{y+1,x} - O_{y,x}|^2 + |O_{y,x+1} - O_{y,x}|^2 + \epsilon} \right\rangle
    $$

    where $\langle\cdot\rangle$ is the mean over all pixels (and modes) of the
    complex object $O$. Unlike `object_smoothness`, which squares the
    differences, TV grows only linearly with them: it removes small noisy
    variations but lets a few large jumps, such as sharp edges, stay. The
    offset $\epsilon$ keeps the gradient finite where the object is flat.

    Args:
        model (PtychographyModel):
            Model whose `object` is penalized.

        weight (float, optional):
            Weight $w$ of the penalty. Defaults to 1e-4.

        epsilon (float, optional):
            Offset $\epsilon$ under the square root, in squared object units.
            Differences much smaller than $\sqrt{\epsilon}$ are penalized
            quadratically, as in `object_smoothness`. Defaults to 1e-6.

    Returns:
        torch.Tensor:
            Real scalar penalty.

    Examples:
        ```python
        from functools import partial
        from PtyLab.Engines.GradientEngine import object_tv

        engine.regularizers = [partial(object_tv, weight=1e-3)]
        ```
    """
    obj = model.object
    # Forward differences, cropped to the common (N - 1, N - 1) grid so that
    # dy and dx belong to the same pixel.
    dy = obj[..., 1:, :-1] - obj[..., :-1, :-1]
    dx = obj[..., :-1, 1:] - obj[..., :-1, :-1]
    return weight * (dy.abs().square() + dx.abs().square() + epsilon).sqrt().mean()

Constraints

In-place constraints applied after optimizer steps.

Assign a list to engine.constraints. After every optimizer step the engine calls each constraint as constraint(engine, iteration) under torch.no_grad. A constraint runs at iterations start, start + step, ... before end (exclusive; None means no end). iteration counts from zero within one run of numIterations, so within one phase of reconstruct(phases=...).

The relaxation \(\rho\) (relax) blends the result with the unconstrained value,

\[ x \leftarrow \rho\,x + (1 - \rho)\,C(x), \]

so \(\rho = 0\) applies the constraint \(C\) fully and values towards 1 apply it gently. Constraints that move a parameter, such as recentring, transform that parameter's optimizer state the same way, so Adam's moments stay aligned with the pixels they belong to.

Constraint

Schedule and relaxation shared by every constraint.

Subclasses implement apply(engine), which runs under torch.no_grad.

Parameters:

Name Type Description Default
start int

First iteration at which the constraint runs. Defaults to 0.

0
step int

Interval between runs, at least 1. Defaults to 1.

1
end int

Iteration before which the constraint stops (exclusive). If None, it never stops.

None
relax float

Relaxation \(\rho\) in \([0, 1)\). Defaults to 0.0.

0.0

Raises:

Type Description
ValueError

If the schedule or the relaxation is invalid.

Examples:

import torch
from PtyLab.Engines.GradientEngine import Constraint


class ObjectPhaseClamp(Constraint):
    # Limit the object phase to [-limit, limit], keeping the amplitude.

    def __init__(self, limit=1.0, **schedule):
        super().__init__(**schedule)
        self.limit = limit

    def apply(self, engine):  # runs under torch.no_grad
        obj = engine.model.object
        phase = obj.angle().clamp(-self.limit, self.limit)
        target = torch.polar(obj.abs(), phase)
        obj.copy_(self.relax * obj + (1 - self.relax) * target)


engine.constraints = [ObjectPhaseClamp(limit=1.0, start=100, step=5)]
Source code in PtyLab/Engines/GradientEngine/constraints.py
class Constraint:
    r"""
    Schedule and relaxation shared by every constraint.

    Subclasses implement `apply(engine)`, which runs under `torch.no_grad`.

    Args:
        start (int, optional):
            First iteration at which the constraint runs. Defaults to 0.

        step (int, optional):
            Interval between runs, at least 1. Defaults to 1.

        end (int, optional):
            Iteration before which the constraint stops (exclusive). If None,
            it never stops.

        relax (float, optional):
            Relaxation $\rho$ in $[0, 1)$. Defaults to 0.0.

    Raises:
        ValueError:
            If the schedule or the relaxation is invalid.

    Examples:
        ```python
        import torch
        from PtyLab.Engines.GradientEngine import Constraint


        class ObjectPhaseClamp(Constraint):
            # Limit the object phase to [-limit, limit], keeping the amplitude.

            def __init__(self, limit=1.0, **schedule):
                super().__init__(**schedule)
                self.limit = limit

            def apply(self, engine):  # runs under torch.no_grad
                obj = engine.model.object
                phase = obj.angle().clamp(-self.limit, self.limit)
                target = torch.polar(obj.abs(), phase)
                obj.copy_(self.relax * obj + (1 - self.relax) * target)


        engine.constraints = [ObjectPhaseClamp(limit=1.0, start=100, step=5)]
        ```
    """

    def __init__(self, start=0, step=1, end=None, relax=0.0):
        for name, value, minimum in (("start", start, 0), ("step", step, 1)):
            if (
                isinstance(value, bool)
                or not isinstance(value, Integral)
                or value < minimum
            ):
                raise ValueError(f"{name} must be an integer >= {minimum}.")
        if end is not None and (
            isinstance(end, bool) or not isinstance(end, Integral) or end <= start
        ):
            raise ValueError("end must be None or an integer > start.")
        if isinstance(relax, bool) or not isinstance(relax, Real) or not 0 <= relax < 1:
            raise ValueError("relax must lie in [0, 1).")
        self.start, self.step, self.end, self.relax = start, step, end, float(relax)

    def active(self, iteration):
        """
        Return whether the schedule applies the constraint at an iteration.

        Args:
            iteration (int):
                Iteration index from 0 within the current run of
                `numIterations`, that is within the current phase.

        Returns:
            bool:
                True if the constraint runs at `iteration`.
        """
        if iteration < self.start or (self.end is not None and iteration >= self.end):
            return False
        return (iteration - self.start) % self.step == 0

    def __call__(self, engine, iteration):
        if self.active(iteration):
            with torch.no_grad():
                self.apply(engine)

    def apply(self, engine):
        raise NotImplementedError

    def __repr__(self):
        return (
            f"{type(self).__name__}(start={self.start}, step={self.step}, "
            f"end={self.end}, relax={self.relax})"
        )

active(iteration)

Return whether the schedule applies the constraint at an iteration.

Parameters:

Name Type Description Default
iteration int

Iteration index from 0 within the current run of numIterations, that is within the current phase.

required

Returns:

Type Description
bool

True if the constraint runs at iteration.

Source code in PtyLab/Engines/GradientEngine/constraints.py
def active(self, iteration):
    """
    Return whether the schedule applies the constraint at an iteration.

    Args:
        iteration (int):
            Iteration index from 0 within the current run of
            `numIterations`, that is within the current phase.

    Returns:
        bool:
            True if the constraint runs at `iteration`.
    """
    if iteration < self.start or (self.end is not None and iteration >= self.end):
        return False
    return (iteration - self.start) % self.step == 0

ProbeCentering

Bases: Constraint

Keep the probe's centre of mass at the window centre.

The probe intensity \(\sum |P|^2\) over all probe axes gives a centre of mass \(\mathbf{c}\) in pixels from the window centre. When \(\max(|c_{\mathrm{row}}|, |c_{\mathrm{col}}|) \geq\) threshold, the probe, the object and their optimizer state are rolled by

\[ -\mathrm{round}\left((1 - \rho)\,\mathbf{c}\right). \]

Exit waves then move by a whole number of pixels inside the window, which leaves far-field (Fraunhofer) intensities unchanged; for near-field propagators recentring changes the prediction.

Parameters:

Name Type Description Default
threshold float

Offset in pixels below which nothing is done. Defaults to 2.

2
**schedule dict

start, step, end and relax, as in Constraint.

{}

Raises:

Type Description
ValueError

If threshold is not a nonnegative number.

Notes

The roll is cyclic, so it assumes the probe is small at the window edge.

Examples:

from PtyLab.Engines.GradientEngine import ProbeCentering

engine.constraints = [ProbeCentering(threshold=2)]
Source code in PtyLab/Engines/GradientEngine/constraints.py
class ProbeCentering(Constraint):
    r"""
    Keep the probe's centre of mass at the window centre.

    The probe intensity $\sum |P|^2$ over all probe axes gives a centre of mass
    $\mathbf{c}$ in pixels from the window centre. When
    $\max(|c_{\mathrm{row}}|, |c_{\mathrm{col}}|) \geq$ `threshold`, the probe,
    the object and their optimizer state are rolled by

    $$
    -\mathrm{round}\left((1 - \rho)\,\mathbf{c}\right).
    $$

    Exit waves then move by a whole number of pixels inside the window, which
    leaves far-field (Fraunhofer) intensities unchanged; for near-field
    propagators recentring changes the prediction.

    Args:
        threshold (float, optional):
            Offset in pixels below which nothing is done. Defaults to 2.

        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Raises:
        ValueError:
            If `threshold` is not a nonnegative number.

    Notes:
        The roll is cyclic, so it assumes the probe is small at the window
        edge.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import ProbeCentering

        engine.constraints = [ProbeCentering(threshold=2)]
        ```
    """

    def __init__(self, threshold=2, **schedule):
        super().__init__(**schedule)
        if (
            isinstance(threshold, bool)
            or not isinstance(threshold, Real)
            or threshold < 0
        ):
            raise ValueError("threshold must be a nonnegative number of pixels.")
        self.threshold = threshold

    @staticmethod
    def centre_of_mass(field):
        r"""
        Return the centre of mass of $\sum |\mathrm{field}|^2$.

        Args:
            field (torch.Tensor):
                Complex field with spatial axes last; all leading axes are
                summed.

        Returns:
            tuple:
                `(row, column)` in pixels relative to the window centre.
        """
        intensity = (
            field.detach().abs().square().reshape(-1, *field.shape[-2:]).sum(dim=0)
        )
        height, width = intensity.shape
        rows = torch.arange(height, device=field.device) - height // 2
        cols = torch.arange(width, device=field.device) - width // 2
        total = intensity.sum()
        return (
            float((intensity.sum(-1) * rows).sum() / total),
            float((intensity.sum(-2) * cols).sum() / total),
        )

    def apply(self, engine):
        model = engine.model
        row, col = self.centre_of_mass(model.probe.field)
        if max(abs(row), abs(col)) < self.threshold:
            return
        shifts = (
            -int(round((1 - self.relax) * row)),
            -int(round((1 - self.relax) * col)),
        )
        if shifts == (0, 0):
            return
        roll_parameter(engine, model.probe.field, shifts)
        roll_parameter(engine, model.object, shifts)

centre_of_mass(field) staticmethod

Return the centre of mass of \(\sum |\mathrm{field}|^2\).

Parameters:

Name Type Description Default
field Tensor

Complex field with spatial axes last; all leading axes are summed.

required

Returns:

Type Description
tuple

(row, column) in pixels relative to the window centre.

Source code in PtyLab/Engines/GradientEngine/constraints.py
@staticmethod
def centre_of_mass(field):
    r"""
    Return the centre of mass of $\sum |\mathrm{field}|^2$.

    Args:
        field (torch.Tensor):
            Complex field with spatial axes last; all leading axes are
            summed.

    Returns:
        tuple:
            `(row, column)` in pixels relative to the window centre.
    """
    intensity = (
        field.detach().abs().square().reshape(-1, *field.shape[-2:]).sum(dim=0)
    )
    height, width = intensity.shape
    rows = torch.arange(height, device=field.device) - height // 2
    cols = torch.arange(width, device=field.device) - width // 2
    total = intensity.sum()
    return (
        float((intensity.sum(-1) * rows).sum() / total),
        float((intensity.sum(-2) * cols).sum() / total),
    )

ObjectAmplitudeClamp

Bases: Constraint

Limit the object amplitude to [minimum, maximum], keeping its phase.

Optimizer state is unchanged: this is a projection, not a move.

Parameters:

Name Type Description Default
maximum float

Upper amplitude bound, or None. 1 suits a transmission sample without gain. Defaults to 1.0.

1.0
minimum float

Lower amplitude bound, or None. Defaults to None.

None
**schedule dict

start, step, end and relax, as in Constraint.

{}

Raises:

Type Description
ValueError

If both bounds are None, a bound is negative, or minimum exceeds maximum.

Examples:

from PtyLab.Engines.GradientEngine import ObjectAmplitudeClamp

engine.constraints = [ObjectAmplitudeClamp(maximum=1.0)]  # no gain
Source code in PtyLab/Engines/GradientEngine/constraints.py
class ObjectAmplitudeClamp(Constraint):
    """
    Limit the object amplitude to `[minimum, maximum]`, keeping its phase.

    Optimizer state is unchanged: this is a projection, not a move.

    Args:
        maximum (float, optional):
            Upper amplitude bound, or None. `1` suits a transmission sample
            without gain. Defaults to 1.0.

        minimum (float, optional):
            Lower amplitude bound, or None. Defaults to None.

        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Raises:
        ValueError:
            If both bounds are None, a bound is negative, or `minimum` exceeds
            `maximum`.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import ObjectAmplitudeClamp

        engine.constraints = [ObjectAmplitudeClamp(maximum=1.0)]  # no gain
        ```
    """

    def __init__(self, maximum=1.0, minimum=None, **schedule):
        super().__init__(**schedule)
        if maximum is None and minimum is None:
            raise ValueError("Give at least one of minimum and maximum.")
        for value in (maximum, minimum):
            if value is not None and (
                isinstance(value, bool) or not isinstance(value, Real) or value < 0
            ):
                raise ValueError("Amplitude bounds must be nonnegative numbers.")
        if maximum is not None and minimum is not None and minimum > maximum:
            raise ValueError("minimum must not exceed maximum.")
        self.maximum, self.minimum = maximum, minimum

    def apply(self, engine):
        obj = engine.model.object
        amplitude = obj.abs()
        clamped = amplitude.clamp(min=self.minimum, max=self.maximum)
        # The phase of a zero pixel is undefined; raise it along the real axis.
        phase = torch.where(amplitude > 0, obj / amplitude.clamp_min(1e-30), 1)
        target = clamped * phase
        obj.copy_(self.relax * obj + (1 - self.relax) * target)

AbsorbingObject

Bases: Constraint

Pull the object towards a pure-absorption object, as Params.absObjectSwitch.

Each call blends the object with its modulus,

\[ O \leftarrow (1 - \beta)\,O + \beta\,|O|, \]

with \(\beta\) = beta. It shrinks the phase of every pixel towards 0 and leaves the amplitude of real positive pixels unchanged. It suits samples whose phase carries little information, and damps phase noise in weakly lit pixels. Called once per iteration it matches the classic engines' constraint; with updatePerBatch it runs after every step.

Optimizer state is unchanged: this is a small pull, not a move of the parameter. With relaxation \(\rho\) the pull is \((1 - \rho)\beta\).

Parameters:

Name Type Description Default
beta float

Pull \(\beta\) in \((0, 1]\) per call, as Params.absObjectBeta. Defaults to 0.01.

0.01
**schedule dict

start, step, end and relax, as in Constraint.

{}

Raises:

Type Description
ValueError

If beta is not in \((0, 1]\).

Examples:

from PtyLab.Engines.GradientEngine import AbsorbingObject

engine.constraints = [AbsorbingObject(beta=0.01, end=200)]  # first 200 only
Source code in PtyLab/Engines/GradientEngine/constraints.py
class AbsorbingObject(Constraint):
    r"""
    Pull the object towards a pure-absorption object, as `Params.absObjectSwitch`.

    Each call blends the object with its modulus,

    $$
    O \leftarrow (1 - \beta)\,O + \beta\,|O|,
    $$

    with $\beta$ = `beta`. It shrinks the phase of every pixel towards 0
    and leaves the amplitude of real positive pixels unchanged. It suits
    samples whose phase carries little information, and damps phase noise in
    weakly lit pixels. Called once per iteration it matches the classic
    engines' constraint; with `updatePerBatch` it runs after every step.

    Optimizer state is unchanged: this is a small pull, not a move of the
    parameter. With relaxation $\rho$ the pull is $(1 - \rho)\beta$.

    Args:
        beta (float, optional):
            Pull $\beta$ in $(0, 1]$ per call, as `Params.absObjectBeta`.
            Defaults to 0.01.

        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Raises:
        ValueError:
            If `beta` is not in $(0, 1]$.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import AbsorbingObject

        engine.constraints = [AbsorbingObject(beta=0.01, end=200)]  # first 200 only
        ```
    """

    def __init__(self, beta=0.01, **schedule):
        super().__init__(**schedule)
        if isinstance(beta, bool) or not isinstance(beta, Real) or not 0 < beta <= 1:
            raise ValueError("beta must lie in (0, 1].")
        self.beta = float(beta)

    def apply(self, engine):
        obj = engine.model.object
        beta = (1 - self.relax) * self.beta  # relaxation keeps a fraction of O
        modulus = obj.abs()  # before the in-place scaling below
        obj.mul_(1 - beta).add_(modulus, alpha=beta)

PhaseRampRemoval

Bases: Constraint

Move a linear phase ramp and a global phase from the object to the probe.

For

\[ O'(\mathbf{x}) = O(\mathbf{x})\,e^{-i(\mathbf{k}\cdot\mathbf{x} + \phi)}, \qquad P'(\mathbf{r}) = P(\mathbf{r})\,e^{i(\mathbf{k}\cdot\mathbf{r} + \phi)}, \]

each exit wave changes only by the constant phase \(e^{-i\mathbf{k}\cdot\mathbf{x}_j}\) of its scan position, so every predicted intensity is unchanged, for any propagator. This fixes a gauge freedom of blind ptychography instead of changing the fit.

\(\mathbf{k}\) is estimated from the illumination-weighted phase of neighbouring object pixels, which does not need phase unwrapping:

\[ k_{\mathrm{row}} = \arg\sum_{\mathbf{x}} w(\mathbf{x})\, O(\mathbf{x} + \mathbf{e}_{\mathrm{row}})\,O^*(\mathbf{x}), \]

and likewise along columns. \(\phi\) is the weighted mean phase after the ramp is removed. The relaxation \(\rho\) removes only the fraction \(1 - \rho\) of both.

Parameters:

Name Type Description Default
ramp bool

Remove the linear phase ramp. Defaults to True.

True
global_phase bool

Remove the global phase. Defaults to True.

True
**schedule dict

start, step, end and relax, as in Constraint.

{}

Raises:

Type Description
ValueError

If neither ramp nor global_phase is selected.

Examples:

from PtyLab.Engines.GradientEngine import PhaseRampRemoval, ProbeCentering

engine.constraints = [ProbeCentering(), PhaseRampRemoval(step=10)]
Source code in PtyLab/Engines/GradientEngine/constraints.py
class PhaseRampRemoval(Constraint):
    r"""
    Move a linear phase ramp and a global phase from the object to the probe.

    For

    $$
    O'(\mathbf{x}) = O(\mathbf{x})\,e^{-i(\mathbf{k}\cdot\mathbf{x} + \phi)}, \qquad P'(\mathbf{r}) = P(\mathbf{r})\,e^{i(\mathbf{k}\cdot\mathbf{r} + \phi)},
    $$

    each exit wave changes only by the constant phase
    $e^{-i\mathbf{k}\cdot\mathbf{x}_j}$ of its scan position, so every
    predicted intensity is unchanged, for any propagator. This fixes a gauge
    freedom of blind ptychography instead of changing the fit.

    $\mathbf{k}$ is estimated from the illumination-weighted phase of
    neighbouring object pixels, which does not need phase unwrapping:

    $$
    k_{\mathrm{row}} = \arg\sum_{\mathbf{x}} w(\mathbf{x})\, O(\mathbf{x} + \mathbf{e}_{\mathrm{row}})\,O^*(\mathbf{x}),
    $$

    and likewise along columns. $\phi$ is the weighted mean phase after the
    ramp is removed. The relaxation $\rho$ removes only the fraction
    $1 - \rho$ of both.

    Args:
        ramp (bool, optional):
            Remove the linear phase ramp. Defaults to True.

        global_phase (bool, optional):
            Remove the global phase. Defaults to True.

        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Raises:
        ValueError:
            If neither `ramp` nor `global_phase` is selected.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import PhaseRampRemoval, ProbeCentering

        engine.constraints = [ProbeCentering(), PhaseRampRemoval(step=10)]
        ```
    """

    def __init__(self, ramp=True, global_phase=True, **schedule):
        super().__init__(**schedule)
        if not (ramp or global_phase):
            raise ValueError("Select ramp, global_phase or both.")
        self.ramp, self.global_phase = bool(ramp), bool(global_phase)

    @staticmethod
    def weights(engine):
        r"""
        Return the illumination over the whole scan.

        $$
        w(\mathbf{x}) = \sum_j |P(\mathbf{x} - \mathbf{x}_j)|^2
        $$

        Args:
            engine (GradientEngine):
                Engine with a prepared model.

        Returns:
            torch.Tensor:
                Real weights with the shape of the object.
        """
        model = engine.model
        indices = torch.arange(len(model.positions), device=model.object.device)
        # Batch by batch, so the engine's batch size bounds the memory; the
        # size is None (one batch) before the first run.
        size = getattr(engine, "effectiveBatchSize", None)
        weight = sum(
            model.illumination(batch) for batch in split_indices(indices, size)
        )
        return weight.expand(model.object.shape)

    def estimate(self, engine):
        r"""
        Estimate the phase ramp and the global phase of the object.

        Args:
            engine (GradientEngine):
                Engine with a prepared model.

        Returns:
            tuple:
                `(k_row, k_col, phi)`: $k_{\mathrm{row}}$ and $k_{\mathrm{col}}$
                in radians per pixel and $\phi$ in radians. Disabled parts are
                zero.
        """
        obj = engine.model.object
        weight = self.weights(engine).to(obj.real.dtype)
        k_row = k_col = 0.0
        if self.ramp:
            k_row = self._neighbour_phase(weight, obj, dim=-2)
            k_col = self._neighbour_phase(weight, obj, dim=-1)
        phi = 0.0
        if self.global_phase:
            phi = float(
                torch.angle((weight * obj * self._ramp(obj, k_row, k_col).conj()).sum())
            )
        return k_row, k_col, phi

    @staticmethod
    def _neighbour_phase(weight, field, dim):
        r"""
        Return $\arg\sum_{\mathbf{x}} w(\mathbf{x} + \mathbf{e})\, O(\mathbf{x} + \mathbf{e})\,O^*(\mathbf{x})$ along `dim`.

        This is the ramp $k$ in radians per pixel along that axis.
        """
        length = field.shape[dim] - 1
        later, earlier = field.narrow(dim, 1, length), field.narrow(dim, 0, length)
        return float(
            torch.angle((weight.narrow(dim, 1, length) * later * earlier.conj()).sum())
        )

    @staticmethod
    def _ramp(field, k_row, k_col):
        r"""
        Return the phase ramp $e^{i(k_{\mathrm{row}} r + k_{\mathrm{col}} c)}$.

        $r$ and $c$ are measured in pixels from the window centre.
        """
        height, width = field.shape[-2:]
        rows = (
            torch.arange(height, device=field.device, dtype=field.real.dtype)
            - height // 2
        )
        cols = (
            torch.arange(width, device=field.device, dtype=field.real.dtype)
            - width // 2
        )
        phase = k_row * rows[:, None] + k_col * cols[None, :]
        return torch.polar(torch.ones_like(phase), phase).to(field.dtype)

    def apply(self, engine):
        model = engine.model
        k_row, k_col, phi = (
            (1 - self.relax) * value for value in self.estimate(engine)
        )
        obj, probe = model.object, model.probe.field
        object_factor = self._ramp(obj, k_row, k_col).conj() * complex(
            torch.polar(torch.tensor(1.0), torch.tensor(-phi))
        )
        # The object ramp is centred on the object; at probe pixel r of frame j
        # the object coordinate is r + x_j relative to the object's corner, so
        # the probe ramp in window coordinates differs only by a per-frame
        # constant, which intensities do not see.
        probe_factor = self._ramp(probe, k_row, k_col) * complex(
            torch.polar(torch.tensor(1.0), torch.tensor(phi))
        )
        multiply_parameter(engine, obj, object_factor)
        multiply_parameter(engine, probe, probe_factor)

weights(engine) staticmethod

Return the illumination over the whole scan.

\[ w(\mathbf{x}) = \sum_j |P(\mathbf{x} - \mathbf{x}_j)|^2 \]

Parameters:

Name Type Description Default
engine GradientEngine

Engine with a prepared model.

required

Returns:

Type Description
Tensor

Real weights with the shape of the object.

Source code in PtyLab/Engines/GradientEngine/constraints.py
@staticmethod
def weights(engine):
    r"""
    Return the illumination over the whole scan.

    $$
    w(\mathbf{x}) = \sum_j |P(\mathbf{x} - \mathbf{x}_j)|^2
    $$

    Args:
        engine (GradientEngine):
            Engine with a prepared model.

    Returns:
        torch.Tensor:
            Real weights with the shape of the object.
    """
    model = engine.model
    indices = torch.arange(len(model.positions), device=model.object.device)
    # Batch by batch, so the engine's batch size bounds the memory; the
    # size is None (one batch) before the first run.
    size = getattr(engine, "effectiveBatchSize", None)
    weight = sum(
        model.illumination(batch) for batch in split_indices(indices, size)
    )
    return weight.expand(model.object.shape)

estimate(engine)

Estimate the phase ramp and the global phase of the object.

Parameters:

Name Type Description Default
engine GradientEngine

Engine with a prepared model.

required

Returns:

Type Description
tuple

(k_row, k_col, phi): \(k_{\mathrm{row}}\) and \(k_{\mathrm{col}}\) in radians per pixel and \(\phi\) in radians. Disabled parts are zero.

Source code in PtyLab/Engines/GradientEngine/constraints.py
def estimate(self, engine):
    r"""
    Estimate the phase ramp and the global phase of the object.

    Args:
        engine (GradientEngine):
            Engine with a prepared model.

    Returns:
        tuple:
            `(k_row, k_col, phi)`: $k_{\mathrm{row}}$ and $k_{\mathrm{col}}$
            in radians per pixel and $\phi$ in radians. Disabled parts are
            zero.
    """
    obj = engine.model.object
    weight = self.weights(engine).to(obj.real.dtype)
    k_row = k_col = 0.0
    if self.ramp:
        k_row = self._neighbour_phase(weight, obj, dim=-2)
        k_col = self._neighbour_phase(weight, obj, dim=-1)
    phi = 0.0
    if self.global_phase:
        phi = float(
            torch.angle((weight * obj * self._ramp(obj, k_row, k_col).conj()).sum())
        )
    return k_row, k_col, phi

ProbeModeOrthogonalization

Bases: Constraint

Rotate the probe modes into orthogonal modes, strongest first.

This is the snapshot orthogonalization (orthogonalizeModes with method="snapShots", used by mPIE's orthogonalizationSwitch), computed in Torch on the engine's device (see snapshot_basis). It diagonalizes the Gram matrix of the modes of each wavelength,

\[ G_{mn} = \sum_{\mathbf{r}} P_m^*(\mathbf{r})\,P_n(\mathbf{r}) = \sum_k W_{mk}\,\lambda_k\,W^*_{nk}, \]

with eigenvalues sorted as \(\lambda_1 \geq \lambda_2 \geq \ldots\), and takes \(V = W^T\) as orthogonalizeModes does. The new modes \(P'_n = \sum_m V_{nm} P_m\) are orthogonal, \(\sum_{\mathbf{r}} P'^*_m P'_n = \lambda_n\,\delta_{mn}\), so their powers are the eigenvalues of \(G\). A unitary rotation of the modes leaves every predicted intensity unchanged, so this only picks a basis: it does not change the fit.

With relaxation \(\rho\) the modes become \(\rho P + (1 - \rho)P'\), that is the mixing matrix \(\rho I + (1 - \rho) V\), which is no longer unitary. The optimizer state is mixed with the same matrix (see mix_states). For an OPRProbe the modes of every frame are orthogonalized separately, like params.OPR_orthogonalize_modes in the classic OPR engine.

Parameters:

Name Type Description Default
**schedule dict

start, step, end and relax, as in Constraint.

required
Notes

Each eigenvector is fixed only up to a phase, so the result agrees with orthogonalizeModes up to one phase factor per mode, which no intensity sees.

Examples:

from PtyLab.Engines.GradientEngine import ProbeModeOrthogonalization

reconstruction.npsm = 4
reconstruction.initializeObjectProbe()
engine = GradientEngine(reconstruction, experimentalData, params, monitor)
engine.constraints = [ProbeModeOrthogonalization(step=10)]
engine.reconstruct()
engine.model.probe.mode_powers()  # (nlambda, npsm), strongest first
Source code in PtyLab/Engines/GradientEngine/constraints.py
class ProbeModeOrthogonalization(Constraint):
    r"""
    Rotate the probe modes into orthogonal modes, strongest first.

    This is the snapshot orthogonalization (`orthogonalizeModes` with
    `method="snapShots"`, used by mPIE's `orthogonalizationSwitch`), computed
    in Torch on the engine's device (see `snapshot_basis`). It diagonalizes
    the Gram matrix of the modes of each wavelength,

    $$
    G_{mn} = \sum_{\mathbf{r}} P_m^*(\mathbf{r})\,P_n(\mathbf{r}) = \sum_k W_{mk}\,\lambda_k\,W^*_{nk},
    $$

    with eigenvalues sorted as $\lambda_1 \geq \lambda_2 \geq \ldots$, and
    takes $V = W^T$ as `orthogonalizeModes` does. The new modes $P'_n = \sum_m V_{nm} P_m$ are
    orthogonal, $\sum_{\mathbf{r}} P'^*_m P'_n = \lambda_n\,\delta_{mn}$, so
    their powers are the eigenvalues of $G$. A unitary
    rotation of the modes leaves every predicted intensity unchanged, so this
    only picks a basis: it does not change the fit.

    With relaxation $\rho$ the modes become $\rho P + (1 - \rho)P'$, that is
    the mixing matrix $\rho I + (1 - \rho) V$, which is no longer unitary.
    The optimizer state is mixed with the same matrix (see `mix_states`).
    For an `OPRProbe` the modes of every frame are orthogonalized separately,
    like `params.OPR_orthogonalize_modes` in the classic `OPR` engine.

    Args:
        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Notes:
        Each eigenvector is fixed only up to a phase, so the result agrees
        with `orthogonalizeModes` up to one phase factor per mode, which no intensity
        sees.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import ProbeModeOrthogonalization

        reconstruction.npsm = 4
        reconstruction.initializeObjectProbe()
        engine = GradientEngine(reconstruction, experimentalData, params, monitor)
        engine.constraints = [ProbeModeOrthogonalization(step=10)]
        engine.reconstruct()
        engine.model.probe.mode_powers()  # (nlambda, npsm), strongest first
        ```
    """

    def apply(self, engine):
        # Shared (nlambda, 1, npsm, 1, Np, Np) or OPR stack with frames first:
        # the mode axis is -4 in both, so an OPR stack is orthogonalized per frame.
        field = engine.model.probe.field
        purities = _orthogonalize_states(engine, field, field.dim() - 4, self.relax)
        if purities:
            # One value per call, the mean over wavelengths (and frames), stored
            # as BaseEngine does; the monitor shows it.
            purity = sum(purities) / len(purities)
            engine.reconstruction.purityProbe = purity
            engine.reconstruction.purityProbeHist.append(purity)

ObjectStateOrthogonalization

Bases: Constraint

Rotate the object states into orthogonal states, strongest first.

The object counterpart of ProbeModeOrthogonalization, as BaseEngine.orthogonalization does for nosm > 1 in the classic engines. For the object states \(O_a\) of each wavelength, over the whole object grid,

\[ G_{ab} = \sum_{\mathbf{x}} O_a^*(\mathbf{x})\,O_b(\mathbf{x}),\qquad O'_b = \sum_a V_{ba} O_a , \]

with \(V = W^T\) from the eigenvectors of \(G\), strongest first. The rotation is unitary over the object states only, so for every probe mode \(m\) the sum \(\sum_a |\mathcal{D}\{O_a P_m\}|^2\), and every prediction, is unchanged. It can therefore run together with ProbeModeOrthogonalization (BaseEngine.orthogonalization orthogonalizes the object only when there is one probe mode). The optimizer state is mixed as in mix_states; relax blends as for the probe modes.

Parameters:

Name Type Description Default
**schedule dict

start, step, end and relax, as in Constraint.

required
Notes

The Gram matrix also counts unlit object pixels, as BaseEngine.orthogonalization does; they hold the start value and change \(\lambda_k\) but not the fit.

Examples:

from PtyLab.Engines.GradientEngine import (
    ObjectStateOrthogonalization,
    ProbeModeOrthogonalization,
)

engine.constraints = [
    ProbeModeOrthogonalization(step=10),
    ObjectStateOrthogonalization(step=10),  # needs nosm > 1
]
Source code in PtyLab/Engines/GradientEngine/constraints.py
class ObjectStateOrthogonalization(Constraint):
    r"""
    Rotate the object states into orthogonal states, strongest first.

    The object counterpart of `ProbeModeOrthogonalization`, as
    `BaseEngine.orthogonalization` does for `nosm > 1` in the classic engines. For the object states
    $O_a$ of each wavelength, over the whole object grid,

    $$
    G_{ab} = \sum_{\mathbf{x}} O_a^*(\mathbf{x})\,O_b(\mathbf{x}),\qquad
    O'_b = \sum_a V_{ba} O_a ,
    $$

    with $V = W^T$ from the eigenvectors of $G$, strongest first. The
    rotation is unitary over the object states only, so for every probe mode
    $m$ the sum $\sum_a |\mathcal{D}\{O_a P_m\}|^2$, and every prediction, is
    unchanged. It can therefore run together with
    `ProbeModeOrthogonalization` (`BaseEngine.orthogonalization` orthogonalizes
    the object only when there is one probe mode). The optimizer state is mixed as in
    `mix_states`; `relax` blends as for the probe modes.

    Args:
        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Notes:
        The Gram matrix also counts unlit object pixels, as
        `BaseEngine.orthogonalization` does;
        they hold the start value and change $\lambda_k$ but not the fit.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import (
            ObjectStateOrthogonalization,
            ProbeModeOrthogonalization,
        )

        engine.constraints = [
            ProbeModeOrthogonalization(step=10),
            ObjectStateOrthogonalization(step=10),  # needs nosm > 1
        ]
        ```
    """

    def apply(self, engine):
        obj = engine.model.object  # (nlambda, nosm, 1, 1, No, No)
        purities = _orthogonalize_states(engine, obj, 1, self.relax)
        if purities:
            # The mean over wavelengths, as ProbeModeOrthogonalization stores it.
            engine.reconstruction.purityObject = sum(purities) / len(purities)

AbsorbingProbeBoundary

Bases: Constraint

Damp the probe towards the edge of its window, akin to Params.absorbingProbeBoundary.

Each call multiplies every probe mode by

\[ P \leftarrow \big[(1 - a) + a\,W(\mathbf{r})\big]\,P, \qquad W(\mathbf{r}) = \exp\left[-\left(\frac{|\mathbf{r}|^2}{2\sigma^2}\right)^{10}\right], \qquad \sigma = \frac{3}{4}\,\frac{N_p}{2.355}, \]

with \(\mathbf{r}\) in pixels on the probe grid of Reconstruction.xp (linspace(-Np/2, Np/2, Np)) and \(a\) = aleph. \(W\) is the super-Gaussian window of BaseEngine._probeWindow: about 1 out to \(0.4\,N_p\) from the centre and 0 beyond \(0.5\,N_p\), so light near the window edges and corners decays by \(1 - a\) per call while the beam is untouched.

Probe light far from the beam reaches object pixels nothing else lights. Such a pair is free to fit diffuse intensity, so without this constraint a weak mode can drift to the window corners.

The factor is real and positive per pixel, so Adam's first moment is scaled by it and the second moment by its square, which keeps the normalized step \(m/\sqrt{v}\) of each pixel unchanged. With relaxation \(\rho\) the factor is \(\rho + (1 - \rho)\big[(1 - a) + a\,W\big]\).

Parameters:

Name Type Description Default
aleph float

Damping \(a\) in \((0, 1]\) per call, as Params.absorbingProbeBoundaryAleph. Defaults to 0.05.

0.05
**schedule dict

start, step, end and relax, as in Constraint.

{}

Raises:

Type Description
ValueError

If aleph is not in \((0, 1]\).

Examples:

from PtyLab.Engines.GradientEngine import AbsorbingProbeBoundary

engine.constraints = [AbsorbingProbeBoundary(aleph=0.05)]
Source code in PtyLab/Engines/GradientEngine/constraints.py
class AbsorbingProbeBoundary(Constraint):
    r"""
    Damp the probe towards the edge of its window, akin to
    `Params.absorbingProbeBoundary`.

    Each call multiplies every probe mode by

    $$
    P \leftarrow \big[(1 - a) + a\,W(\mathbf{r})\big]\,P, \qquad
    W(\mathbf{r}) = \exp\left[-\left(\frac{|\mathbf{r}|^2}{2\sigma^2}\right)^{10}\right], \qquad
    \sigma = \frac{3}{4}\,\frac{N_p}{2.355},
    $$

    with $\mathbf{r}$ in pixels on the probe grid of `Reconstruction.xp`
    (`linspace(-Np/2, Np/2, Np)`) and $a$ = `aleph`. $W$ is the
    super-Gaussian window of `BaseEngine._probeWindow`: about 1 out to
    $0.4\,N_p$ from the centre and 0 beyond $0.5\,N_p$, so light near the
    window edges and corners decays by $1 - a$ per call while the beam is
    untouched.

    Probe light far from the beam reaches object pixels nothing else lights.
    Such a pair is free to fit diffuse intensity, so without this constraint
    a weak mode can drift to the window corners.

    The factor is real and positive per pixel, so Adam's first moment is
    scaled by it and the second moment by its square, which keeps the
    normalized step $m/\sqrt{v}$ of each pixel unchanged. With relaxation
    $\rho$ the factor is $\rho + (1 - \rho)\big[(1 - a) + a\,W\big]$.

    Args:
        aleph (float, optional):
            Damping $a$ in $(0, 1]$ per call, as
            `Params.absorbingProbeBoundaryAleph`. Defaults to 0.05.

        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Raises:
        ValueError:
            If `aleph` is not in $(0, 1]$.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import AbsorbingProbeBoundary

        engine.constraints = [AbsorbingProbeBoundary(aleph=0.05)]
        ```
    """

    def __init__(self, aleph=0.05, **schedule):
        super().__init__(**schedule)
        if isinstance(aleph, bool) or not isinstance(aleph, Real) or not 0 < aleph <= 1:
            raise ValueError("aleph must lie in (0, 1].")
        self.aleph = float(aleph)

    @staticmethod
    def window(size, device=None, dtype=torch.float32):
        r"""
        Return an absorbing-boundary window $W$ for an `size`^2 probe.

        Args:
            size (int):
                Probe pixels per side, $N_p$.

            device (torch.device or str, optional):
                Device of the result.

            dtype (torch.dtype, optional):
                Real dtype of the result. Defaults to `torch.float32`.

        Returns:
            torch.Tensor:
                $W$ of shape `(size, size)`.
        """
        # In pixels dxp cancels: |r|^2 / (2 sigma^2) with r on Reconstruction.xp's linspace grid.
        x = torch.linspace(
            -size / 2, size / 2, size, device=device, dtype=torch.float64
        )
        sigma = 3 / 4 * size / 2.355
        radius2 = x[:, None] ** 2 + x[None, :] ** 2
        return torch.exp(-((radius2 / (2 * sigma**2)) ** 10)).to(dtype)

    def apply(self, engine):
        field = engine.model.probe.field  # (nlambda, 1, npsm, 1, Np, Np)
        W = self.window(field.shape[-1], field.device, field.real.dtype)
        factor = self.relax + (1 - self.relax) * ((1 - self.aleph) + self.aleph * W)
        field.mul_(factor)
        for key, value in _moments(engine, field).items():
            # m scales like P; v (real and imaginary parts) like |P|^2.
            value.mul_(factor**2 if key in ("exp_avg_sq", "max_exp_avg_sq") else factor)

window(size, device=None, dtype=torch.float32) staticmethod

Return an absorbing-boundary window \(W\) for an size^2 probe.

Parameters:

Name Type Description Default
size int

Probe pixels per side, \(N_p\).

required
device device or str

Device of the result.

None
dtype dtype

Real dtype of the result. Defaults to torch.float32.

float32

Returns:

Type Description
Tensor

\(W\) of shape (size, size).

Source code in PtyLab/Engines/GradientEngine/constraints.py
@staticmethod
def window(size, device=None, dtype=torch.float32):
    r"""
    Return an absorbing-boundary window $W$ for an `size`^2 probe.

    Args:
        size (int):
            Probe pixels per side, $N_p$.

        device (torch.device or str, optional):
            Device of the result.

        dtype (torch.dtype, optional):
            Real dtype of the result. Defaults to `torch.float32`.

    Returns:
        torch.Tensor:
            $W$ of shape `(size, size)`.
    """
    # In pixels dxp cancels: |r|^2 / (2 sigma^2) with r on Reconstruction.xp's linspace grid.
    x = torch.linspace(
        -size / 2, size / 2, size, device=device, dtype=torch.float64
    )
    sigma = 3 / 4 * size / 2.355
    radius2 = x[:, None] ** 2 + x[None, :] ** 2
    return torch.exp(-((radius2 / (2 * sigma**2)) ** 10)).to(dtype)

OPRProjection

Bases: Constraint

Keep a per-frame probe stack low rank (orthogonal probe relaxation).

For each wavelength and probe mode, the frame probes are the rows of \(A\) (\(A_{j\mathbf{r}} = P_j(\mathbf{r})\), \(J\) frames). With the eigenvectors \(V\) of the small Gram matrix \(G = AA^\dagger\) (see frame_modes), the closest rank-\(K\) stack is

\[ A_K = V_K V_K^\dagger A = \sum_{k=1}^{K} v_k\,(\sigma_k u_k^\dagger), \]

so every frame probe becomes a combination of \(K\) shared patterns \(\sigma_k u_k^\dagger\) with frame coefficients \(v_{jk}\). With relaxation \(\rho\) the stack becomes \(\rho A + (1 - \rho) A_K\); \(\rho\) plays the role of params.OPR_alpha of the classic OPR engine (0.05 there). It needs an OPRProbe (GradientEngine.relaxProbe).

Adam's moments are left as they are: the projection removes the directions outside the subspace, and the next step starts from there.

Parameters:

Name Type Description Default
rank int

Number \(K\) of kept components, like params.OPR_subspace. Defaults to 4.

4
**schedule dict

start, step, end and relax, as in Constraint.

{}

Raises:

Type Description
ValueError

If rank is not a positive integer.

Examples:

from PtyLab.Engines.GradientEngine import OPRProjection

engine.relaxProbe()  # one probe per frame, from the shared probe
engine.constraints = [OPRProjection(rank=4, relax=0.05)]
engine.reconstruct()
Source code in PtyLab/Engines/GradientEngine/constraints.py
class OPRProjection(Constraint):
    r"""
    Keep a per-frame probe stack low rank (orthogonal probe relaxation).

    For each wavelength and probe mode, the frame probes are the rows of
    $A$ ($A_{j\mathbf{r}} = P_j(\mathbf{r})$, $J$ frames). With the
    eigenvectors $V$ of the small Gram matrix $G = AA^\dagger$ (see
    `frame_modes`), the closest rank-$K$ stack is

    $$
    A_K = V_K V_K^\dagger A = \sum_{k=1}^{K} v_k\,(\sigma_k u_k^\dagger),
    $$

    so every frame probe becomes a combination of $K$ shared patterns
    $\sigma_k u_k^\dagger$ with frame coefficients $v_{jk}$. With
    relaxation $\rho$ the stack becomes $\rho A + (1 - \rho) A_K$; $\rho$
    plays the role of `params.OPR_alpha` of the classic `OPR` engine (0.05
    there). It needs an `OPRProbe` (`GradientEngine.relaxProbe`).

    Adam's moments are left as they are: the projection removes the
    directions outside the subspace, and the next step starts from there.

    Args:
        rank (int, optional):
            Number $K$ of kept components, like `params.OPR_subspace`.
            Defaults to 4.

        **schedule (dict):
            `start`, `step`, `end` and `relax`, as in `Constraint`.

    Raises:
        ValueError:
            If `rank` is not a positive integer.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import OPRProjection

        engine.relaxProbe()  # one probe per frame, from the shared probe
        engine.constraints = [OPRProjection(rank=4, relax=0.05)]
        engine.reconstruct()
        ```
    """

    def __init__(self, rank=4, **schedule):
        super().__init__(**schedule)
        if isinstance(rank, bool) or not isinstance(rank, Integral) or rank < 1:
            raise ValueError("rank must be a positive integer.")
        self.rank = rank

    def apply(self, engine):
        probe = engine.model.probe
        if not isinstance(probe, OPRProbe):
            raise TypeError(
                "OPRProjection needs an OPRProbe; call engine.relaxProbe()."
            )
        field = probe.field  # (J, nlambda, 1, npsm, 1, Np, Np)
        if self.rank >= field.shape[0]:
            return  # every stack of J frames has rank <= J
        # One wavelength and mode at a time keeps the extra memory to one mode.
        for wavelength in range(field.shape[1]):
            for mode in range(field.shape[3]):
                frames = field[:, wavelength, 0, mode, 0]  # (J, Np, Np), a view
                rows = frames.flatten(-2)  # A: (J, N)
                _, V = frame_modes(rows)
                V = V[:, : self.rank]  # (J, K), strongest first
                low_rank = V @ (V.conj().T @ rows)  # A_K = V_K V_K^† A
                # rho A + (1 - rho) A_K, in place to keep one extra copy of A.
                low_rank.mul_(1 - self.relax).add_(rows, alpha=self.relax)
                frames.copy_(low_rank.view(frames.shape))

roll_parameter(engine, parameter, shifts)

Roll a parameter and its optimizer state over the last two axes.

Parameters:

Name Type Description Default
engine GradientEngine

Engine whose optimizer holds the state.

required
parameter Tensor

Parameter rolled in place.

required
shifts tuple

(rows, columns) shift in pixels.

required
Source code in PtyLab/Engines/GradientEngine/constraints.py
def roll_parameter(engine, parameter, shifts):
    """
    Roll a parameter and its optimizer state over the last two axes.

    Args:
        engine (GradientEngine):
            Engine whose optimizer holds the state.

        parameter (torch.Tensor):
            Parameter rolled in place.

        shifts (tuple):
            `(rows, columns)` shift in pixels.
    """
    parameter.copy_(torch.roll(parameter, shifts, dims=(-2, -1)))
    for value in _moments(engine, parameter).values():
        value.copy_(torch.roll(value, shifts, dims=(-2, -1)))

multiply_parameter(engine, parameter, factor)

Multiply a complex parameter and its optimizer state by a unit-modulus factor.

First moments (Adam exp_avg, SGD momentum_buffer) rotate with the parameter exactly. Adam's exp_avg_sq holds separate real and imaginary second moments, which a rotation mixes; both are replaced by their mean, the rotation-invariant part.

Parameters:

Name Type Description Default
engine GradientEngine

Engine whose optimizer holds the state.

required
parameter Tensor

Complex parameter multiplied in place.

required
factor Tensor or complex

Unit-modulus factor, broadcastable to parameter.

required
Source code in PtyLab/Engines/GradientEngine/constraints.py
def multiply_parameter(engine, parameter, factor):
    """
    Multiply a complex parameter and its optimizer state by a unit-modulus factor.

    First moments (Adam `exp_avg`, SGD `momentum_buffer`) rotate with the
    parameter exactly. Adam's `exp_avg_sq` holds separate real and imaginary
    second moments, which a rotation mixes; both are replaced by their mean,
    the rotation-invariant part.

    Args:
        engine (GradientEngine):
            Engine whose optimizer holds the state.

        parameter (torch.Tensor):
            Complex parameter multiplied in place.

        factor (torch.Tensor or complex):
            Unit-modulus factor, broadcastable to `parameter`.
    """
    parameter.mul_(factor)
    for key, value in _moments(engine, parameter).items():
        if key in ("exp_avg_sq", "max_exp_avg_sq") and value.is_complex():
            mean = 0.5 * (value.real + value.imag)
            value.copy_(torch.complex(mean, mean))
        else:
            value.mul_(factor)

snapshot_basis(states)

Return the snapshot orthogonalization of a set of states.

For states \(S_m\) (rows of states) it diagonalizes the Gram matrix

\[ G_{mn} = \sum_{\mathbf{r}} S_m^*(\mathbf{r})\,S_n(\mathbf{r}) = \sum_k W_{mk}\,\lambda_k\,W^*_{nk}, \]

sorts \(\lambda_1 \geq \lambda_2 \geq \ldots\) and returns \(V = W^T\), as PtyLab.utils.utils.orthogonalizeModes(..., method="snapShots"). The states \(S'_n = \sum_m V_{nm} S_m\) are orthogonal with powers \(\lambda_n\).

Parameters:

Name Type Description Default
states Tensor

Complex tensor of shape (..., n, pixels); leading axes are batched.

required

Returns:

Type Description
tuple

(V, eigenvalues) of shapes (..., n, n) and (..., n).

Source code in PtyLab/Engines/GradientEngine/constraints.py
def snapshot_basis(states):
    r"""
    Return the snapshot orthogonalization of a set of states.

    For states $S_m$ (rows of `states`) it diagonalizes the Gram matrix

    $$
    G_{mn} = \sum_{\mathbf{r}} S_m^*(\mathbf{r})\,S_n(\mathbf{r}) = \sum_k W_{mk}\,\lambda_k\,W^*_{nk},
    $$

    sorts $\lambda_1 \geq \lambda_2 \geq \ldots$ and returns $V = W^T$, as
    `PtyLab.utils.utils.orthogonalizeModes(..., method="snapShots")`. The states
    $S'_n = \sum_m V_{nm} S_m$ are orthogonal with powers $\lambda_n$.

    Args:
        states (torch.Tensor):
            Complex tensor of shape `(..., n, pixels)`; leading axes are
            batched.

    Returns:
        tuple:
            `(V, eigenvalues)` of shapes `(..., n, n)` and `(..., n)`.
    """
    # G = conj(S) S^T as in orthogonalizeModes; eigh in double precision, since weak
    # states have eigenvalues many orders below the strongest.
    gram = (states.conj() @ states.transpose(-2, -1)).to(torch.complex128)
    eigenvalues, W = torch.linalg.eigh(gram)
    order = eigenvalues.argsort(dim=-1, descending=True)  # strongest first
    eigenvalues = eigenvalues.gather(-1, order)
    W = W.gather(-1, order.unsqueeze(-2).expand_as(W))
    # V = W^T: row n holds the weights of the new state n.
    return W.transpose(-2, -1).to(states.dtype), eigenvalues

mix_states(engine, parameter, dim, matrix)

Replace the states along one axis by linear combinations of them.

\[ S'_n = \sum_m M_{nm} S_m , \]

and the same for the optimizer state. First moments (Adam exp_avg) mix exactly like the states. Adam's second moments (exp_avg_sq, real and imaginary parts separately) cannot be mixed linearly; they become \(v'_n = \sum_m |M_{nm}|^2 v_m\), which is exact if the gradients of different states are uncorrelated.

Parameters:

Name Type Description Default
engine GradientEngine

Engine whose optimizer holds the state.

required
parameter Tensor

Parameter changed in place, for example the probe (nlambda, 1, npsm, 1, Np, Np) with dim=2 or the object (nlambda, nosm, 1, 1, No, No) with dim=1.

required
dim int

State axis.

required
matrix Tensor

Complex mixing matrix \(M\) of shape (*parameter.shape[:dim], n, n): one matrix per index of the axes before dim.

required
Source code in PtyLab/Engines/GradientEngine/constraints.py
def mix_states(engine, parameter, dim, matrix):
    r"""
    Replace the states along one axis by linear combinations of them.

    $$
    S'_n = \sum_m M_{nm} S_m ,
    $$

    and the same for the optimizer state. First moments (Adam `exp_avg`)
    mix exactly like the states. Adam's second moments (`exp_avg_sq`, real
    and imaginary parts separately) cannot be mixed linearly; they become
    $v'_n = \sum_m |M_{nm}|^2 v_m$, which is exact if the gradients of
    different states are uncorrelated.

    Args:
        engine (GradientEngine):
            Engine whose optimizer holds the state.

        parameter (torch.Tensor):
            Parameter changed in place, for example the probe
            `(nlambda, 1, npsm, 1, Np, Np)` with `dim=2` or the object
            `(nlambda, nosm, 1, 1, No, No)` with `dim=1`.

        dim (int):
            State axis.

        matrix (torch.Tensor):
            Complex mixing matrix $M$ of shape `(*parameter.shape[:dim], n, n)`:
            one matrix per index of the axes before `dim`.
    """

    def mix(tensor, weights):
        # (*batch, n, ...) -> (*batch, n, rest): mix rows, write back in place.
        flat = tensor.reshape(*tensor.shape[: dim + 1], -1)
        tensor.copy_((weights @ flat).reshape(tensor.shape))

    mix(parameter, matrix)
    for key, value in _moments(engine, parameter).items():
        if key in ("exp_avg_sq", "max_exp_avg_sq"):
            # Real weights |M|^2 act on the real and imaginary parts alike.
            mix(value, matrix.abs().square().to(value.dtype))
        else:
            mix(value, matrix.to(value.dtype))

Phases

Reconstruction phases: ordered optimizer settings for GradientEngine.reconstruct(phases=...).

Phase dataclass

One stretch of a reconstruction with fixed optimizer settings.

The phase runs with a fresh optimizer, starting from the estimates the previous phase left. Every optional field left at None keeps the engine's own setting.

Parameters:

Name Type Description Default
iterations int

Number of full-scan iterations.

required
parameters Mapping

Parameter selection with learning rates, as engine.parameters.

None
optimizerType str

"adam" or "preconditioned", as engine.optimizerType.

None
lossFunction callable

Loss function, as engine.lossFunction.

None
constraints Sequence

Constraints applied after every step, as engine.constraints.

None
readoutSigma float or array_like

Readout noise handed to the loss, as engine.readoutSigma.

None
name str

Label of the phase in the history that reconstruct returns. Defaults to "".

''

Examples:

from PtyLab.Engines.GradientEngine import Phase, ProbeCentering, poisson_loss

phase = Phase(
    500,
    {"object": {"lr": 0.03}, "probe": {"lr": 0.1}},
    lossFunction=poisson_loss,
    constraints=[ProbeCentering()],
    name="poisson",
)
engine.reconstruct(phases=[phase])
Source code in PtyLab/Engines/GradientEngine/phases.py
@dataclass
class Phase:
    """
    One stretch of a reconstruction with fixed optimizer settings.

    The phase runs with a fresh optimizer, starting from the estimates the
    previous phase left. Every optional field left at None keeps the engine's
    own setting.

    Args:
        iterations (int):
            Number of full-scan iterations.

        parameters (Mapping, optional):
            Parameter selection with learning rates, as `engine.parameters`.

        optimizerType (str, optional):
            `"adam"` or `"preconditioned"`, as `engine.optimizerType`.

        lossFunction (callable, optional):
            Loss function, as `engine.lossFunction`.

        constraints (Sequence, optional):
            Constraints applied after every step, as `engine.constraints`.

        readoutSigma (float or array_like, optional):
            Readout noise handed to the loss, as `engine.readoutSigma`.

        name (str, optional):
            Label of the phase in the history that `reconstruct` returns.
            Defaults to `""`.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import Phase, ProbeCentering, poisson_loss

        phase = Phase(
            500,
            {"object": {"lr": 0.03}, "probe": {"lr": 0.1}},
            lossFunction=poisson_loss,
            constraints=[ProbeCentering()],
            name="poisson",
        )
        engine.reconstruct(phases=[phase])
        ```
    """

    iterations: int
    parameters: Optional[Mapping[str, Mapping[str, Any]]] = None
    optimizerType: Optional[str] = None
    lossFunction: Optional[Callable] = None
    constraints: Optional[Sequence[Callable]] = None
    readoutSigma: Optional[Any] = None
    name: str = ""

    def settings(self):
        """
        Return the engine attribute values this phase sets.

        Returns:
            dict:
                Values keyed by engine attribute name, for the fields that are
                not None.
        """
        return {
            attribute: getattr(self, name)
            for name, attribute in _SETTINGS.items()
            if getattr(self, name) is not None
        }

settings()

Return the engine attribute values this phase sets.

Returns:

Type Description
dict

Values keyed by engine attribute name, for the fields that are not None.

Source code in PtyLab/Engines/GradientEngine/phases.py
def settings(self):
    """
    Return the engine attribute values this phase sets.

    Returns:
        dict:
            Values keyed by engine attribute name, for the fields that are
            not None.
    """
    return {
        attribute: getattr(self, name)
        for name, attribute in _SETTINGS.items()
        if getattr(self, name) is not None
    }

blind_recipe(iterations=1000, lossFunction=None, start_fraction=0.2, object_lr=0.03, probe_lr=0.1, start_lr=0.3, constraints=None, readoutSigma=None)

Build two phases that recover object and probe from a flat start.

  1. A fraction start_fraction of the iterations runs PIE-style preconditioned descent on the plain amplitude loss, with object and probe at start_lr, and without readout noise. This finds the right basin from a generic circ probe.
  2. Adam on lossFunction runs for the rest, with object rate object_lr and scale-free probe rate probe_lr, and readout noise readoutSigma.

The arguments named like engine attributes (lossFunction, constraints, readoutSigma) set those attributes; the others are the recipe's own.

Parameters:

Name Type Description Default
iterations int

Total number of full-scan iterations. Defaults to 1000.

1000
lossFunction callable

Loss of the Adam phase. If None, the engine's loss is kept.

None
start_fraction float

Fraction of the iterations in the preconditioned phase, in \((0, 1)\). Defaults to 0.2.

0.2
object_lr float

Adam learning rate of the object. Defaults to 0.03.

0.03
probe_lr float

Scale-free Adam learning rate of the probe. Defaults to 0.1.

0.1
start_lr float

Preconditioned step size of object and probe. Defaults to 0.3.

0.3
constraints Sequence

Constraints of both phases. If None, the engine's are kept.

None
readoutSigma float or array_like

Readout noise \(\sigma\) of the Adam phase, set as engine.readoutSigma: a scalar for every pixel, or one \((N_p, N_p)\) map in centered order, for example dark.std(axis=0) of dark frames whose mean is subtracted from the data, in the units of the data. If None, the Adam phase keeps engine.readoutSigma.

None
Notes

The start always runs with \(\sigma = 0\). On measured data with the background in the model, a shifted amplitude start (\(c = 3/8 + \sigma^2\)) made the probe collapse in a following shifted Poisson phase; the plain start did not, and was as good or better on simulated data.

Returns:

Type Description
list

The two Phase objects, for GradientEngine.reconstruct(phases=...).

Raises:

Type Description
ValueError

If start_fraction is outside \((0, 1)\) or iterations is too small for two phases.

Examples:

from PtyLab.Engines.GradientEngine import ProbeCentering, blind_recipe

phases = blind_recipe(1000, constraints=[ProbeCentering()])
[phase.iterations for phase in phases]  # [200, 800]
engine.reconstruct(phases=phases)
Source code in PtyLab/Engines/GradientEngine/phases.py
def blind_recipe(
    iterations=1000,
    lossFunction=None,
    start_fraction=0.2,
    object_lr=0.03,
    probe_lr=0.1,
    start_lr=0.3,
    constraints=None,
    readoutSigma=None,
):
    r"""
    Build two phases that recover object and probe from a flat start.

    1. A fraction `start_fraction` of the iterations runs PIE-style
       preconditioned descent on the plain amplitude loss, with object and
       probe at `start_lr`, and without readout noise. This finds the right
       basin from a generic `circ` probe.
    2. Adam on `lossFunction` runs for the rest, with object rate `object_lr`
       and scale-free probe rate `probe_lr`, and readout noise `readoutSigma`.

    The arguments named like engine attributes (`lossFunction`, `constraints`,
    `readoutSigma`) set those attributes; the others are the recipe's own.

    Args:
        iterations (int, optional):
            Total number of full-scan iterations. Defaults to 1000.

        lossFunction (callable, optional):
            Loss of the Adam phase. If None, the engine's loss is kept.

        start_fraction (float, optional):
            Fraction of the iterations in the preconditioned phase, in
            $(0, 1)$. Defaults to 0.2.

        object_lr (float, optional):
            Adam learning rate of the object. Defaults to 0.03.

        probe_lr (float, optional):
            Scale-free Adam learning rate of the probe. Defaults to 0.1.

        start_lr (float, optional):
            Preconditioned step size of object and probe. Defaults to 0.3.

        constraints (Sequence, optional):
            Constraints of both phases. If None, the engine's are kept.

        readoutSigma (float or array_like, optional):
            Readout noise $\sigma$ of the Adam phase, set as
            `engine.readoutSigma`: a scalar for every pixel, or one
            $(N_p, N_p)$ map in centered order, for example
            `dark.std(axis=0)` of dark frames whose mean is subtracted from
            the data, in the units of the data. If None, the Adam phase keeps
            `engine.readoutSigma`.

    Notes:
        The start always runs with $\sigma = 0$. On measured data with the
        background in the model, a shifted amplitude start
        ($c = 3/8 + \sigma^2$) made the probe collapse in a following shifted
        Poisson phase; the plain start did not, and was as good or better on
        simulated data.

    Returns:
        list:
            The two `Phase` objects, for `GradientEngine.reconstruct(phases=...)`.

    Raises:
        ValueError:
            If `start_fraction` is outside $(0, 1)$ or `iterations` is too small
            for two phases.

    Examples:
        ```python
        from PtyLab.Engines.GradientEngine import ProbeCentering, blind_recipe

        phases = blind_recipe(1000, constraints=[ProbeCentering()])
        [phase.iterations for phase in phases]  # [200, 800]
        engine.reconstruct(phases=phases)
        ```
    """
    if not 0 < start_fraction < 1:
        raise ValueError("start_fraction must lie in (0, 1).")
    start = max(1, round(start_fraction * iterations))
    if start >= iterations:
        raise ValueError("iterations is too small for two phases.")
    return [
        Phase(
            start,
            {"object": {"lr": start_lr}, "probe": {"lr": start_lr}},
            optimizerType="preconditioned",
            lossFunction=amplitude_loss,
            constraints=constraints,
            # Plain amplitude has no readout term; 0 overrides engine.readoutSigma.
            readoutSigma=0.0,
            name="preconditioned amplitude start",
        ),
        Phase(
            iterations - start,
            {"object": {"lr": object_lr}, "probe": {"lr": probe_lr}},
            optimizerType="adam",
            lossFunction=lossFunction,
            constraints=constraints,
            readoutSigma=readoutSigma,
            name="adam",
        ),
    ]

Batching

Batching of GradientEngine iterations: where the measurements live, how a scan is split into batches, how each batch's frames reach the device, and the largest batch that fits a CUDA memory budget.

MeasurementLoader

Yields the measured frames of index batches on the model's device.

Device-resident data are indexed directly. Host-resident data for a CUDA run are pinned once, gathered into one of two pinned buffers and copied on a side stream; the copy of the next batch overlaps the computation on the current one.

Parameters:

Name Type Description Default
data Tensor

Measurements of shape (frames, Np, Np), on device or the host.

required
device str or device

Device of the model.

required

Attributes:

Name Type Description
data Tensor

The measurements, pinned if they stay on the host of a CUDA run.

Source code in PtyLab/Engines/GradientEngine/batching.py
class MeasurementLoader:
    """
    Yields the measured frames of index batches on the model's device.

    Device-resident data are indexed directly. Host-resident data for a CUDA
    run are pinned once, gathered into one of two pinned buffers and copied on
    a side stream; the copy of the next batch overlaps the computation on the
    current one.

    Args:
        data (torch.Tensor):
            Measurements of shape `(frames, Np, Np)`, on `device` or the host.

        device (str or torch.device):
            Device of the model.

    Attributes:
        data (torch.Tensor):
            The measurements, pinned if they stay on the host of a CUDA run.
    """

    def __init__(self, data, device):
        self.device = torch.device(device)
        self.onDevice = data.device == torch.empty(0, device=self.device).device
        if not self.onDevice and self.device.type == "cuda":
            data = data.pin_memory()
        self.data = data
        self._buffers = None
        self._stream = None

    def __call__(self, batches):
        """
        Yield the measured frames of each index batch on `device`, in order.

        Args:
            batches (Sequence):
                Index tensors, one per batch.

        Yields:
            torch.Tensor:
                Measured frames of each batch.
        """
        data, device = self.data, self.device
        if self.onDevice:
            for batch in batches:
                yield data[batch]
            return
        host_batches = [batch.cpu() for batch in batches]
        if device.type != "cuda":
            for batch in host_batches:
                yield data[batch].to(device)
            return
        # Two buffers sized for the largest batch: one is filled on the host
        # while the other's copy is still in flight.
        largest = max(len(batch) for batch in host_batches)
        if self._buffers is None or self._buffers[0].shape[0] < largest:
            shape = (largest,) + tuple(data.shape[1:])
            self._buffers = [
                torch.empty(shape, dtype=data.dtype, pin_memory=True) for _ in range(2)
            ]
            self._stream = torch.cuda.Stream(device)
        buffers, stream = self._buffers, self._stream
        copies = [None, None]

        def start(position):
            slot = position % 2
            if copies[slot] is not None:
                copies[slot][1].synchronize()  # the buffer's last copy is done
            host = buffers[slot][: len(host_batches[position])]
            torch.index_select(data, 0, host_batches[position], out=host)
            with torch.cuda.stream(stream):
                copy = host.to(device, non_blocking=True)
                event = torch.cuda.Event()
                event.record(stream)
            copies[slot] = (copy, event)
            return copies[slot]

        pending = start(0)
        for position in range(len(host_batches)):
            copy, event = pending
            if position + 1 < len(host_batches):
                pending = start(position + 1)
            current = torch.cuda.current_stream(device)
            current.wait_event(event)
            # The copy was allocated on the side stream; keep its memory alive
            # until the compute stream is done with it.
            copy.record_stream(current)
            yield copy

__call__(batches)

Yield the measured frames of each index batch on device, in order.

Parameters:

Name Type Description Default
batches Sequence

Index tensors, one per batch.

required

Yields:

Type Description
Tensor

Measured frames of each batch.

Source code in PtyLab/Engines/GradientEngine/batching.py
def __call__(self, batches):
    """
    Yield the measured frames of each index batch on `device`, in order.

    Args:
        batches (Sequence):
            Index tensors, one per batch.

    Yields:
        torch.Tensor:
            Measured frames of each batch.
    """
    data, device = self.data, self.device
    if self.onDevice:
        for batch in batches:
            yield data[batch]
        return
    host_batches = [batch.cpu() for batch in batches]
    if device.type != "cuda":
        for batch in host_batches:
            yield data[batch].to(device)
        return
    # Two buffers sized for the largest batch: one is filled on the host
    # while the other's copy is still in flight.
    largest = max(len(batch) for batch in host_batches)
    if self._buffers is None or self._buffers[0].shape[0] < largest:
        shape = (largest,) + tuple(data.shape[1:])
        self._buffers = [
            torch.empty(shape, dtype=data.dtype, pin_memory=True) for _ in range(2)
        ]
        self._stream = torch.cuda.Stream(device)
    buffers, stream = self._buffers, self._stream
    copies = [None, None]

    def start(position):
        slot = position % 2
        if copies[slot] is not None:
            copies[slot][1].synchronize()  # the buffer's last copy is done
        host = buffers[slot][: len(host_batches[position])]
        torch.index_select(data, 0, host_batches[position], out=host)
        with torch.cuda.stream(stream):
            copy = host.to(device, non_blocking=True)
            event = torch.cuda.Event()
            event.record(stream)
        copies[slot] = (copy, event)
        return copies[slot]

    pending = start(0)
    for position in range(len(host_batches)):
        copy, event = pending
        if position + 1 < len(host_batches):
            pending = start(position + 1)
        current = torch.cuda.current_stream(device)
        current.wait_event(event)
        # The copy was allocated on the side stream; keep its memory alive
        # until the compute stream is done with it.
        copy.record_stream(current)
        yield copy

data_device(device, requested, nbytes)

Return the device on which measurements of nbytes bytes are kept.

Parameters:

Name Type Description Default
device str or device

Device of the model.

required
requested str or None

The engine's dataDevice. A device of the same type as device means device itself.

required
nbytes int

Size of the measurements in bytes.

required

Returns:

Type Description
device

requested if given, otherwise device unless the data would take more than half of its free CUDA memory, in which case the host.

Source code in PtyLab/Engines/GradientEngine/batching.py
def data_device(device, requested, nbytes):
    """
    Return the device on which measurements of `nbytes` bytes are kept.

    Args:
        device (str or torch.device):
            Device of the model.

        requested (str or None):
            The engine's `dataDevice`. A device of the same type as `device`
            means `device` itself.

        nbytes (int):
            Size of the measurements in bytes.

    Returns:
        torch.device:
            `requested` if given, otherwise `device` unless the data would take
            more than half of its free CUDA memory, in which case the host.
    """
    device = torch.device(device)
    if requested is not None:
        requested = torch.device(requested)
        return device if requested.type == device.type else requested
    if device.type == "cuda":
        free, _ = torch.cuda.mem_get_info(device)
        # Blocks PyTorch has cached but not allocated (such as a previous
        # run's data) are free for these data too.
        free += torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)
        if nbytes > 0.5 * free:
            return torch.device("cpu")
    return device

split_indices(indices, size)

Split frame indices into consecutive batches of size.

Parameters:

Name Type Description Default
indices Tensor

Frame indices of the scan.

required
size int or None

Frames per batch; None keeps the whole scan as one batch.

required

Returns:

Type Description
list

Index tensors, one per batch; the last may be shorter.

Source code in PtyLab/Engines/GradientEngine/batching.py
def split_indices(indices, size):
    """
    Split frame indices into consecutive batches of `size`.

    Args:
        indices (torch.Tensor):
            Frame indices of the scan.

        size (int or None):
            Frames per batch; None keeps the whole scan as one batch.

    Returns:
        list:
            Index tensors, one per batch; the last may be shorter.
    """
    return list(torch.split(indices, len(indices) if size is None else int(size)))

largest_batch_within(budget, frames, peak)

Return the largest batch size whose measured peak fits a memory budget.

peak(size) is evaluated at batch sizes 1, 2, 4, ... until it exceeds budget (an out-of-memory error counts as exceeding it) or the batch holds all frames, then bisected between the last size that fits and the first that does not. The returned size was itself measured, because the peak is not exactly linear in the batch size (allocator rounding).

Parameters:

Name Type Description Default
budget float

Memory budget in bytes.

required
frames int

Frames in the scan, the largest possible batch.

required
peak Callable

Peak bytes of one iteration at a given batch size.

required

Returns:

Type Description
dict

"batch size", its "peak bytes", and "measurements", the peak of every size tried.

Raises:

Type Description
MemoryError

If one frame per batch already exceeds the budget.

Source code in PtyLab/Engines/GradientEngine/batching.py
def largest_batch_within(budget, frames, peak):
    """
    Return the largest batch size whose measured peak fits a memory budget.

    `peak(size)` is evaluated at batch sizes 1, 2, 4, ... until it exceeds
    `budget` (an out-of-memory error counts as exceeding it) or the batch holds
    all `frames`, then bisected between the last size that fits and the first
    that does not. The returned size was itself measured, because the peak is
    not exactly linear in the batch size (allocator rounding).

    Args:
        budget (float):
            Memory budget in bytes.

        frames (int):
            Frames in the scan, the largest possible batch.

        peak (Callable):
            Peak bytes of one iteration at a given batch size.

    Returns:
        dict:
            `"batch size"`, its `"peak bytes"`, and `"measurements"`, the peak
            of every size tried.

    Raises:
        MemoryError:
            If one frame per batch already exceeds the budget.
    """
    measured = {}

    def fits(size):
        if size not in measured:
            try:
                measured[size] = peak(size)
            except torch.OutOfMemoryError:
                torch.cuda.empty_cache()
                measured[size] = float("inf")
        return measured[size] <= budget

    if not fits(1):
        raise MemoryError(
            f"memoryBudget {budget:.4g} B is below the {measured[1]:.4g} B "
            "one frame per batch needs."
        )
    low, high = 1, None
    while high is None and low < frames:
        size = min(2 * low, frames)
        if fits(size):
            low = size
        else:
            high = size
    while high is not None and high - low > 1:
        middle = (low + high) // 2
        if fits(middle):
            low = middle
        else:
            high = middle
    return {
        "batch size": low,
        "peak bytes": measured[low],
        "measurements": dict(sorted(measured.items())),
    }

iteration_peak(engine, batch_size)

Return the peak allocated CUDA bytes of an engine iteration, restoring its state.

Two iterations run and the second is measured: the optimizer state (Adam's moments) is first allocated in the first step, after that iteration's peak, and is resident in every later one. Parameters and optimizer state are restored afterwards; constraints and afterStep do run, and a random position order draws from NumPy's global generator.

Parameters:

Name Type Description Default
engine GradientEngine

A prepared engine on a CUDA device.

required
batch_size int

Frames per batch to measure.

required

Returns:

Type Description
int

Peak bytes, without the copies made here to restore the state.

Source code in PtyLab/Engines/GradientEngine/batching.py
def iteration_peak(engine, batch_size):
    """
    Return the peak allocated CUDA bytes of an engine iteration, restoring its state.

    Two iterations run and the second is measured: the optimizer state (Adam's
    moments) is first allocated in the first step, after that iteration's peak,
    and is resident in every later one. Parameters and optimizer state are
    restored afterwards; constraints and `afterStep` do run, and a random
    position order draws from NumPy's global generator.

    Args:
        engine (GradientEngine):
            A prepared engine on a CUDA device.

        batch_size (int):
            Frames per batch to measure.

    Returns:
        int:
            Peak bytes, without the copies made here to restore the state.
    """
    device = engine.device
    parameters = list(engine.model.parameters())
    saved = [parameter.detach().clone() for parameter in parameters]
    saved_bytes = sum(t.numel() * t.element_size() for t in saved)
    optimizer_state = copy.deepcopy(engine.optimizer.state_dict())
    previous = engine.effectiveBatchSize
    engine.effectiveBatchSize = batch_size
    try:
        engine.runIteration(0)
        torch.cuda.synchronize(device)
        torch.cuda.reset_peak_memory_stats(device)
        engine.runIteration(1)
        torch.cuda.synchronize(device)
        # The copies made above are not part of a normal iteration.
        peak = torch.cuda.max_memory_allocated(device) - saved_bytes
    finally:
        engine.effectiveBatchSize = previous
        with torch.no_grad():
            for parameter, value in zip(parameters, saved):
                parameter.copy_(value)
        engine.optimizer.zero_grad(set_to_none=True)
        engine.optimizer.load_state_dict(optimizer_state)
    return peak