kemstem.fourier

Submodules

kemstem.fourier.fourierfilter module

kemstem.fourier.fourierfilter.coarsening_length(size, sigma, c=4)

Calculate the real space coarsening length for a given Gaussian filter applied in reciprocal space to an image of shape size with standard deviation sigma.

Parameters:
  • size (int) – Size of the image in pixels.

  • sigma (float) – Standard deviation of the Gaussian filter in reciprocal space pixels.

  • c (float, optional) – Constant factor (default is 4) setting the cutoff width. c=4 corresponds to width at half maximum.

Returns:

Real space coarsening radius, in pixels.

Return type:

float

kemstem.fourier.fourierfilter.create_gaussian_filter(shape, p, sigma)

Generate a Gaussian filter.

Creates a real image of 2D Gaussians with standard deviation sigma at the points p.

Parameters:
  • shape (tuple) – Shape of the filter (height, width).

  • p (ndarray, shape (2,) or (n,2)) – Peak position(s) (y, x) in the Fourier transform.

  • sigma (float) – Standard deviation of the Gaussian filter.

Returns:

filt – Image with 2D Gaussians

Return type:

ndarray

kemstem.fourier.fourierfilter.damp_complex_amplitude(array_c, level)

Damp the amplitude of a complex array to a specified level.

Parameters:
  • array_c (ndarray) – Complex input array.

  • level (float) – Target amplitude level.

Returns:

damped – Damped complex array.

Return type:

ndarray

kemstem.fourier.fourierfilter.damp_peaks_circle(pattern_c, p, levels, radius)

Damp peaks in a complex array by setting a circular area around each to a specified amplitude.

Parameters:
  • pattern_c (ndarray) – Complex input pattern (Fourier transform of an image).

  • p (ndarray, shape (n,2)) – Peak positions (y, x) in the Fourier transform.

  • levels (ndarray) – Target amplitude levels for each peak (typically the background level).

  • radius (float) – Radius of the circular mask.

Returns:

  • damped_pattern_c (ndarray) – Damped complex pattern

  • damped_image (ndarray) – Absolute value of the inverse transform of the damped pattern. Real valued.

kemstem.fourier.fourierfilter.fourier_filter(pattern_c, p, sigma, phase_shift=0)

Apply a Gaussian filter to a complex array.

Parameters:
  • pattern_c (ndarray) – Complex input pattern (Typically Fourier transform of an image).

  • p (ndarray, shape (2,) or (n,2)) – Peak position(s) (y, x) in the Fourier transform.

  • sigma (float) – Standard deviation of the Gaussian filter.

  • phase_shift (float) – Value (typically [0,2pi]) to shift the phase of the filtered signals.

Returns:

  • filtered_im_c (ndarray) – Complex inverse fourier transformed, filtered pattern.

  • filtered_pattern_c (ndarray) – Complex filtered pattern

  • filt (ndarray) – The filter used specified by p and sigma.

kemstem.fourier.fourierfilter.mask_peaks_circle(pattern_c, p, levels, radius)

kemstem.fourier.peakpick module

kemstem.fourier.peakpick.prepare_fourier_pattern(image, log=False, log_offset=1.0, edge_reduction=None)

Calculate 0-frequency centered FFT of a 2D image.

Returned FFT is complex unless log transformed for visualization.

Parameters:
  • image (ndarray) – 2D array for transformation

  • log (boolean) – Whether to take absolute value and log transform the result for visualization

  • log_offset (float) – Value added to FFT magnitude prior to log transform to enhance contrast.

  • edge_reduction (string) – Optionally apply a transform to the image to reduce edge artifacts. Options are: ‘hann’ – applies hann window, see util.image.hann_filter ‘pplus’ – applies periodic-plus-smooth decomposition, see util.image.periodic_plus_smooth_decomposition

Returns:

pattern – The Fourier pattern, with the same shape as the input image

Return type:

ndarray

kemstem.fourier.peakpick.refine_peaks_com(pattern, p0, crop_window, iters=10)

Refine peak positions using center of mass calculations.

This function iteratively refines the positions of n initially detected peaks using the center of mass method within a specified window around each peak.

Parameters:
  • pattern (ndarray) – Real valued 2D array representing the Fourier pattern.

  • p0 (array-like, shape (n,2)) – Initial peak positions as (y, x) coordinates.

  • crop_window (int) – Radius of the window around each peak for refinement.

  • iters (int, optional) – Number of refinement iterations (default is 10).

  • viz (bool, optional) – If True, visualize the refinement process for each peak (default is False).

Returns:

p_ref – Array of refined peak positions.

Return type:

ndarray, shape (n,2)

kemstem.fourier.peakpick.refine_peaks_gf(pattern, p0, window_dimension=5, remove_unfit=True, verbose=True)

Refine peak positions with 2D Gaussian fits. Currently wraps util.general.gaussian_fit_peaks

kemstem.fourier.peakpick.select_peaks(pattern, preselected=None, cmap='gray', vmin=None, vmax=None, zoom=None, figsize=None, select_conjugates=False, delete_within=None)

Interactive peak selection tool.

This function displays the input pattern and allows the user to select peaks by clicking on the image. It provides options for zooming, selecting conjugate peaks, and deleting nearby peaks.

Parameters:
  • pattern (ndarray) – 2D array representing the Fourier pattern.

  • preselected (ndarray, shape (n,2)) – Optional initial set of (y,x) points which will be preselected.

  • cmap (str, optional) – Colormap for displaying the pattern (default is ‘gray’).

  • vmin (float, optional) – Minimum value for color scaling (default is None).

  • vmax (float, optional) – Maximum value for color scaling (default is None).

  • zoom (float, optional) – Zoom factor for the display (default is None). A box in the center of the pattern with width and height 2*zoom will be shown.

  • figsize (tuple, optional) – Figure size in inches (width, height) (default is None).

  • select_conjugates (bool, optional) – If True, automatically select the conjugate peak for each clicked point (default is False).

  • delete_within (float, optional) – Distance threshold for deleting nearby peaks instead of adding new ones (default is None). When set, clicking within this many pixels of a previously selected point will delete the original point.

Returns:

peaks_selected – A tuple containing two lists (y, x) of the selected peak coordinates.

Return type:

ndarray, shape

Notes

Left-click to add peaks. If delete_within is set, clicking near an existing peak will delete it instead of adding a new one.

The result is returned as a tuple of mutable lists to allow peaks to be conveniently added and removed in the midst of analysis, but this data structure does not conform to the kemstem conventions for points. To use the selected peaks for further analysis the result should be transformed as: p0 = np.array(peaks_selected).T to arrive at an array with shape (n,2).

kemstem.fourier.phaselock module

kemstem.fourier.phaselock.create_references(p, shape)

Create reference cosine and sine reference waves for phase lock-in.

Parameters:
  • p (tuple) – Peak position (y, x) in the Fourier transform.

  • shape (tuple) – Shape of the image (height, width).

Returns:

  • cosRef (ndarray) – Real valued sine reference wave

  • sinRef (ndarray) – Real valued cosine reference wave

  • p (tuple) – Reference wavevector (y, x).

kemstem.fourier.phaselock.gpa(filtered_im_c, p)

Calculate the Geometric Phase from a fourier filtered complex image.

This function subtracts the carrier frequency corresponding to peak p from the phase of the filtered image.

Implemented based on Niels Cautaerts’s TEMMETA package.

Parameters:
  • filtered_im_c (ndarray) – Fourier filtered complex image.

  • p (tuple) – Peak position (y, x) in the Fourier transform used for filtering.

Returns:

gpa_phase – Real valued phase image.

Return type:

ndarray

kemstem.fourier.phaselock.phaselock(filtered_im_c, p, sigma)

Perform phase lock in on a fourier filtered complex image.

Parameters:
  • filtered_im_c (ndarray) – Fourier filtered complex image.

  • p (tuple) – Peak position (y, x) in the Fourier transform.

  • sigma (float) – Standard deviation for the lock-in Gaussian low-pass filter.

Returns:

phase – Real valued phase - range of 0 to 2π.

Return type:

ndarray

kemstem.fourier.strain module

kemstem.fourier.strain.calculate_strain_tensor(phase1, phase2, p1, p2, mask_threshold=None)

Calculate the full 2D strain tensor from two phase images.

Implemented based on Niels Cautaerts’s TEMMETA package.

Parameters:
  • phase1 (ndarray) – Phase image corresponding to reflection 1.

  • phase2 (ndarray) – Phase image corresponding to reflection 2.

  • p1 (tuple) – Peak position (y, x) for reflection 1 in the Fourier transform.

  • p2 (tuple) – Peak position (y, x) for reflection 2 in the Fourier transform.

  • mask_threshold (float, optional) – Threshold for masking out outlier strain values. If None, no masking/filtering (default is None).

Returns:

  • exx (ndarray) – Epsilon_xx strain component.

  • eyy (ndarray) – Epsilon_yy strain component.

  • exy (ndarray) – Epsilon_xy shear strain component (symmetric part).

  • oxy (ndarray) – Omega_xy rotation component (antisymmetric part).

kemstem.fourier.strain.phase_to_strain(phase, p, mask_threshold=None)

Calculate longitudinal and transverse strain components from spatially varying phase.

Projections of the gradient of the phase along and transverse to a reference wavevector are assigned as the longitudinal and transverse components.

Parameters:
  • phase (ndarray) – Real valued 2D phase image.

  • p (tuple) – Peak position (y, x) in the Fourier transform.

  • mask_threshold (float, optional) – Threshold for masking strain values. If None, no masking/filtering is applied (default is None).

Returns:

  • eps_longitudinal (ndarray) – longitudinal/parallel component of the strain

  • eps_transverse (ndarray) – transvserse / orthogonal component of the strain

Notes

This function calculates compression and shear strain components from a real valued phase. Uses improved complex exponential differentiation.

kemstem.fourier.wavefit module

kemstem.fourier.wavefit.fit_grating(grating, patch_size, step_size, guess, chunksize=None, verbose=True, renormalize_patches=False, match_image_shape=True, store_full_results=False)

Fit 2D sinusoidal functions to patches of a grating image.

Divides the input grating into patches and fits each patch with a 2D sinusoid using parallel processing.

Parameters:
  • grating (ndarray) – Input real valued grating image to analyze.

  • patch_size (int) – Size of each square patch (must be odd).

  • step_size (int) – Number of pixels to move between patch centers.

  • guess (tuple) – Initial parameter guess for the sinusoidal fit. See peak_to_fit_guess

  • chunksize (int, optional) – Size of chunks for parallel processing. Default is npatches//20.

  • verbose (bool, optional) – Whether to print progress information. Default is True.

  • renormalize_patches (bool, optional) – Whether to normalize patches before fitting. Default is False.

  • match_image_shape (bool, optional) – Whether to interpolate results to match original image shape. Default is True. Assumes target shape is square.

  • store_full_results (bool, optional) – Whether to return additional fitting results. Default is False.

Returns:

  • amplitude (ndarray) – Fitted amplitude values.

  • spacing (ndarray) – Fitted spacing values (pixels).

  • rotation (ndarray) – Fitted rotation angles (radians).

  • sampled_points (ndarray (n,2)) – Coordinates of patch centers, each tuple is a (y,x) point

  • If store_full_results is True, also returns

    optsndarray

    All fitted parameters.

    errsndarray

    Parameter fitting covariances.

    patchesndarray

    Original patches.

    meshtuple

    Coordinate meshgrid for patches.

kemstem.fourier.wavefit.peak_to_fit_guess(pt, imshape)

Convert a peak position to initial parameter guesses for sinusoidal fitting.

Calculates initial guesses for amplitude, spacing, and rotation based on the position of a peak relative to the image center.

Parameters:
  • pt (ndarray) – Peak position coordinates (y, x).

  • imshape (tuple) – Shape of the image (height, width).

Returns:

Initial parameter guesses (amplitude, radius, theta, phase) for sinusoidal fitting.

Return type:

tuple

kemstem.fourier.wavefit.test_fit(grating, patch_size, step_size, guess, test_patch_idx=None, renormalize_patches=False)

Test sinusoidal fitting on a single patch from the grating.

Extracts patches from the grating and performs fitting on a single selected patch for testing purposes.

Parameters:
  • grating (ndarray) – Input grating image.

  • patch_size (int) – Size of each square patch (must be odd).

  • step_size (int) – Number of pixels to move between patch centers.

  • guess (tuple) – Initial parameter guess for the fit.

  • test_patch_idx (int, optional) – Index of patch to test. Default is npatches//4.

  • renormalize_patches (bool, optional) – Whether to normalize patches before fitting. Default is False.

Returns:

Results from fit_patch for the selected patch: - Optimal parameter values - Parameter errors - Original and fitted data

Return type:

tuple

Module contents