abtem.measurements#
Module for describing abTEM measurement objects.
Module Contents#
Classes#
Base class for all measurement types. |
|
One or more diffraction patterns. |
|
A collection of 2D measurements such as HRTEM or STEM-ADF images. May be used to represent a reconstructed phase. |
|
Diffraction patterns indexed by their Miller indices. |
|
Momentum-resolved energy-loss spectrum S(q, E). |
|
Class describing polar measurements with a specified number of radial and azimuthal bins. |
|
A collection of real-space line profile(s). |
|
A collection of reciprocal-space line profile(s). |
Functions#
Integrate the values of a 2d measurement on a disc-shaped region. |
|
Build S(q, E) from energy-resolved TDS diffraction patterns. |
|
Crop an array with periodic boundary conditions. The cropping region is wrapped around the array. |
|
Compute inelastic (TDS) diffraction patterns from energy-resolved frozen-phonon exit waves. |
|
Data#
API#
- class abtem.measurements.BaseMeasurements(...)[source]#
Bases:
abtem.array.ArrayObject,abtem.core.utils.EqualityMixin,abtem.core.utils.CopyMixinBase class for all measurement types.
- Parameters:
array (ndarray) – Array containing data of type float or complex.
ensemble_axes_metadata (list of AxisMetadata, optional) – Metadata associated with an ensemble axis.
metadata (dict, optional) – A dictionary defining simulation metadata.
Initialization
- normalize_ensemble(...)[source]#
Normalize the ensemble by shifting ad scaling each member.
- Parameters:
scale ({'max', 'min', 'sum', 'mean', 'ptp'})
shift ({'max', 'min', 'sum', 'mean', 'ptp'})
- Returns:
normalized_measurements
- Return type:
BaseMeasurements or subclass of _BaseMeasurement
- poisson_noise(...) Self[source]#
Add Poisson noise (i.e. shot noise) to a measurement corresponding to the provided ‘total_dose’ (per measurement if applied to an ensemble) or ‘dose_per_area’ (not applicable for single measurements).
- Parameters:
dose_per_area (float, sequence of float, optional) – The irradiation dose [electrons per Å:sup:2]. May be given as a single value or as a sequence of values for each ensemble member.
total_dose (float, optional) – The irradiation dose per diffraction pattern.
samples (int, optional) – The number of samples to draw from a Poisson distribution. If this is greater than 1, an additional ensemble axis will be added to the measurement.
seed (int, optional) – Seed the random number generator.
- Returns:
noisy_measurement – The noisy measurement.
- Return type:
BaseMeasurements or subclass of _BaseMeasurement
- reduce_ensemble() Self[source]#
Calculates the mean of an ensemble measurement (e.g. of frozen phonon configurations).
- relative_difference(...) Self[source]#
Calculates the relative difference with respect to another compatible measurement.
- Parameters:
other (BaseMeasurements) – Measurement to which the difference is calculated.
min_relative_tol (float) – Avoids division by zero errors by defining a minimum value of the divisor in the relative difference.
- Returns:
difference – The relative difference as a measurement of the same type.
- Return type:
- abtem.measurements.BaseMeasurementsSubclass#
‘TypeVar(…)’
- class abtem.measurements.DiffractionPatterns(...)[source]#
Bases:
abtem.measurements._BaseMeasurement2DOne or more diffraction patterns.
- Parameters:
array (ndarray) – 2D or greater array containing data with float type. The second-to-last and last dimensions are the reciprocal space y- and x-axis of the diffraction pattern.
sampling (float or two float) – The reciprocal-space sampling of the diffraction patterns [1 / Å].
fftshift (bool, optional) – If True, the diffraction patterns are assumed to have the zero-frequency component to the center of the spectrum, otherwise the center(s) are assumed to be at (0, 0).
ensemble_axes_metadata (list of AxisMetadata, optional) – List of metadata associated with the ensemble axes. The length and item order must match the ensemble axes.
metadata (dict, optional) – A dictionary defining measurement metadata.
Initialization
- property angular_limits: list[tuple[float, float]]#
Lowest and highest scattering angle in x and y [mrad].
- property angular_sampling: tuple[float, float]#
Angular sampling of diffraction patterns in x and y [mrad].
- azimuthal_average(...) ReciprocalSpaceLineProfiles[source]#
Calculate the azimuthal averages of the diffraction patterns.
- Parameters:
max_angle (float, optional) – The maximum included scattering angle in the azimuthal averages [mrad].
radial_sampling (float, optional) – The radial sampling of the azimuthal averages [mrad]. Default is equal to the smallest value of the x and y component of the angular sampling.
weighting_function (str) – The weighting function to determining how to average the diffraction patterns. The weighting function determines the shape of the mask that is applied to the diffraction patterns before averaging. The options are ‘step’ and ‘gaussian’. Default is ‘step’.
width (float, optional) – The width of the weighting function [mrad]. Default is 1.0. For the ‘step’ weighting function, this is the width of the step function. For the ‘gaussian’ weighting function, this is the standard deviation of the Gaussian function.
- Returns:
azimuthal_averages – The azimuthal averages of the diffraction patterns.
- Return type:
- bandlimit(...) DiffractionPatterns[source]#
Bandlimit diffraction pattern(s) by setting everything outside an annulus defined by two radial angles to zero.
- Parameters:
- Returns:
band-limited_diffraction_patterns – The band-limited diffraction pattern(s).
- Return type:
- property base_axes_metadata#
- block_direct(...) DiffractionPatterns[source]#
Block the direct beam by setting the pixels of the zeroth-order Bragg reflection (non-scattered beam) to zero.
- Parameters:
radius (float, optional) – The radius of the zeroth-order reflection to block [mrad]. If not given this will be inferred from the metadata, if available.
margin (bool, optional) – If True adds a margin to the blocking radius to fully block soft apertures. Margin is true by default for diffraction patterns with semiangle_cutoff in metadata.
- Returns:
diffraction_patterns – The diffraction pattern(s) with the direct beam removed.
- Return type:
- center_of_mass(...) Images | RealSpaceLineProfiles[source]#
Calculate center-of-mass images or line profiles from diffraction patterns. The results are of type complex where the real and imaginary part represents the x and y component.
- Parameters:
units ({'1/Å', 'mrad'}) – Units of the center-of-mass values of the output images or line profiles. Default is ‘1/Å’.
- Returns:
com_images (Images) – Center-of-mass images.
com_line_profiles (RealSpaceLineProfiles) – Center-of-mass line profiles (returned if there is only one scan axis).
- crop(...) DiffractionPatterns[source]#
Crop the diffraction patterns such that they only include spatial frequencies (scattering angles) up to a given limit.
- Parameters:
- Returns:
cropped_diffraction_patterns – The cropped diffraction pattern(s).
- Return type:
- classmethod from_array_and_metadata(...) Self[source]#
Creates diffraction pattern(s) from a given array and metadata.
- Parameters:
array (array) – Complex array defining one or more 2D diffraction patterns. The second-to-last and last dimensions are the diffraction pattern y- and x-axis.
axes_metadata (list of AxesMetadata) – Axis metadata for each axis. The axis metadata must be compatible with the shape of the array. The last two axes must be RealSpaceAxis.
metadata (dict) – A dictionary defining the measurement metadata.
- Returns:
diffraction_patterns – Diffraction pattern(s) from the array and metadata.
- Return type:
- gaussian_source_size(...) DiffractionPatterns[source]#
Simulate the effect of a finite source size on diffraction pattern(s) using a Gaussian filter.
The filter is not applied to diffraction pattern individually, but the intensity of diffraction patterns are mixed across scan axes. Applying this filter requires two linear scan axes.
Applying this filter before integrating the diffraction patterns will produce the same image as integrating the diffraction patterns first then applying a Gaussian filter.
- Parameters:
sigma (float or two float) – Standard deviation of Gaussian kernel in the x and y-direction. If given as a single number, the standard deviation is equal for both axes.
- Returns:
filtered_diffraction_patterns – The filtered diffraction pattern(s).
- Return type:
- index_diffraction_spots(...) IndexedDiffractionPatterns[source]#
Indexes the Bragg reflections (diffraction spots) by their Miller indices.
- Parameters:
cell (ase.cell.Cell or float or tuple of float) – The assumed unit cell with respect to the diffraction pattern should be indexed. Must be one of ASE Cell object, float (for a cubic unit cell) or three floats (for orthorhombic unit cells).
orientation_matrices (ndarray, optional) – Orientation matrices used for indexing the diffraction spots. The shape of the orientation matrices must be broadcastable with the ensemble shape of the diffraction patterns.
sg_max (float, optional) – Maximum excitation error [1/Å] of the indexed diffraction spots. The default is estimated from the energy and g_max.
g_max (float, optional) – Maximum scattering vector [1/Å] of the indexed diffraction spots. The default is the maximum frequency of the diffraction patterns.
radius (float, optional) – Integration Radius of the diffraction spots [1/Å]. The default is the reciprocal-space sampling of the diffraction patterns.
centering ({'P', 'F', 'I', 'A', 'B', 'C'}) – Assumed lattice centering used for determining the reflection conditions.
energy (float, optional) – The energy of the electrons [keV]. The default is the energy stored in the metadata.
- Returns:
indexed_patterns – The indexed diffraction pattern(s).
- Return type:
- integrate_radial(...) Images[source]#
Create images by integrating the diffraction patterns over an annulus defined by an inner and outer integration angle.
- integrated_center_of_mass() Images[source]#
Calculate integrated center-of-mass (iCOM) images from diffraction patterns. This method is only implemented for diffraction patterns with exactly two scan axes.
- Returns:
icom_images – The iCOM images.
- Return type:
- interpolate(...)[source]#
Interpolate diffraction pattern(s) producing equivalent pattern(s) with a different sampling.
- Parameters:
sampling ('uniform' or float or two floats) – Sampling of diffraction patterns after interpolation in x and y [1 / Å]. If a single value, the same sampling is used for both axes. If ‘uniform’, the diffraction patterns are down-sampled along the axis with the smallest pixel size such that the sampling is uniform.
gpts (tuple of int) – Number of grid points of the diffraction patterns after interpolation in x and y. Do not use if ‘sampling’ is used.
- Returns:
interpolated_diffraction_patterns – The interpolated diffraction pattern(s).
- Return type:
- property limits: list[tuple[float, float]]#
Lowest and highest spatial frequency in x and y [1 / Å].
- lorentzian_source_size(...) DiffractionPatterns[source]#
Simulate the effect of a finite source size on diffraction pattern(s) using a Lorentzian (Cauchy) filter.
The filter mixes intensities across scan axes (not within each diffraction pattern) and requires two linear scan axes. Applying this filter before integrating gives the same result as integrating first and then applying a
lorentzian_filter()to the resulting images.- Parameters:
- Returns:
filtered_diffraction_patterns – The filtered diffraction pattern(s).
- Return type:
Notes
The Lorentzian kernel is parameterized by its HWHM γ (
half_width), with FWHM_L = 2γ. This differs fromgaussian_source_size(), which uses the standard deviation σ (FWHM_G ≈ 2.3548·σ).
- property max_frequency#
Maximum spatial frequency in x and y [1 / Å].
- poisson_noise(...)[source]#
Add Poisson noise (i.e. shot noise) to a measurement corresponding to the provided total_dose (per measurement if applied to an ensemble) or dose_per_area (not applicable for single measurements).
- Parameters:
dose_per_area (float, optional) – The irradiation dose per unit of scan area [electrons per Å:sup:2]. This is only valid if the diffraction patterns has two scan axes.
total_dose (float, optional) – The irradiation dose per diffraction pattern.
samples (int, optional) – The number of samples to draw from a Poisson distribution. If this is greater than 1, an additional ensemble axis will be added to the measurement.
seed (int, optional) – Seed the random number generator.
- Returns:
noisy_measurement – The noisy measurement.
- Return type:
- polar_binning(...)[source]#
Create polar measurements from the diffraction patterns by binning the measurements on a polar grid. This method may be used to simulate a segmented detector with a specified number of radial and azimuthal bins.
Each bin is a segment of an annulus and the bins are spaced equally in the radial and azimuthal directions. The bins fit between a given inner and outer integration limit, they may be rotated around the origin, and their center may be shifted from the origin.
- Parameters:
nbins_radial (int) – Number of radial bins.
nbins_azimuthal (int) – Number of angular bins.
inner (float) – Inner integration limit of the bins [mrad] (default is 0.0).
outer (float) – Outer integration limit of the bins [mrad]. If not specified, this is set to be the maximum detected angle of the diffraction pattern.
rotation (float) – Rotation of the bins around the origin [mrad] (default is 0.0).
offset (two float) – Offset of the bins from the origin in x and y [mrad]. Default is (0.0, 0.0).
- Returns:
polar_measurements – The polar measurements.
- Return type:
- pseudo_voigtian_source_size(...) DiffractionPatterns[source]#
Simulate the effect of a finite source size on diffraction pattern(s) using a pseudo-Voigtian filter (weighted sum of Gaussian and Lorentzian).
The filter mixes intensities across scan axes (not within each diffraction pattern) and requires two linear scan axes. Applying this filter before integrating gives the same result as integrating first and then applying a
pseudo_voigtian_filter()to the resulting images.- Parameters:
gaussian_sigma (float or two float) – Standard deviation (σ) of the Gaussian component [Å]. If given as a single number it is equal for both axes.
lorentzian_gamma (float or two float) – Half-width at half-maximum (HWHM, γ) of the Lorentzian component [Å]. If given as a single number it is equal for both axes.
eta (float) – Lorentzian mixing fraction η ∈ [0, 1]. η = 0 gives a pure Gaussian; η = 1 gives a pure Lorentzian.
truncate (float, optional) – Truncate the kernel at this many effective half-widths (default 10.0).
- Returns:
filtered_diffraction_patterns – The filtered diffraction pattern(s).
- Return type:
Notes
The pseudo-Voigt profile is PV = (1-η)·G + η·L, where G and L are Gaussian and Lorentzian profiles with widths σ and γ respectively. Width parameterization: FWHM_G = 2√(2 ln 2)·σ ≈ 2.3548·σ; FWHM_L = 2γ.
- radial_binning(...) PolarMeasurements[source]#
Create polar measurement(s) from the diffraction pattern(s) by binning the measurements in annular regions. This method may be used to simulate a segmented detector with a specified number of radial bins.
This is equivalent to detecting a wave function using the FlexibleAnnularDetector.
- Parameters:
step_size (float, optional) – Radial extent of the bins [mrad]. Default is 1.0.
inner (float, optional) – Inner integration limit of the bins [mrad]. Default is 0.0.
outer (float, optional) – Outer integration limit of the bins [mrad]. If not specified, this is set to be the maximum detected angle of the diffraction pattern.
- Returns:
radially_binned_measurement – Radially binned polar measurement(s).
- Return type:
- tile_scan(...) DiffractionPatterns[source]#
Tile the scan axes of the diffraction patterns. The diffraction patterns must have one or more scan axes.
- Parameters:
repetitions (two int) – The number of repetitions of the scan positions along the x- and y-axis.
- Returns:
tiled_diffraction_patterns – The tiled diffraction patterns.
- Return type:
- voigtian_source_size(...) DiffractionPatterns[source]#
Simulate the effect of a finite source size on diffraction pattern(s) using a Voigt filter (convolution of Gaussian and Lorentzian).
The filter mixes intensities across scan axes (not within each diffraction pattern) and requires two linear scan axes. Applying this filter before integrating gives the same result as integrating first and then applying a
voigtian_filter()to the resulting images.- Parameters:
gaussian_sigma (float or two float) – Standard deviation (σ) of the Gaussian component [Å]. If given as a single number it is equal for both axes.
lorentzian_gamma (float or two float) – Half-width at half-maximum (HWHM, γ) of the Lorentzian component [Å]. If given as a single number it is equal for both axes.
truncate (float, optional) – Truncate the Lorentzian component at this many half-widths (default 10.0). The Gaussian component uses the SciPy default (4·σ).
- Returns:
filtered_diffraction_patterns – The filtered diffraction pattern(s).
- Return type:
Notes
The Voigt profile combines two width parameters:
gaussian_sigma(σ): standard deviation of the Gaussian component, FWHM_G = 2√(2 ln 2)·σ ≈ 2.3548·σ.lorentzian_gamma(γ): HWHM of the Lorentzian component, FWHM_L = 2γ.
For the same FWHM, γ = FWHM / 2 but σ = FWHM / (2√(2 ln 2)) ≈ FWHM / 2.3548.
- class abtem.measurements.Images(...)[source]#
Bases:
abtem.measurements._BaseMeasurement2DA collection of 2D measurements such as HRTEM or STEM-ADF images. May be used to represent a reconstructed phase.
- Parameters:
array (ndarray) – 2D or greater array containing data of type float or complex. The second-to-last and last dimensions are the image y- and x-axis, respectively.
sampling (two float) – Lateral sampling of images in x and y [Å].
ensemble_axes_metadata (list of AxisMetadata, optional) – List of metadata associated with the ensemble axes. The length and item order must match the ensemble axes.
metadata (dict, optional) – A dictionary defining measurement metadata.
Initialization
- property base_axes_metadata: list[AxisMetadata]#
- diffractograms() DiffractionPatterns[source]#
Calculate diffractograms (i.e. power spectra) from image(s).
- Returns:
diffractograms – Diffractograms of image(s).
- Return type:
- classmethod from_array_and_metadata(...) Images[source]#
Creates an image from a given array and metadata.
- Parameters:
array (array) – Complex array defining one or more 2D wave functions. The second-to-last and last dimensions are the y- and x-axis.
axes_metadata (list of AxesMetadata) – Axis metadata for each axis. The axis metadata must be compatible with the shape of the array. The last two axes must be RealSpaceAxis.
metadata (dict) – A dictionary defining the measurement metadata.
- Returns:
images – Images from the array and metadata.
- Return type:
- integrate_gradient()[source]#
Calculate integrated gradients. Requires complex images whose real and imaginary parts represent the x and y components of a gradient.
- Returns:
integrated_gradient – The integrated gradient.
- Return type:
- interpolate(...) Images[source]#
Interpolate images producing equivalent images with a different sampling. Either ‘sampling’ or ‘gpts’ must be provided (but not both).
- Parameters:
sampling (float or two float) – Sampling of images after interpolation in x and y [Å].
gpts (int or two int) – Number of grid points of images after interpolation in x and y. Do not use if ‘sampling’ is used.
method ({'fft', 'spline'}) –
The interpolation method.
fft:Interpolate by cropping or zero-padding in reciprocal space. This method should be preferred for periodic images.
spline:Interpolate using spline interpolation. This method should be preferred for non-periodic images.
boundary ({'periodic', 'reflect', 'constant'}) –
The boundary parameter determines how the input array is extended beyond its boundaries for spline interpolation.
periodic:The images are extended by wrapping around to the opposite edge. Use this mode for periodic images (default).
reflect:The images are extended by reflecting about the edge of the last pixel.
constant:The images are extended by filling all values beyond the edge with the same constant value, defined by the ‘cval’ parameter.
order (int) – The order of the spline interpolation (default is 3). The order has to be in the range 0-5.
normalization ({'values', 'amplitude'}) –
The normalization parameter determines which quantity is preserved after normalization.
values:The pixel-wise values of the images are preserved.
intensity:The total intensity of the images is preserved.
cval (scalar, optional) – Value to fill past edges in spline interpolation input if boundary is ‘constant’ (default is 0.0).
- Returns:
interpolated_images – The interpolated images.
- Return type:
- class abtem.measurements.IndexedDiffractionPatterns(...)[source]#
Bases:
abtem.measurements.BaseMeasurementsDiffraction patterns indexed by their Miller indices.
- Parameters:
array (ndarray) – 1D or greater array of type float or complex. The last axis represents the diffraction spots and should have the same length as the number of miller indices, any preceding axis represents an ensemble axis.
miller_indices (ndarray) – The miller indices of the diffraction spots as an N x 3 array where N is the number of miller indices. The order of the miller indices must correspond to the array of intensities. The second axis represents each hkl miller index.
reciprocal_lattice_vectors (ndarray) – The reciprocal lattice vectors of the crystal as a 3 x 3 array. The first axis represents miller indices and the order of the items must correspond to the array of intensities. The second axis represents the reciprocal space positions in x, y and z [1/Å].
ensemble_axes_metadata (list of AxisMetadata, optional) – List of metadata associated with the ensemble axes. The length and item order must match the ensemble axes.
metadata (dict, optional) – A dictionary defining measurement metadata.
Initialization
- property angular_positions#
Scattering angles of the diffraction spots.
- property base_axes_metadata: list[AxisMetadata]#
- block_direct()[source]#
Remove the zero-order spot.
- Returns:
blocked – The indexed diffraction spots without the zero-order spot.
- Return type:
- crop(...)[source]#
Crop the indexed diffraction patterns such that they only include spots with spatial frequencies (scattering angles) up to a given limit.
- Parameters:
- Returns:
cropped – The cropped indexed diffraction spots.
- Return type:
- abstract from_array_and_metadata(...) BaseMeasurements[source]#
- property intensities_dict: dict[tuple, ndarray]#
A dictionary mapping miller indices to intensities.
- normalize_to_spot(...)[source]#
Normalize the intensity of the diffraction spots.
- Parameters:
spot (tuple of three int) – The intensities will be normalized with respect to the intensity of this spot. Defaults to the most intense spot.
- Returns:
normalized_indexed_diffraction_patterns
- Return type:
- property positions_dict: dict[tuple, ndarray]#
A dictionary mapping miller indices to reciprocal space positions [1/Å].
- remove_low_intensity(...)[source]#
Remove diffraction spots with intensity below a threshold for all ensemble dimensions.
- Parameters:
threshold (float) – Intensity threshold for removing diffraction spots.
- Returns:
thresholded_spots – The indexed diffraction spots with an intensity above the given threshold.
- Return type:
- show(...)[source]#
Show the diffraction spots as an EllipseCollection using matplotlib.
- Parameters:
ax (matplotlib.axes.Axes, optional) – If given the plots are added to the axis. This is not available for exploded plots.
cbar (bool, optional) – Add colorbar(s) to the image(s). The size and padding of the colorbars may be adjusted using the set_cbar_size and set_cbar_padding methods.
cmap (str, optional) – Matplotlib colormap name used to map scalar data to colors. If the measurement is complex the colormap must be one of ‘hsv’ or ‘hsluv’.
vmin (float, optional) – Minimum of the intensity color scale. Default is the minimum of the array values.
vmax (float, optional) – Maximum of the intensity color scale. Default is the maximum of the array values.
power (float) – Show diffraction spots intensities on a power scale. Cannot be used together with
logscale.logscale (bool) – If True, show diffraction spots on a logarithmic intensity scale. Cannot be used together with
power != 1.0.common_color_scale (bool, optional) – If True all images in an image grid are shown on the same colorscale, and a single colorbar is created (if it is requested). Default is False.
scale (float, optional) – Scale the radii of the circles representing the diffraction spots.
explode (bool or sequence of bool, optional) – If True, a grid of plots is created for all the items of the last two ensemble axes. If False, the first ensemble item is shown. May be given as a sequence of axis indices to create a grid of plots from the specified axes. The default is determined by the axis metadata.
overlay (bool or sequence of int, optional) – If True, all line profiles in the ensemble are shown in a single plot. If False, only the first ensemble item is shown. May be given as a sequence of axis indices to specify which line profiles in the ensemble to show together. The default is determined by the axis metadata.
figsize (two int, optional) – The figure size given as width and height in inches, passed to matplotlib.pyplot.figure.
title (bool or str, optional) – Set the column title of the plots. If True is given instead of a string the title will be given by the value corresponding to the “name” key of the axes metadata dictionary, if this item exists.
units (str) – The units used for the x and y axes. The given units must be compatible with the axes of the plots.
interact (bool) – If True, create an interactive visualization. This requires enabling the ipympl Matplotlib backend.
display (bool, optional) – If True (default) the figure is displayed immediately.
- Returns:
visualization
- Return type:
- sort(...)[source]#
Sort the diffraction spots according to a given criterion.
- Parameters:
criterion ({'distance', 'intensity'}) –
The boundary parameter determines how the images are extended beyond their boundaries when the filter overlaps with a border.
distance:Sort according to the distance in reciprocal space from the zero frequency.
intensity:Sort according to the intensity of the diffraction spots.
- Returns:
sorted_spots – The indexed diffraction spots sorted according to the given criterion.
- Return type:
- class abtem.measurements.MeasurementsEnsemble(...)[source]#
Bases:
abtem.measurements.BaseMeasurements- property base_axes_metadata#
- show(...) Visualization[source]#
Show the image(s) using matplotlib.
- Parameters:
ax (matplotlib.axes.Axes, optional) – If given the plots are added to the axis. This is not available for exploded plots.
power (float) – Show image on a power scale.
explode (bool, optional) – If True, a grid of images is created for all the items of the last two ensemble axes. If False, the first ensemble item is shown. May be given as a sequence of axis indices to create a grid of images from the specified axes. The default is determined by the axis metadata.
overlay (bool or sequence of int, optional) – If True, all line profiles in the ensemble are shown in a single plot. If False, only the first ensemble item is shown. May be given as a sequence of axis indices to specify which line profiles in the ensemble to show together. The default is determined by the axis metadata.
figsize (two int, optional) – The figure size given as width and height in inches, passed to matplotlib.pyplot.figure.
title (bool or str, optional) – Set the column title of the images. If True is given instead of a string the title will be given by the value corresponding to the “name” key of the axes metadata dictionary, if this item exists.
units (str) – The units used for the x and y axes. The given units must be compatible with the axes of the images.
interact (bool) – If True, create an interactive visualization. This requires enabling the ipympl Matplotlib backend.
display (bool, optional) – If True (default) the figure is displayed immediately.
- Returns:
measurement_visualization_2d
- Return type:
VisualizationImshow
- class abtem.measurements.MomentumResolvedSpectrum(...)[source]#
Bases:
abtem.measurements.BaseMeasurementsMomentum-resolved energy-loss spectrum S(q, E).
Stores a 2D intensity array whose last two dimensions correspond to scattering-vector bins (q) and energy bins (E). Additional leading dimensions are ensemble axes.
Use
crop()to restrict the q/energy-loss range before plotting withshow()– besides zooming in, this also rescales the colour scale (and, for an exploded grid, every panel’s shared colour scale) to the cropped region instead of the full data.- Parameters:
array (ndarray or dask array) – Array of shape
(..., n_q, n_E).q_values (sequence of float) – Scattering-vector values [mrad] for each q bin.
e_values (sequence of float) – Energy-loss values [eV] for each energy bin.
ensemble_axes_metadata (list of AxisMetadata, optional)
metadata (dict, optional)
Initialization
- property base_axes_metadata: list[AxisMetadata]#
- crop(...) MomentumResolvedSpectrum[source]#
Crop the spectrum to a q and/or energy-loss range.
- Parameters:
q_range (tuple of float, optional) – Inclusive
(min, max)scattering-vector range [mrad] to keep. If None (default), the full q range is kept.e_range (tuple of float, optional) – Inclusive
(min, max)energy-loss range [eV] to keep – note this is in eV (the unite_valuesis stored in) regardless of thee_unitsdisplay option ofshow(). If None (default), the full energy range is kept.
- Returns:
cropped – The cropped spectrum.
- Return type:
- classmethod from_array_and_metadata(...) MomentumResolvedSpectrum[source]#
- show(...) tuple[source]#
Show the spectrum as a 2D heatmap with q on the x-axis and energy on the y-axis.
Unlike other abTEM measurements this method plots directly with matplotlib (the q and energy axes are non-linear, so the shared
Visualizationimshow machinery does not apply) and therefore returns the raw matplotlib objects rather than aVisualization.- Parameters:
ax (matplotlib Axes, optional) – Only used for the single-panel case (ignored when exploding).
cbar (bool) – Show colorbar. Default True.
cmap (str, optional) – Colormap name. Default ‘viridis’.
vmin (float, optional) – Colour-scale limits. When exploding, a value left as None is filled from the global min/max across all panels so the shared colorbar is meaningful.
vmax (float, optional) – Colour-scale limits. When exploding, a value left as None is filled from the global min/max across all panels so the shared colorbar is meaningful.
power (float) – Display on a power scale.
explode (bool or sequence of int) – If True, explode all ensemble axes into a panel grid. If a sequence of ints, explode only those ensemble-axis indices (the remaining ensemble axes collapse to their first element). If falsy (default), a single panel is shown.
figsize ((width, height), optional)
title (bool or str) – If a string, used as the (base) title. If True, a default title is generated. If False, no title is set.
e_units (str) – Units for the energy axis (‘meV’ or ‘eV’). Default ‘meV’.
kwargs – Forwarded to
matplotlib.axes.Axes.pcolormesh().
- Returns:
fig, ax – (exploded grid).
- Return type:
matplotlib Figure and Axes (single panel) or ndarray of Axes
- class abtem.measurements.PolarMeasurements(...)[source]#
Bases:
abtem.measurements.BaseMeasurementsClass describing polar measurements with a specified number of radial and azimuthal bins.
Each bin is a segment of an annulus and the bins are spaced equally in the radial and azimuthal directions. The bins may be rotated around the origin, and their center may be shifted from the origin.
- Parameters:
array (ndarray) – Array containing the measurement.
radial_sampling (float) – Sampling of the radial bins [mrad].
azimuthal_sampling (int) – Sampling of the azimuthal bins [rad].
radial_offset (float, optional) – Offset of the bins from the origin [mrad] (default is 0.0).
azimuthal_offset (float, optional) – Rotation of the bins around the origin [rad] (default is 0.0).
ensemble_axes_metadata (list of AxisMetadata, optional) – List of metadata associated with the ensemble axes. The length and item order must match the ensemble axes.
metadata (dict, optional) – A dictionary defining measurement metadata.
- Returns:
polar_measurements – The polar measurements.
- Return type:
Initialization
- property base_axes_metadata: list[AxisMetadata]#
- differentials(...) Images[source]#
Calculate the differential signal by subtracting the intensity of specified detector regions.
- Parameters:
direction_1 (tuple of int or tuple of tuple of int) – The detector regions used for calculating the differential signal for the first direction. The first item is the detector region(s) contributing to the positive term and the second item is the detector region(s) contributing to the negative terms.
direction_2 (tuple of int or tuple of tuple of int) – The detector regions used for calculating the differential signal for the second direction. The first item is the detector region(s) contributing to the positive term and the second item is the detector region(s) contributing to the negative terms.
return_complex (bool, optional) – If True, return a complex image where the real and imaginary part represents direction_1 and direction_2. If False, return images with an ensemble dimension for the directions.
- Returns:
differential_image – The (complex) differential image(s).
- Return type:
- property extent#
- classmethod from_array_and_metadata(...) PolarMeasurements[source]#
Creates polar measurements(s) from a given array and metadata.
- Parameters:
array (array) – Complex array defining one or more polar measurements. The second-to-last and last dimensions are the measurement y- and x-axis.
axes_metadata (list of AxesMetadata) – Axis metadata for each axis. The axis metadata must be compatible with the shape of the array. The last two axes must be RealSpaceAxis.
metadata (dict) – A dictionary defining the measurement metadata.
- Returns:
polar_measurements – Polar measurement(s) from the array and metadata.
- Return type:
- gaussian_source_size(...) PolarMeasurements[source]#
Simulate the effect of a finite source size on diffraction pattern(s) using a Gaussian filter.
The filter is not applied to diffraction pattern individually, but the intensity of diffraction patterns are mixed across scan axes. Applying this filter requires two linear scan axes.
Applying this filter before integrating the diffraction patterns will produce the same image as integrating the diffraction patterns first then applying a Gaussian filter.
- Parameters:
sigma (float or two float) – Standard deviation of Gaussian kernel in the x and y-direction. If given as a single number, the standard deviation is equal for both axes.
- Returns:
filtered_diffraction_patterns – The filtered diffraction pattern(s).
- Return type:
- integrate(...) Images | RealSpaceLineProfiles[source]#
Integrate polar regions to produce an image or line profiles.
- Parameters:
- Returns:
integrated_images
- Return type:
- integrate_radial(...) Images | RealSpaceLineProfiles[source]#
Create images by integrating the polar measurements over an annulus defined by an inner and outer integration angle.
- lorentzian_source_size(...) PolarMeasurements[source]#
Simulate the effect of a finite source size on polar measurement(s) using a Lorentzian (Cauchy) filter.
The filter mixes intensities across scan axes (not within each measurement) and requires two linear scan axes.
- Parameters:
- Returns:
filtered_measurements – The filtered measurement(s).
- Return type:
Notes
The Lorentzian kernel is parameterized by its HWHM γ (
half_width), with FWHM_L = 2γ. This differs fromgaussian_source_size(), which uses the standard deviation σ (FWHM_G ≈ 2.3548·σ).
- property offset#
- poisson_noise(...)[source]#
Add Poisson noise (i.e. shot noise) to a measurement corresponding to the provided ‘total_dose’ (per measurement if applied to an ensemble) or ‘dose_per_area’ (not applicable for single measurements).
- Parameters:
dose_per_area (float, optional) – The irradiation dose per unit of scan area [electrons per Å:sup:2]. This is only valid if the diffraction patterns has two scan axes.
total_dose (float, optional) – The irradiation dose per diffraction pattern.
samples (int, optional) – The number of samples to draw from a Poisson distribution. If this is greater than 1, an additional ensemble axis will be added to the measurement.
seed (int, optional) – Seed the random number generator.
- Returns:
noisy_measurement – The noisy measurement.
- Return type:
- pseudo_voigtian_source_size(...) PolarMeasurements[source]#
Simulate the effect of a finite source size on polar measurement(s) using a pseudo-Voigtian filter (weighted sum of Gaussian and Lorentzian).
The filter mixes intensities across scan axes (not within each measurement) and requires two linear scan axes.
- Parameters:
gaussian_sigma (float or two float) – Standard deviation (σ) of the Gaussian component [Å]. If given as a single number it is equal for both axes.
lorentzian_gamma (float or two float) – Half-width at half-maximum (HWHM, γ) of the Lorentzian component [Å]. If given as a single number it is equal for both axes.
eta (float) – Lorentzian mixing fraction η ∈ [0, 1]. η = 0 gives a pure Gaussian; η = 1 gives a pure Lorentzian.
truncate (float, optional) – Truncate the kernel at this many effective half-widths (default 10.0).
- Returns:
filtered_measurements – The filtered measurement(s).
- Return type:
Notes
The pseudo-Voigt profile is PV = (1-η)·G + η·L, where G and L are Gaussian and Lorentzian profiles with widths σ and γ respectively. Width parameterization: FWHM_G = 2√(2 ln 2)·σ ≈ 2.3548·σ; FWHM_L = 2γ.
- property sampling#
- show(...) Visualization[source]#
Show the polar measurements as an image or a grid of images. The images are shown by discretizing the polar bins on a regular grid.
- Parameters:
ax (matplotlib.axes.Axes, optional) – If given the plots are added to the axis. This is not available for exploded plots.
gpts (int or tuple of int, optional) – Number of grid points in the image(s).
cbar (bool, optional) – Add colorbar(s) to the image(s). The size and padding of the colorbars may be adjusted using the set_cbar_size and set_cbar_padding methods.
cmap (str, optional) – Matplotlib colormap name used to map scalar data to colors. If the measurement is complex the colormap must be one of ‘hsv’ or ‘hsluv’.
vmin (float, optional) – Minimum of the intensity color scale. Default is the minimum of the array values.
vmax (float, optional) – Maximum of the intensity color scale. Default is the maximum of the array values.
power (float) – Show image on a power scale. Cannot be used together with
logscale.logscale (bool) – If True, show image on a logarithmic intensity scale. Cannot be used together with
power != 1.0.common_color_scale (bool, optional) – If True all images in an image grid are shown on the same colorscale, and a single colorbar is created (if it is requested). Default is False.
explode (bool, optional) – If True, a grid of images is created for all the items of the last two ensemble axes. If False, the first ensemble item is shown. May be given as a sequence of axis indices to create a grid of images from the specified axes. The default is determined by the axis metadata.
overlay (bool or sequence of int, optional) – If True, all line profiles in the ensemble are shown in a single plot. If False, only the first ensemble item is shown. May be given as a sequence of axis indices to specify which line profiles in the ensemble to show together. The default is determined by the axis metadata.
figsize (two int, optional) – The figure size given as width and height in inches, passed to matplotlib.pyplot.figure.
title (bool or str, optional) – Set the column title of the images. If True is given instead of a string the title will be given by the value corresponding to the “name” key of the axes metadata dictionary, if this item exists.
units (str) – The units used for the x and y axes. The given units must be compatible with the axes of the images.
interact (bool) – If True, create an interactive visualization. This requires enabling the ipympl Matplotlib backend.
display (bool, optional) – If True (default) the figure is displayed immediately.
- Returns:
measurement_visualization_2d
- Return type:
MeasurementVisualizationImshow
- to_diffraction_patterns(...)[source]#
Convert the polar measurements to diffraction patterns by discretizing the polar bins on a regular grid.
- Parameters:
- Returns:
diffraction_patterns – The diffraction patterns discretized from the polar measurements.
- Return type:
- to_image_ensemble()[source]#
Convert the polar measurements to an ensemble of images, where the radial and azimuthal angles becomes ensemble axes.
- Returns:
image_ensemble
- Return type:
- voigtian_source_size(...) PolarMeasurements[source]#
Simulate the effect of a finite source size on polar measurement(s) using a Voigt filter (convolution of Gaussian and Lorentzian).
The filter mixes intensities across scan axes (not within each measurement) and requires two linear scan axes.
- Parameters:
gaussian_sigma (float or two float) – Standard deviation (σ) of the Gaussian component [Å]. If given as a single number it is equal for both axes.
lorentzian_gamma (float or two float) – Half-width at half-maximum (HWHM, γ) of the Lorentzian component [Å]. If given as a single number it is equal for both axes.
truncate (float, optional) – Truncate the Lorentzian component at this many half-widths (default 10.0). The Gaussian component uses the SciPy default (4·σ).
- Returns:
filtered_measurements – The filtered measurement(s).
- Return type:
Notes
The Voigt profile combines two width parameters:
gaussian_sigma(σ): standard deviation of the Gaussian component, FWHM_G = 2√(2 ln 2)·σ ≈ 2.3548·σ.lorentzian_gamma(γ): HWHM of the Lorentzian component, FWHM_L = 2γ.
For the same FWHM, γ = FWHM / 2 but σ = FWHM / (2√(2 ln 2)) ≈ FWHM / 2.3548.
- class abtem.measurements.RealSpaceLineProfiles(...)[source]#
Bases:
abtem.measurements._BaseMeasurement1DA collection of real-space line profile(s).
- Parameters:
array (ndarray) – 1D or greater array containing data of type float or complex.
sampling (float) – Sampling of line profiles [Å].
ensemble_axes_metadata (list of AxisMetadata, optional) – List of metadata associated with the ensemble axes. The length and item order must match the ensemble axes.
metadata (dict, optional) – A dictionary defining measurement metadata.
Initialization
- property base_axes_metadata: list[RealSpaceAxis]#
- tile(...) RealSpaceLineProfiles[source]#
Tile line profiles(s).
- Parameters:
repetitions (int) – The number of repetitions of the line profiles.
- Returns:
tiled_line_profiles – The tiled line profiles(s).
- Return type:
- class abtem.measurements.ReciprocalSpaceLineProfiles(...)[source]#
Bases:
abtem.measurements._BaseMeasurement1DA collection of reciprocal-space line profile(s).
- Parameters:
array (ndarray) – 1D or greater array containing data of type float or complex.
sampling (float) – Sampling of line profiles [1 / Å].
ensemble_axes_metadata (list of AxisMetadata, optional) – List of metadata associated with the ensemble axes. The length and item order must match the ensemble axes.
metadata (dict, optional) – A dictionary defining measurement metadata.
Initialization
- property angular_extent#
Extent of line profiles given as scattering angels [mrad].
- property base_axes_metadata: list[AxisMetadata]#
- abtem.measurements.integrate_disc(...) float[source]#
Integrate the values of a 2d measurement on a disc-shaped region.
- Parameters:
measurement (2d measurement) – The measurement to integrate
position (two floats) – Center of disc-shaped integration region
radius (float) – Radius of disc-shaped integration region
return_mean (bool) – If true return the mean, otherwise return the sum.
border (str) –
Specify how to treat integration regions that cross the image border. The valid values and their behaviours are:
- ’wrap’
The measurement is extended by wrapping around to the opposite edge.
- ’raise’
Raise an error if the integration region crosses the measurement border.
interpolate (float or False) – The image will be interpolated to this sampling. Units of Angstrom.
- Returns:
Integral value
- Return type:
- abtem.measurements.momentum_resolved_spectrum(...) MomentumResolvedSpectrum[source]#
Build S(q, E) from energy-resolved TDS diffraction patterns.
Dispatches on the type of detector:
SpectralAnnularDetector— sweeps an offset circular acceptance disk (acceptance radiusouter, inner always 0) along a radial direction at each q-step. The q-axis runs fromq_mintoq_maxin steps ofouter(one disk-radius per step).SpectralSlitDetector— usesDiffractionPatterns.interpolate_line()(spline interpolation) to integrate strips along the slit’s long axis. Samples directly fromq_mintoq_max(defaultq_min=0includes the direct beam). The integration aperture perpendicular to q has full widthwidth(=2 * outerof an equivalent annular detector).
Both detector types share the same
q_min/q_maxconvention — the same numerical values yield the same q-range in the output spectrum:SpectralAnnularDetector(outer=r, q_min=Q0, q_max=Q) SpectralSlitDetector(q_min=Q0, q_max=Q, width=2*r)
- Parameters:
tds_diffraction_patterns (DiffractionPatterns) – Energy-resolved TDS diffraction patterns as returned by
phonon_loss_diffraction_patterns(). Must have anEnergyLossAxisin its ensemble axes.detector (SpectralAnnularDetector or SpectralSlitDetector) – Detector that controls the integration strategy and q-range.
- Return type:
- abtem.measurements.pd: Optional[ModuleType]#
None
- abtem.measurements.periodic_crop(...) ndarray[source]#
Crop an array with periodic boundary conditions. The cropping region is wrapped around the array.
- Parameters:
array (ndarray) – The array to crop.
corner (two floats) – The corner of the cropping region.
new_shape (two ints) – The shape of the cropping region.
- Returns:
cropped_array – The cropped array.
- Return type:
ndarray
- abtem.measurements.phonon_loss_diffraction_patterns(...) DiffractionPatterns[source]#
Compute inelastic (TDS) diffraction patterns from energy-resolved frozen-phonon exit waves.
The thermal diffuse scattering signal is obtained per energy bin as:
I_coherent = |FT(Σ_j psi_j)|² / N² (elastic) I_incoherent = Σ_j |FT(psi_j)|² / N (total) I_tds = I_incoherent - I_coherent (inelastic / phonon loss)
The returned
DiffractionPatternsretain theEnergyLossAxisbut theFrozenPhononsAxisis collapsed. Apply an offsetAnnularDetectororSlitDetectorto integrate over desired q points.Note that
I_tdsis the variance of the diffracted amplitude across frozen-phonon configurations: with a single configuration per energy,I_incoherentandI_coherentare identical by construction andI_tdsis exactly zero everywhere, not a numerical artifact. At least 2 configurations per energy are required forcomponent="tds"/"all"(this is enforced with aValueError); in practice many more are needed for good statistics.- Parameters:
exit_waves (Waves) – Complex exit waves from a multislice simulation with an
EnergyResolvedAtomsEnsemble(ensemble_mean=False). Must contain both aFrozenPhononsAxisand anEnergyLossAxisin its ensemble axes. If the potential used more than one slice, prefer building it withprojection="finite"— see theEnergyResolvedAtomsEnsemblenotes on slice-boundary artifacts with out-of-plane displacement.component ({'tds', 'coherent', 'incoherent', 'all'}) – Which component to return.
'all'stacks the three along a new leadingOrdinalAxis(label='component').max_angle (str or float) – Passed to
Waves.diffraction_patterns.parity (str) – Passed to
Waves.diffraction_patterns.block_direct (bool or float, optional) – If True, the direct beam is blocked in the resulting diffraction patterns. If given as a float, masks up to that scattering angle [mrad]. Default is False.
temperature (float, optional) – Sample temperature [K]. If given, unfolds the TDS signal — computed from a single frozen-phonon run per energy magnitude — into signed quantum loss (
+E) and gain (-E) sides using Bose-Einstein detailed balance, following P. Zeiger’s approach. Requirescomponent="tds"and anEnergyLossAxiswhose values start at 0 and strictly increase (the classical/incoherent-minus-coherent signal is symmetric in loss/gain; only their split is a quantum effect). The zero-energy bin is unweighted. Default is None (no unfolding — the returned energies are the ones inexit_waves).
- Returns:
Intensity patterns with the
FrozenPhononsAxisremoved and theEnergyLossAxispreserved (or replaced by its signed loss/gain unfolding iftemperatureis given).- Return type:
- abtem.measurements.xr: Optional[ModuleType]#
None