DiffractionPatterns

Contents

DiffractionPatterns#

class abtem.measurements.DiffractionPatterns(array, sampling, fftshift=False, ensemble_axes_metadata=None, metadata=None)[source]#

Bases: _BaseMeasurement2D

One or more diffraction patterns.

Parameters:
  • array (np.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.

__init__(array, sampling, fftshift=False, ensemble_axes_metadata=None, metadata=None)[source]#

Methods

__init__(array, sampling[, fftshift, ...])

abs()

Calculates the absolute value of a complex-valued measurement.

apply_func(func, **kwargs)

rtype:

TypeVar(T, bound= ArrayObject)

apply_transform(transform[, max_batch])

Transform the wave functions by a given transformation.

azimuthal_average([max_angle, ...])

Calculate the azimuthal averages of the diffraction patterns.

bandlimit(inner, outer)

Bandlimit diffraction pattern(s) by setting everything outside an annulus defined by two radial angles to zero.

block_direct([radius, margin])

Block the direct beam by setting the pixels of the zeroth-order Bragg reflection (non-scattered beam) to zero.

center_of_mass([units])

Calculate center-of-mass images or line profiles from diffraction patterns.

compute([progress_bar, profiler, ...])

Turn a lazy abTEM object into its in-memory equivalent.

copy()

Make a copy.

copy_to_device(device)

Copy array to specified device.

crop([max_angle, max_frequency, gpts])

Crop the diffraction patterns such that they only include spatial frequencies (scattering angles) up to a given limit.

ensemble_blocks([chunks])

Split the ensemble into an array of smaller ensembles.

ensure_lazy([chunks])

Creates an equivalent lazy version of the array object.

expand_dims([axis, axis_metadata])

Expand the shape of the array object.

fourier_shell_correlation(other[, ...])

from_array_and_metadata(array, axes_metadata)

Creates diffraction pattern(s) from a given array and metadata.

from_zarr(url[, chunks])

Read wave functions from a hdf5 file.

gaussian_filter(sigma[, boundary, cval])

Apply 2D gaussian filter to measurements.

gaussian_source_size(sigma)

Simulate the effect of a finite source size on diffraction pattern(s) using a Gaussian filter.

generate_blocks([chunks])

Generate chunks of the ensemble.

generate_ensemble([keepdims])

Generate every member of the ensemble.

get_from_metadata(name[, broadcastable])

get_items(items[, keepdims])

Index the array and the corresponding axes metadata.

imag()

Returns the imaginary part of a complex-valued measurement.

index_diffraction_spots(cell[, ...])

Indexes the Bragg reflections (diffraction spots) by their Miller indices.

integrate_radial(inner, outer[, offset])

Create images by integrating the diffraction patterns over an annulus defined by an inner and outer integration angle.

integrated_center_of_mass()

Calculate integrated center-of-mass (iCOM) images from diffraction patterns.

intensity()

Calculates the squared norm of a complex-valued measurement.

interpolate([sampling, gpts])

Interpolate diffraction pattern(s) producing equivalent pattern(s) with a different sampling.

interpolate_line([start, end, sampling, ...])

Interpolate image(s) along a given line.

interpolate_line_at_position(center, angle, ...)

Interpolate image(s) along a line centered at a specified position.

lazy([chunks])

rtype:

TypeVar(T, bound= ArrayObject)

max([axis, keepdims, split_every])

Maximum of array object over one or more axes.

mean([axis, keepdims, split_every])

Mean of array object over one or more axes.

min([axis, keepdims, split_every])

Minmimum of array object over one or more axes.

no_base_chunks()

Rechunk to remove chunks across the base dimensions.

normalize_ensemble([scale, shift])

Normalize the ensemble by shifting ad scaling each member.

phase()

Calculates the phase of a complex-valued measurement.

poisson_noise([dose_per_area, total_dose, ...])

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).

polar_binning(nbins_radial, nbins_azimuthal)

Create polar measurements from the diffraction patterns by binning the measurements on a polar grid.

radial_binning([step_size, inner, outer])

Create polar measurement(s) from the diffraction pattern(s) by binning the measurements in annular regions.

real()

Returns the real part of a complex-valued measurement.

rechunk(chunks, **kwargs)

Rechunk dask array.

reduce_ensemble()

Calculates the mean of an ensemble measurement (e.g. of frozen phonon configurations).

relative_difference(other[, min_relative_tol])

Calculates the relative difference with respect to another compatible measurement.

select_block(index, chunks)

Select a block from the ensemble.

set_ensemble_axes_metadata(axes_metadata, axis)

Sets the axes metadata of an ensemble axis.

show([ax, cbar, cmap, vmin, vmax, power, ...])

Show the image(s) using matplotlib.

squeeze([axis])

Remove axes of length one from array object.

std([axis, keepdims, split_every])

Standard deviation of array object over one or more axes.

sum([axis, keepdims, split_every])

Sum of array object over one or more axes.

tile_scan(repetitions)

Tile the scan axes of the diffraction patterns.

to_cpu()

Move the array to the host memory from an arbitrary source array.

to_data_array()

Convert ArrayObject to a xarray DataArray.

to_gpu([device])

Move the array from the host memory to a gpu.

to_hyperspy()

Convert ArrayObject to a Hyperspy signal.

to_measurement_ensemble()

to_tiff(filename, **kwargs)

Write data to a tiff file.

to_zarr(url[, compute, overwrite])

Write data to a zarr file.

Attributes

angular_coordinates

Scattering angle coordinates [mrad].

angular_limits

Lowest and highest scattering angle in x and y [mrad].

angular_sampling

Angular sampling of diffraction patterns in x and y [mrad].

array

Underlying array describing the array object.

axes_metadata

List of AxisMetadata.

base_axes_metadata

List of AxisMetadata of the base axes.

base_dims

Number of base dimensions.

base_shape

Shape of the base axes of the underlying array.

coordinates

Reciprocal-space frequency coordinates [1 / Å].

device

The device where the array is stored.

dtype

Datatype of array.

ensemble_axes_metadata

List of AxisMetadata of the ensemble axes.

ensemble_dims

Number of ensemble dimensions.

ensemble_shape

Shape of the ensemble axes of the underlying array.

extent

Extent of measurements in x and y [Å] or [1/Å].

fftshift

True if the zero-frequency is shifted to the center of the array.

is_complex

True if array is complex.

is_lazy

True if array is lazy.

limits

Lowest and highest spatial frequency in x and y [1 / Å].

max_angles

Maximum scattering angle in x and y [mrad].

max_frequency

metadata

Metadata describing the measurement.

offset

The offset of the origin of the measurement coordinates [Å] or [1/Å].

sampling

Sampling of the measurements in x and y [Å] or [1/Å].

shape

Shape of the underlying array.

abs()#

Calculates the absolute value of a complex-valued measurement.

Return type:

TypeVar(T, bound= BaseMeasurements)

property angular_coordinates: tuple[ndarray, ndarray]#

Scattering angle coordinates [mrad].

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].

apply_transform(transform, max_batch='auto')#

Transform the wave functions by a given transformation.

Parameters:
  • transform (ArrayObjectTransform) – The array object transformation to apply.

  • max_batch (int, optional) – The number of wave functions in each chunk of the Dask array. If ‘auto’ (default), the batch size is automatically chosen based on the abtem user configuration settings “dask.chunk-size” and “dask.chunk-size-gpu”.

Returns:

transformed_array_object – The transformed array object.

Return type:

ArrayObjectTransform

property array: ndarray | Array#

Underlying array describing the array object.

property axes_metadata: AxesMetadataList#

List of AxisMetadata.

azimuthal_average(max_angle=None, radial_sampling=1.0, weighting_function='step', width=1.0)[source]#

Calculate the azimuthal averages of the diffraction patterns.

Parameters:
  • max_angle (float, optional) – The maximum included scattering angle in the azimuthal averages [mrad].

  • order (float, optional) – The spline interpolation order. Default is 1.

  • 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.

  • weigthing_method (str) –

Return type:

ReciprocalSpaceLineProfiles

bandlimit(inner, outer)[source]#

Bandlimit diffraction pattern(s) by setting everything outside an annulus defined by two radial angles to zero.

Parameters:
  • inner (float) – Inner limit of zero region [mrad].

  • outer (float) – Outer limit of zero region [mrad].

Returns:

band-limited_diffraction_patterns – The band-limited diffraction pattern(s).

Return type:

DiffractionPatterns

property base_axes_metadata#

List of AxisMetadata of the base axes.

property base_dims#

Number of base dimensions.

property base_shape: tuple[int, ...]#

Shape of the base axes of the underlying array.

block_direct(radius=None, margin=None)[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:

DiffractionPatterns

center_of_mass(units='1/Å')[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.

Return type:

Images | RealSpaceLineProfiles

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).

compute(progress_bar=None, profiler=False, resource_profiler=False, **kwargs)#

Turn a lazy abTEM object into its in-memory equivalent.

Parameters:
  • progress_bar (bool) – Display a progress bar in the terminal or notebook during computation. The progress bar is only displayed with a local scheduler.

  • profiler (bool) – Return Profiler class used to profile Dask’s execution at the task level. Only execution with a local is profiled.

  • resource_profiler (bool) – Return ResourceProfiler class is used to profile Dask’s execution at the resource level.

  • kwargs – Additional keyword arguments passes to dask.compute.

property coordinates: tuple[ndarray, ndarray]#

Reciprocal-space frequency coordinates [1 / Å].

copy()#

Make a copy.

copy_to_device(device)#

Copy array to specified device.

Parameters:

device (str) –

Returns:

object_on_device

Return type:

T

crop(max_angle=None, max_frequency=None, gpts=None)[source]#

Crop the diffraction patterns such that they only include spatial frequencies (scattering angles) up to a given limit.

Parameters:
  • max_angle (float, optional) – The maximum included scattering angle in the cropped diffraction patterns.

  • max_frequency (float, optional) – The maximum included spatial frequency in the cropped diffraction patterns.

  • gpts (tuple of int) – The number of gpts in the cropped diffraction patterns.

Returns:

cropped_diffraction_patterns

Return type:

DiffractionPatterns

property device: str#

The device where the array is stored.

property dtype: base#

Datatype of array.

property ensemble_axes_metadata#

List of AxisMetadata of the ensemble axes.

ensemble_blocks(chunks=None)#

Split the ensemble into an array of smaller ensembles.

Parameters:

chunks (iterable of tuples) – Block sizes along each dimension.

Return type:

Array

property ensemble_dims#

Number of ensemble dimensions.

property ensemble_shape: tuple[int, ...]#

Shape of the ensemble axes of the underlying array.

ensure_lazy(chunks='auto')#

Creates an equivalent lazy version of the array object.

Parameters:

chunks (int or tuple or str) – How to chunk the array. See dask.array.from_array.

Returns:

lazy_array_object – Lazy version of the array object.

Return type:

ArrayObject or subclass of ArrayObject

expand_dims(axis=None, axis_metadata=None)#

Expand the shape of the array object.

Parameters:
  • axis (int or tuple of ints) – Position in the expanded axes where the new axis (or axes) is placed.

  • axis_metadata (AxisMetadata or List of AxisMetadata, optional) – The axis metadata describing the expanded axes. Default is UnknownAxis.

Returns:

expanded – View of array object with the number of dimensions increased.

Return type:

ArrayObject or subclass of ArrayObject

property extent: tuple[float, float]#

Extent of measurements in x and y [Å] or [1/Å].

property fftshift: bool#

True if the zero-frequency is shifted to the center of the array.

classmethod from_array_and_metadata(array, axes_metadata, metadata=None)[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:

DiffractionPatterns

classmethod from_zarr(url, chunks='auto')#

Read wave functions from a hdf5 file.

Return type:

TypeVar(T, bound= ArrayObject)

urlstr

Location of the data, typically a path to a local file. A URL can also include a protocol specifier like s3:// for remote data.

chunkstuple of ints or tuples of ints

Passed to dask.array.from_array(), allows setting the chunks on initialisation, if the chunking scheme in the on-disc dataset is not optimal for the calculations to follow.

gaussian_filter(sigma, boundary='periodic', cval=0.0)#

Apply 2D gaussian filter to measurements.

Parameters:
  • sigma (float or two float) – Standard deviation for the Gaussian kernel in the x and y-direction. If given as a single number, the standard deviation is equal for both axes.

  • boundary ({'periodic', 'reflect', 'constant'}) –

    The boundary parameter determines how the images are extended beyond their boundaries when the filter overlaps with a border.

    periodic :

    The images are extended by wrapping around to the opposite edge. Use this mode for periodic (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.

  • cval (scalar, optional) – Value to fill past edges in spline interpolation input if boundary is ‘constant’ (default is 0.0).

Returns:

filtered_images – The filtered image(s).

Return type:

Images

gaussian_source_size(sigma)[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:

DiffractionPatterns

generate_blocks(chunks=1)#

Generate chunks of the ensemble.

Parameters:

chunks (iterable of tuples) – Block sizes along each dimension.

generate_ensemble(keepdims=False)#

Generate every member of the ensemble.

Parameters:

keepdims (bool, opptional) – If True, all ensemble axes are left in the result as dimensions with size one. Default is False.

Yields:

ArrayObject or subclass of ArrayObject – Member of the ensemble.

get_items(items, keepdims=False)#

Index the array and the corresponding axes metadata. Only ensemble axes can be indexed.

Parameters:
  • items (int or tuple of int or slice) – The array is indexed according to this.

  • keepdims (bool, optional) – If True, all ensemble axes are left in the result as dimensions with size one. Default is False.

Returns:

indexed_array – The indexed array object.

Return type:

ArrayObject or subclass of ArrayObject

imag()#

Returns the imaginary part of a complex-valued measurement.

Return type:

TypeVar(T, bound= BaseMeasurements)

index_diffraction_spots(cell, orientation_matrices=None, sg_max=None, k_max=None, energy=None, centering='P')[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).

  • centering ({'P', 'F', 'I', 'A', 'B', 'C'}) – Assumed lattice centering used for determining the reflection conditions.

Returns:

indexed_patterns – The indexed diffraction pattern(s).

Return type:

IndexedDiffractionPatterns

integrate_radial(inner, outer, offset=(0.0, 0.0))[source]#

Create images by integrating the diffraction patterns over an annulus defined by an inner and outer integration angle.

Parameters:
  • inner (float) – Inner integration limit [mrad].

  • outer (float) – Outer integration limit [mrad].

  • offset (tuple of float) – Offset of center of annular integration region [mrad].

Returns:

integrated_images – The integrated images.

Return type:

Images

integrated_center_of_mass()[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:

Images

intensity()#

Calculates the squared norm of a complex-valued measurement.

Return type:

TypeVar(T, bound= BaseMeasurements)

interpolate(sampling=None, gpts=None)[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:

DiffractionPatterns

interpolate_line(start=None, end=None, sampling=None, gpts=None, width=0.0, margin=0.0, order=3, endpoint=False, fractional=False)#

Interpolate image(s) along a given line. Either ‘sampling’ or ‘gpts’ must be provided.

Parameters:
  • start (two float, Atom, optional) – Starting position of the line [Å] (alternatively taken from a selected atom).

  • end (two float, Atom, optional) – Ending position of the line [Å] (alternatively taken from a selected atom).

  • sampling (float) – Sampling of grid points along the line [1 / Å].

  • gpts (int) – Number of grid points along the line.

  • width (float, optional) – The interpolation will be averaged across a perpendicular distance equal to this width.

  • margin (float or tuple of float, optional) – Add margin [Å] to the start and end interpolated line.

  • order (int, optional) – The spline interpolation order.

  • endpoint (bool) – Sets whether the ending position is included or not.

  • fractional (bool) – If True, use fractional coordinates with respect to the extent of the measurement.

Returns:

line_profiles – The interpolated line(s).

Return type:

RealSpaceLineProfiles

interpolate_line_at_position(center, angle, extent, gpts=None, sampling=None, width=0.0, order=3, endpoint=True)#

Interpolate image(s) along a line centered at a specified position.

Parameters:
  • center (two float) – Center position of the line [Å]. May be given as an Atom.

  • angle (float) – Angle of the line [deg.].

  • extent (float) – Extent of the line [Å].

  • gpts (int) – Number of grid points along the line.

  • sampling (float) – Sampling of grid points along the line [Å].

  • width (float, optional) – The interpolation will be averaged across a perpendicular distance equal to this width.

  • order (int, optional) – The spline interpolation order.

  • endpoint (bool) – Sets whether the ending position is included or not.

Returns:

line_profiles – The interpolated line(s).

Return type:

RealSpaceLineProfiles or ReciprocalSpaceProfiles

property is_complex: bool#

True if array is complex.

property is_lazy: bool#

True if array is lazy.

property limits: list[tuple[float, float]]#

Lowest and highest spatial frequency in x and y [1 / Å].

max(axis=None, keepdims=False, split_every=2)#

Maximum of array object over one or more axes. Only ensemble axes can be reduced.

Parameters:
  • axis (int or tuple of ints, optional) – Axis or axes along which a maxima are calculated. The default is to compute the mean of the flattened array. If this is a tuple of ints, the maxima are calculated over multiple axes. The indicated axes must be ensemble axes.

  • keepdims (bool, optional) – If True, the reduced axes are left in the result as dimensions with size one. Default is False.

  • split_every (int) – Only used for lazy arrays. See dask.array.reductions.

Returns:

reduced_array – The reduced array object.

Return type:

ArrayObject or subclass of ArrayObject

property max_angles: tuple[float, float]#

Maximum scattering angle in x and y [mrad].

mean(axis=None, keepdims=False, split_every=2)#

Mean of array object over one or more axes. Only ensemble axes can be reduced.

Parameters:
  • axis (int or tuple of ints, optional) – Axis or axes along which a means are calculated. The default is to compute the mean of the flattened array. If this is a tuple of ints, the mean is calculated over multiple axes. The indicated axes must be ensemble axes.

  • keepdims (bool, optional) – If True, the reduced axes are left in the result as dimensions with size one. Default is False.

  • split_every (int) – Only used for lazy arrays. See dask.array.reductions.

Returns:

reduced_array – The reduced array object.

Return type:

ArrayObject or subclass of ArrayObject

property metadata: dict#

Metadata describing the measurement.

min(axis=None, keepdims=False, split_every=2)#

Minmimum of array object over one or more axes. Only ensemble axes can be reduced.

Parameters:
  • axis (int or tuple of ints, optional) – Axis or axes along which a minima are calculated. The default is to compute the mean of the flattened array. If this is a tuple of ints, the minima are calculated over multiple axes. The indicated axes must be ensemble axes.

  • keepdims (bool, optional) – If True, the reduced axes are left in the result as dimensions with size one. Default is False.

  • split_every (int) – Only used for lazy arrays. See dask.array.reductions.

Returns:

reduced_array – The reduced array object.

Return type:

ArrayObject or subclass of ArrayObject

no_base_chunks()#

Rechunk to remove chunks across the base dimensions.

normalize_ensemble(scale='max', shift='mean')#

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

property offset: tuple[float, float]#

The offset of the origin of the measurement coordinates [Å] or [1/Å].

phase()#

Calculates the phase of a complex-valued measurement.

Return type:

TypeVar(T, bound= BaseMeasurements)

poisson_noise(dose_per_area=None, total_dose=None, samples=1, seed=None)[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:

BaseMeasurements

polar_binning(nbins_radial, nbins_azimuthal, inner=0.0, outer=None, rotation=0.0, offset=(0.0, 0.0))[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:

PolarMeasurements

radial_binning(step_size=1.0, inner=0.0, outer=None)[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:

PolarMeasurements

real()#

Returns the real part of a complex-valued measurement.

Return type:

TypeVar(T, bound= BaseMeasurements)

rechunk(chunks, **kwargs)#

Rechunk dask array.

chunksint or tuple or str

How to rechunk the array. See dask.array.rechunk.

kwargs :

Additional keyword arguments passes to dask.array.rechunk.

reduce_ensemble()#

Calculates the mean of an ensemble measurement (e.g. of frozen phonon configurations).

Return type:

TypeVar(T, bound= BaseMeasurements)

relative_difference(other, min_relative_tol=0.0)#

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:

BaseMeasurements

property sampling: tuple[float, float]#

Sampling of the measurements in x and y [Å] or [1/Å].

select_block(index, chunks)#

Select a block from the ensemble.

Parameters:
  • index (tuple of ints) – Index of selected block.

  • chunks (iterable of tuples) – Block sizes along each dimension.

set_ensemble_axes_metadata(axes_metadata, axis)#

Sets the axes metadata of an ensemble axis.

Parameters:
  • axes_metadata (AxisMetadata) – The new axis metadata.

  • axis (int) – The axis to set.

property shape: tuple[int, ...]#

Shape of the underlying array.

show(ax=None, cbar=False, cmap=None, vmin=None, vmax=None, power=1.0, common_color_scale=False, explode=(), overlay=(), figsize=None, title=True, units=None, interact=False, display=True, **kwargs)#

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.

  • 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.

  • 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.

  • 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

squeeze(axis=None)#

Remove axes of length one from array object.

Parameters:

axis (int or tuple of ints, optional) – Selects a subset of the entries of length one in the shape.

Returns:

squeezed – The input array object, but with all or a subset of the dimensions of length 1 removed.

Return type:

ArrayObject or subclass of ArrayObject

std(axis=None, keepdims=False, split_every=2)#

Standard deviation of array object over one or more axes. Only ensemble axes can be reduced.

Parameters:
  • axis (int or tuple of ints, optional) – Axis or axes along which a standard deviations are calculated. The default is to compute the mean of the flattened array. If this is a tuple of ints, the standard deviations are calculated over multiple axes. The indicated axes must be ensemble axes.

  • keepdims (bool, optional) – If True, the reduced axes are left in the result as dimensions with size one. Default is False.

  • split_every (int) – Only used for lazy arrays. See dask.array.reductions.

Returns:

reduced_array – The reduced array object.

Return type:

ArrayObject or subclass of ArrayObject

sum(axis=None, keepdims=False, split_every=2)#

Sum of array object over one or more axes. Only ensemble axes can be reduced.

Parameters:
  • axis (int or tuple of ints, optional) – Axis or axes along which a sums are performed. The default is to compute the mean of the flattened array. If this is a tuple of ints, the sum is performed over multiple axes. The indicated axes must be ensemble axes.

  • keepdims (bool, optional) – If True, the reduced axes are left in the result as dimensions with size one. Default is False.

  • split_every (int) – Only used for lazy arrays. See dask.array.reductions.

Returns:

reduced_array – The reduced array object.

Return type:

ArrayObject or subclass of ArrayObject

tile_scan(repetitions)[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, respectively.

Returns:

tiled_diffraction_patterns – The tiled diffraction patterns.

Return type:

DiffractionPatterns

to_cpu()#

Move the array to the host memory from an arbitrary source array.

Return type:

TypeVar(T, bound= ArrayObject)

to_data_array()#

Convert ArrayObject to a xarray DataArray.

to_gpu(device='gpu')#

Move the array from the host memory to a gpu.

Return type:

TypeVar(T, bound= ArrayObject)

to_hyperspy()#

Convert ArrayObject to a Hyperspy signal.

to_tiff(filename, **kwargs)#

Write data to a tiff file.

Parameters:
  • filename (str) – The filename of the file to write.

  • kwargs – Keyword arguments passed to tifffile.imwrite.

to_zarr(url, compute=True, overwrite=False, **kwargs)#

Write data to a zarr file.

Parameters:
  • url (str) – Location of the data, typically a path to a local file. A URL can also include a protocol specifier like s3:// for remote data.

  • compute (bool) – If true compute immediately; return dask.delayed.Delayed otherwise.

  • overwrite (bool) – If given array already exists, overwrite=False will cause an error, where overwrite=True will replace the existing data.

  • kwargs – Keyword arguments passed to dask.array.to_zarr.