Skip to content

pypty.objective

loss_and_direction

Compute the total loss and gradients for ptychographic reconstruction.

This is the core function of PyPty that performs forward and backward propagation, calculates the loss between measured and simulated patterns, and computes the gradients of all active reconstruction parameters (object, probe, positions, tilts, etc.).

PARAMETER DESCRIPTION
this_obj

Complex 4D object (current estimate)

TYPE: ndarray

full_probe

Complex probe (y,x,modes) optionally 4D (y,x,modes, scenatios)

TYPE: ndarray

this_pos_array

Integer beam postions in pixels [[y0,x0],.. [yn, xn]]. Note: units are pixels, not angstrom!

TYPE: ndarray

this_pos_correction

Float sub-pixel postions for more precise beam shift. Note: units are pixels, not angstrom!

TYPE: ndarray

this_tilt_array

Beam tilts in radians, shape should be (N_measurements, 6), where first two tilts are applied before the sample, second and third are applied inside (tilted propagator) and two last are applied after the sample

TYPE: ndarray

this_tilts_correction

legacy paramter, actually is not really required. It is a correction that is added to the tilts array.

TYPE: ndarray

this_distances

either just one value for a common slice spacing or list of values for each slice. If object has N slices, it should have N-1 entries.

TYPE: ndarray

measured_array

array or h5-dataset with diffraction patterns. Should be 3D, [N_measurements, y,x]

TYPE: ndarray

algorithm_type

string indicating the loss function (error metric)

this_wavelength

Electron wavelength in Angstrom

TYPE: float

this_step_probe

do you refine the beam?

TYPE: float

this_step_obj

do you refine the object?

TYPE: float

this_step_pos_correction

do you refine the positions?

this_step_tilts

do you refine the tilts?

TYPE: float

masks

optional, if the data is compressed, you should provide the 3D array with virtual detectors [N_detectors, y,x].

TYPE: ndarray

pixel_size_x_A

real-space pixel size in x-direction (Angstrom).

TYPE: float

pixel_size_y_A

real-space pixel size in y-direction (Angstrom).

TYPE: float

recon_type

"far_field" or "near_field". Changes the exit-wave propagation regime.

TYPE: string

Cs

Spherical aberration (Angstrom). Only needed for near-field propagation.

TYPE: float

defocus_array

Array of exit-wave defocus values (Angstrom). Only needed for near-field propagation.

TYPE: ndarray

alpha_near_field

Flux-preserving correction for near-field propagation.

TYPE: float

damping_cutoff_multislice

Cutoff (fraction smaller than 1) beyond which the Fouirer-space is cleaned.

TYPE: float

smooth_rolloff

Smooth rolloff for Fourier masking

TYPE: float

propmethod

string indicating the method for split-step integration

TYPE: string

this_chopped_sequence

sequence of measruement indices used for loss and grad calculation (should be sorted)

TYPE: ndarray

load_one_by_one

boolean flag. should be True for lazy loading.

TYPE: bool

data_multiplier

multiplicative factor applied to data on the fly.

TYPE: int

data_pad

padding factor applied to data on the fly.

TYPE: int

phase_plate_in_h5

path to h5 dataset containing phase plates for each measurement.

TYPE: string

this_loss_weight

weight applied to the main part of the loss

TYPE: float

data_bin

binning factor applied to data on the fly

TYPE: int

data_shift_vector

shift vector in pixels (y,x) applied to data on the fly

TYPE: tuple

upsample_pattern

virtual "decompression" of the data used to enlarge the probe window

TYPE: int

static_background

real-valued array descripting the square root of the static offset on the diffraction patterns.

TYPE: ndarray or float

this_step_static_background

do you refine the static background?

TYPE: float

tilt_mode

flag for tilting

TYPE: int

aberration_marker

TYPE: ndarray

probe_marker

TYPE: ndarray

aberrations_array

TYPE: ndarray

compute_batch

TYPE: int

phase_only_obj

TYPE: bool

beam_current

TYPE: ndarray

this_beam_current_step

TYPE: float

this_step_aberrations_array

TYPE: float

default_float

TYPE: dtype

default_complex

TYPE: dtype

xp

TYPE: module

is_first_epoch

TYPE: bool

scan_size

TYPE: tuple

fast_axis_reg_weight_positions

TYPE: float

slow_axis_reg_weight_positions

TYPE: float

slow_axis_reg_weight_tilts

TYPE: float

current_deformation_reg_weight_positions

TYPE: float

current_deformation_reg_weight_tilts

TYPE: float

fast_axis_reg_weight_tilts

TYPE: float

aperture_mask

TYPE: ndarray

probe_reg_weight

TYPE: float

current_window_weight

TYPE: float

current_window

TYPE: ndarray

phase_norm_weight

TYPE: float

abs_norm_weight

TYPE: float

atv_weight

TYPE: float

atv_q

TYPE: float

atv_p

TYPE: float

mixed_variance_weight

TYPE: float

mixed_variance_sigma

TYPE: float

smart_memory

do you want to prevent memory fragmentation? Makes the reconstrcution slightly slower

TYPE: bool

print_flag

verbodity level

TYPE: int

RETURNS DESCRIPTION
loss

Total loss value.

TYPE: float

sse

Sum of squared errors.

TYPE: float

object_grad

Gradient of the loss with respect to the object.

TYPE: ndarray

probe_grad

Gradient of the loss with respect to the probe.

TYPE: ndarray

pos_grad

Gradient of the loss with respect to scan position corrections.

TYPE: ndarray

tilts_grad

Gradient of the loss with respect to tilts.

TYPE: ndarray

static_background_grad

Gradient of the loss with respect to static background.

TYPE: ndarray

aberrations_array_grad

Gradient of the loss with respect to aberration coefficients.

TYPE: ndarray

beam_current_grad

Gradient of the loss with respect to beam current.

TYPE: ndarray

constraint_contributions

Individual regularization loss terms added to the total loss.

TYPE: list

scatteradd_probe

Adds batched probe updates to their respective positions in the full probe array. This wrapper is needed to support older CuPy version.

PARAMETER DESCRIPTION
full

Full probe gradient array.

TYPE: ndarray

indic

Indices specifying where to add each batch.

TYPE: array_like

batches

Batched gradients to scatter-add.

TYPE: ndarray

scatteradd_abers

Adds batched aberration updates to their respective positions in the full aberration array. This wrapper is needed to support older CuPy version.

PARAMETER DESCRIPTION
full

Full aberration gradient array.

TYPE: ndarray

indic

Indices specifying where to add each batch.

TYPE: array_like

batches

Batched gradients to scatter-add.

TYPE: ndarray

charge_flip

Perform charge-flipping style object regularization to enhance phase and absorption contrast.

PARAMETER DESCRIPTION
a

Complex object to regularize.

TYPE: ndarray

delta_phase

Phase threshold ratio.

TYPE: float DEFAULT: 0.03

delta_abs

Absorption threshold ratio.

TYPE: float DEFAULT: 0.14

beta_phase

Inversion multiplier for low-phase regions.

TYPE: float DEFAULT: -0.95

beta_abs

Inversion multiplier for low-absorption regions.

TYPE: float DEFAULT: -0.95

fancy_sigma

Tuple of atomic-shape gaussian kernel sigmas (for phase, absorption).

TYPE: tuple or None DEFAULT: None

RETURNS DESCRIPTION
ndarray

Regularized complex object.

make_states_orthogonal

Apply Gram-Schmidt orthogonalization to probe modes.

PARAMETER DESCRIPTION
probe_states

Probe array with multiple modes.

TYPE: ndarray

RETURNS DESCRIPTION
ndarray

Orthogonalized probe states.

make_basis_orthogonal

Orthogonalize a set of 1D basis vectors using Gram-Schmidt.

PARAMETER DESCRIPTION
vectors

2D array of vectors to orthogonalize.

TYPE: ndarray

RETURNS DESCRIPTION
ndarray

Orthogonalized basis.

compute_fast_axis_constraint_on_grid

Apply second-order TV regularization along the fast scan axis.

PARAMETER DESCRIPTION
something

Positions or tilts to regularize.

TYPE: ndarray

scan_size

Size of the scan grid.

TYPE: tuple

tv_reg_weight

Regularization weight.

TYPE: float

RETURNS DESCRIPTION
reg_term

Value of the regularization term.

TYPE: float

grad

Gradient of the regularization.

TYPE: ndarray

compute_slow_axis_constraint_on_grid

Apply second-order TV regularization along the slow scan axis.

PARAMETER DESCRIPTION
something

Positions or tilts to regularize.

TYPE: ndarray

scan_size

Size of the scan grid.

TYPE: tuple

tv_reg_weight

Regularization weight.

TYPE: float

RETURNS DESCRIPTION
reg_term

Regularization loss.

TYPE: float

grad

Gradient with respect to the input.

TYPE: ndarray

compute_deformation_constraint_on_grid

Penalize deviations from affine transformations in local scan patches.

PARAMETER DESCRIPTION
something

Grid to regularize (positions or tilts).

TYPE: ndarray

scan_size

Dimensions of the scan.

TYPE: tuple

reg_weight

Regularization weight.

TYPE: float

RETURNS DESCRIPTION
reg_term

Regularization loss.

TYPE: float

grad

Gradient of the loss with respect to the grid.

TYPE: ndarray

compute_full_l1_constraint

Apply L1 norm regularization to the object's phase and absorption.

PARAMETER DESCRIPTION
object

Complex object array.

TYPE: ndarray

abs_norm_weight

Weight for absorption norm.

TYPE: float

phase_norm_weight

Weight for phase norm.

TYPE: float

grad_mask

Mask to restrict gradient computation.

TYPE: ndarray

return_direction

If True, return the gradient.

TYPE: bool

smart_memory

Memory-efficient option.

TYPE: bool

RETURNS DESCRIPTION
reg_term

Regularization loss.

TYPE: float

grad

Gradient if return_direction is True, else None.

TYPE: ndarray or None

compute_window_constraint

Penalize probe values outside a predefined window region in real-space.

PARAMETER DESCRIPTION
to_reg_probe

Complex probe array.

TYPE: ndarray

current_window

Window mask.

TYPE: ndarray

current_window_weight

Weight of the constraint.

TYPE: float

RETURNS DESCRIPTION
reg_term

Window constraint loss.

TYPE: float

reg_grad

Gradient of the loss with respect to the probe.

TYPE: ndarray

compute_probe_constraint

Apply reciprocal space constraint to the probe using an aperture mask. Penalize probe values outside an aperture.

PARAMETER DESCRIPTION
to_reg_probe

Complex probe array.

TYPE: ndarray

aperture

Binary mask or scalar defining aperture radius.

TYPE: ndarray or float

weight

Regularization weight.

TYPE: float

return_direction

If True, return the gradient.

TYPE: bool

RETURNS DESCRIPTION
reg_term

Loss from masked frequency components.

TYPE: float

probe_fft

Gradient of the constraint if requested.

TYPE: ndarray or None

compute_atv_constraint

Apply adaptive total variation (ATV) regularization to the object.

PARAMETER DESCRIPTION
obj

Complex object.

TYPE: ndarray

atv_weight

Regularization weight.

TYPE: float

atv_q

q-norm parameter.

TYPE: float

atv_p

p-norm parameter.

TYPE: float

pixel_size_x_A

Pixel size along x (Å).

TYPE: float

pixel_size_y_A

Pixel size along y (Å).

TYPE: float

atv_grad_mask

Optional gradient mask.

TYPE: ndarray or None

return_direction

If True, return the gradient.

TYPE: bool

smart_memory

If True, use memory-efficient computation.

TYPE: bool

RETURNS DESCRIPTION
reg_term

ATV regularization value.

TYPE: float

dR_dTerm

Gradient with respect to the object.

TYPE: ndarray

compute_missing_wedge_constraint

Enforce missing wedge constraint in 3D reciprocal space.

PARAMETER DESCRIPTION
obj

3D complex object.

TYPE: ndarray

pixel_size_x_A

Pixel size along x (Å).

TYPE: float

pixel_size_y_A

Pixel size along y (Å).

TYPE: float

slice_distance

Slice spacing (Å).

TYPE: float

beta_wedge

Cone sharpness.

TYPE: float

wedge_mu

Regularization weight.

TYPE: float

RETURNS DESCRIPTION
loss_term

Regularization loss.

TYPE: float

grad_obj

Gradient of the loss with respect to the object.

TYPE: ndarray

compute_mixed_object_variance_constraint

Regularize variance across object modes by penalizing their differences.

PARAMETER DESCRIPTION
this_obj

Complex object array with multiple modes.

TYPE: ndarray

weight

Regularization strength.

TYPE: float

sigma

Smoothing kernel width in frequency space.

TYPE: float

return_direction

If True, return the gradient.

TYPE: bool

smart_memory

Use memory-efficient FFT loops.

TYPE: bool

RETURNS DESCRIPTION
reg_term

Mixed variance loss.

TYPE: float

grad

Gradient with respect to the object if return_direction is True.

TYPE: ndarray or None