pyxem.signals package

Submodules

pyxem.signals.crystallographic_map module

class pyxem.signals.crystallographic_map.CrystallographicMap(*args, **kwargs)[source]

Bases: hyperspy.signal.BaseSignal

Crystallographic mapping results containing the best matching crystal phase and orientation at each navigation position with associated metrics.

The Signal at each navigation position is an array of,

[phase, np.array((z,x,z)), dict(metrics)]

which defines the phase, orientation as Euler angles in the zxz convention and metrics associated with the indexation / matching.

Metrics depend on the method used (template matching vs. vector matching) to obtain the crystallographic map.

‘correlation’ ‘match_rate’ ‘total_error’ ‘orientation_reliability’ ‘phase_reliability’

method

Method used to obtain crystallographic mapping results, may be ‘template_matching’ or ‘vector_matching’.

Type

string

get_distance_from_modal_angle()[source]

Obtain the misorinetation with respect to the modal angle for the scan region, at each navigation position.

NB: This view of the data is typically only useful when the orientation spread across the navigation axes is small.

Returns

mode_distance_map – Misorientation with respect to the modal angle at each navigtion position.

Return type

list

See also

method()

save_mtex_map

get_metric_map(metric)[source]

Obtain a map of an indexation / matching metric at each navigation position.

Parameters

metric (string) – String identifier for the indexation / matching metric to be mapped, for template matching valid metrics are {‘correlation’, ‘orientation_reliability’, ‘phase_reliability’}. For vector matching valid metrics are {‘match_rate’, ‘ehkls’, ‘total_error’, ‘orientation_reliability’, ‘phase_reliability’}.

Returns

metric_map – A map of the specified metric at each navigation position.

Return type

Signal2D

Notes

For template matching, orientation reliability is given by

100 * (1 - second_best_correlation/best_correlation)

and phase reliability is given by

100 * (1 - second_best_correlation_of_other_phase/best_correlation)

For vector matching, orientation reliability is given by

100 * (1 - lowest_error/second_lowest_error)

and phase reliability is given by

100 * (1 - lowest_error/lowest_error_of_other_phase)

get_modal_angles()[source]

Obtain the modal angles (and their fractional occurances).

Returns

modal_angles – [modal_angles, fractional_occurance]

Return type

list

get_orientation_map()[source]

Obtain a map of the rotational angle associated with the best matching crystal orientation at each navigation position.

Returns

orientation_map – The rotation angle assocaiated with the orientation at each navigation position.

Return type

Signal2D

get_phase_map()[source]

Obtain a map of the best matching phase at each navigation position.

save_mtex_map(filename)[source]

Save map in a format such that it can be imported into MTEX http://mtex-toolbox.github.io/

Columns: 1 = phase id, 2-4 = Euler angles in the zxz convention (radians), 5 = Correlation score (only the best match is saved), 6 = x co-ord in navigation space, 7 = y co-ord in navigation space.

pyxem.signals.crystallographic_map.load_mtex_map(filename)[source]

Loads a crystallographic map saved by previously saved via .save_map()

Columns: 1 = phase id, 2-4 = Euler angles in the zxz convention (radians), 5 = Correlation score (only the best match is saved), 6 = x co-ord in navigation space, 7 = y co-ord in navigation space.

Parameters

filename (string) – Path to the file to be loaded.

Returns

crystallographic_map – Crystallographic map loaded from the specified file.

Return type

CrystallographicMap

pyxem.signals.diffraction_profile module

Signal class for Electron Diffraction radial profiles

class pyxem.signals.diffraction_profile.ElectronDiffractionProfile(*args, **kwargs)[source]

Bases: hyperspy._signals.signal1d.Signal1D

get_virtual_image(left, right)[source]

Obtains a virtual image associated with a specified scattering range.

Parameters
  • left (float) – Lower bound of the data range to be plotted.

  • right (float) – Upper bound of the data range to be plotted.

Returns

dark_field_sum – The virtual image signal associated with the specified scattering range.

Return type

hyperspy.signals.BaseSignal

Examples

rp.get_virtual_image(left=0.5, right=0.7)
plot_interactive_virtual_image(left, right, **kwargs)[source]

Plots an interactive virtual image formed by integrating scatterered intensity over a specified range.

Parameters
  • left (float) – Lower bound of the data range to be plotted.

  • right (float) – Upper bound of the data range to be plotted.

  • **kwargs – Keyword arguments to be passed to ElectronDiffractionProfile.plot

Examples

rp.plot_interactive_virtual_image(left=0.5, right=0.7)
set_diffraction_calibration(calibration)[source]

Set diffraction profile channel size in reciprocal Angstroms.

Parameters

calibration (float) – Diffraction profile calibration in reciprocal Angstroms per pixel.

set_experimental_parameters(accelerating_voltage=None, camera_length=None, scan_rotation=None, convergence_angle=None, rocking_angle=None, rocking_frequency=None, exposure_time=None)[source]

Set experimental parameters in metadata.

Parameters
  • accelerating_voltage (float) – Accelerating voltage in kV

  • camera_length (float) – Camera length in cm

  • scan_rotation (float) – Scan rotation in degrees

  • convergence_angle (float) – Convergence angle in mrad

  • rocking_angle (float) – Beam rocking angle in mrad

  • rocking_frequency (float) – Beam rocking frequency in Hz

  • exposure_time (float) – Exposure time in ms.

set_scan_calibration(calibration)[source]

Set scan pixel size in nanometres.

Parameters

calibration (float) – Scan calibration in nanometres per pixel.

pyxem.signals.diffraction_simulation module

class pyxem.signals.diffraction_simulation.DiffractionSimulation(coordinates=None, indices=None, intensities=None, calibration=1.0, offset=(0.0, 0.0), with_direct_beam=False)[source]

Bases: object

Holds the result of a kinematic diffraction pattern simulation.

Parameters
  • coordinates (array-like, shape [n_points, 2]) – The x-y coordinates of points in reciprocal space.

  • indices (array-like, shape [n_points, 3]) – The indices of the reciprocal lattice points that intersect the Ewald sphere.

  • intensities (array-like, shape [n_points, ]) – The intensity of the reciprocal lattice points.

  • calibration (float or tuple of float, optional) – The x- and y-scales of the pattern, with respect to the original reciprocal angstrom coordinates.

  • offset (tuple of float, optional) – The x-y offset of the pattern in reciprocal angstroms. Defaults to zero in each direction.

as_signal(size, sigma, max_r)[source]

Returns the diffraction data as an ElectronDiffraction signal with two-dimensional Gaussians representing each diffracted peak. Should only be used for qualitative work.

Parameters
  • size (int) – Side length (in pixels) for the signal to be simulated.

  • sigma (float) – Standard deviation of the Gaussian function to be plotted.

  • max_r (float) – Half the side length in reciprocal Angstroms. Defines the signal’s calibration

Returns

dp – Simulated electron diffraction pattern.

Return type

ElectronDiffraction

calibrated_coordinates

Coordinates converted into pixel space.

Type

ndarray

calibration

The x- and y-scales of the pattern, with respect to the original reciprocal angstrom coordinates.

Type

tuple of float

coordinates

The coordinates of all unmasked points.

Type

ndarray

direct_beam_mask

If with_direct_beam is True, returns a True array for all points. If with_direct_beam is False, returns a True array with False in the position of the direct beam.

Type

ndarray

intensities

The intensities of all unmasked points.

Type

ndarray

class pyxem.signals.diffraction_simulation.ProfileSimulation(magnitudes, intensities, hkls)[source]

Bases: object

Holds the result of a given kinematic simulation of a diffraction profile

Parameters
  • magnitudes (array-like, shape [n_peaks, 1]) – Magnitudes of scattering vectors.

  • intensities (array-like, shape [n_peaks, 1]) – The kinematic intensity of the diffraction peaks.

  • hkls ([{(h, k, l): mult}] {(h, k, l): mult} is a dict of Miller) – indices for all diffracted lattice facets contributing to each intensity.

get_plot(g_max, annotate_peaks=True, with_labels=True, fontsize=12)[source]

Plots the diffraction profile simulation.

Parameters
  • g_max (float) – Maximum g-vector magnitude to plot.

  • annotate_peaks (boolean) – If True, peaks are annotaed with hkl information.

  • with_labels (boolean) – If True, xlabels and ylabels are added to the plot.

  • fontsize (integer) – Fontsize for peak labels.

pyxem.signals.diffraction_vectors module

class pyxem.signals.diffraction_vectors.DiffractionVectors(*args, **kwargs)[source]

Bases: hyperspy.signal.BaseSignal

Crystallographic mapping results containing the best matching crystal phase and orientation at each navigation position with associated metrics.

cartesian

Array of 3-vectors describing Cartesian coordinates associated with each diffraction vector.

Type

np.array()

hkls

Array of Miller indices associated with each diffraction vector following indexation.

Type

np.array()

calculate_cartesian_coordinates(accelerating_voltage, camera_length, *args, **kwargs)[source]

Get cartesian coordinates of the diffraction vectors.

Parameters
  • accelerating_voltage (float) – The acceleration voltage with which the data was acquired.

  • camera_length (float) – The camera length in meters.

get_diffracting_pixels_map(binary=False)[source]

Map of the number of vectors at each navigation position.

Parameters

binary (boolean) – If True a binary image with diffracting pixels taking value == 1 is returned.

Returns

crystim – 2D map of diffracting pixels.

Return type

Signal2D

get_magnitude_histogram(bins, *args, **kwargs)[source]

Obtain a histogram of gvector magnitudes.

Parameters
  • bins (numpy array) – The bins to be used to generate the histogram.

  • *args – Arguments to get_magnitudes().

  • **kwargs – Keyword arguments to get_magnitudes().

Returns

ghis – Histogram of gvector magnitudes.

Return type

Signal1D

get_magnitudes(*args, **kwargs)[source]

Calculate the magnitude of diffraction vectors.

Parameters
  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to map().

Returns

magnitudes – A signal with navigation dimensions as the original diffraction vectors containging an array of gvector magnitudes at each navigation position.

Return type

BaseSignal

get_unique_vectors(distance_threshold=0)[source]

Obtain the unique diffraction vectors.

Parameters

distance_threshold (float) – The minimum distance between diffraction vectors for them to be considered unique diffraction vectors.

Returns

unique_vectors – A DiffractionVectors object containing only the unique diffraction vectors in the original object.

Return type

DiffractionVectors

plot_diffraction_vectors(xlim, ylim, distance_threshold)[source]

Plot the unique diffraction vectors.

Parameters
  • xlim (float) – The maximum x coordinate to be plotted.

  • ylim (float) – The maximum y coordinate to be plotted.

  • distance_threshold (float) – The minimum distance between diffraction vectors to be passed to get_unique_vectors.

Returns

fig – The plot as a matplot lib figure.

Return type

matplotlib figure

plot_diffraction_vectors_on_signal(signal, *args, **kwargs)[source]

Plot the diffraction vectors on a signal.

Parameters
  • signal (ElectronDiffraction) – The ElectronDiffraction signal object on which to plot the peaks. This signal must have the same navigation dimensions as the peaks.

  • *args – Arguments passed to signal.plot()

  • **kwargs – Keyword arguments passed to signal.plot()

pyxem.signals.electron_diffraction module

Signal class for Electron Diffraction data.

class pyxem.signals.electron_diffraction.ElectronDiffraction(*args, **kwargs)[source]

Bases: hyperspy._signals.signal2d.Signal2D

apply_affine_transformation(D, order=3, inplace=True, *args, **kwargs)[source]

Correct geometric distortion by applying an affine transformation.

Parameters
  • D (array) – 3x3 np.array specifying the affine transform to be applied.

  • inplace (bool) – If True (default), this signal is overwritten. Otherwise, returns a new signal.

  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to be passed to map().

Returns

  • ElectronDiffraction Signal containing the affine Transformed

  • diffraction patterns.

apply_gain_normalisation(dark_reference, bright_reference, inplace=True, *args, **kwargs)[source]

Apply gain normalization to experimentally acquired electron diffraction patterns.

Parameters
  • dark_reference (ElectronDiffraction) – Dark reference image.

  • bright_reference (DiffractionSignal) – Bright reference image.

  • inplace (bool) – If True (default), this signal is overwritten. Otherwise, returns a new signal.

  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to be passed to map().

center_direct_beam(radius_start, radius_finish, square_width=None, *args, **kwargs)[source]

Estimate the direct beam position in each experimentally acquired electron diffraction pattern and translate it to the center of the image square.

Parameters
  • radius_start (int) – The lower bound for the radius of the central disc to be used in the alignment.

  • radius_finish (int) – The upper bounds for the radius of the central disc to be used in the alignment.

  • square_width (int) – Half the side length of square that captures the direct beam in all scans. Means that the centering algorithm is stable against diffracted spots brighter than the direct beam.

  • *args – Arguments to be passed to align2D().

  • **kwargs – Keyword arguments to be passed to align2D().

Returns

centered – The centered diffraction data.

Return type

ElectronDiffraction

decomposition(*args, **kwargs)[source]

Decomposition with a choice of algorithms.

Parameters
  • *args – Arguments to be passed to decomposition().

  • **kwargs – Keyword arguments to be passed to decomposition().

Returns

find_peaks(method, *args, **kwargs)[source]

Find the position of diffraction peaks.

Function to locate the positive peaks in an image using various, user specified, methods. Returns a structured array containing the peak positions.

Parameters
  • method (str) – Select peak finding algorithm to implement. Available methods are {‘zaefferer’, ‘stat’, ‘laplacian_of_gaussians’, ‘difference_of_gaussians’, ‘xc’}

  • *args (arguments) – Arguments to be passed to the peak finders.

  • **kwargs (arguments) – Keyword arguments to be passed to the peak finders.

Returns

peaks – A DiffractionVectors object with navigation dimensions identical to the original ElectronDiffraction object. Each signal is a BaseSignal object contiaining the diffraction vectors found at each navigation position, in calibrated units.

Return type

DiffractionVectors

Notes

Peak finding methods are detailed as:

  • ‘zaefferer’ - based on gradient thresholding and refinement by local region of interest optimisation

  • ‘stat’ - statistical approach requiring no free params.

  • ‘laplacian_of_gaussians’ - a blob finder implemented in scikit-image which uses the laplacian of Gaussian matrices approach.

  • ‘difference_of_gaussians’ - a blob finder implemented in scikit-image which uses the difference of Gaussian matrices approach.

  • ‘xc’ - A cross correlation peakfinder

find_peaks_interactive(disc_image=None, imshow_kwargs={})[source]

Find peaks using an interactive tool.

Parameters
  • disc_image (numpy.array) – See .utils.peakfinders2D.peak_finder_xc for details. If not given a warning will be raised.

  • imshow_kwargs (arguments) – kwargs to be passed to internal imshow statements

Notes

Requires ipywidgets and traitlets to be installed.

get_direct_beam_mask(radius)[source]

Generate a signal mask for the direct beam.

Parameters

radius (float) – Radius for the circular mask in pixel units.

Returns

signal-mask – The mask of the direct beam

Return type

ndarray

get_direct_beam_position(radius_start, radius_finish, *args, **kwargs)[source]

Estimate the direct beam position in each experimentally acquired electron diffraction pattern.

Parameters
  • radius_start (int) – The lower bound for the radius of the central disc to be used in the alignment.

  • radius_finish (int) – The upper bounds for the radius of the central disc to be used in the alignment.

  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to be passed to map().

Returns

centers – Array containing the centers for each SED pattern.

Return type

ndarray

get_radial_profile(mask_array=None, inplace=False, *args, **kwargs)[source]

Return the radial profile of the diffraction pattern.

Parameters
  • mask_array (numpy.array) – Optional array with the same dimensions as the signal axes. Consists of 0s for excluded pixels and 1s for non-excluded pixels. The 0-pixels are excluded from the radial average.

  • inplace (bool) – If True (default), this signal is overwritten. Otherwise, returns a new signal.

  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to be passed to map().

Returns

radial_profile – The radial average profile of each diffraction pattern in the ElectronDiffraction signal as a Signal1D.

Return type

hyperspy.signals.Signal1D

get_virtual_image(roi)[source]

Obtains a virtual image associated with a specified ROI.

Parameters

roi (hyperspy.roi.BaseInteractiveROI) – Any interactive ROI detailed in HyperSpy.

Returns

dark_field_sum – The virtual image signal associated with the specified roi.

Return type

hyperspy.signals.BaseSignal

Examples

import hyperspy.api as hs
roi = hs.roi.CircleROI(0, 0, 0.2)
data.get_virtual_image(roi)
plot_interactive_virtual_image(roi, **kwargs)[source]

Plots an interactive virtual image formed with a specified and adjustable roi.

Parameters
  • roi (hyperspy.roi.BaseInteractiveROI) – Any interactive ROI detailed in HyperSpy.

  • **kwargs – Keyword arguments to be passed to ElectronDiffraction.plot

Examples

import hyperspy.api as hs
roi = hs.roi.CircleROI(0, 0, 0.2)
data.plot_interactive_virtual_image(roi)
remove_background(method, *args, **kwargs)[source]

Perform background subtraction via multiple methods.

Parameters
  • method (string) –

    Specify the method used to determine the direct beam position.

    • ’h-dome’ -

    • ‘gaussian_difference’ - Uses a difference between two gaussian

      convolutions to determine where the peaks are, and sets all other pixels to 0.

    • ’median’ - Use a median filter for background removal

    • ’reference_pattern’ - Subtract a user-defined reference patterns

      from every diffraction pattern.

  • sigma_min (int, float) – Standard deviation for the minimum gaussian convolution (gaussian_difference only)

  • sigma_max (int, float) – Standard deviation for the maximum gaussian convolution (gaussian_difference only)

  • footprint (int) – Size of the window that is convoluted with the array to determine the median. Should be large enough that it is about 3x as big as the size of the peaks (median only).

  • implementation ('scipy' or 'skimage') – (median only) see expt_utils.subtract_background_median for details, if not selected ‘scipy’ is used

  • bg (array) – Background array extracted from vacuum. (subtract_reference only)

  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to be passed to map().

Returns

bg_subtracted – A copy of the data with the background subtracted. Be aware that this function will only return inplace.

Return type

ElectronDiffraction

remove_deadpixels(deadpixels, deadvalue='average', inplace=True, progress_bar=True, *args, **kwargs)[source]

Remove deadpixels from experimentally acquired diffraction patterns.

Parameters
  • deadpixels (ElectronDiffraction) – List

  • deadvalue (string) – Specify how deadpixels should be treated. ‘average’ sets the dead pixel value to the average of adjacent pixels. ‘nan’ sets the dead pixel to nan

  • inplace (bool) – If True (default), this signal is overwritten. Otherwise, returns a new signal.

  • *args – Arguments to be passed to map().

  • **kwargs – Keyword arguments to be passed to map().

set_diffraction_calibration(calibration, center=None)[source]

Set diffraction pattern pixel size in reciprocal Angstroms and origin location.

Parameters
  • calibration (float) – Diffraction pattern calibration in reciprocal Angstroms per pixel.

  • center (tuple) – Position of the direct beam center, in pixels. If None the center of the data array is assumed to be the center of the pattern.

set_experimental_parameters(accelerating_voltage=None, camera_length=None, scan_rotation=None, convergence_angle=None, rocking_angle=None, rocking_frequency=None, exposure_time=None)[source]

Set experimental parameters in metadata.

Parameters
  • accelerating_voltage (float) – Accelerating voltage in kV

  • camera_length (float) – Camera length in cm

  • scan_rotation (float) – Scan rotation in degrees

  • convergence_angle (float) – Convergence angle in mrad

  • rocking_angle (float) – Beam rocking angle in mrad

  • rocking_frequency (float) – Beam rocking frequency in Hz

  • exposure_time (float) – Exposure time in ms.

set_scan_calibration(calibration)[source]

Set scan pixel size in nanometres.

Parameters

calibration (float) – Scan calibration in nanometres per pixel.

pyxem.signals.indexation_results module

class pyxem.signals.indexation_results.TemplateMatchingResults(*args, **kwargs)[source]

Bases: hyperspy.signal.BaseSignal

Template matching results containing the top n best matching crystal phase and orientation at each navigation position with associated metrics.

vectors

Diffraction vectors indexed.

Type

DiffractionVectors

hkls

Miller indices associated with each diffraction vector.

Type

BaseSignal

get_crystallographic_map(*args, **kwargs)[source]

Obtain a crystallographic map specifying the best matching phase and orientation at each probe position with corresponding metrics.

Returns

cryst_map – Crystallographic mapping results containing the best matching phase and orientation at each navigation position with associated metrics.

The Signal at each navigation position is an array of,

[phase, np.array((z,x,z)), dict(metrics)]

which defines the phase, orientation as Euler angles in the zxz convention and metrics associated with the matching.

Metrics for template matching results are

’correlation’ ‘orientation_reliability’ ‘phase_reliability’

Return type

CrystallographicMap

plot_best_matching_results_on_signal(signal, library, permanent_markers=True, *args, **kwargs)[source]

Plot the best matching diffraction vectors on a signal.

Parameters
  • signal (ElectronDiffraction) – The ElectronDiffraction signal object on which to plot the peaks. This signal must have the same navigation dimensions as the peaks.

  • library (DiffractionLibrary) – Diffraction library containing the phases and rotations

  • permanent_markers (bool) – Permanently save the peaks as markers on the signal

  • *args – Arguments passed to signal.plot()

  • **kwargs – Keyword arguments passed to signal.plot()

class pyxem.signals.indexation_results.VectorMatchingResults(*args, **kwargs)[source]

Bases: hyperspy.signal.BaseSignal

Vector matching results containing the top n best matching crystal phase and orientation at each navigation position with associated metrics.

vectors

Diffraction vectors indexed.

Type

DiffractionVectors

hkls

Miller indices associated with each diffraction vector.

Type

BaseSignal

get_crystallographic_map(*args, **kwargs)[source]

Obtain a crystallographic map specifying the best matching phase and orientation at each probe position with corresponding metrics.

Returns

cryst_map – Crystallographic mapping results containing the best matching phase and orientation at each navigation position with associated metrics.

The Signal at each navigation position is an array of,

[phase, np.array((z,x,z)), dict(metrics)]

which defines the phase, orientation as Euler angles in the zxz convention and metrics associated with the matching.

Metrics for template matching results are

’match_rate’ ‘total_error’ ‘orientation_reliability’ ‘phase_reliability’

Return type

CrystallographicMap

get_indexed_diffraction_vectors(vectors, overwrite=False, *args, **kwargs)[source]

Obtain an indexed diffraction vectors object.

Parameters

vectors (DiffractionVectors) – A diffraction vectors object to be indexed.

Returns

indexed_vectors – An indexed diffraction vectors object.

Return type

DiffractionVectors

plot_best_matching_results_on_signal(signal, library, permanent_markers=True, *args, **kwargs)[source]

Plot the best matching diffraction vectors on a signal.

Parameters
  • signal (ElectronDiffraction) – The ElectronDiffraction signal object on which to plot the peaks. This signal must have the same navigation dimensions as the peaks.

  • library (DiffractionLibrary) – Diffraction library containing the phases and rotations

  • permanent_markers (bool) – Permanently save the peaks as markers on the signal. Default True.

  • *args – Arguments passed to signal.plot()

  • **kwargs – Keyword arguments passed to signal.plot()

pyxem.signals.tensor_field module

class pyxem.signals.tensor_field.DisplacementGradientMap(*args, **kwargs)[source]

Bases: hyperspy._signals.signal2d.Signal2D

get_strain_maps()[source]

Obtain strain maps from the displacement gradient tensor at each navigation position in the small strain approximation.

Returns

strain_results – Signal of shape < 4 | , > , navigation order is e11,e22,e12,theta

Return type

BaseSignal

polar_decomposition()[source]

Perform polar decomposition on the second rank tensors describing the TensorField. The polar decomposition is right handed and given by \(D = RU\)

Returns

  • R (TensorField) – The orthogonal matrix describing the rotation field.

  • U (TensorField) – The strain tensor field.

pyxem.signals.vdf_image module

Signal class for virtual diffraction contrast images.

class pyxem.signals.vdf_image.VDFImage(*args, **kwargs)[source]

Bases: hyperspy._signals.signal2d.Signal2D

Module contents