API Reference

This section provides detailed documentation for all QEM modules, classes, and functions.

Core Analysis Classes

These are the main classes you’ll use for electron microscopy analysis:

ImageFitting

The primary class for analyzing STEM images and fitting atomic models.

Model Classes

Core model implementations for different peak shapes:

class qem.model.ImageModel(*args: Any, **kwargs: Any)[source]

Bases: Model

Base class for all image models.

__init__(dx: float = 1.0)[source]

Initialize the model.

Parameters:

dx (float, optional) – Pixel size. Defaults to 1.0.

set_grid(x_grid, y_grid)[source]
set_params(params)[source]
update_params(params)[source]

Update the model parameters (values only, not shapes).

build()[source]
get_params()[source]
call(inputs=None)[source]

Forward pass of the model.

abstract model_fn(x, y, pos_x, pos_y, height, width, *args)[source]

Core model function that defines the peak shape.

abstract volume(params: dict) numpy.ndarray[source]

Calculate the volume of each peak.

sum(local=True)[source]

Calculate sum of peaks using Keras.

Parameters:
  • x_grid (array) – x_grid coordinates mesh

  • y_grid (array) – y_grid coordinates mesh

  • local (bool, optional) – If True, calculate peaks locally within a fixed window. Defaults to False.

Returns:

array – Sum of all peaks plus background

class qem.model.GaussianModel(*args: Any, **kwargs: Any)[source]

Bases: ImageModel

Gaussian peak model.

volume(params: dict) numpy.ndarray[source]

Calculate the volume of each Gaussian peak.

For a 2D Gaussian, the volume is: height * 2π * width²

model_fn(x, y, pos_x, pos_y, height, width, *args)[source]

Core computation for Gaussian model using Keras.

class qem.model.LorentzianModel(*args: Any, **kwargs: Any)[source]

Bases: ImageModel

Lorentzian peak model.

volume(params: dict) numpy.ndarray[source]

Calculate the volume of each Lorentzian peak.

For a 2D Lorentzian, the volume is: height * π * width²

model_fn(x, y, pos_x, pos_y, height, width, *args)[source]

Core computation for Lorentzian model using Keras.

class qem.model.VoigtModel(*args: Any, **kwargs: Any)[source]

Bases: ImageModel

Voigt peak model.

__init__(dx: float = 1.0)[source]

Initialize the model.

Parameters:

dx (float, optional) – Pixel size. Defaults to 1.0.

set_params(params)[source]
build()[source]
get_params()[source]
volume(params: dict) numpy.ndarray[source]

Calculate the volume of each Voigt peak.

For a 2D Voigt profile, the volume is a weighted sum of Gaussian and Lorentzian volumes: V = ratio * (height * 2π * width²) + (1-ratio) * (height * π * width²)

model_fn(x, y, pos_x, pos_y, height, width, ratio)[source]

Core computation for Voigt model using Keras.

Essential Modules

Core functionality modules:

qem.model

Analysis and Processing Modules

Specialized analysis tools:

qem.processing

qem.refine

qem.region

qem.stats

qem.atomic_column

qem.crystal_analyzer

Utility Modules

Supporting utilities and tools:

qem.backend_utils

Backend detection and configuration utilities.

qem.utils

qem.io

qem.periodic_table

qem.color

qem.zoom

Specialized Modules

Advanced features and specialized functionality:

qem.probe

Functions for emulating electron optics of a TEM.

qem.abberration

qem.gui_classes

Key Functions

Backend Utilities

Backend detection and configuration utilities for JAX/TensorFlow/PyTorch support.

Backend detection and configuration utilities.

qem.backend_utils.detect_available_backends()[source]

Detect which Keras backends are available in the current environment.

Returns:

list – List of available backend names in order of preference

qem.backend_utils.get_best_backend()[source]

Get the best available backend for the current environment.

Returns:

str – Name of the best available backend

Raises:

RuntimeError – If no backends are available

qem.backend_utils.configure_backend(backend_name=None, force=False)[source]

Configure Keras to use the specified backend.

Parameters:
  • backend_name (str, optional) – Backend to use. If None, auto-detect best.

  • force (bool) – Whether to force reconfiguration even if already set.

Returns:

str – Name of the configured backend

qem.backend_utils.setup_test_backend()[source]

Set up the best available backend for testing.

Returns:

str – Name of the configured backend

qem.backend_utils.backend_specific_config(backend_name)[source]

Apply backend-specific configurations.

Parameters:

backend_name (str) – Name of the backend to configure

qem.backend_utils.auto_configure()[source]

Auto-configure backend if none is set.

Utility Functions

General utility functions for data processing and analysis.

qem.utils.plot_image(image, x_labels, y_labels, colormap='gray', colorbar=True)[source]

Plot an image. with x and y labels.

Parameters:
  • image (numpy.ndarray) – The image to plot.

  • x_labels (list) – The labels for the x-axis.

  • y_labels (list) – The labels for the y-axis.

  • colormap (str, optional) – The colormap to use.

  • colorbar (bool, optional) – Whether to show a colorbar.

Returns:

matplotlib.pyplot.figure – The figure containing the plot.

qem.utils.safe_ln(x)[source]

Natural logarithm function, avoiding division by zero warnings.

Parameters:

x (float) – The value to take the logarithm of.

Returns:

float – The natural logarithm of x.

qem.utils.fft2d(array)[source]

2D FFT of a numpy array.

Parameters:

array (numpy.ndarray) – The array to transform.

Returns:

numpy.ndarray – The transformed array.

qem.utils.ifft2d(array)[source]

2D inverse FFT of a numpy array.

Parameters:

array (numpy.ndarray) – The array to transform.

Returns:

numpy.ndarray – The transformed array.

qem.utils.remove_freq(image, low, high)[source]
qem.utils.apply_threshold(image, image_ref, threshold)[source]
qem.utils.make_mask_circle_centre(arr, radius)

Create a circular mask with same shape as arr

The circle is centered on the center of the array, with the circle having True values.

Similar to _make_circular_mask, but simpler and potentially faster.

Numba jit compatible.

Parameters:
  • arr (NumPy array) – Must be 2 dimensions

  • radius (scalar) – Radius of the circle

Returns:

mask (NumPy array) – Boolean array

Example

>>> import atomap.atom_finding_refining as afr
>>> arr = np.random.randint(100, size=(20, 20))
>>> mask = afr._make_mask_circle_centre(arr, 10)
qem.utils.find_duplicate_row_indices(array)[source]

Find the indices of duplicate rows in a NumPy array.

Parameters: - array: NumPy array to check for duplicate rows.

Returns: - idx_duplicates: NumPy array of indices of the duplicate rows.

qem.utils.find_row_indices(array1, array2)[source]

Efficiently find the indices of rows of array1 in array2.

Parameters:
  • array1 – A NumPy array of shape (M, N).

  • array2 – A NumPy array of shape (K, N).

Returns:

A NumPy array of indices indicating the position of each row of array1 in array2. If a row from array1 is not found in array2, the corresponding index is -1.

qem.utils.find_element_indices(array1, array2)[source]

Find indices of elements of array1 in array2.

Parameters:
  • array1 – A 1D NumPy array of elements to find.

  • array2 – A 1D NumPy array where to search for the elements.

Returns:

A list of indices indicating the position of each element of array1 in array2. If an element from array1 is not found in array2, the corresponding index is -1.

qem.utils.remove_close_coordinates(coordinates, threshold)[source]

Remove coordinates that are within a specified threshold distance of each other.

Parameters: - threshold: The distance below which coordinates are considered too close and should be removed.

qem.utils.export_params(params, filename)[source]

Export the parameters to a file.

Parameters: - params: Dictionary of parameters to export. - filename: Name of the file to export to.

qem.utils.get_random_indices_in_batches(total_examples, batch_size)[source]
qem.utils.is_point_in_polygon(point, polygon)[source]

Determine if a point is inside a polygon using the ray casting algorithm.

Parameters: - point: A 2D point as a tuple or numpy array (x, y). - polygon: A list of tuples or numpy arrays [(x1, y1), (x2, y2), …, (xn, yn)] representing the polygon vertices.

Returns: - Boolean indicating whether the point is inside the polygon.

qem.utils.find_peaks_in_rectangle(peaks, origin, a, b)[source]

Find all peaks that lie within the rectangle defined by origin, origin+a, origin+b, and origin+a+b.

Parameters: - peaks: A list of peak positions as tuples or numpy arrays (x, y). - origin: The origin point as a tuple or numpy array (x, y). - a: The vector a as a tuple or numpy array (x, y). - b: The vector b as a tuple or numpy array (x, y).

Returns: - A list of peaks within the defined rectangle.

qem.utils.rotate_vector(vector, axis, angle)[source]
qem.utils.q_space_array(pixels, gridsize, meshed=True)[source]

Return the appropriately scaled 2D reciprocal space coordinates.

Parameters:
  • pixels ((N,) array_like) – Pixels in each dimension of a ND array

  • gridsize ((N,) array_like) – Dimensions of the array in real space units

  • meshed (bool, optional) – Option to output dense meshed grid (True) or output unbroadcasted arrays (False)

  • pixels – Pixels in each dimension of a 2D array

  • gridsize – Dimensions of the array in real space units

qem.utils.broadcast_from_unmeshed(coords)[source]

For an unmeshed set of coordinates broadcast to a meshed ND array.

Examples

>>> broadcast_from_unmeshed([np.arange(5),np.arange(6)])
[array([[0, 0, 0, 0, 0, 0],
   [1, 1, 1, 1, 1, 1],
   [2, 2, 2, 2, 2, 2],
   [3, 3, 3, 3, 3, 3],
   [4, 4, 4, 4, 4, 4]]), array([[0, 1, 2, 3, 4, 5],
   [0, 1, 2, 3, 4, 5],
   [0, 1, 2, 3, 4, 5],
   [0, 1, 2, 3, 4, 5],
   [0, 1, 2, 3, 4, 5]])]
qem.utils.safe_convert_to_numpy(tensor)[source]

Safely convert a Keras tensor to numpy array, handling different backends.

Parameters:

tensor – Keras tensor or numpy array

Returns:

numpy.ndarray – The tensor converted to numpy array

qem.utils.safe_convert_to_tensor(array, dtype='float32')[source]

Safely convert a numpy array to Keras tensor.

Parameters:
  • array – numpy array or tensor

  • dtype – target dtype for the tensor

Returns:

Keras tensor

qem.utils.safe_deepcopy_params(params)[source]

Safely deep copy a parameter dictionary containing tensors.

Parameters:

params – Dictionary containing tensors and other values

Returns:

Dictionary with safely copied parameters

Processing Functions

Image processing and filtering functions.

qem.processing.butterworth_window(shape, cutoff_radius_ftr, order)[source]

Generate a 2D Butterworth window.

Parameters: - shape: tuple of ints, the shape of the window (height, width). - cutoff_radius_ftr: float, the cutoff frequency as a fraction of the radius (0, 0.5]. - order: int, the order of the Butterworth filter.

Returns: - window: 2D numpy array, the Butterworth window.