kemstem.util

Submodules

kemstem.util.func module

kemstem.util.func.gaussian_2d(yx, amp, xo, yo, sigma_x, sigma_y, theta, offset)
kemstem.util.func.sin2D(yx, amp, qr, angle, phi)

kemstem.util.general module

kemstem.util.general.gaussian_fit_peaks(image, peaks0, window_dimension=5, remove_unfit=True, verbose=True)

Fit 2D Gaussian functions to peaks in an image.

This function refines the positions of n initially detected peaks by fitting a 2D Gaussian function to the region around each peak.

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

  • peaks0 (ndarray, shape (n,2)) – Initial peak positions as (y, x) coordinates.

  • window_dimension (int, optional) – Full width of the window around each peak for Gaussian fitting (default is 5). Must be an odd number.

  • store_fits (bool, optional) – Not implemented. If True, store the Gaussian fit parameters and fitted data (default is True).

  • remove_unfit (bool, optional) – If True, remove peaks that fail to fit properly (default is True).

Returns:

  • p_ref (ndarray, shape (n,2)) – Refined peak positions as (y, x) coordinates.

  • errors (ndarray, shape (n,)) – Boolean array indicating fitting errors.

  • fit_params (ndarray, shape (n,7)) – Gaussian fit parameters for each peak: (amplitude, x-position, y-position, stdev1, stdev2, angle, offset).

  • data_fits (ndarray, shape (window_dimension, window_dimension, n, 2)) – Original and fitted data for each peak with shape: The last dimension contains the original data (index 0) and the fitted data (index 1).

Raises:

ValueError – If window_dimension is not an odd number.

Notes

This function uses scipy.optimize.curve_fit to perform the Gaussian fitting.

kemstem.util.general.get_patch(image, p, patch_dimension)
kemstem.util.general.normalize(data)

Normalize an array between 0 and 1 (inclusive).

Subtract array minimum and divide by its maximum. No type conversions made.

Parameters:

data (ndarray) – Array to normalize.

Returns:

normalized – The normalized array.

Return type:

ndarray

kemstem.util.general.normalize_max(data)

Normalize an array by dividing by its maximum value.

Parameters:

data (ndarray) – Array to normalize.

Returns:

normalized – The normalized array where the maximum value is 1.

Return type:

ndarray

kemstem.util.general.normalize_mean(data)

Normalize an array by centering the mean and scaling by the standard deviation

Parameters:

data (ndarray) – Array to normalize

Returns:

normalize – The normalized array with mean of 0 and one standard deviation at +-1

Return type:

ndarray

kemstem.util.general.normalize_sum(data)

Normalize an array by dividing by its sum.

Parameters:

data (ndarray) – Array to normalize.

Returns:

normalized – The normalized array where the sum of all elements equals 1.

Return type:

ndarray

kemstem.util.general.rasterize_from_points(points, values, output_shape, method='nearest', fill_value=nan)

Interpolate scattered data onto a regular grid.

Parameters:
  • points (ndarray, shape (n,2)) – Array of point coordinate pairs (y,x).

  • values (ndarray, shape (n,)) – Array of values at the given points.

  • output_shape (tuple) – Shape of the output grid (H, W).

  • method (str, optional) – Interpolation method: ‘nearest’, ‘linear’, or ‘cubic’ (default is ‘nearest’).

  • fill_value (float, optional) – Value used to fill points outside of the convex hull of input points (default is np.nan).

Returns:

interp – Interpolated values on a regular grid with the specified output_shape.

Return type:

ndarray

Notes

This function uses scipy.interpolate.griddata for interpolation.

kemstem.util.image module

kemstem.util.image.faux_highpass_filter(image, lowpass_sigma)

Apply a pseudo high-pass filter to an image.

Creates a high-pass filtered version of the input image by subtracting a Gaussian-blurred version from the original image.

Parameters:
  • image (ndarray) – Input image to be filtered.

  • lowpass_sigma (float or sequence of floats) – Standard deviation for Gaussian kernel.

Returns:

High-pass filtered image (original minus low-pass filtered version).

Return type:

ndarray

kemstem.util.image.hann_filter(image)

Apply a 2D Hann window filter to an image and compute its FFT.

Multiplies the image by a 2D Hann window (sin²) to reduce edge effects in the Fourier transform.

Parameters:

image (ndarray) – Input image to be filtered, 2D array.

Returns:

  • fim (ndarray) – Image after applying the Hann window.

  • fft (ndarray) – 2D Fourier transform of the windowed image.

Notes

The Hann window is created using sin²(πx/nx)sin²(πy/ny) where nx, ny are the image dimensions. This helps reduce spectral leakage in the Fourier transform.

kemstem.util.image.periodic_plus_smooth_decomposition(im)

Decompose an image into periodic and smooth components.

Implements the periodic-plus-smooth decomposition as implemented at www.roberthovden.com/tutorial/2015_fftartifacts.html. This decomposition helps reduce artifacts in Fourier transforms of non-periodic images by separating the image into a periodic component and a smooth component. See: Hovden, R., Jiang, Y., Xin, H. L., & Kourkoutis, L. F. (2015). Periodic artifact reduction in Fourier transforms of full field atomic resolution images. Microscopy and Microanalysis, 21(2), 436-441. https://doi.org/10.1017/S1431927614014639

Parameters:

im (ndarray) – Input image to be decomposed, 2D array.

Returns:

  • P (ndarray) – FFT of the periodic component.

  • S (ndarray) – FFT of the smooth component.

Notes

The decomposition solves a Poisson equation with boundary conditions determined by the discontinuities at the image edges. The smooth component captures these discontinuities, leaving the periodic component better suited for Fourier analysis.

The implementation enforces zero mean in the frequency domain by setting the DC component (0,0) appropriately.

kemstem.util.point module

kemstem.util.point.extrapolate_point_pair(pt1, pt2, frac_pre, frac_post)

Extrapolate a line segment defined by two points.

Parameters:
  • pt1 (array-like) – First point (y, x).

  • pt2 (array-like) – Second point (y, x).

  • frac_pre (float) – Fraction of the segment length to extend before pt1.

  • frac_post (float) – Fraction of the segment length to extend after pt2.

Returns:

extrapolated – Array containing the two extrapolated points [adj1, adj2].

Return type:

ndarray, shape (2, 2)

kemstem.util.point.get_nearest_points(points, guesses, k=1, handle_nan=False)

Find k nearest neighbors for each point in guesses using KDTree. Handles NaN values in guesses by returning NaN for those positions (still finnicky).

Parameters:
  • points (array-like, shape (n, d)) – The reference points to search within

  • guesses (array-like, shape (m, d)) – The query points to find neighbors for

  • k (int) – Number of nearest neighbors to find

Returns:

corresponding to NaN inputs in guesses

Return type:

tuple of (match_points, idx, dist) where each has NaN values

kemstem.util.point.rotate_image_and_calculate_transform(angle_rad, im)

Rotate an image and return functions to map points between original and rotated coordinates.

Parameters:
  • angle_rad (float) – Rotation angle in radians.

  • im (ndarray) – Image to rotate.

Returns:

  • rot_im (ndarray) – The rotated image.

  • applyToPoints (function) – Function that takes points (y,x) in original image coordinates and returns points in the rotated image coordinates.

  • applyToImage (function) – Function that takes an image and applies the same rotation.

kemstem.util.point.rotate_points(points, angle, center=(0, 0))

Rotate points around a center by a given angle.

Parameters:
  • points (array-like, shape (n, 2)) – List of (x,y) points to rotate.

  • angle (float) – Rotation angle in radians.

  • center (tuple, optional) – Center of rotation (x,y). Default is (0,0).

Returns:

rotated – The rotated points.

Return type:

ndarray, shape (n, 2)

kemstem.util.viz module

kemstem.util.viz.coarsening_marker(axis, coarsening_radius, position_frac=(0.95, 0.95), facecolor='w', edgecolor='k', **kwargs)

Add a circular marker to indicate coarsening length scale.

Parameters:
  • axis (matplotlib.axes.Axes) – Axes to add the marker to.

  • coarsening_radius (float) – Radius of the coarsening marker.

  • position_frac (tuple, optional) – Fractional position of the marker center (x, y) (default is (0.95, 0.95)).

  • facecolor (str, optional) – Fill color of the marker (default is ‘w’).

  • edgecolor (str, optional) – Edge color of the marker (default is ‘k’).

  • **kwargs (dict) – Additional arguments to pass to matplotlib.patches.Circle.

Returns:

The circular marker patch.

Return type:

matplotlib.patches.Circle

kemstem.util.viz.neighborhood_scatter_plot(neighborhood, ax=None, clusters=None, fontsize=8)

Create a scatter plot of n pair correlation vectors with optional labeled cluster centers.

Parameters:
  • neighborhood (ndarray, shape (n,2)) – Array of point coordinates as (y, x).

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • clusters (ndarray, shape (n,2) optional) – Array of cluster center coordinates as (y, x).

Returns:

The axes containing the plot.

Return type:

matplotlib.axes.Axes

kemstem.util.viz.plot_color_wheel(cm, filename=None, dpi=150, transparent=True, n_points=1024, r_inner=0.3, r_outer=0.8, s=1.0)

Plots a color wheel for the provided colormap

Parameters:
  • cm (colormap) – Colormap to plot a colorwheel for

  • filename (string, optional) – Path to save color wheel image to.

  • dpi (int, optional) – dots per inch for saved image. No effect if no filename provided. Default 150.

  • transparent (boolean, optional) – Save with transparent background. Default True.

  • n_points (int, optional) – Number of points used for plotting. Default 1024.

  • r_inner (float, optional) – Inner radius of color wheel. Default 0.3

  • r_outer (float, optional) – Outer radius of color wheel. Default 0.8

  • s (float, optional) – Size of markers comprising wheel. Default 1.

kemstem.util.viz.plot_displaced_site(columns, displacements, scale, colors='angle', ax=None, cmap='hsv', linewidth=0.2, shape=4, angleshift=0, disp_min=0, disp_max=inf, scale_power=0.5)

Plot n displaced sites as colored triangles.

Parameters:
  • columns (ndarray, shape (n,2)) – Array of original site coordinates as (y, x).

  • displacements (ndarray, shape (n,2)) – Array of displacement vectors as (dy, dx).

  • scale (float) – Scaling factor for displacements.

  • colors (str or ndarray, optional) – Coloring method (‘angle’, ‘mag’) or array of color values (default is ‘angle’).

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • cmap (str, optional) – Colormap for the triangles (default is ‘hsv’).

  • linewidth (float, optional) – Width of the triangle edges (default is 0.2).

  • shape (float, optional) – Shape factor for triangles (default is 4).

  • angleshift (float, optional) – Angle shift for color mapping (default is 0).

  • disp_min (float, optional) – Minimum and maximum displacement magnitudes to plot.

  • disp_max (float, optional) – Minimum and maximum displacement magnitudes to plot.

  • scale_power (float, optional) – Power scaling factor for displacement magnitudes (default is 0.5).

Returns:

The collection of triangle patches.

Return type:

matplotlib.collections.PatchCollection

kemstem.util.viz.plot_fit_comparison(data_fit_stack, figsize=(6, 3), cmap='viridis')

Plot a comparison of original data and fitted data.

Parameters:
  • data_fit_stack (ndarray, shape (fit_window, fit_window, n_fits, 2)) – Array where the last dimension contains the original data (index 0) and the fitted data (index 1).

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

  • cmap (str, optional) – Colormap for the plots (default is ‘viridis’).

Returns:

Figure and axes objects (fig, ax).

Return type:

tuple

kemstem.util.viz.plot_numbered_points(image, points, ax=None, delta=0, delta_step=0, verbose=0, zoom=100, vmin=None, vmax=None, color='r', fontsize=8)

Plot numbered points on an image.

Parameters:
  • image (ndarray or None) – 2D array representing the image. If None, only points are plotted.

  • points (array-like, shape (n,2)) – Array of point coordinates as (y, x).

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • delta (float, optional) – Initial offset for point labels (default is 0).

  • delta_step (float, optional) – Step size for incrementing label offset (default is 0).

  • verbose (int, optional) – If non-zero, print point coordinates (default is 0).

  • zoom (float, optional) – Zoom factor for display (default is 100).

  • vmin (float, optional) – Color scale range for image display.

  • vmax (float, optional) – Color scale range for image display.

  • color (str, optional) – Color of the points (default is ‘r’).

  • fontsize (float,optional) – Font size for point labels. Default is 8.

Returns:

The axes containing the plot.

Return type:

matplotlib.axes.Axes

kemstem.util.viz.plot_phase(phase, ax=None, contour_angles=[0, 2.0943951023931953, 4.1887902047863905], contour_phase_shift=0, linewidths=1, colors='black', **kwargs)

Plot a phase image with contour lines.

Contours are drawn at 2*pi/3 steps.

Parameters:
  • phase (ndarray) – Real valued 2D array of phase values, in radians.

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • contour_angles (iterable) – Angles in the range [0,2*pi] at which to draw contour lines

  • contour_phase_shift (float) – phase offset at which to draw contours

  • linewidths (float, optional) – Width of the contour lines (default is 1).

  • colors (string or list) – Colors passed to call to contour to color contour lines

  • **kwargs (dict) – Additional arguments to pass to ax.contour().

Returns:

Axes and colorbar mappable object (ax, mappable).

Return type:

tuple

kemstem.util.viz.plot_scalar_bonds(ax, scalar, sites_1, sites_2, cmap='inferno', linewidth=1, vmin=None, vmax=None, **lcargs)

Plot scalar values as colored bonds between sites.

Note: to plot lines of all a single color, pass cmap=None and color=[your color of interest]

Parameters:
  • ax (matplotlib.axes.Axes) – Axes to plot on.

  • scalar (array-like, shape (n)) – Scalar values to be plotted.

  • sites_1 (ndarray, shape (n,2)) – Arrays of coordinates for the start points of bonds as (y, x).

  • sites_2 (ndarray, shape (n,2)) – Arrays of coordinates for the end points of bonds as (y, x).

  • cmap (str, optional) – Colormap for scalar values (default is ‘inferno’).

  • linewidth (float, optional) – Width of the bond lines (default is 1).

  • vmin (float, optional) – Color scale range for scalar values.

  • vmax (float, optional) – Color scale range for scalar values.

  • **lcargs (dict) – Additional arguments to pass to LineCollection.

Returns:

The line collection representing the bonds.

Return type:

matplotlib.collections.LineCollection

kemstem.util.viz.plot_scalar_polygons(ax, sites, scalar, cmap='inferno', vmin=None, vmax=None, linewidth=0, alpha=1)

Plot n scalar values as colored polygons with k sides.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes to plot on.

  • sites (ndarray, shape (k,n,2)) – Coordinates (y,x) of k vertices of each n polygons to be plotted.

  • scalar (ndarray, shape (n,)) – Scalar values to be plotted.

  • cmap (str, optional) – Colormap for scalar values (default is ‘inferno’).

  • linewidth (float, optional) – Width of the outer polygon lines (default is 0).

  • vmin (float, optional) – Color scale range for scalar values.

  • vmax (float, optional) – Color scale range for scalar values.

  • alpha (float, optional) – Transparency of the polygons, default 1.

Returns:

The Patch collection of the polygons.

Return type:

matplotlib.collections.PatchCollection

kemstem.util.viz.plot_scalar_sites(ax, scalar, sites, s=5, cmap='inferno', **scatterargs)

Plot scalar values at a set of n points.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes to plot on.

  • scalar (array-like, shape (n)) – Scalar values to be plotted.

  • sites (ndarray, shape (n,2)) – Array of point coordinates as (y, x).

  • s (float, optional) – Marker size (default is 5).

  • cmap (str, optional) – Colormap for scalar values (default is ‘inferno’).

  • **scatterargs (dict) – Additional arguments to pass to ax.scatter().

Returns:

The scatter plot collection.

Return type:

matplotlib.collections.PathCollection

Module contents