Skip to content

pypty.vaa

plot_modes

Plot probe/object modes in real and reciprocal space.

Shows four panels per mode: real-space magnitude/phase and Fourier-space magnitude/phase.

PARAMETER DESCRIPTION
ttt

Complex mode stack. Accepted shapes are (Ny, Nx, nmodes) or (Ny, Nx, nstates, nmodes).

TYPE: ndarray

RETURNS DESCRIPTION
None

The function displays figures using Matplotlib.

fit_aberrations_to_wave

Fit aberration coefficients to a complex wave by matching Fourier phase.

The function computes the Fourier transform of wave, unwraps its phase (optionally masked by magnitude threshold and angular cutoff), and fits a Krivanek-style aberration expansion using nonlinear least squares.

PARAMETER DESCRIPTION
wave

Complex real-space wave, shape (Ny, Nx).

TYPE: ndarray

px_size_A

Real-space pixel size in Å.

TYPE: float

acc_voltage

Acceleration voltage in kV.

TYPE: float

thresh

Relative magnitude threshold (fraction of max) used to mask Fourier pixels before fitting.

TYPE: float DEFAULT: 0

aberrations_guess

Initial guess for aberration coefficients in Å. Length sets the number of fitted aberration terms.

TYPE: array_like DEFAULT: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

plot

If True, show diagnostic plots (fitted phase, target phase, difference).

TYPE: bool DEFAULT: True

ftol

Relative tolerance for termination by the change of the cost function.

TYPE: float DEFAULT: 1e-20

xtol

Relative tolerance for termination by the change of the parameters.

TYPE: float DEFAULT: 1e-20

loss

Loss function for scipy.optimize.least_squares.

TYPE: str DEFAULT: 'linear'

max_mrad

Maximum scattering angle included in the fit, in mrad.

TYPE: float DEFAULT: inf

RETURNS DESCRIPTION
aberrations

Fitted aberration coefficients in Å.

TYPE: ndarray

Notes

This routine assumes the Fourier phase of the wave is dominated by probe aberrations after removing the center-of-mass (COM) tilt term.

mesh_model_positions

Compute an ideal rotated scan grid from step size and angle.

PARAMETER DESCRIPTION
step_size

Step size in the same units as x/y.

TYPE: float

angle_rad

Rotation angle in radians.

TYPE: float

x

Flattened coordinate arrays describing the nominal scan grid.

TYPE: ndarray

y

Flattened coordinate arrays describing the nominal scan grid.

TYPE: ndarray

RETURNS DESCRIPTION
x_model, y_model : numpy.ndarray

Modeled coordinates after applying the rotation and step size.

mesh_objective_positions

Objective for fitting a rotated/stepped grid to measured positions.

PARAMETER DESCRIPTION
ini_guess

Two parameters [step, angle] where angle is in radians.

TYPE: array_like

x

Flattened nominal grid coordinates.

TYPE: ndarray

y

Flattened nominal grid coordinates.

TYPE: ndarray

mesh_x

Flattened measured coordinates to be matched.

TYPE: ndarray

mesh_y

Flattened measured coordinates to be matched.

TYPE: ndarray

RETURNS DESCRIPTION
float

Sum of squared residuals between modeled and measured coordinates.

get_step_angle_scan_grid

Estimate mean scan step and rotation angle from measured positions.

A simple global fit is performed assuming a rectangular scan grid that is uniformly rotated and scaled.

PARAMETER DESCRIPTION
positions

Measured positions with shape (N, 2) ordered as (y, x).

TYPE: ndarray

scan_size

Scan grid size (Ny, Nx).

TYPE: tuple of int

print_flag

If True, prints the standard deviation of the residuals in pixels.

TYPE: bool DEFAULT: 1

RETURNS DESCRIPTION
step

Estimated step size (same units as positions).

TYPE: float

angle_deg

Estimated rotation angle in degrees.

TYPE: float

get_affine_tranform

Estimate an affine deformation matrix from measured scan positions.

The mapping is fit from ideal integer grid coordinates to measured positions using linear least squares. The returned matrix is scaled by px_size_A.

PARAMETER DESCRIPTION
positions

Measured positions with shape (N, 2) ordered as (y, x).

TYPE: ndarray

scan_size

Scan grid size (Ny, Nx).

TYPE: tuple of int

px_size_A

Pixel size used to scale the affine transform, in Å.

TYPE: float

print_flag

If True, prints deformation and shift parameters.

TYPE: bool DEFAULT: 1

RETURNS DESCRIPTION
deformation

2×2 deformation matrix mapping ideal grid vectors to measured coordinates, scaled by px_size_A.

TYPE: ndarray

add_scalebar_ax

Add a scale bar annotation to an image axis.

PARAMETER DESCRIPTION
ax

Axis to draw into.

TYPE: Axes

x

Bottom-left corner of the bar in data coordinates.

TYPE: float

y

Bottom-left corner of the bar in data coordinates.

TYPE: float

width

Scale bar length in unit.

TYPE: float

height

Bar thickness in data pixels.

TYPE: float

x_t

Text anchor position in data coordinates.

TYPE: float

y_t

Text anchor position in data coordinates.

TYPE: float

px_size

Pixel size in the same physical units as width.

TYPE: float

unit

Unit label (e.g. 'Å', 'nm').

TYPE: str

fontsize

Font size for the label.

TYPE: int DEFAULT: 20

RETURNS DESCRIPTION
None

The function modifies ax in place.

outputlog_plots

Plot PyPty optimization log columns from a CSV file.

PARAMETER DESCRIPTION
loss_path

Path to the CSV log file.

TYPE: str

skip_first

If nonzero, ignore iterations with epoch < skip_first.

TYPE: int DEFAULT: 0

plot_time

If True, adds a secondary x-axis showing elapsed time (hours).

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
figs

One figure per plotted column.

TYPE: list of matplotlib.figure.Figure

radial_average

Compute radial average of a 2D Fourier-domain quantity.

PARAMETER DESCRIPTION
ff

2D array to be radially averaged.

TYPE: ndarray

r_bins

Bin width in pixels (in Fourier grid radius units).

TYPE: float

r_max

Maximum and minimum normalized radii (fractions of the max radius).

TYPE: float

r_min

Maximum and minimum normalized radii (fractions of the max radius).

TYPE: float

px_size_A

Real-space pixel size in Å (used to label spatial frequency axis).

TYPE: float

plot

If True, plots the radial average.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
fig

Figure handle if plot=True.

TYPE: Figure

complex_pca

Perform PCA on complex observations.

The last axis is treated as the observation axis. The covariance is computed on mean-centered complex data and eigen-decomposed.

PARAMETER DESCRIPTION
data

Complex array with shape (Ny, Nx, N_obs).

TYPE: ndarray

n_components

Number of principal components to retain.

TYPE: int

RETURNS DESCRIPTION
data_reduced

Complex array with shape (Ny, Nx, n_components).

TYPE: ndarray

complex_array_to_rgb

Map a complex array to an RGB image using phase/magnitude encoding.

Hue encodes the complex phase. Magnitude is mapped either to value (dark theme) or saturation (light theme).

PARAMETER DESCRIPTION
X

Complex array.

TYPE: ndarray

theme

Rendering theme.

TYPE: (dark, light) DEFAULT: 'dark'

rmax

Magnitude used for normalization. If None, uses abs(X).max().

TYPE: float DEFAULT: None

RETURNS DESCRIPTION
rgb

RGB image array with shape X.shape + (3,) and dtype float.

TYPE: ndarray

plot_complex_modes

Plot a subset of complex modes in RGB with intensity percentages.

PARAMETER DESCRIPTION
p

Complex mode stack with shape (Ny, Nx, nmodes).

TYPE: ndarray

nm

Number of modes to plot.

TYPE: int

sub

Number of subplot rows.

TYPE: int

RETURNS DESCRIPTION
fig

Figure handle.

TYPE: Figure

plot_complex_colorwheel

Complex-plane color wheel legend on an axis. This helper renders the HSV mapping used by :func:complex_array_to_rgb by drawing a filled disk of radius rmax in the complex plane. Hue encodes the complex phase (argument), while value/saturation encodes magnitude depending on theme.

PARAMETER DESCRIPTION
ax

Axis to draw into.

TYPE: Axes

theme

Color theme that matches :func:complex_array_to_rgb. For 'dark', magnitude is mapped to value (brightness) and saturation is fixed. For 'light', magnitude is mapped to saturation.

TYPE: (dark, light) DEFAULT: 'dark'

N

Grid size used to sample the complex plane (image will be N x N).

TYPE: int DEFAULT: 512

rmax

Maximum radius shown in the colorwheel. Values outside the disk are set to a uniform background.

TYPE: float DEFAULT: 1.0

fontsize

Font size for the annotations ("0", rmax, and 2pi).

TYPE: int DEFAULT: 15

background

If truthy, sets the outside-of-disk background to white; otherwise uses a theme-appropriate background (black for 'dark', white for 'light').

TYPE: bool DEFAULT: 0

RETURNS DESCRIPTION
None

The function draws directly onto ax.

crop_ptycho_object_to_stem_roi

Crop a reconstructed ptychography object to the STEM scan region of interest.

The function rotates the object by params["PLRotation_deg"] (in degrees) without reshaping and then crops the rotated object to the field of view implied by the scan parameters.

PARAMETER DESCRIPTION
o

2D object array with axes (y, x). Can be real or complex.

TYPE: ndarray

params

Parameter dictionary. Must contain:

  • PLRotation_deg : float
  • scan_size : tuple of int
  • scan_step_A : float
  • pixel_size_x_A : float
  • pixel_size_y_A : float

TYPE: dict

RETURNS DESCRIPTION
ndarray

Cropped object array with axes (y, x).

Notes

The crop size is computed in physical units (Å) from scan_size*scan_step_A and then converted to pixels using the object pixel sizes.