Skip to content

pypty.initialize

create_pypty_data

Create a PyPty-style .h5 dataset from 4D-STEM data.

PARAMETER DESCRIPTION
data

Path to .h5 or .npy data file or a 4D numpy array [scan_y, scan_x, ky, kx].

TYPE: str or ndarray

path_output

Output file path for the PyPty .h5 dataset.

TYPE: str

swap_axes

Swap the last two axes (kx, ky). Default is False.

TYPE: bool DEFAULT: False

flip_ky

Flip the data along specific axes. Default is False.

TYPE: bool DEFAULT: False

flip_kx

Flip the data along specific axes. Default is False.

TYPE: bool DEFAULT: False

flip_y

Flip the data along specific axes. Default is False.

TYPE: bool DEFAULT: False

flip_x

Flip the data along specific axes. Default is False.

TYPE: bool DEFAULT: False

comcalc_len

Number of patterns to use to estimate center-of-mass. Default is 1000.

TYPE: int DEFAULT: 1000

comx

Predefined center-of-mass. If None, it will be computed.

TYPE: int or None DEFAULT: None

comy

Predefined center-of-mass. If None, it will be computed.

TYPE: int or None DEFAULT: None

bin

Spatial binning factor on the diffraction patterns. Default is 1.

TYPE: int DEFAULT: 1

crop_left

Crop edges of patterns. Defaults are None.

TYPE: int or None DEFAULT: None

crop_right

Crop edges of patterns. Defaults are None.

TYPE: int or None DEFAULT: None

crop_top

Crop edges of patterns. Defaults are None.

TYPE: int or None DEFAULT: None

crop_bottom

Crop edges of patterns. Defaults are None.

TYPE: int or None DEFAULT: None

normalize

Normalize pattern sums to 1. Default is False.

TYPE: bool DEFAULT: False

cutoff_ratio

Mask out pixels farther than cutoff_ratio × max_radius. Default is None.

TYPE: float or None DEFAULT: None

pad_k

Padding to apply to diffraction patterns. Default is 0.

TYPE: int DEFAULT: 0

data_dtype

Output data type. Default is np.float32.

TYPE: dtype DEFAULT: float32

rescale

Scale factor for intensity. Default is 1.

TYPE: float DEFAULT: 1

exist_ok

If True, skip writing if file exists. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
None
Notes

Saves a .h5 file containing processed 4D-STEM data with standardized formatting for PyPty.

append_exp_params

Attach experimental parameters to a PyPty preset dictionary and calibrate an extisting PyPty preset to new data.

PARAMETER DESCRIPTION
experimental_params

Dictionary containing experimental metadata and setup for PyPty reconstruction.

TYPE: dict

pypty_params

Existing PyPty preset to update, a filepath to a preset, or None to create a new one.

TYPE: dict or str or None DEFAULT: None

RETURNS DESCRIPTION
dict

Updated PyPty parameter dictionary.

Notes

experimental_params should contain following entries:

data_path - path to a PyPty-style 3d .h5 file [N_measurements, ky,kx] or .npy Nion-style 4d-stem dataset (or 3d .npy dataset)

masks - 3d numpy array or None. if data is compressed provide the virtual detectors (masks) shape should be [N_masks,ky,kx]

output_folder - path to an outputfolder where the results will be stored

path_json - path to a nion-style json file with metadata (optional)

acc_voltage - float, accelerating voltage in kV

One or multiple of the following callibrations:
    rez_pixel_size_A - reciprocal pixel size in Å^-1
    rez_pixel_size_mrad - reciprocal pixel size in mrad
    conv_semiangle_mrad - beam convergence semi-angle in mrad
    aperture - (optional)- binary 2D mask
    bright_threshold - threshold to estimate an aperture, everything above threshold times maximum value in a pacbed will be concidered as bright field disk.

data_pad - int, reciprocal space padding. If None (default), pading is 1/4 of the total width of a diffraction pattern
upsample_pattern - int, default 1 (no upsampling)

aberrations - list or 1d numpy array containing beam aberrations (in Å). Aberrations are stored in Krivanek notation, e.g. C10, C12a, C12b, C21a, C21b, C23a, C23b, C30 etc

defocus - float, default 0. Extra probe defocus besides the one contained in aberrations.

scan_size - tuple of two ints, number of scan points along slow (y) and fast (x) axes. Optional. If no scan step or position grid is provided, it will be used to get the scan step

scan_step_A - float, scan step (STEM pixel size) in Å.

fov_nm - float, FOV along the fast axis in nm.

special_postions_A - 2d numpy array, default None. If you acquiered a data on a special non-rectangular grid, please specify the positions in Å via this array for all measurements in a following format: [[y_0,x_0],[y_1,x_1],....[y_n,x_n]]

transform_axis_matrix- 2x2 matrix for postions transformation

PLRotation_deg - float, rotation angle between scan and detector axes. Default None. If None, a DPC measurement will be executed to get this angle. !!!!!!! Note that negative PLRotation_deg values rotate scan counter clockwise and diffraction space clockwise !!!!!!!!!!!

flip_ky - boolean Flag. Default is False. If no PyPty-style h5 data was created, this flag will flip the y-axis of diffraction patterns.

total_thickness - total thickness of a sample in Å. Has no effect if num_slices is 1 and propagation method (pypty_params entry) is multislice

num_slices - integer, number of slices, default is 1.

num_obj_modes - integer, number of object modes, default is None (single mode)

obj_phase_sigma - float, random noise std. used for for object initialization. default is 0

plot - boolean Flag, default is True

print_flag - integer. Default is 1. If 0 nothing will be printed. 1 prints only thelatest state of the computation, 2 prints every state as a separate line. 3 prints the linesearch progress in iterative optimization. 4 prints everything that 3 does and if constraints are applied, it prints how they contribute so that a user can configure the weights properly.

save_preprocessing_files - Boolean Flag. Default is True. 
erase_probe -  Boolean Flag. Default is False. If True, probe will be deleted from provided preset. This is usefull when replicating a reconstruction setting created for a completely different dataset.

chemical_formula - Nexus tag, composition of the sample
sample_name - Nexus tag, name of a sample

get_offset

Compute pixel offsets between scan grid and reconstruction grid. In PyPty framework, scan grid is usually rotated to compensate the misalignment between scan- and detector- axes. Also, a reconstruction grid is larger than the scanned FOV, this is done to accomodate the extent of the probe.

PARAMETER DESCRIPTION
x_range

Scan dimensions.

TYPE: int

y_range

Scan dimensions.

TYPE: int

scan_step_A

STEM scan step size in Å.

TYPE: float

detector_pixel_size_rezA

Reciprocal space pixel size in Å⁻¹.

TYPE: float

patternshape

Shape of diffraction patterns.

TYPE: tuple

rot_angle_deg

Rotation between scan and detector axes (degrees).

TYPE: float DEFAULT: 0

RETURNS DESCRIPTION
offy, offx : float

Offset values (in reconstruction pixels).

get_positions_pixel_size

Generate scan positions in reconstruction pixel units.

PARAMETER DESCRIPTION
x_range

Scan grid size.

TYPE: int

y_range

Scan grid size.

TYPE: int

scan_step_A

STEM scan step size (Å).

TYPE: float

detector_pixel_size_rezA

Pixel size in reciprocal space (Å⁻¹).

TYPE: float

patternshape

Shape of the diffraction pattern.

TYPE: tuple

rot_angle_deg

Scan-detector rotation angle in degrees. Default is 0.

TYPE: float DEFAULT: 0

flip_x

Flip scan axes. Default is False.

TYPE: bool DEFAULT: False

flip_y

Flip scan axes. Default is False.

TYPE: bool DEFAULT: False

print_flag

Print pixel size. Default is False.

TYPE: bool DEFAULT: False

transform_axis_matrix

Optional 2x2 matrix to apply to positions.

TYPE: array_like DEFAULT: eye(2)

RETURNS DESCRIPTION
positions

Scan positions in reconstruction pixels.

TYPE: ndarray

pixel_size

Size of one reconstruction pixel in Å.

TYPE: float

get_grid_for_upsampled_image

Map coordinates of an upsampled image onto the reconstruction grid.

This function calculates where pixel of an arbitary image (e.g. upsampled tcBF image) will land on a grid corresponding to a ptychographic reconstruction.

PARAMETER DESCRIPTION
pypty_params

Dictionary of PyPty reconstruction parameters.

TYPE: dict

image

2D image (e.g., upsampled tcBF) to map.

TYPE: ndarray

image_pixel_size

Pixel size of the image in Å.

TYPE: float

left_zero_of_scan_grid

Pixel offset on left side of image relative to scan grid. Default is 0.

TYPE: int DEFAULT: 0

top_zero_of_scan_grid

Pixel offset on top side of image relative to scan grid. Default is 0.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
sc

Array of pixel coordinates [[y, x], ...] in reconstruction grid units (pixels of final object).

TYPE: ndarray

get_ptycho_obj_from_scan

Construct an initial object guess using interpolated phase and amplitude maps. You can use output of dpc, wdd of tcBF reconstructions to generate it.

PARAMETER DESCRIPTION
params

PyPty parameter dictionary.

TYPE: dict

num_slices

Number of slices or "auto" to estimate from max phase shift.

TYPE: int or str DEFAULT: None

array_phase

2D phase map to interpolate.

TYPE: ndarray DEFAULT: None

array_abs

2D amplitude map to interpolate.

TYPE: ndarray DEFAULT: None

scale_phase

Scale factor for phase.

TYPE: float DEFAULT: 1

scale_abs

Scale factor for amplitude.

TYPE: float DEFAULT: 1

scan_array_A

Spatial reference grid for the input maps (in Å).

TYPE: ndarray or None DEFAULT: None

fill_value_type

Padding strategy outside scanned region: None, "edge", or "median".

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
dict

Updated PyPty parameter dictionary with object guess.

create_aberrations_chunks

Create chunks, i.e. multiple subscans with independent beam aberrations. Usefull for large fields of view where the beam is varyying. If applied, the iterative reconstruction will have the same beam in each subscan, but apply a different CTF in each of these regions.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

chop_size

Size of each subscan region (in scan points).

TYPE: int

n_abs

Number of aberration coefficients per region.

TYPE: int

RETURNS DESCRIPTION
dict

Updated parameter dictionary with aberration array and marker.

create_probe_marker_chunks

Creates chunks, i.e. multiple subscans with independent beam aberrations. Usefull for large fields of view where the beam is varyying. If applied, the iterative reconstruction will have the a differenet beam in each of these subscans.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

chop_size

Size of each subscan region (in scan points).

TYPE: int

RETURNS DESCRIPTION
dict

Updated dictionary with probe marker.

create_sub_sequence

Define a measurement subsequence for local reconstructions.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

left

Leftmost scan coordinate.

TYPE: int

top

Top scan coordinate.

TYPE: int

width

Width of subregion (in scan points).

TYPE: int

height

Height of subregion (in scan points).

TYPE: int

sub

Sampling factor (take every Nth point).

TYPE: int

RETURNS DESCRIPTION
dict

Updated parameter dictionary with sequence key.

create_sequence_from_points

Create scan subsequence around specified feature points.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

yf

Y-coordinates of feature points (in scan points).

TYPE: list of int

xf

X-coordinates of feature points.

TYPE: list of int

width_roi

Width of the reconstruction window around each point.

TYPE: int DEFAULT: 20

RETURNS DESCRIPTION
list

List of scan indices to reconstruct.

rotate_scan_grid

Apply a rigid rotation to the scan grid.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

angle_deg

Rotation angle in degrees.

TYPE: float DEFAULT: None

RETURNS DESCRIPTION
dict

Updated dictionary with rotated positions and angle.

conjugate_beam

Apply beam conjugation (flip defocus and aberrations).

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

RETURNS DESCRIPTION
dict

Updated dictionary with conjugated probe and CTF.

get_focussed_probe_from_vacscan

Reconstruct a focused probe from a vacuum PACBED pattern.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

mean_pattern

Measured PACBED from vacuum.

TYPE: ndarray

RETURNS DESCRIPTION
dict

Updated dictionary with a probe estimate.

append_aperture_to_params

Append a measured aperture to the reconstruction parameters.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

mean_pattern

Aperture image to be rescaled and added.

TYPE: ndarray

RETURNS DESCRIPTION
dict

Updated dictionary with aperture.

tiltbeamtodata

Align the probe momentum to the center of the measured PACBED pattern.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

align_type

Type of alignment ("com" or "cross_corr").

TYPE: str DEFAULT: 'com'

RETURNS DESCRIPTION
dict

Updated dictionary with shifted probe.

get_approx_beam_tilt

Estimate scan-position-dependent beam tilt from PACBED.

PARAMETER DESCRIPTION
pypty_params

PyPty parameter dictionary.

TYPE: dict

power

Degree of polynomial fitting.

TYPE: int or str DEFAULT: 3

make_binary

If True or float > 0, binarize patterns.

TYPE: bool or float DEFAULT: False

percentile_filter_value

Value for optional percentile filtering.

TYPE: float or None DEFAULT: None

percentile_filter_size

Filter size if filtering is enabled.

TYPE: int DEFAULT: 10

RETURNS DESCRIPTION
dict

Updated dictionary with estimated tilts.

prepare_restart

Prepare a reconstruction restart by loading the latest checkpoint.

PARAMETER DESCRIPTION
output_folder

Directory containing checkpoint files.

TYPE: str

new_folder

New output directory for resumed reconstruction. Default is None.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
dict

Updated pypty_params dictionary including loaded state and 'epoch_prev'.

RAISES DESCRIPTION
ValueError

If no checkpoints are available to restart from.