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,
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:
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 |
required |
monitor
|
Monitor
|
Monitor used to visualize and report reconstruction progress. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
numIterations |
int
|
Full-scan iterations per |
parameters |
Mapping or None
|
Estimated parameters and their optimizer options, as
|
learningRateObject |
float
|
Object learning rate when |
learningRateProbe |
float
|
Scale-free probe learning rate when |
lossFunction |
callable
|
Data objective from |
regularizers |
list
|
Penalties called with the model, added once per full scan. Initialized to an empty list. |
optimizerType |
str
|
|
preconditionerAlpha |
float
|
Regularization \(\alpha\) of the preconditioner, see
|
updatePerBatch |
bool
|
Take one optimizer step per batch instead of one per full scan.
With it, |
constraints |
list
|
In-place operations applied after every optimizer step, each with
its own schedule (see |
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 |
dataDevice |
str or None
|
Where the measurements live. None keeps them on |
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 |
readoutSigma |
float or array_like or None
|
Readout noise \(\sigma\) handed to the loss as |
compile |
bool
|
Compile the loss with |
device |
str
|
Torch device of the model. Initialized to |
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 | |
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
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 | |
preparePropagation()
¶
Create fixed propagation kernels on the selected Torch 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
createModel()
¶
Create the default object and shared-probe component model.
initializeParameters()
¶
Create components once, or move retained components to the run device.
Source code in PtyLab/Engines/GradientEngine/engine.py
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
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
snapshot(stack=True)
¶
Return detached CPU NumPy copies of the current physical parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stack
|
bool
|
With an |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Arrays keyed like the |
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
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 |
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
createOptimizer()
¶
Create a fresh optimizer of optimizerType for the selected parameters.
Source code in PtyLab/Engines/GradientEngine/engine.py
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
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
prepareReconstruction()
¶
Prepare data, retained components, propagation and a fresh optimizer.
Source code in PtyLab/Engines/GradientEngine/engine.py
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
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
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
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
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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
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 |
Source code in PtyLab/Engines/GradientEngine/engine.py
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
regularizationLoss()
¶
Return the sum of the regularization penalties of the current model.
Returns:
| Type | Description |
|---|---|
Tensor or None
|
Sum of the |
Source code in PtyLab/Engines/GradientEngine/engine.py
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
|
required |
Source code in PtyLab/Engines/GradientEngine/engine.py
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
|
required |
Returns:
| Type | Description |
|---|---|
float
|
Full-scan loss of the iteration. |
Source code in PtyLab/Engines/GradientEngine/engine.py
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 |
None
|
Returns:
| Type | Description |
|---|---|
list or None
|
With |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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
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
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 |
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
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
physical_field()
¶
Return the physical probe \(P = sF\).
Returns:
| Type | Description |
|---|---|
Tensor
|
Differentiable physical probe. |
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
mode_powers()
¶
Return the power of each probe mode.
in physical units, so \(\sum_m s_m\) is the total probe power.
Returns:
| Type | Description |
|---|---|
Tensor
|
Detached real powers of shape |
Source code in PtyLab/Engines/GradientEngine/models.py
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
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the shape differs from the parameter's. |
Source code in PtyLab/Engines/GradientEngine/models.py
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,
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
|
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
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 | |
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
mode_powers()
¶
Return the power of each probe mode, averaged over the frames.
Returns:
| Type | Description |
|---|---|
Tensor
|
Detached real powers of shape |
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\),
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
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 |
required |
Source code in PtyLab/Engines/GradientEngine/models.py
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
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 |
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
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 | |
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
set_positions(positions)
¶
Replace the integer patch origins without changing model parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
positions
|
array_like
|
Patch origins of shape |
required |
Source code in PtyLab/Engines/GradientEngine/models.py
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 |
required |
Source code in PtyLab/Engines/GradientEngine/models.py
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
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
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
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
illumination(indices)
¶
Return the probe power that the frames of a batch put on the object.
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 |
Source code in PtyLab/Engines/GradientEngine/models.py
gradient_preconditioners(indices)
¶
Return diagonal curvature maps for PIE-style preconditioning.
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
|
|
Source code in PtyLab/Engines/GradientEngine/models.py
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
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 |
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,
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
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
|
Source code in PtyLab/Engines/GradientEngine/models.py
probe_scale(photons_per_frame, frame_pixels)
¶
Return the probe scale for a mean frame power, rounded to a power of two.
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
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 |
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
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
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
fft2c(field)
staticmethod
¶
Apply a centered, unitary 2D FFT over the last two dimensions.
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 |
Source code in PtyLab/Engines/GradientEngine/propagation.py
ifft2c(field)
staticmethod
¶
Invert fft2c over the last two dimensions.
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 |
Source code in PtyLab/Engines/GradientEngine/propagation.py
__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 ( |
required |
propagator
|
str
|
|
required |
device
|
str or device
|
Device of the kernels. Defaults to |
'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
__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 |
Source code in PtyLab/Engines/GradientEngine/propagation.py
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
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 |
Source code in PtyLab/Engines/GradientEngine/propagation.py
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.
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:
Source code in PtyLab/Engines/GradientEngine/losses.py
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.
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 |
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
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.
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:
\(\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 |
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
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 | |
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.
\(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 |
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
Regularizers¶
Optional penalties on a PtychographyModel state.
object_smoothness(model, weight=0.0001)
¶
Penalize squared differences between neighbouring object pixels.
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 |
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
object_tv(model, weight=0.0001, epsilon=1e-06)
¶
Penalize the isotropic total variation (TV) of the object.
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 |
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 |
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
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,
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
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
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
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the constraint runs at |
Source code in PtyLab/Engines/GradientEngine/constraints.py
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
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
|
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
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 | |
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
|
|
Source code in PtyLab/Engines/GradientEngine/constraints.py
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.0
|
minimum
|
float
|
Lower amplitude bound, or None. Defaults to None. |
None
|
**schedule
|
dict
|
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If both bounds are None, a bound is negative, or |
Examples:
from PtyLab.Engines.GradientEngine import ObjectAmplitudeClamp
engine.constraints = [ObjectAmplitudeClamp(maximum=1.0)] # no gain
Source code in PtyLab/Engines/GradientEngine/constraints.py
AbsorbingObject
¶
Bases: Constraint
Pull the object towards a pure-absorption object, as Params.absObjectSwitch.
Each call blends the object with its modulus,
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 |
0.01
|
**schedule
|
dict
|
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
PhaseRampRemoval
¶
Bases: Constraint
Move a linear phase ramp and a global phase from the object to the probe.
For
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:
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
|
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
Examples:
from PtyLab.Engines.GradientEngine import PhaseRampRemoval, ProbeCentering
engine.constraints = [ProbeCentering(), PhaseRampRemoval(step=10)]
Source code in PtyLab/Engines/GradientEngine/constraints.py
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 | |
weights(engine)
staticmethod
¶
Return the illumination over the whole scan.
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
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
|
|
Source code in PtyLab/Engines/GradientEngine/constraints.py
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,
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
|
|
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
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,
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
|
|
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
AbsorbingProbeBoundary
¶
Bases: Constraint
Damp the probe towards the edge of its window, akin to
Params.absorbingProbeBoundary.
Each call multiplies every probe mode by
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
|
0.05
|
**schedule
|
dict
|
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from PtyLab.Engines.GradientEngine import AbsorbingProbeBoundary
engine.constraints = [AbsorbingProbeBoundary(aleph=0.05)]
Source code in PtyLab/Engines/GradientEngine/constraints.py
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 | |
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 |
float32
|
Returns:
| Type | Description |
|---|---|
Tensor
|
\(W\) of shape |
Source code in PtyLab/Engines/GradientEngine/constraints.py
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
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 |
4
|
**schedule
|
dict
|
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
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
|
|
required |
Source code in PtyLab/Engines/GradientEngine/constraints.py
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 |
required |
Source code in PtyLab/Engines/GradientEngine/constraints.py
snapshot_basis(states)
¶
Return the snapshot orthogonalization of a set of states.
For states \(S_m\) (rows of states) it diagonalizes the Gram matrix
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
|
Source code in PtyLab/Engines/GradientEngine/constraints.py
mix_states(engine, parameter, dim, matrix)
¶
Replace the states along one axis by linear combinations of them.
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
|
required |
dim
|
int
|
State axis. |
required |
matrix
|
Tensor
|
Complex mixing matrix \(M\) of shape |
required |
Source code in PtyLab/Engines/GradientEngine/constraints.py
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 |
None
|
optimizerType
|
str
|
|
None
|
lossFunction
|
callable
|
Loss function, as |
None
|
constraints
|
Sequence
|
Constraints applied after every step, as |
None
|
readoutSigma
|
float or array_like
|
Readout noise handed to the loss, as |
None
|
name
|
str
|
Label of the phase in the history that |
''
|
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
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
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.
- A fraction
start_fractionof the iterations runs PIE-style preconditioned descent on the plain amplitude loss, with object and probe atstart_lr, and without readout noise. This finds the right basin from a genericcircprobe. - Adam on
lossFunctionruns for the rest, with object rateobject_lrand scale-free probe rateprobe_lr, and readout noisereadoutSigma.
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
|
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
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 | |
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 |
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
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 | |
__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
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 |
required |
nbytes
|
int
|
Size of the measurements in bytes. |
required |
Returns:
| Type | Description |
|---|---|
device
|
|
Source code in PtyLab/Engines/GradientEngine/batching.py
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
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
|
|
Raises:
| Type | Description |
|---|---|
MemoryError
|
If one frame per batch already exceeds the budget. |
Source code in PtyLab/Engines/GradientEngine/batching.py
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. |