# API reference#

This reference manual details the public modules, classes, and functions in kikuchipy, as generated from their docstrings. Many of the docstrings contain examples, however, see the user guide for how to use kikuchipy.

Caution

kikuchipy is in continuous development (alpha stage), so expect some breaking changes with each release.

The list of top modules and the load function:

 crystallography Crystallographic computations not found (easily) elsewhere. data Test data. detectors An EBSD detector and related quantities. draw Creation of HyperSpy markers to add to signals and other tools. filters Pattern filters used on signals. generators Generate signals and simulations, sometimes from other signals. indexing Tools for indexing of EBSD patterns by matching to a dictionary of simulated patterns. io Read and write signals from and to file. load(filename[, lazy]) Load an EBSD or EBSDMasterPattern object from a supported file format. pattern Single and chunk pattern processing used by signals. projections Various projections and transformations relevant to EBSD. signals Experimental and simulated diffraction patterns and virtual backscatter electron images. simulations Simulations returned by a generator and handling of Kikuchi bands and zone axes.

## crystallography#

Crystallographic computations not found (easily) elsewhere.

 [Deprecated] Direct structure matrix as defined in EMsoft. [Deprecated] Reciprocal metric tensor as defined in EMsoft. [Deprecated] Reciprocal structure matrix as defined in EMsoft.
kikuchipy.crystallography.get_direct_structure_matrix(lattice)[source]#

[Deprecated] Direct structure matrix as defined in EMsoft.

Parameters:

lattice (Lattice) – Crystal structure lattice.

Notes

Deprecated since version 0.6: Function get_direct_structure_matrix() is deprecated and will be removed in version 0.7. Use diffpy.structure.Lattice.base instead.

Return type:

ndarray

kikuchipy.crystallography.get_reciprocal_metric_tensor(lattice)[source]#

[Deprecated] Reciprocal metric tensor as defined in EMsoft.

Parameters:

lattice (Lattice) – Crystal structure lattice.

Return type:

numpy.ndarray

Notes

Deprecated since version 0.6: Function get_reciprocal_metric_tensor() is deprecated and will be removed in version 0.7. Use diffpy.structure.Lattice.reciprocal().metrics instead.

kikuchipy.crystallography.get_reciprocal_structure_matrix(lattice)[source]#

[Deprecated] Reciprocal structure matrix as defined in EMsoft.

Parameters:

lattice (Lattice) – Crystal structure lattice.

Return type:

numpy.ndarray

Notes

Deprecated since version 0.6: Function get_reciprocal_structure_matrix() is deprecated and will be removed in version 0.7. Use diffpy.structure.Lattice.recbase instead.

## data#

 nickel_ebsd_small(**kwargs) 9 EBSD patterns in a (3, 3) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19]. nickel_ebsd_large([allow_download, progressbar]) 4125 EBSD patterns in a (55, 75) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19]. (401, 401) uint8 square Lambert or stereographic projection of the northern and southern hemisphere of a Nickel master pattern at 20 keV accelerating voltage. One EBSD pattern of (480, 480) detector pixels from a single crystal Silicon sample, acquired on a NORDIF UF-420 detector. One EBSD pattern of (480, 480) detector pixels from a single crystal Silicon sample, acquired on a NORDIF UF-420 detector. One EBSD pattern of (480, 480) detector pixels from a single crystal Silicon sample, acquired on a NORDIF UF-420 detector.

Test data.

Some datasets must be downloaded from the web. For more test datasets, see open datasets.

Some datasets must be downloaded from the web. Datasets are placed in a local cache, in the location returned from pooch.os_cache(“kikuchipy”) by default. The location can be overwritten with a global KIKUCHIPY_DATA_DIR environment variable.

With every new version of kikuchipy, a new directory of datasets with the version name is added to the cache directory. Any old directories are not deleted automatically, and should then be deleted manually if desired.

kikuchipy.data.nickel_ebsd_large(allow_download=False, progressbar=True, **kwargs)[source]#

4125 EBSD patterns in a (55, 75) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19].

Carries a CC BY 4.0 license.

Parameters:
• allow_download (bool) – Whether to allow downloading the dataset from the kikuchipy-data GitHub repository (https://github.com/pyxem/kikuchipy-data) to the local cache with the pooch Python package. Default is False.

• progressbar (bool) – Whether to show a progressbar when downloading. Default is False.

• kwargs – Keyword arguments passed to load().

Returns:

signal – EBSD signal.

Return type:

EBSD

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_large(allow_download=True)
>>> s
<EBSD, title: patterns Scan 1, dimensions: (75, 55|60, 60)>

kikuchipy.data.nickel_ebsd_master_pattern_small(**kwargs)[source]#

(401, 401) uint8 square Lambert or stereographic projection of the northern and southern hemisphere of a Nickel master pattern at 20 keV accelerating voltage.

Carries a CC BY 4.0 license.

Parameters:

kwargs – Keyword arguments passed to load().

Returns:

signal – EBSD master pattern signal.

Return type:

EBSDMasterPattern

Notes

Initially generated using the EMsoft EMMCOpenCL and EMEBSDMaster programs. The included file was rewritten to disk with h5py, where the master patterns’ data type is converted from float32 to uint8 with rescale_intensity(), all datasets were written with dict2h5ebsdgroup() with keyword arguments compression=”gzip” and compression_opts=9. All other HDF5 groups and datasets are the same as in the original file.

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_master_pattern_small()
>>> s
<EBSDMasterPattern, title: ni_mc_mp_20kv_uint8_gzip_opts9, dimensions: (|401, 401)>
>>> s.projection
'stereographic'


Import master pattern in the square Lambert projection

>>> s2 = kp.data.nickel_ebsd_master_pattern_small(projection="lambert")
>>> s2.projection
'lambert'

kikuchipy.data.nickel_ebsd_small(**kwargs)[source]#

9 EBSD patterns in a (3, 3) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19].

Carries a CC BY 4.0 license.

Parameters:

kwargs – Keyword arguments passed to load().

Returns:

signal – EBSD signal.

Return type:

EBSD

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s
<EBSD, title: patterns My awes0m4 ..., dimensions: (3, 3|60, 60)>

kikuchipy.data.silicon_ebsd_moving_screen_in(allow_download=False, progressbar=True, **kwargs)[source]#

One EBSD pattern of (480, 480) detector pixels from a single crystal Silicon sample, acquired on a NORDIF UF-420 detector.

This pattern and two other patterns from the same sample position but with 5 mm and 10 mm greater sample-screen-distances were acquired to test the moving-screen projection center estimation technique [HH91].

Carries a CC BY 4.0 license.

Parameters:
• allow_download (bool) – Whether to allow downloading the dataset from the kikuchipy-data GitHub repository (https://github.com/pyxem/kikuchipy-data) to the local cache with the pooch Python package. Default is False.

• progressbar (bool) – Whether to show a progressbar when downloading. Default is False.

• kwargs – Keyword arguments passed to load().

Returns:

signal – EBSD signal.

Return type:

EBSD

Examples

>>> import kikuchipy as kp
>>> s = kp.data.silicon_ebsd_moving_screen_in(allow_download=True)
>>> s
<EBSD, title: si_in Scan 1, dimensions: (|480, 480)>

kikuchipy.data.silicon_ebsd_moving_screen_out10mm(allow_download=False, progressbar=True, **kwargs)[source]#

One EBSD pattern of (480, 480) detector pixels from a single crystal Silicon sample, acquired on a NORDIF UF-420 detector.

This pattern and two other patterns from the same sample position but with sample-screen-distances 10 mm shorter (silicon_ebsd_moving_screen_in()) and 5 mm shorter (silicon_ebsd_moving_screen_out5mm()) were acquired to test the moving-screen projection center estimation technique [HH91].

Carries a CC BY 4.0 license.

Parameters:
• allow_download (bool) – Whether to allow downloading the dataset from the kikuchipy-data GitHub repository (https://github.com/pyxem/kikuchipy-data) to the local cache with the pooch Python package. Default is False.

• progressbar (bool) – Whether to show a progressbar when downloading. Default is False.

• kwargs – Keyword arguments passed to load().

Returns:

signal – EBSD signal.

Return type:

EBSD

Examples

>>> import kikuchipy as kp
>>> s = kp.data.silicon_ebsd_moving_screen_out10mm(allow_download=True)
>>> s
<EBSD, title: si_out10mm Scan 1, dimensions: (|480, 480)>

kikuchipy.data.silicon_ebsd_moving_screen_out5mm(allow_download=False, progressbar=True, **kwargs)[source]#

One EBSD pattern of (480, 480) detector pixels from a single crystal Silicon sample, acquired on a NORDIF UF-420 detector.

This pattern and two other patterns from the same sample position but with sample-screen-distances 5 mm shorter (silicon_ebsd_moving_screen_in()) and 5 mm greater (silicon_ebsd_moving_screen_out10mm()) were acquired to test the moving-screen projection center estimation technique [HH91].

Carries a CC BY 4.0 license.

Parameters:
• allow_download (bool) – Whether to allow downloading the dataset from the kikuchipy-data GitHub repository (https://github.com/pyxem/kikuchipy-data) to the local cache with the pooch Python package. Default is False.

• progressbar (bool) – Whether to show a progressbar when downloading. Default is False.

• kwargs – Keyword arguments passed to load().

Returns:

signal – EBSD signal.

Return type:

EBSD

Examples

>>> import kikuchipy as kp
>>> s = kp.data.silicon_ebsd_moving_screen_out5mm(allow_download=True)
>>> s
<EBSD, title: si_out5mm Scan 1, dimensions: (|480, 480)>


## detectors#

An EBSD detector and related quantities.

 EBSDDetector([shape, px_size, binning, ...]) An EBSD detector class storing its shape, pixel size, binning factor, detector tilt, sample tilt and projection center (PC) per pattern. PCCalibrationMovingScreen(pattern_in, ...[, ...]) A class to perform and inspect the calibration of the EBSD projection center (PC) using the "moving screen" technique from [HH91].

### EBSDDetector#

 Return a deep copy using copy.deepcopy(). Return PC in the Bruker convention, defined in __init__(). pc_emsoft([version]) Return PC in the EMsoft convention. Return PC in the Oxford convention. Return PC in the EDAX TSL convention. plot([coordinates, show_pc, pc_kwargs, ...]) Plot the detector screen.
class kikuchipy.detectors.EBSDDetector(shape=(1, 1), px_size=1, binning=1, tilt=0, azimuthal=0, sample_tilt=70, pc=(0.5, 0.5, 0.5), convention=None)[source]#

Bases: object

An EBSD detector class storing its shape, pixel size, binning factor, detector tilt, sample tilt and projection center (PC) per pattern. Given one or multiple PCs, the detector’s gnomonic coordinates are calculated. Uses of these include projecting Kikuchi bands, given a unit cell, unit cell orientation and family of planes, onto the detector.

Calculation of gnomonic coordinates is based on the work by Aimo Winkelmann in the supplementary material to [BJG+16].

__init__(shape=(1, 1), px_size=1, binning=1, tilt=0, azimuthal=0, sample_tilt=70, pc=(0.5, 0.5, 0.5), convention=None)[source]#

Create an EBSD detector with a shape, pixel size, binning, and projection/pattern center(s) (PC(s)).

Parameters:
• shape (Tuple[int, int]) – Number of detector rows and columns in pixels. Default is (1, 1).

• px_size (float) – Size of unbinned detector pixel in um, assuming a square pixel shape. Default is 1 um.

• binning (int) – Detector binning, i.e. how many pixels are binned into one. Default is 1, i.e. no binning.

• tilt (float) – Detector tilt from horizontal in degrees. Default is 0.

• azimuthal (float) – Sample tilt about the sample RD (downwards) axis. A positive angle means the sample normal moves towards the right looking from the sample to the detector. Default is 0.

• sample_tilt (float) – Sample tilt from horizontal in degrees. Default is 70.

• pc (Union[ndarray, list, tuple]) – X, Y and Z coordinates of the projection/pattern centers (PCs), describing the location of the beam on the sample measured relative to the detection screen. See Notes for the definition and conversions between conventions. If multiple PCs are passed, they are assumed to be on the form [[x0, y0, z0], [x1, y1, z1], …]. Default is [[0.5, 0.5, 0.5]].

• convention (Optional[str]) – PC convention. If None (default), Bruker’s convention is assumed. Options are “tsl”, “oxford”, “bruker”, “emsoft”, “emsoft4”, and “emsoft5”. “emsoft” and “emsoft5” is the same convention. See Notes for conversions between conventions.

Notes

The pattern on the detector is always viewed from the detector towards the sample. Pattern width and height is here given as $N_x$ and $N_y$ (possibly binned).

The Bruker PC coordinates $(x_B^*, y_B^*, z_B^*)$ are defined in fractions of $N_x$, $N_y$, and $N_y$, respectively, with $x_B^*$ and $y_B^*$ defined with respect to the upper left corner of the detector. These coordinates are used internally, called ($PC_x, PC_y, PC_z$) in the rest of the documentation when there is no reference to Bruker specifically.

The EDAX TSL PC coordinates $(x_T^*, y_T^*, z_T^*)$ and Oxford Instruments PC coordinates $(x_O^*, y_O^*, z_O^*)$ are identical and defined in fractions of $N_x$ with respect to the lower left corner of the detector.

The EMsoft PC coordinates $(x_{pc}, y_{pc})$ are defined as number of pixels (subpixel accuracy) with resepct to the center of the detector, with $x_{pc}$ towards the right and $y_{pc}$ upwards. The final PC coordinate $L$ is the detector distance in microns. Note that before EMsoft v5.0, $x_{pc}$ was defined towards the left.

Given these definitions, the following is the conversion from TSL/Oxford to Bruker

$\begin{split}x_B^* &= x_T^*,\\ y_B^* &= 1 - \frac{N_x}{N_y} y_T^*,\\ z_B^* &= \frac{N_x}{N_y} z_T^*.\end{split}$

The conversion from EMsoft to Bruker is given as

$\begin{split}x_B^* &= \frac{1}{2} - \frac{x_{pc}}{N_x b},\\ y_B^* &= \frac{1}{2} - \frac{y_{pc}}{N_y b},\\ z_B^* &= \frac{L}{N_y b \delta},\end{split}$

where $$\delta$$ is the unbinned detector pixel size in microns, and $b$ is the binning factor.

Examples

>>> import numpy as np
>>> from kikuchipy.detectors import EBSDDetector
>>> det = EBSDDetector(
...     shape=(60, 60),
...     pc=np.ones((149, 200, 3)) * (0.421, 0.779, 0.505),
...     convention="tsl",
...     px_size=70,
...     binning=8,
...     tilt=5,
...     sample_tilt=70,
... )
>>> det
EBSDDetector (60, 60), px_size 70 um, binning 8, tilt 5, azimuthal 0, pc (0.421, 0.221, 0.505)
>>> det.navigation_shape  # (nrows, ncols)
(149, 200)
>>> det.bounds
array([ 0, 59,  0, 59])
>>> det.gnomonic_bounds[0, 0]
array([-0.83366337,  1.14653465, -0.83366337,  1.14653465])
>>> det.plot()

property aspect_ratio: float#

Number of detector columns divided by rows.

Return type:

float

property bounds: ndarray#

Detector bounds [x0, x1, y0, y1] in pixel coordinates.

Return type:

ndarray

deepcopy()[source]#

Return a deep copy using copy.deepcopy().

property gnomonic_bounds: ndarray#

Detector bounds [x0, x1, y0, y1] in gnomonic coordinates.

Return type:

ndarray

property height: float#

Detector height in microns.

Return type:

float

property navigation_dimension: int#

Number of navigation dimensions of the projection center array (a maximum of 2).

Return type:

int

property navigation_shape: tuple#

Navigation shape of the projection center array.

Return type:

tuple

property ncols: int#

Number of detector pixel columns.

Return type:

int

property nrows: int#

Number of detector pixel rows.

Return type:

int

property pc: ndarray#

All projection center coordinates.

Return type:

ndarray

property pc_average: ndarray#

Return the overall average projection center.

Return type:

ndarray

pc_bruker()[source]#

Return PC in the Bruker convention, defined in __init__().

Return type:

ndarray

pc_emsoft(version=5)[source]#

Return PC in the EMsoft convention.

Parameters:

version (int) – Which EMsoft PC convention to use. The direction of the x PC coordinate, $x_{pc}$, flipped in version 5.

Notes

The PC coordinate conventions of Bruker, EDAX TSL, Oxford Instruments and EMsoft are explained in __init__(). The PC is stored in the Bruker convention internally, so the conversion is

$\begin{split}x_{pc} &= N_x b \left(\frac{1}{2} - x_B^*\right),\\ y_{pc} &= N_y b \left(\frac{1}{2} - y_B^*\right),\\ L &= N_y b \delta z_B^*,\end{split}$

where $N_x$ and $N_y$ are number of detector columns and rows, $b$ is binning, $$\delta$$ is the unbinned pixel size, $(x_B^*, y_B^*, z_B^*)$ are the Bruker PC coordinates, and $(x_{pc}, y_{pc}, L)$ are the returned EMsoft PC coordinates.

Return type:

ndarray

pc_oxford()[source]#

Return PC in the Oxford convention.

Notes

The Oxford PC coordinates are identical to the TSL coordinates, see pc_tsl().

Return type:

ndarray

pc_tsl()[source]#

Return PC in the EDAX TSL convention.

Notes

The PC coordinate conventions of Bruker, EDAX TSL, Oxford Instruments and EMsoft are explained in __init__(). The PC is stored in the Bruker convention internally, so the conversion is

$\begin{split}x_T^* &= x_B^*,\\ y_T^* &= \frac{N_y}{N_x} (1 - y_B^*),\\ z_T^* &= \frac{N_y}{N_x} z_B^*,\end{split}$

where $N_x$ and $N_y$ are number of detector columns and rows, $(x_B^*, y_B^*, z_B^*)$ are the Bruker PC coordinates, and $(x_T^*, y_T^*, z_T^*)$ are the returned EDAX TSL PC coordinates.

Return type:

ndarray

property pcx: ndarray#

Projection center x coordinates.

Return type:

ndarray

property pcy: ndarray#

Projection center y coordinates.

Return type:

ndarray

property pcz: ndarray#

Projection center z coordinates.

Return type:

ndarray

plot(coordinates='detector', show_pc=True, pc_kwargs=None, pattern=None, pattern_kwargs=None, draw_gnomonic_circles=False, gnomonic_angles=None, gnomonic_circles_kwargs=None, zoom=1, return_fig_ax=False)[source]#

Plot the detector screen.

The plotting of gnomonic circles and general style is adapted from the supplementary material to [BJG+16] by Aimo Winkelmann.

Parameters:
Return type:
Returns:

• fig – Matplotlib figure object, if return_fig_ax is True.

• ax – Matplotlib axes object, if return_fig_ax is True.

Examples

>>> import numpy as np
>>> from kikuchipy.detectors import EBSDDetector
>>> det = EBSDDetector(
...     shape=(60, 60),
...     pc=np.ones((149, 200, 3)) * (0.421, 0.779, 0.505),
...     convention="tsl",
...     sample_tilt=70,
... )
>>> det.plot()
>>> det.plot(
...     coordinates="gnomonic",
...     draw_gnomonic_circles=True,
...     gnomonic_circles_kwargs={"edgecolor": "b", "alpha": 0.3}
... )
>>> fig, ax = det.plot(
...     pattern=np.ones(det.shape),
...     show_pc=True,
...     return_fig_ax=True,
... )
>>> fig.savefig("detector.png")

property px_size_binned: float#

Binned pixel size in microns.

Return type:

float

property r_max: ndarray#

Maximum distance from PC to detector edge in gnomonic coordinates.

Return type:

ndarray

property size: int#

Number of detector pixels.

Return type:

int

property specimen_scintillator_distance: float#

Specimen to scintillator distance (SSD), known in EMsoft as L.

Return type:

float

property unbinned_shape: Tuple[int, int]#

Unbinned detector shape in pixels.

Return type:
property width: float#

Detector width in microns.

Return type:

float

property x_max: Union[ndarray, float]#

Right bound of detector in gnomonic coordinates.

Return type:
property x_min: Union[ndarray, float]#

Left bound of detector in gnomonic coordinates.

Return type:
property x_range: ndarray#

X detector limits in gnomonic coordinates.

Return type:

ndarray

property x_scale: ndarray#

Width of a pixel in gnomonic coordinates.

Return type:

ndarray

property y_max: Union[ndarray, float]#

Bottom bound of detector in gnomonic coordinates.

Return type:
property y_min: Union[ndarray, float]#

Top bound of detector in gnomonic coordinates.

Return type:
property y_range: ndarray#

The y detector limits in gnomonic coordinates.

Return type:

ndarray

property y_scale: ndarray#

Height of a pixel in gnomonic coordinates.

Return type:

ndarray

### PCCalibrationMovingScreen#

 Draw lines between all points within a pattern and populate self.lines. plot([pattern_kwargs, line_kwargs, ...]) A convenience method of three images, the first two with the patterns with points and lines annotated, and the third with the calibration results.
class kikuchipy.detectors.PCCalibrationMovingScreen(pattern_in, pattern_out, points_in, points_out, delta_z=1, px_size=None, binning=1, convention='tsl')[source]#

Bases: object

A class to perform and inspect the calibration of the EBSD projection center (PC) using the “moving screen” technique from [HH91].

The technique requires two patterns acquired with a stationary beam but with different detector distances (DDs) where the difference is known. First, the goal is to find the pattern region which does not shift between the two camera positions, (PCx, PCy). This point can be estimated by selecting the same pattern features in both patterns. Second, the DD (PCz) can be estimated in the same unit as the known camera distance difference. If also the detector pixel size is known, PCz can be given in the fraction of the detector screen height.

__init__(pattern_in, pattern_out, points_in, points_out, delta_z=1, px_size=None, binning=1, convention='tsl')[source]#

Return a class instance storing the PC estimates, the average PC, and other parameters relevant for the estimation.

Parameters:
property line_lengths: ndarray#

Length of lines within the patterns in pixels.

Return type:

ndarray

property lines: ndarray#

Start and end points of all possible lines between all points per pattern, of shape (2, n_lines, 4), where the last axis is (x1, y1, x2, y2).

Return type:

ndarray

property lines_end: ndarray#

End points of lines within both patterns, of shape (2, n_lines, 2).

Return type:

ndarray

property lines_out_in: ndarray#

Start (out) and end (in) points of the lines between corresponding points in the patterns, of shape (n_points, 4).

Return type:

ndarray

property lines_out_in_end: ndarray#

End points of the lines between corresponding points in the patterns, of shape (n_points, 2).

Return type:

ndarray

property lines_out_in_start: ndarray#

Starting points of the lines between corresponding points in the patterns, of shape (n_points, 2).

Return type:

ndarray

property lines_start: ndarray#

Starting points of lines within the patterns, of shape (2, n_lines, 2).

Return type:

ndarray

make_lines()[source]#

Draw lines between all points within a pattern and populate self.lines. Is first run upon initialization.

property n_lines: int#

Number of lines in each pattern.

Return type:

int

property n_points: int#

Number of points of pattern features in each pattern.

Return type:

int

property ncols: int#

Number of detector columns.

Return type:

int

property nrows: int#

Number of detector rows.

Return type:

int

property pc: ndarray#

The average PC calculated from all estimates.

Return type:

ndarray

property pc_all: ndarray#

All estimates of PC.

Return type:

ndarray

property pcx_all: ndarray#

All estimates of PCx.

Return type:

ndarray

property pcy_all: ndarray#

All estimates of PCy.

Return type:

ndarray

property pcz_all: ndarray#

All estimates of PCz, scaled to fraction of detector height if px_size is not None.

Return type:

ndarray

plot(pattern_kwargs={'cmap': 'gray'}, line_kwargs={'linewidth': 2, 'zorder': 1}, scatter_kwargs={'zorder': 2}, pc_kwargs={'edgecolor': 'k', 'facecolor': 'gold', 'marker': '*', 's': 300}, return_fig_ax=False, **kwargs)[source]#

A convenience method of three images, the first two with the patterns with points and lines annotated, and the third with the calibration results.

Parameters:
Return type:
Returns:

• fig – Figure, returned if return_fig_ax is True.

• ax – Axes, returned if return_fig_ax is True.

property pxy: float#

Average of intersections of the lines between corresponding points in the patterns.

Return type:

float

property pxy_all: ndarray#

Intersections of the lines between the corresponding points in the patterns, i.e. estimates of (PCx, PCy), of shape (n_points, 2).

Return type:

ndarray

property pxy_within_detector: ndarray#

A boolean array stating whether each intersection of lines between corresponding points in the patterns are inside the detector (True), or outside (False).

Return type:

ndarray

property shape: Tuple[int, int]#

Detector shape, (nrows, ncols).

Return type:

## draw#

Creation of HyperSpy markers to add to signals and other tools.

 colors Color palettes for plotting Kikuchi bands. get_rgb_navigator(image[, dtype]) Create an RGB navigator signal which is suitable to pass to plot() as the navigator parameter. markers Creation of lists of HyperSpy markers.
kikuchipy.draw.get_rgb_navigator(image, dtype=<class 'numpy.uint16'>)[source]#

Create an RGB navigator signal which is suitable to pass to plot() as the navigator parameter.

Parameters:
• image (numpy.ndarray) – RGB color image of shape (n rows, n columns, 3).

• dtype (numpy.dtype) – Which data type to cast the signal data to, either uint16 (default) or uint8.

Returns:

signal – Signal with an (n columns, n rows) signal shape and no navigation shape, of data type either rgb8 or rgb16.

Return type:

hyperspy.signals.Signal2D

### markers#

Creation of lists of HyperSpy markers.

 get_line_segment_list(lines, **kwargs) Return a list of line segment markers. get_point_list(points, **kwargs) Return a list of point markers. get_text_list(texts, coordinates, **kwargs) Return a list of text markers.
kikuchipy.draw.markers.get_line_segment_list(lines, **kwargs)[source]#

Return a list of line segment markers.

Parameters:
Returns:

marker_list – List of hyperspy.drawing._markers.line_segment.LineSegment.

Return type:

list

kikuchipy.draw.markers.get_point_list(points, **kwargs)[source]#

Return a list of point markers.

Parameters:
Returns:

marker_list – List of hyperspy.drawing._markers.point.Point.

Return type:

list

kikuchipy.draw.markers.get_text_list(texts, coordinates, **kwargs)[source]#

Return a list of text markers.

Parameters:
Returns:

marker_list – List of hyperspy.drawing._markers.text.Text.

Return type:

list

### colors#

Color palettes for plotting Kikuchi bands.

## filters#

Pattern filters used on signals.

 distance_to_origin(shape[, origin]) Return the distance to the window origin in pixels. highpass_fft_filter(shape, cutoff[, ...]) Return a frequency domain high-pass filter transfer function in 2D. lowpass_fft_filter(shape, cutoff[, cutoff_width]) Return a frequency domain low-pass filter transfer function in 2D. Return a 1D modified Hann window with the maximum value normalized to 1. Window([window, shape]) A window/kernel/mask/filter of a given shape with some values.
kikuchipy.filters.distance_to_origin(shape, origin=None)[source]#

Return the distance to the window origin in pixels.

Parameters:
Return type:

ndarray

kikuchipy.filters.highpass_fft_filter(shape, cutoff, cutoff_width=None)[source]#

Return a frequency domain high-pass filter transfer function in 2D.

Used in [WMD06].

Parameters:
Returns:

w – 2D transfer function.

Return type:

numpy.ndarray

Notes

The high-pass filter transfer function is defined as

$\begin{split}w(r) = e^{-\left(\frac{c - r}{\sqrt{2}w_c/2}\right)^2}, w(r) = \begin{cases} 0, & r < c - 2w_c\\ 1, & r > c, \end{cases}\end{split}$

where $$r$$ is the radial distance to the window centre, $$c$$ is the cut-off frequency, and $$w_c$$ is the width of the cut-off region.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> w1 = kp.filters.Window(
...     "highpass", cutoff=1, cutoff_width=0.5, shape=(96, 96)
... )
>>> w2 = kp.filters.highpass_fft_filter(
...     shape=(96, 96), cutoff=1, cutoff_width=0.5
... )
>>> np.allclose(w1, w2)
True

kikuchipy.filters.lowpass_fft_filter(shape, cutoff, cutoff_width=None)[source]#

Return a frequency domain low-pass filter transfer function in 2D.

Used in [WMD06].

Parameters:
Returns:

2D transfer function.

Return type:

w

Notes

The low-pass filter transfer function is defined as

$\begin{split}w(r) = e^{-\left(\frac{r - c}{\sqrt{2}w_c/2}\right)^2}, w(r) = \begin{cases} 0, & r > c + 2w_c \\ 1, & r < c, \end{cases}\end{split}$

where $$r$$ is the radial distance to the window centre, $$c$$ is the cut-off frequency, and $$w_c$$ is the width of the cut-off region.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> w1 = kp.filters.Window(
...     "lowpass", cutoff=30, cutoff_width=15, shape=(96, 96)
... )
>>> w2 = kp.filters.lowpass_fft_filter(
...     shape=(96, 96), cutoff=30, cutoff_width=15
... )
>>> np.allclose(w1, w2)
True

kikuchipy.filters.modified_hann(Nx)[source]#

Return a 1D modified Hann window with the maximum value normalized to 1.

Used in [WMD06].

Parameters:

Nx (int) – Number of points in the window.

Returns:

1D Hann window.

Return type:

w

Notes

The modified Hann window is defined as

$w(x) = \cos\left(\frac{\pi x}{N_x}\right),$

with $$x$$ relative to the window centre.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> w1 = kp.filters.modified_hann(Nx=30)
>>> w2 = kp.filters.Window("modified_hann", shape=(30,))
>>> np.allclose(w1, w2)
True


### Window#

 Return whether the window is in a valid state. Make window circular. plot([grid, show_values, textcolors, cmap, ...]) Plot window values with indices relative to the origin. shape_compatible(shape) Return whether window shape is compatible with a data shape.
class kikuchipy.filters.Window(window: = None, shape: = None, **kwargs)[source]#

Bases: ndarray

A window/kernel/mask/filter of a given shape with some values.

This class is a subclass of numpy.ndarray with some additional convenience methods.

It can be used to create a transfer function for filtering in the frequency domain, create an averaging window for averaging patterns with their nearest neighbours, and so on.

Parameters:
• window ("circular", "rectangular", "gaussian", str, numpy.ndarray, or dask.array.Array, optional) – Window type to create. Available types are listed in scipy.signal.windows.get_window() and includes “rectangular” and “gaussian”, in addition to a “circular” window (default) filled with ones in which corner data are set to zero, a “modified_hann” window and “lowpass” and “highpass” FFT windows. A window element is considered to be in a corner if its radial distance to the origin (window centre) is shorter or equal to the half width of the windows’s longest axis. A 1D or 2D numpy.ndarray or dask.array.Array can also be passed.

• shape (sequence of int, optional) – Shape of the window. Not used if a custom window is passed to window. This can be either 1D or 2D, and can be asymmetrical. Default is (3, 3).

• **kwargs – Required keyword arguments passed to the window type.

Examples

>>> import numpy as np
>>> import kikuchipy as kp


The following passed parameters are the default

>>> w = kp.filters.Window(window="circular", shape=(3, 3))
>>> w
Window (3, 3) circular
[[0. 1. 0.]
[1. 1. 1.]
[0. 1. 0.]]


A window can be made circular

>>> w = kp.filters.Window(window="rectangular")
>>> w
Window (3, 3) rectangular
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
>>> w.make_circular()
>>> w
Window (3, 3) circular
[[0. 1. 0.]
[1. 1. 1.]
[0. 1. 0.]]


A custom window can be created

>>> w = kp.filters.Window(np.arange(6).reshape(3, 2))
>>> w
Window (3, 2) custom
[[0 1]
[2 3]
[4 5]]


To create a Gaussian window with a standard deviation of 2, obtained from scipy.signal.windows.gaussian()

>>> w = kp.filters.Window(window="gaussian", std=2)
>>> w
Window (3, 3) gaussian
[[0.7788 0.8825 0.7788]
[0.8825 1.     0.8825]
[0.7788 0.8825 0.7788]]

__init__()#
circular: bool = False#
property distance_to_origin: ndarray#

Radial distance to the window origin.

Return type:

ndarray

is_valid()[source]#

Return whether the window is in a valid state.

Return type:

bool

make_circular()[source]#

Make window circular.

The data of window elements who’s radial distance to the window origin is shorter or equal to the half width of the window’s longest axis are set to zero. This has no effect if the window has only one axis.

property n_neighbours: tuple#

Maximum number of nearest neighbours in each navigation axis to the origin.

Return type:

tuple

name: str = None#
property origin: tuple#

Window origin.

Return type:

tuple

plot(grid=True, show_values=True, textcolors=None, cmap='viridis', cmap_label='Value', colorbar=True, return_figure=False)[source]#

Plot window values with indices relative to the origin.

Parameters:
Return type:

fig

Examples

A plot of window data with indices relative to the origin, showing element values and x/y ticks, can be produced and written to file

>>> import kikuchipy as kp
>>> w = kp.filters.Window()
>>> fig = w.plot(return_figure=True)
>>> fig.savefig('my_kernel.png')


If getting the figure axes, image array or colorbar is necessary

>>> ax = fig.axes[0]
>>> im = ax.get_images()[0]
>>> arr = im.get_array()
>>> cbar = im.colorbar

shape_compatible(shape)[source]#

Return whether window shape is compatible with a data shape.

Parameters:

shape (Tuple[int]) – Shape of data to apply window to.

Return type:

bool

## generators#

Generate signals and simulations, sometimes from other signals.

 EBSDSimulationGenerator(detector, phase, ...) [Deprecated] A generator storing necessary parameters to simulate geometrical EBSD patterns. VirtualBSEGenerator(signal) Generates virtual backscatter electron (BSE) images for a specified electron backscatter diffraction (EBSD) signal and a set of EBSD detector areas. Return an RGB image from three numpy arrays, with a potential alpha channel. Normalize an image's intensities to a mean of 0 and a standard deviation of 1, with the possibility to also scale by a contrast factor and shift the brightness values.

### EBSDSimulationGenerator#

 Project a set of Kikuchi bands and zone axes onto the detector, one set for each rotation of the unit cell.
class kikuchipy.generators.EBSDSimulationGenerator(detector, phase, rotations)[source]#

Bases: object

[Deprecated] A generator storing necessary parameters to simulate geometrical EBSD patterns.

Notes

Deprecated since version 0.6: Class EBSDSimulationGenerator is deprecated and will be removed in version 0.7. Use KikuchiPatternSimulator instead.

__init__(detector, phase, rotations)[source]#

A generator storing necessary parameters to simulate geometrical EBSD patterns.

Parameters:
• detector (EBSDDetector) – Detector describing the detector-sample geometry.

• phase (Phase) – A phase container with a crystal structure and a space and point group describing the allowed symmetry operations.

• rotations (Rotation) – Unit cell rotations to simulate patterns for. The navigation shape of the resulting simulation is determined from the rotations’ shape, with a maximum dimension of 2.

Examples

>>> from orix import crystal_map, quaternion
>>> import kikuchipy as kp
>>> det = kp.detectors.EBSDDetector(
...     shape=(60, 60), sample_tilt=70, pc=[0.5,] * 3
... )
>>> p = crystal_map.Phase(name="ni", space_group=225)
>>> p.structure.lattice.setLatPar(3.52, 3.52, 3.52, 90, 90, 90)
>>> simgen = kp.generators.EBSDSimulationGenerator(
...     detector=det,
...     phase=p,
...     rotations=Rotation.from_euler([1.57, 0, 1.57])
... )
>>> simgen
EBSDSimulationGenerator (1,)
EBSDDetector (60, 60), px_size 1 um, binning 1, tilt 0, azimuthal 0, pc (0.5, 0.5, 0.5)
<name: ni. space group: Fm-3m. point group: m-3m. proper point group: 432. color: tab:blue>
Rotation (1,)

geometrical_simulation(reciprocal_lattice_point=None)[source]#

Project a set of Kikuchi bands and zone axes onto the detector, one set for each rotation of the unit cell.

The zone axes are calculated from the Kikuchi bands.

Parameters:

reciprocal_lattice_point (Optional[ReciprocalLatticePoint]) – Crystal planes to project onto the detector. If None, and the generator has a phase with a unit cell with a point group, a set of planes with minimum distance of 1 Å and their symmetrically equivalent planes are used.

Return type:

GeometricalEBSDSimulation

Examples

>>> from diffsims.crystallography import ReciprocalLatticePoint
>>> from orix import crystal_map, quaternion
>>> import kikuchipy as kp
>>> det = kp.detectors.EBSDDetector(
...     shape=(60, 60), sample_tilt=70, pc=[0.5,] * 3
... )
>>> p = crystal_map.Phase(name="ni", space_group=225)
>>> p.structure.lattice.setLatPar(3.52, 3.52, 3.52, 90, 90, 90)
>>> simgen = kp.generators.EBSDSimulationGenerator(
...     detector=det,
...     phase=p,
...     rotations=quaternion.Rotation.from_euler([0, 0, 0])
... )
>>> sim1 = simgen.geometrical_simulation()
>>> sim1.bands.size
94
>>> rlp = ReciprocalLatticePoint(
...     phase=p, hkl=[[1, 1, 1], [2, 0, 0]]
... ).symmetrise()
>>> sim2 = simgen.geometrical_simulation(rlp)
>>> sim2.bands.size
7

property navigation_dimension: int#

Number of navigation dimensions (a maximum of 2).

Return type:

int

property navigation_shape: tuple#

Navigation shape of the rotations and detector projection center array (maximum of 2).

Return type:

tuple

property rotations: Rotation#

Unit cell rotations to simulate patterns for.

Return type:

Rotation

### VirtualBSEGenerator#

 get_images_from_grid([dtype_out]) Return an in-memory signal with a stack of virtual backscatter electron (BSE) images by integrating the intensities within regions of interest (ROI) defined by the detector grid_shape. get_rgb_image(r, g, b[, percentiles, ...]) Return an in-memory RGB virtual BSE image from three regions of interest (ROIs) on the EBSD detector, with a potential "alpha channel" in which all three arrays are multiplied by a fourth. plot_grid([pattern_idx, rgb_channels, ...]) Plot a pattern with the detector grid superimposed, potentially coloring the edges of three grid tiles red, green and blue. roi_from_grid(index) Return a rectangular region of interest (ROI) on the EBSD detector from one or multiple generator grid tile indices as row(s) and column(s).
class kikuchipy.generators.VirtualBSEGenerator(signal)[source]#

Bases: object

Generates virtual backscatter electron (BSE) images for a specified electron backscatter diffraction (EBSD) signal and a set of EBSD detector areas.

signal#
Type:

kikuchipy.signals.EBSD

grid_shape#
Type:

Tuple[int]

__init__(signal)[source]#
get_images_from_grid(dtype_out=<class 'numpy.float32'>)[source]#

Return an in-memory signal with a stack of virtual backscatter electron (BSE) images by integrating the intensities within regions of interest (ROI) defined by the detector grid_shape.

Parameters:

dtype_out (dtype) – Output data type, default is float32.

Returns:

vbse_images – In-memory signal with virtual BSE images.

Return type:

VirtualBSEImage

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s
<EBSD, title: patterns My awes0m4 ..., dimensions: (3, 3|60, 60)>
>>> vbse_gen = kp.generators.VirtualBSEGenerator(s)
>>> vbse_gen.grid_shape = (5, 5)
>>> vbse = vbse_gen.get_images_from_grid()
>>> vbse
<VirtualBSEImage, title: , dimensions: (5, 5|3, 3)>

get_rgb_image(r, g, b, percentiles=None, normalize=True, alpha=None, dtype_out=<class 'numpy.uint8'>, **kwargs)[source]#

Return an in-memory RGB virtual BSE image from three regions of interest (ROIs) on the EBSD detector, with a potential “alpha channel” in which all three arrays are multiplied by a fourth.

Parameters:
Returns:

vbse_rgb_image – Virtual RGB image in memory.

Return type:

VirtualBSEImage

Notes

HyperSpy only allows for RGB signal dimensions with data types unsigned 8 or 16 bit.

property grid_cols: ndarray#

Return detector grid columns, defined by grid_shape.

Return type:

ndarray

property grid_rows: ndarray#

Return detector grid rows, defined by grid_shape.

Return type:

ndarray

plot_grid(pattern_idx=None, rgb_channels=None, visible_indices=True, **kwargs)[source]#

Plot a pattern with the detector grid superimposed, potentially coloring the edges of three grid tiles red, green and blue.

Parameters:
Returns:

pattern – A single pattern with the markers added.

Return type:

kikuchipy.signals.EBSD

roi_from_grid(index)[source]#

Return a rectangular region of interest (ROI) on the EBSD detector from one or multiple generator grid tile indices as row(s) and column(s).

Parameters:

index (Union[Tuple, List[Tuple]]) – Row and column of one or multiple grid tiles as a tuple or a list of tuples.

Returns:

roi – ROI defined by the grid indices.

Return type:

hyperspy.roi.RectangularROI

### Other functions#

kikuchipy.generators.virtual_bse_generator.get_rgb_image(channels, percentiles=None, normalize=True, alpha=None, dtype_out=<class 'numpy.uint8'>, **kwargs)[source]#

Return an RGB image from three numpy arrays, with a potential alpha channel.

Parameters:
Returns:

rgb_image – RGB image.

Return type:

np.ndarray

kikuchipy.generators.virtual_bse_generator.normalize_image(image, add_bright=0, contrast=1.0, dtype_out=<class 'numpy.uint8'>)[source]#

Normalize an image’s intensities to a mean of 0 and a standard deviation of 1, with the possibility to also scale by a contrast factor and shift the brightness values.

Clips intensities to uint8 data type range, [0, 255].

Adapted from the aloe/xcdskd package.

Parameters:
Returns:

image_out

Return type:

np.ndarray

## indexing#

Tools for indexing of EBSD patterns by matching to a dictionary of simulated patterns.

The EBSD method dictionary_indexing() uses some of these tools for dictionary indexing.

 compute_refine_orientation_results(results, ...) Compute the results from refine_orientation() and return the CrystalMap. Compute the results from refine_orientation_projection_center() and return the CrystalMap and EBSDDetector. Compute the results from refine_projection_center() and return the score array and EBSDDetector. orientation_similarity_map(xmap[, n_best, ...]) Compute an orientation similarity map where the ranked list of the dictionary indices of the best matching simulated patterns in one point is compared to the corresponding lists in the nearest neighbour points . merge_crystal_maps(crystal_maps[, ...]) Merge a list of at least two single phase CrystalMap with a 1D or 2D navigation shape into one multi phase map. similarity_metrics Similarity metrics for comparing grayscale patterns.
kikuchipy.indexing.compute_refine_orientation_results(results, xmap, master_pattern)[source]#

Compute the results from refine_orientation() and return the CrystalMap.

Parameters:
Returns:

Crystal map with refined orientations and scores.

Return type:

refined_xmap

kikuchipy.indexing.compute_refine_orientation_projection_center_results(results, detector, xmap, master_pattern)[source]#

Compute the results from refine_orientation_projection_center() and return the CrystalMap and EBSDDetector.

Parameters:
• results (Array) – The dask array returned from refine_orientation_projection_center().

• detector (EBSDDetector) – Detector passed to refine_orientation_projection_center() to obtain results.

• xmap (CrystalMap) – Crystal map passed to refine_orientation_projection_center() to obtain results.

• master_pattern (EBSDMasterPattern) – Master pattern passed to refine_orientation_projection_center() to obtain results.

Returns:

kikuchipy.indexing.compute_refine_projection_center_results(results, detector, xmap)[source]#

Compute the results from refine_projection_center() and return the score array and EBSDDetector.

Parameters:
• results (Array) – The dask array returned from refine_projection_center().

• detector (EBSDDetector) – Detector passed to refine_projection_center() to obtain results.

• xmap (CrystalMap) – Crystal map passed to refine_projection_center() to obtain results.

Returns:

kikuchipy.indexing.orientation_similarity_map(xmap, n_best=None, simulation_indices_prop='simulation_indices', normalize=False, from_n_best=None, footprint=None, center_index=2)[source]#

Compute an orientation similarity map where the ranked list of the dictionary indices of the best matching simulated patterns in one point is compared to the corresponding lists in the nearest neighbour points .

Parameters:
• xmap (CrystalMap) – A crystal map with a ranked list of the array indices of the best matching simulated patterns among its properties.

• n_best (Optional[int]) – Number of ranked indices to compare. If None (default), all indices are compared.

• simulation_indices_prop (str) – Name of simulated indices array in the crystal maps’ properties. Default is “simulation_indices”.

• normalize (bool) – Whether to normalize the number of equal indices to the range [0, 1], by default False.

• from_n_best (Optional[int]) – Return an OSM for each n in the range [from_n_best, n_best]. If None (default), only the OSM for n_best indices is returned.

• footprint (Optional[ndarray]) – Boolean 2D array specifying which neighbouring points to compare lists with, by default the four nearest neighbours.

• center_index (int) – Flat index of central navigation point in the truthy values of footprint, by default 2.

Returns:

osm – Orientation similarity map(s). If from_n_best is not None, the returned array has three dimensions, where n_best is at array[:, :, 0] and from_n_best at array[:, :, -1].

Return type:

ndarray

Notes

If the set $$S_{r,c}$$ is the ranked list of best matching indices for a given point $$(r,c)$$, then the orientation similarity index $$\eta_{r,c}$$ is the average value of the cardinalities (#) of the intersections with the neighbouring sets

$\eta_{r,c} = \frac{1}{4} \left( \#(S_{r,c} \cap S_{r-1,c}) + \#(S_{r,c} \cap S_{r+1,c}) + \#(S_{r,c} \cap S_{r,c-1}) + \#(S_{r,c} \cap S_{r,c+1}) \right).$

Changed in version 0.5: Default value of normalize changed to False.

kikuchipy.indexing.merge_crystal_maps(crystal_maps, mean_n_best=1, greater_is_better=None, scores_prop='scores', simulation_indices_prop=None)[source]#

Merge a list of at least two single phase CrystalMap with a 1D or 2D navigation shape into one multi phase map.

It is required that all maps have the same number of rotations and scores (and simulation indices if applicable) per point.

Parameters:
• crystal_maps (List[CrystalMap]) – A list of crystal maps with simulated indices and scores among their properties.

• mean_n_best (int) – Number of best metric results to take the mean of before comparing. Default is 1. If given with a negative sign and greater_is_better is not given, the n lowest valued metric results are chosen.

• greater_is_better (Optional[int]) – True if a higher score means a better match. Default is None, in which case the sign of mean_n_best is used, with a positive sign meaning True.

• scores_prop (str) – Name of scores array in the crystal maps’ properties. Default is “scores”.

• simulation_indices_prop (Optional[str]) – Name of simulated indices array in the crystal maps’ properties. If None (default), the merged crystal map will not contain an array of merged simulation indices from the input crystal maps’ properties. If a string, there must be as many simulation indices per point as there are scores.

Returns:

merged_xmap – A crystal map where the rotation of the phase with the best matching score(s) is assigned to each point. The best matching scores, merge sorted, are added to its properties with a name equal to whatever passed to scores_prop with “merged” as a suffix. If simulation_indices_prop is passed, the best matching simulation indices are added in the same way as the scores.

Return type:

CrystalMap

Notes

Changed in version 0.5: The greater_is_better parameter replaced metric.

### similarity_metrics#

Similarity metrics for comparing grayscale patterns.

 SimilarityMetric([n_experimental_patterns, ...]) Abstract class implementing a similarity metric to match experimental and simulated EBSD patterns in a dictionary. Similarity metric implementing the normalized cross-correlation, or Pearson Correlation Coefficient [GW17] Similarity metric implementing the normalized dot product [CPW+15]
class kikuchipy.indexing.similarity_metrics.SimilarityMetric(n_experimental_patterns=None, n_dictionary_patterns=None, signal_mask=None, dtype=<class 'numpy.float32'>, rechunk=False)[source]#

Abstract class implementing a similarity metric to match experimental and simulated EBSD patterns in a dictionary.

For use in dictionary_indexing() or directly on pattern arrays if a __call__() method is implemented. Note that dictionary_indexing() will always reshape the dictionary pattern array to 2D (1 navigation dimension, 1 signal dimension) before calling prepare_dictionary() and match().

Take a look at the implementation of NormalizedCrossCorrelationMetric for how to write a concrete custom metric.

When writing a custom similarity metric class, the methods listed as abstract below must be implemented. Any number of custom parameters can be passed. Also listed are the attributes available to the methods if set properly during initialization or after.

allowed_dtypes#

List of allowed array data types used during matching.

Type:

list of numpy.dtype

dtype#

Which data type to cast the patterns to before matching. Must be listed in allowed_dtypes.

Type:

numpy.dtype

n_dictionary_patterns#

Number of dictionary patterns to match. This information might be necessary when reshaping the dictionary array in prepare_dictionary().

Type:

int or None

n_experimental_patterns#

Number of experimental patterns to match. This information might be necessary when reshaping the dictionary array in prepare_experimental().

Type:

int or None

sign#

+1 if a greater match is better, -1 if a lower match is better. This must be set in the inheriting class.

Type:

int or None

signal_mask#

A boolean mask equal to the experimental patterns’ detector shape (n rows, n columns), where only pixels equal to False are matched.

Type:

numpy.ndarray or None

rechunk#

Whether to allow rechunking of arrays before matching.

Type:

bool

__init__(n_experimental_patterns=None, n_dictionary_patterns=None, signal_mask=None, dtype=<class 'numpy.float32'>, rechunk=False)[source]#

Create a similarity metric matching experimental and simulated EBSD patterns in a dictionary.

Parameters:
• n_experimental_patterns (Optional[int]) – Number of experimental patterns. If not given, this is set to None and must be set later. Must be at least 1.

• n_dictionary_patterns (Optional[int]) – Number of dictionary patterns. If not given, this is set to None and must be set later. Must be at least 1.

• signal_mask (Optional[ndarray]) – A boolean mask equal to the experimental patterns’ detector shape (n rows, n columns), where only pixels equal to False are matched. If not given, all pixels are used.

• dtype (type) – Which data type to cast the patterns to before matching to.

• rechunk (bool) – Whether to allow rechunking of arrays before matching. Default is False.

abstract match(*args, **kwargs)[source]#

Match all experimental patterns to all dictionary patterns and return their similarities.

abstract prepare_dictionary(*args, **kwargs)[source]#

Prepare dictionary patterns before matching to experimental patterns in match().

abstract prepare_experimental(*args, **kwargs)[source]#

Prepare experimental patterns before matching to dictionary patterns in match().

raise_error_if_invalid()[source]#

Raise a ValueError if self.dtype is not among self.allowed_dtypes and the latter is not an empty list.

class kikuchipy.indexing.similarity_metrics.NormalizedCrossCorrelationMetric(n_experimental_patterns=None, n_dictionary_patterns=None, signal_mask=None, dtype=<class 'numpy.float32'>, rechunk=False)[source]#

Similarity metric implementing the normalized cross-correlation, or Pearson Correlation Coefficient [GW17]

$r = \frac {\sum^n_{i=1}(x_i - \bar{x})(y_i - \bar{y})} { \sqrt{\sum ^n _{i=1}(x_i - \bar{x})^2} \sqrt{\sum ^n _{i=1}(y_i - \bar{y})^2} },$

where experimental patterns $$x$$ and simulated patterns $$y$$ are centered by subtracting out the mean of each pattern, and the sum of cross-products of the centered patterns is accumulated. The denominator adjusts the scales of the patterns to have equal units.

Equivalent results are obtained with dask.array.tensordot() with axes=([2, 3], [1, 2])) for 4D and 3D experimental and simulated data sets, respectively.

See SimilarityMetric for remaining attributes.

allowed_dtypes#

float32 and float64.

sign#

+1, meaning greater is better.

__call__(experimental, dictionary)[source]#

Compute the similarities between experimental patterns and simulated dictionary patterns.

Before calling match(), this method calls prepare_experimental(), reshapes the dictionary patterns to 1 navigation dimension and 1 signal dimension, and calls prepare_dictionary().

Parameters:
Return type:

similarities

match(experimental, dictionary)[source]#

Match all experimental patterns to all dictionary patterns and return their similarities.

Return type:

Array

prepare_dictionary(patterns)[source]#

Prepare dictionary patterns before matching to experimental patterns in match().

Return type:
prepare_experimental(patterns)[source]#

Prepare experimental patterns before matching to dictionary patterns in match().

Return type:
class kikuchipy.indexing.similarity_metrics.NormalizedDotProductMetric(n_experimental_patterns=None, n_dictionary_patterns=None, signal_mask=None, dtype=<class 'numpy.float32'>, rechunk=False)[source]#

Similarity metric implementing the normalized dot product [CPW+15]

$\rho = \frac {\langle \mathbf{X}, \mathbf{Y} \rangle} {||\mathbf{X}|| \cdot ||\mathbf{Y}||},$

where $${\langle \mathbf{X}, \mathbf{Y} \rangle}$$ is the dot (inner) product of the pattern vectors $$\mathbf{X}$$ and $$\mathbf{Y}$$.

See SimilarityMetric for remaining attributes.

allowed_dtypes#

float32 and float64.

sign#

+1, meaning greater is better.

__call__(experimental, dictionary)[source]#

Compute the similarities between experimental patterns and simulated dictionary patterns.

Before calling match(), this method calls prepare_experimental(), reshapes the dictionary patterns to 1 navigation dimension and 1 signal dimension, and calls prepare_dictionary().

Parameters:
Return type:

similarities

match(experimental, dictionary)[source]#

Match all experimental patterns to all dictionary patterns and return their similarities.

Return type:

Array

prepare_dictionary(patterns)[source]#

Prepare dictionary patterns before matching to experimental patterns in match().

Return type:
prepare_experimental(patterns)[source]#

Prepare experimental patterns before matching to dictionary patterns in match().

Return type:

## io#

Read and write signals from and to file.

 _io.load(filename[, lazy]) Load an EBSD or EBSDMasterPattern object from a supported file format. plugins Input/output plugins.
kikuchipy.io._io.load(filename, lazy=False, **kwargs)[source]#

Load an EBSD or EBSDMasterPattern object from a supported file format.

This function is a modified version of hyperspy.io.load().

Parameters:
• filename (str) – Name of file to load.

• lazy (bool) – Open the data lazily without actually reading the data from disk until required. Allows opening arbitrary sized datasets. Default is False.

• kwargs – Keyword arguments passed to the corresponding kikuchipy reader. See their individual documentation for available options.

Return type:

kikuchipy.signals.EBSD, kikuchipy.signals.EBSDMasterPattern, list of kikuchipy.signals.EBSD or list of kikuchipy.signals.EBSDMasterPattern

Examples

Import nine patterns from an HDF5 file in a directory DATA_DIR

>>> import kikuchipy as kp
>>> s = kp.load(DATA_DIR + "/patterns.h5")
>>> s
<EBSD, title: patterns My awes0m4 ..., dimensions: (3, 3|60, 60)>


### plugins#

Input/output plugins.

 emsoft_ebsd Read support for simulated EBSD patterns in EMsoft's HDF5 format. emsoft_ebsd_master_pattern Read support for simulated EBSD master patterns in EMsoft's HDF5 format. h5ebsd Read/write support for EBSD patterns in some HDF5 file formats. nordif Read/write support for EBSD patterns in NORDIF's binary format. nordif_calibration_patterns Read support for NORDIF's calibration patterns. oxford_binary Read support for uncompressed EBSD patterns in Oxford Instruments' binary .ebsp file format.

The plugins import patterns and parameters from file formats into EBSD or EBSDMasterPattern (or LazyEBSD or LazyEBSDMasterPattern if loading lazily) objects.

#### emsoft_ebsd#

Read support for simulated EBSD patterns in EMsoft’s HDF5 format.

kikuchipy.io.plugins.emsoft_ebsd.file_reader(filename, scan_size=None, lazy=False, **kwargs)[source]#

Read dynamically simulated electron backscatter diffraction patterns from EMsoft’s format produced by their EMEBSD.f90 program.

Parameters:
Returns:

signal_dict_list – Data, axes, metadata and original metadata.

Return type:

list of dicts

#### emsoft_ebsd_master_pattern#

Read support for simulated EBSD master patterns in EMsoft’s HDF5 format.

kikuchipy.io.plugins.emsoft_ebsd_master_pattern.file_reader(filename, energy=None, projection='stereographic', hemisphere='upper', lazy=False, **kwargs)[source]#

Read electron backscatter diffraction master patterns from EMsoft’s HDF5 file format .

Parameters:
• filename (str) – Full file path of the HDF file.

• energy (Optional[range]) – Desired beam energy or energy range. If None is passed (default), all available energies are read.

• projection (str) – Projection(s) to read. Options are "stereographic" (default) or "lambert".

• hemisphere (str) – Projection hemisphere(s) to read. Options are "upper" (default), "lower" or "both". If "both", these will be stacked in the vertical navigation axis.

• lazy (bool) – Open the data lazily without actually reading the data from disk until requested. Allows opening datasets larger than available memory. Default is False.

• kwargs – Keyword arguments passed to h5py.File.

Returns:

signal_dict_list – Data, axes, metadata and original metadata.

Return type:

list of dicts

#### h5ebsd#

Read/write support for EBSD patterns in some HDF5 file formats.

kikuchipy.io.plugins.h5ebsd.brukerheader2dicts(scan_group, md)[source]#

Return scan metadata dictionaries from a Bruker h5ebsd file.

Parameters:
Return type:
Returns:

• md – kikuchipy metadata elements available in Bruker file.

• omd – All metadata available in Bruker file.

• scan_size – Scan, image, step and detector pixel size available in Bruker file.

kikuchipy.io.plugins.h5ebsd.check_h5ebsd(file)[source]#

Check if HDF file is an h5ebsd file by searching for datasets containing manufacturer, version and scans in the top group.

Parameters:

file (h5py:File) – File where manufacturer, version and scan datasets should reside in the top group.

kikuchipy.io.plugins.h5ebsd.dict2h5ebsdgroup(dictionary, group, **kwargs)[source]#

Write a dictionary from metadata to datasets in a new group in an opened HDF file in the h5ebsd format.

Parameters:
• dictionary (dict) – Metadata, with keys as dataset names.

• group (h5py:Group) – HDF group to write dictionary to.

• kwargs – Keyword arguments passed to h5py:Group.require_dataset().

kikuchipy.io.plugins.h5ebsd.edaxheader2dicts(scan_group, md)[source]#

Return scan metadata dictionaries from an EDAX TSL h5ebsd file.

Parameters:
Return type:
Returns:

• md – kikuchipy metadata elements available in EDAX file.

• omd – All metadata available in EDAX file.

• scan_size – Scan, image, step and detector pixel size available in EDAX file.

kikuchipy.io.plugins.h5ebsd.file_reader(filename, scan_group_names=None, lazy=False, **kwargs)[source]#

Read electron backscatter diffraction patterns from an h5ebsd file [Jackson2014]. A valid h5ebsd file has at least one top group with the subgroup ‘EBSD’ with the subgroups ‘Data’ (patterns etc.) and ‘Header’ (metadata etc.).

Parameters:
Returns:

scan_dict_list – Data, axes, metadata and original metadata.

Return type:

list of dicts

References

M. A. Jackson, M. A. Groeber, M. D. Uchic, D. J. Rowenhorst and M. De Graef, “h5ebsd: an archival data format for electron back-scatter diffraction data sets,” Integrating Materials and Manufacturing Innovation 3 (2014), doi: https://doi.org/10.1186/2193-9772-3-4.

kikuchipy.io.plugins.h5ebsd.file_writer(filename, signal, add_scan=None, scan_number=1, **kwargs)[source]#

Write an EBSD or LazyEBSD signal to an existing, but not open, or new h5ebsd file.

Only writing to kikuchipy’s h5ebsd format is supported.

Parameters:
kikuchipy.io.plugins.h5ebsd.get_desired_scan_groups(file, scan_group_names=None)[source]#

Get the desired HDF5 groups with scans within them.

Parameters:
Returns:

A list of the desired scan group(s) in the file.

Return type:

scan_groups

kikuchipy.io.plugins.h5ebsd.get_scan_groups(file)[source]#

Return a list of the scan group names from an h5ebsd file.

Parameters:

file (h5py:File) – File where manufacturer, version and scan datasets should reside in the top group.

Returns:

scan_groups – List of available scan groups.

Return type:

h5py:Group

kikuchipy.io.plugins.h5ebsd.h5ebsd2signaldict(scan_group, manufacturer, version, lazy=False)[source]#

Return a dictionary with signal, metadata and original_metadata from an h5ebsd scan.

Parameters:
• scan_group (h5py:Group) – HDF group of scan.

• manufacturer (str) – Manufacturer of file. Options are “kikuchipy”/”EDAX”/”Bruker Nano”.

• version (str) – Version of manufacturer software.

• lazy (bool) – Read dataset lazily.

Returns:

scan – Dictionary with patterns, metadata and original_metadata.

Return type:

dict

kikuchipy.io.plugins.h5ebsd.h5ebsdheader2dicts(scan_group, manufacturer, version, lazy=False)[source]#

Return three dictionaries in HyperSpy’s hyperspy.misc.utils.DictionaryTreeBrowser format, one with the h5ebsd scan header parameters as kikuchipy metadata, another with all datasets in the header as original metadata, and the last with info about scan size, image size and detector pixel size.

Parameters:
• scan_group (h5py:Group) – HDF group of scan data and header.

• manufacturer (str) – Manufacturer of file. Options are “kikuchipy”/”EDAX”/”Bruker Nano”

• version (str) – Version of manufacturer software used to create file.

• lazy (bool) – Read dataset lazily.

Return type:
Returns:

• md – kikuchipy metadata elements available in file.

• omd – All metadata available in file.

• scan_size – Scan, image, step and detector pixel size available in file.

kikuchipy.io.plugins.h5ebsd.hdf5group2dict(group, dictionary=None, recursive=False, data_dset_names=None, **kwargs)[source]#

Return a dictionary with values from datasets in a group in an opened HDF5 file.

Parameters:
Returns:

dictionary – Dataset values in group (and subgroups if recursive=True).

Return type:

dict

kikuchipy.io.plugins.h5ebsd.kikuchipyheader2dicts(scan_group, md)[source]#

Return scan metadata dictionaries from a kikuchipy h5ebsd file.

Parameters:
Return type:
Returns:

• md – kikuchipy metadata elements available in kikuchipy file.

• omd – All metadata available in kikuchipy file.

• scan_size – Scan, image, step and detector pixel size available in kikuchipy file.

kikuchipy.io.plugins.h5ebsd.manufacturer_pattern_names()[source]#

Return mapping of string of supported manufacturers to the names of their HDF dataset where the patterns are stored.

Return type:

dict

kikuchipy.io.plugins.h5ebsd.manufacturer_version(file)[source]#

Get manufacturer and version from h5ebsd file.

Parameters:

file (h5py:File) – File with manufacturer and version datasets in the top group.

Return type:
Returns:

• manufacturer (str)

• version (str)

#### nordif#

Read/write support for EBSD patterns in NORDIF’s binary format.

kikuchipy.io.plugins.nordif.file_reader(filename, mmap_mode=None, scan_size=None, pattern_size=None, setting_file=None, lazy=False)[source]#

Read electron backscatter patterns from a NORDIF data file.

Parameters:
Returns:

scan – Data, axes, metadata and original metadata.

Return type:

list of dicts

kikuchipy.io.plugins.nordif.file_writer(filename, signal)[source]#

Write an EBSD or LazyEBSD object to a NORDIF binary file.

Parameters:
kikuchipy.io.plugins.nordif.get_settings_from_file(filename)[source]#

Return metadata with parameters from NORDIF setting file.

Parameters:

filename (str) – File path of NORDIF setting file.

Return type:
Returns:

• md – Metadata complying with HyperSpy’s metadata structure.

• omd – Metadata that does not fit into HyperSpy’s metadata structure.

• scan_size – Information on image size, scan size and scan steps.

kikuchipy.io.plugins.nordif.get_string(content, expression, line_no, file)[source]#

Get relevant part of string using regular expression.

Parameters:
Returns:

Output string with relevant value.

Return type:

str

#### nordif_calibration_patterns#

Read support for NORDIF’s calibration patterns.

kikuchipy.io.plugins.nordif_calibration_patterns.file_reader(filename, lazy=False)[source]#

Reader electron backscatter patterns from .bmp files stored in a NORDIF project directory, their filenames listed in a text file.

Parameters:
Returns:

scan – Data, axes, metadata and original metadata.

Return type:

list of dicts

#### oxford_binary#

Read support for uncompressed EBSD patterns in Oxford Instruments’ binary .ebsp file format.

Information about the file format was provided by Oxford Instruments.

class kikuchipy.io.plugins.oxford_binary.OxfordBinaryFileReader(file)[source]#

Bases: object

Oxford Instruments’ binary .ebsp file reader.

property all_patterns_present: bool#

Whether all or only non-indexed patterns are stored in the file.

Return type:

bool

property data_shape: tuple#

Full data shape.

Return type:

tuple

property first_pattern_position: int#

File byte position of first pattern after the file header.

Return type:

int

get_memmap()[source]#

Return a memory map of the pattern header, actual patterns, and a potential pattern footer.

The memory map has the shape of (n indexed patterns,), and the patterns have the correct signal shape (n rows, n columns).

If the pattern footer is available, the memory map has these fields:

Name

Data type

Shape

is_compressed

int32

(1,)

nrows

int32

(1,)

ncols

int32

(1,)

n_bytes

int32

(1,)

pattern

uint8 or uint16

(n rows, n columns)

has_beam_x

bool

(1,)

beam_x

float64

(1,)

has_beam_y

bool

(1,)

beam_y

float64

(1,)

Return type:

numpy.memmap

get_navigation_shape_and_step_size()[source]#

Return the navigation shape and step size.

An equal step size between rows and columns is assumed.

The navigation shape is determined by evaluating the beam row and column position of the upper left and lower right patterns. The step size is determined from the difference in column position of the upper left pattern and the pattern in the next column.

Return type:
Returns:

• nrows – Number of navigation (map) rows.

• ncols – Number of navigation (map) columns.

• step_size – Step size between rows and columns.

Return the pattern footer data types to be used when memory mapping.

Parameters:

footer_dtype – Format of each pattern footer as a list of tuples with a field name, data type and size. The format depends on the version.

Return type:
get_pattern_starts()[source]#

Return the file byte positions of each pattern.

Parameters:

pattern_starts – Integer array of file byte positions.

Return type:

ndarray

get_patterns(lazy)[source]#

Return the EBSD patterns in the file.

The patterns are read from the memory map. They are sorted into their correct navigation (map) position if necessary.

Parameters:

lazy (bool) – Whether to return a numpy.ndarray or dask.array.Array.

Returns:

EBSD patterns of shape (n navigation rows, n navigation columns, n signal rows, n signal columns).

Return type:

data

get_scan(lazy)[source]#

Return a dictionary with the necessary information to initialize an EBSD instance.

Parameters:

lazy (bool) – Whether to return the EBSD patterns as a numpy.ndarray or dask.array.Array.

Returns:

Dictionary of axes, data, metadata and original metadata.

Return type:

scan

Return a single pattern footer with pattern beam positions.

Parameters:

offset (int) – File byte pattern start of the pattern of interest.

Returns:

The format of this depends on the file version.

Return type:

footer

get_single_pattern_header(offset)[source]#

Return a single pattern header.

Parameters:

offset (int) – File byte pattern start of the pattern of interest.

Return type:
Returns:

• is_compressed – Whether the pattern is compressed.

• nrows – Number of signal (detector) rows.

• ncols – Number of signal (detector) columns.

• n_bytes – Number of pattern bytes.

get_version()[source]#

Return the .ebsp file version.

The first version of the .ebsp format did not store a version number. Subsequent versions store the version number as a negative number.

Return type:

version

guess_number_of_patterns(min_assumed_n_pixels=1600)[source]#

Guess the number of patterns in the file based upon an assumed lower bound for the number of pattern pixels and the file size.

Parameters:

min_assumed_n_pixels (int) – Assumed lower bound for the number of pattern pixels. Default is 1600 pixels.

Returns:

Guess of the number of EBSD patterns in the file.

Return type:

n_patterns

property n_patterns_present: int#

Number of patterns actually stored in the file.

Return type:

int

pattern_header_dtype = [('is_compressed', <class 'numpy.int32'>, (1,)), ('nrows', <class 'numpy.int32'>, (1,)), ('ncols', <class 'numpy.int32'>, (1,)), ('n_bytes', <class 'numpy.int32'>, (1,))]#
pattern_header_size = 16#
property pattern_is_present: ndarray#

Boolean array indicating whether a pattern listed in the file header is present in the file or not. If not, its pattern_starts entry is zero.

Return type:

ndarray

property pattern_order: ndarray#

Flattened index of each consecutive pattern in the file into the 2D navigation (map) shape. This usually varies within rows, but not across rows.

Return type:

ndarray

property pattern_starts_byte_position: int#

File byte position of file byte positions of patterns. For .ebsp file version 0, this is at the first byte, while for later versions, this is at the ninth byte, after the file version.

Return type:

int

kikuchipy.io.plugins.oxford_binary.file_reader(filename, lazy=False)[source]#

Read EBSD patterns from an Oxford Instruments’ binary .ebsp file.

Only uncompressed patterns can be read. If only non-indexed patterns are stored in the file, the navigation shape will be 1D.

Parameters:
• filename (str) – File path to .ebsp file.

• lazy (bool) – Read the data lazily without actually reading the data from disk until required. Default is False.

Returns:

Data, axes, metadata and original metadata.

Return type:

scan

Notes

Information about the .ebsp file format was provided by Oxford Instruments.

## pattern#

Single and chunk pattern processing used by signals.

 chunk Functions for operating on numpy.ndarray or dask.array.Array chunks of EBSD patterns. fft(pattern[, apodization_window, shift, ...]) Compute the discrete Fast Fourier Transform (FFT) of an EBSD pattern. fft_filter(pattern, transfer_function[, ...]) Filter an EBSD patterns in the frequency domain. Get the frequency vectors in a Fourier Transform spectrum. fft_spectrum(fft_pattern) Compute the FFT spectrum of a Fourier transformed EBSD pattern. get_dynamic_background(pattern[, ...]) Get the dynamic background in an EBSD pattern. get_image_quality(pattern[, normalize, ...]) Return the image quality of an EBSD pattern. ifft(fft_pattern[, shift, real_fft_only]) Compute the inverse Fast Fourier Transform (IFFT) of an FFT of an EBSD pattern. normalize_intensity(pattern[, num_std, ...]) Normalize image intensities to a mean of zero and a given standard deviation. remove_dynamic_background(pattern[, ...]) Remove the dynamic background in an EBSD pattern. rescale_intensity(pattern[, in_range, ...]) Rescale intensities in an EBSD pattern.

Functions operating on single EBSD patterns as ndarray.

Single and chunk pattern processing used by signals.

kikuchipy.pattern.fft(pattern, apodization_window=None, shift=False, real_fft_only=False, **kwargs)[source]#

Compute the discrete Fast Fourier Transform (FFT) of an EBSD pattern.

Very light wrapper around routines in scipy.fft. The routines are wrapped instead of used directly to accommodate easy setting of shift and real_fft_only.

Parameters:
Returns:

out – The result of the 2D FFT.

Return type:

numpy.ndarray

kikuchipy.pattern.fft_filter(pattern, transfer_function, apodization_window=None, shift=False)[source]#

Filter an EBSD patterns in the frequency domain.

Parameters:
Returns:

filtered_pattern – Filtered EBSD pattern.

Return type:

numpy.ndarray

kikuchipy.pattern.fft_frequency_vectors(shape)[source]#

Get the frequency vectors in a Fourier Transform spectrum.

Parameters:

shape (Tuple[int, int]) – Fourier transform shape.

Returns:

frequency_vectors – Frequency vectors.

Return type:

numpy.ndarray

kikuchipy.pattern.fft_spectrum(fft_pattern)[source]#

Compute the FFT spectrum of a Fourier transformed EBSD pattern.

Parameters:

fft_pattern (ndarray) – Fourier transformed EBSD pattern.

Returns:

fft_spectrum – 2D FFT spectrum of the EBSD pattern.

Return type:

numpy.ndarray

kikuchipy.pattern.get_dynamic_background(pattern, filter_domain='frequency', std=None, truncate=4.0)[source]#

Get the dynamic background in an EBSD pattern.

The background is obtained either in the frequency domain, by a low pass Fast Fourier Transform (FFT) Gaussian filter, or in the spatial domain by a Gaussian filter.

Data type is preserved.

Parameters:
Returns:

dynamic_bg – The dynamic background.

Return type:

numpy.ndarray

kikuchipy.pattern.get_image_quality(pattern, normalize=True, frequency_vectors=None, inertia_max=None)[source]#

Return the image quality of an EBSD pattern.

The image quality is calculated based on the procedure defined by Krieger Lassen [Lassen1994].

Parameters:
Returns:

image_quality – Image quality of the pattern.

Return type:

numpy.ndarray

kikuchipy.pattern.ifft(fft_pattern, shift=False, real_fft_only=False, **kwargs)[source]#

Compute the inverse Fast Fourier Transform (IFFT) of an FFT of an EBSD pattern.

Very light wrapper around routines in scipy.fft. The routines are wrapped instead of used directly to accommodate easy setting of shift and real_fft_only.

Parameters:
Returns:

pattern – Real part of the IFFT of the EBSD pattern.

Return type:

numpy.ndarray

kikuchipy.pattern.normalize_intensity(pattern, num_std=1, divide_by_square_root=False)[source]#

Normalize image intensities to a mean of zero and a given standard deviation.

Data type is preserved.

Parameters:
• pattern (ndarray) – EBSD pattern.

• num_std (int) – Number of standard deviations of the output intensities (default is 1).

• divide_by_square_root (bool) – Whether to divide output intensities by the square root of the image size (default is False).

Returns:

normalized_pattern – Normalized pattern.

Return type:

numpy.ndarray

Notes

Data type should always be changed to floating point, e.g. np.float32 with numpy.ndarray.astype(), before normalizing the intensities.

kikuchipy.pattern.remove_dynamic_background(pattern, operation='subtract', filter_domain='frequency', std=None, truncate=4.0, dtype_out=None)[source]#

Remove the dynamic background in an EBSD pattern.

The removal is performed by subtracting or dividing by a Gaussian blurred version of the pattern. The blurred version is obtained either in the frequency domain, by a low pass Fast Fourier Transform (FFT) Gaussian filter, or in the spatial domain by a Gaussian filter. Returned pattern intensities are rescaled to fill the input data type range.

Parameters:
Returns:

corrected_pattern – Pattern with the dynamic background removed.

Return type:

numpy.ndarray

kikuchipy.pattern.rescale_intensity(pattern, in_range=None, out_range=None, dtype_out=None)[source]#

Rescale intensities in an EBSD pattern.

Pattern max./min. intensity is determined from out_range or the data type range of numpy.dtype passed to dtype_out.

This method is based on skimage.exposure.rescale_intensity().

Parameters:
Returns:

rescaled_pattern – Rescaled pattern.

Return type:

numpy.ndarray

### chunk#

Functions for operating on ndarray or Array chunks of EBSD patterns.

 adaptive_histogram_equalization(patterns, ...) Local contrast enhancement of a chunk of EBSD patterns with adaptive histogram equalization. average_neighbour_patterns(patterns, ...[, ...]) Average a chunk of patterns with its neighbours within a window. fft_filter(patterns, filter_func, ...[, ...]) Filter a chunk of EBSD patterns in the frequency domain. get_dynamic_background(patterns, filter_func) Obtain the dynamic background in a chunk of EBSD patterns. get_image_quality(patterns[, ...]) [Deprecated] Compute the image quality in a chunk of EBSD patterns. normalize_intensity(patterns[, num_std, ...]) Normalize intensities in a chunk of EBSD patterns to a mean of zero with a given standard deviation. remove_dynamic_background(patterns, ...[, ...]) [Deprecated] Correct the dynamic background in a chunk of EBSD patterns. remove_static_background(patterns, ...[, ...]) [Deprecated] Remove the static background in a chunk of EBSD patterns. rescale_intensity(patterns[, in_range, ...]) Rescale pattern intensities in a chunk of EBSD patterns.

Functions for operating on numpy.ndarray or dask.array.Array chunks of EBSD patterns.

Warning

This module will be become private for internal use only in v0.7. If you need to process multiple EBSD patterns at once, please do this using EBSD.

kikuchipy.pattern.chunk.adaptive_histogram_equalization(patterns, kernel_size, clip_limit=0, nbins=128)[source]#

Local contrast enhancement of a chunk of EBSD patterns with adaptive histogram equalization.

This method makes use of skimage.exposure.equalize_adapthist().

Parameters:
Returns:

equalized_patterns – Patterns with enhanced contrast.

Return type:

numpy.ndarray

kikuchipy.pattern.chunk.average_neighbour_patterns(patterns, window_sums, window, dtype_out=None)[source]#

Average a chunk of patterns with its neighbours within a window.

The amount of averaging is specified by the window coefficients. All patterns are averaged with the same window. Map borders are extended with zeros. Resulting pattern intensities are rescaled to fill the input patterns’ data type range individually.

Parameters:
Returns:

averaged_patterns – Averaged patterns.

Return type:

numpy.ndarray

kikuchipy.pattern.chunk.fft_filter(patterns, filter_func, transfer_function, dtype_out=None, **kwargs)[source]#

Filter a chunk of EBSD patterns in the frequency domain.

Patterns are transformed via the Fast Fourier Transform (FFT) to the frequency domain, where their spectrum is multiplied by a filter transfer_function, and the filtered spectrum is subsequently transformed to the spatial domain via the inverse FFT (IFFT).

Filtered patterns are rescaled to the data type range of dtype_out.

Parameters:
Returns:

filtered_patterns – Filtered EBSD patterns.

Return type:

numpy.ndarray

kikuchipy.pattern.chunk.get_dynamic_background(patterns, filter_func, dtype_out=None, **kwargs)[source]#

Obtain the dynamic background in a chunk of EBSD patterns.

Parameters:
Returns:

background – Large scale variations in the input EBSD patterns.

Return type:

numpy.ndarray

kikuchipy.pattern.chunk.get_image_quality(patterns, frequency_vectors=None, inertia_max=None, normalize=True)[source]#

[Deprecated] Compute the image quality in a chunk of EBSD patterns.

The image quality is calculated based on the procedure defined by Krieger Lassen [Lassen1994].

Parameters:
Returns:

image_quality_chunk – Image quality of patterns.

Return type:

numpy.ndarray

Notes

Deprecated since version 0.6: Function get_image_quality() is deprecated and will be removed in version 0.7. Use kikuchipy.signals.EBSD.get_image_quality() instead.

kikuchipy.pattern.chunk.normalize_intensity(patterns, num_std=1, divide_by_square_root=False, dtype_out=None)[source]#

Normalize intensities in a chunk of EBSD patterns to a mean of zero with a given standard deviation.

Parameters:
Returns:

normalized_patterns – Normalized patterns.

Return type:

numpy.ndarray

Notes

Data type should always be changed to floating point, e.g. np.float32 with numpy.ndarray.astype(), before normalizing the intensities.

kikuchipy.pattern.chunk.remove_dynamic_background(patterns, filter_func, operation_func, out_range=None, dtype_out=None, **kwargs)[source]#

[Deprecated] Correct the dynamic background in a chunk of EBSD patterns.

The correction is performed by subtracting or dividing by a Gaussian blurred version of each pattern. Returned pattern intensities are rescaled to fill the input data type range.

Parameters:
Returns:

corrected_patterns – Dynamic background corrected patterns.

Return type:

numpy.ndarray

See also

kikuchipy.signals.ebsd.EBSD.remove_dynamic_background, kikuchipy.util.pattern.remove_dynamic_background

Notes

Deprecated since version 0.6: Function remove_dynamic_background() is deprecated and will be removed in version 0.7. Use kikuchipy.signals.EBSD.remove_dynamic_background() instead.

kikuchipy.pattern.chunk.remove_static_background(patterns, static_bg, operation_func, scale_bg=False, in_range=None, out_range=None, dtype_out=None)[source]#

[Deprecated] Remove the static background in a chunk of EBSD patterns.

Removal is performed by subtracting or dividing by a static background pattern. Resulting pattern intensities are rescaled keeping relative intensities or not and stretched to fill the available grey levels in the patterns’ data type range.

Parameters:
Returns:

corrected_patterns – Patterns with the static background removed.

Return type:

numpy.ndarray

Notes

Deprecated since version 0.6: Function remove_static_background() is deprecated and will be removed in version 0.7. Use kikuchipy.signals.EBSD.remove_static_background() instead.

kikuchipy.pattern.chunk.rescale_intensity(patterns, in_range=None, out_range=None, dtype_out=None, percentiles=None)[source]#

Rescale pattern intensities in a chunk of EBSD patterns.

Chunk max./min. intensity is determined from out_range or the data type range of numpy.dtype passed to dtype_out.

Parameters:
Returns:

rescaled_patterns – Rescaled patterns.

Return type:

numpy.ndarray

## projections#

Various projections and transformations relevant to EBSD.

 ebsd_projections Rotations to align the EBSD detector with the tilted sample. Hessian normal form of a plane given by polar coordinates. Spherical projection of a cartesian vector according to the ISO 31-11 standard [SphericalWolfram].

### ebsd_projections#

 detector2direct_lattice(sample_tilt, ...) Rotation U_K from detector frame D to direct crystal lattice frame K. detector2reciprocal_lattice(sample_tilt, ...) Rotation U_Kstar from detector to reciprocal crystal lattice frame Kstar. detector2sample(sample_tilt, detector_tilt) Rotation U_S to align detector frame D with sample frame S.

Rotations to align the EBSD detector with the tilted sample. Notation from [BJG+16].

kikuchipy.projections.ebsd_projections.detector2direct_lattice(sample_tilt, detector_tilt, lattice, rotation)[source]#

Rotation U_K from detector frame D to direct crystal lattice frame K.

Parameters:
Return type:

np.ndarray

kikuchipy.projections.ebsd_projections.detector2reciprocal_lattice(sample_tilt, detector_tilt, lattice, rotation)[source]#

Rotation U_Kstar from detector to reciprocal crystal lattice frame Kstar.

Parameters:
Return type:

np.ndarray

kikuchipy.projections.ebsd_projections.detector2sample(sample_tilt, detector_tilt, convention=None)[source]#

Rotation U_S to align detector frame D with sample frame S.

Parameters:
Return type:

Rotation

### HesseNormalForm#

Hessian normal form of a plane given by polar coordinates. (Not currently used anywhere.)

class kikuchipy.projections.hesse_normal_form.HesseNormalForm[source]#

Bases: object

Hessian normal form of a plane given by polar coordinates.

static project_cartesian(cartesian, radius=10)[source]#

Return the Hesse normal form of plane(s) given by cartesian coordinates.

Parameters:
Returns:

Hesse normal form coordinates distance and angle.

Return type:

hesse

static project_polar(polar, radius=10)[source]#

Return the Hesse normal form of plane(s) given by spherical coordinates.

Parameters:
Returns:

Hesse normal form coordinates distance and angle.

Return type:

hesse

### SphericalProjection#

Spherical projection of a cartesian vector according to the ISO 31-11 standard [SphericalWolfram].

class kikuchipy.projections.spherical_projection.SphericalProjection[source]#

Bases: object

Spherical projection of a cartesian vector according to the ISO 31-11 standard [SphericalWolfram].

References

[SphericalWolfram] (1,2,3,4)

Weisstein, Eric W. “Spherical Coordinates,” From MathWorld–A Wolfram Web Resource, url: https://mathworld.wolfram.com/SphericalCoordinates.html

spherical_region = SphericalRegion (1,) [[0 0 1]]#
classmethod vector2xy(v)[source]#

Convert from cartesian to spherical coordinates according to the ISO 31-11 standard [SphericalWolfram].

Parameters:

v (Union[Vector3d, ndarray]) – 3D vector(s) on the form [[x0, y0, z0], [x1, y1, z1], …].

Returns:

Spherical coordinates theta, phi and r on the form [[theta1, phi1, r1], [theta2, phi2, r2], …].

Return type:

spherical_coordinates

Examples

>>> import numpy as np
>>> from kikuchipy.projections.spherical_projection import (
...     SphericalProjection
... )
>>> v = np.random.random_sample(30).reshape((10, 3))
>>> theta, phi, r = SphericalProjection.vector2xy(v).T
>>> np.allclose(np.arccos(v[:, 2] / r), theta)
True
>>> np.allclose(np.arctan2(v[:, 1], v[:, 0]), phi)
True


## signals#

Experimental and simulated diffraction patterns and virtual backscatter electron images.

 EBSD(*args, **kwargs) Scan of Electron Backscatter Diffraction (EBSD) patterns. EBSDMasterPattern(*args, **kwargs) Simulated Electron Backscatter Diffraction (EBSD) master pattern. VirtualBSEImage(*args, **kwargs) Virtual backscatter electron (BSE) image(s). util Signal utilities for handling signal metadata and attributes, output from signal methods, and for controlling chunking of lazy signal data in Array.

### EBSD#

All methods listed here are also available to LazyEBSD instances.

See Signal2D for methods inherited from HyperSpy.

 Enhance the local contrast in an EBSD scan inplace using adaptive histogram equalization. average_neighbour_patterns([window, ...]) Average patterns inplace with its neighbours within a window. dictionary_indexing(dictionary[, metric, ...]) Match each experimental pattern to a dictionary of simulated patterns of known orientations to index the them . fft_filter(transfer_function, function_domain) Filter an EBSD scan inplace in the frequency domain. Get a map of the average dot product between patterns and their neighbours within an averaging window. get_decomposition_model([components, dtype_out]) Get the model signal generated with the selected number of principal components from a decomposition. get_dynamic_background([filter_domain, std, ...]) Get the dynamic background per EBSD pattern in a scan. get_image_quality([normalize]) Compute the image quality map of patterns in an EBSD scan. get_neighbour_dot_product_matrices([window, ...]) Get an array with dot products of a pattern and its neighbours within a window. get_virtual_bse_intensity(roi[, out_signal_axes]) Get a virtual backscatter electron (VBSE) image formed from intensities within a region of interest (ROI) on the detector. normalize_intensity([num_std, ...]) Normalize image intensities in inplace to a mean of zero with a given standard deviation. plot_virtual_bse_intensity(roi[, ...]) Plot an interactive virtual backscatter electron (VBSE) image formed from intensities within a specified and adjustable region of interest (ROI) on the detector. refine_orientation(xmap, detector, ...[, ...]) Refine orientations by searching orientation space around the best indexed solution using fixed projection centers. Refine orientations and projection centers simultaneously by searching the orientation and PC parameter space. refine_projection_center(xmap, detector, ...) Refine projection centers by searching the parameter space using fixed orientations. remove_dynamic_background([operation, ...]) Remove the dynamic background in an EBSD scan inplace. remove_static_background([operation, ...]) Remove the static background inplace. rescale_intensity([relative, in_range, ...]) Rescale image intensities inplace. save([filename, overwrite, extension]) Write the signal to file in the specified format. Set detector pixel size in microns. set_experimental_parameters([detector, ...]) [Deprecated] Set experimental parameters in signal metadata. set_phase_parameters([number, ...]) [Deprecated] Set parameters for one phase in signal metadata. set_scan_calibration([step_x, step_y]) Set the step size in microns.
class kikuchipy.signals.EBSD(*args, **kwargs)[source]#

Bases: CommonImage, Signal2D

Scan of Electron Backscatter Diffraction (EBSD) patterns.

This class extends HyperSpy’s Signal2D class for EBSD patterns, with common intensity processing methods and some analysis methods.

Methods inherited from HyperSpy can be found in the HyperSpy user guide.

See the docstring of hyperspy.signal.BaseSignal for a list of attributes in addition to the ones listed below.

adaptive_histogram_equalization(kernel_size=None, clip_limit=0, nbins=128)[source]#

Enhance the local contrast in an EBSD scan inplace using adaptive histogram equalization.

This method uses skimage.exposure.equalize_adapthist().

Parameters:

Examples

To best understand how adaptive histogram equalization works, we plot the histogram of the same image before and after equalization:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s2 = s.inav[0, 0].deepcopy()
>>> s2.adaptive_histogram_equalization()
>>> hist, _ = np.histogram(
...     s.inav[0, 0].data, bins=255, range=(0, 255)
... )
>>> hist2, _ = np.histogram(s2.data, bins=255, range=(0, 255))
>>> fig, ax = plt.subplots(nrows=2, ncols=2)
>>> _ = ax[0, 0].imshow(s.inav[0, 0].data)
>>> _ = ax[1, 0].plot(hist)
>>> _ = ax[0, 1].imshow(s2.data)
>>> _ = ax[1, 1].plot(hist2)


Notes

• It is recommended to perform adaptive histogram equalization only after static and dynamic background corrections, otherwise some unwanted darkening towards the edges might occur.

• The default window size might not fit all pattern sizes, so it may be necessary to search for the optimal window size.

as_lazy(*args, **kwargs)[source]#

Create a copy of the given Signal as a LazySignal.

Parameters:
• copy_variance (bool) – Whether or not to copy the variance from the original Signal to the new lazy version. Default is True.

• copy_navigator (bool) – Whether or not to copy the navigator from the original Signal to the new lazy version. Default is True.

• copy_learning_results (bool) – Whether to copy the learning_results from the original signal to the new lazy version. Default is True.

Returns:

res – The same signal, converted to be lazy

Return type:

LazySignal

average_neighbour_patterns(window='circular', window_shape=(3, 3), **kwargs)[source]#

Average patterns inplace with its neighbours within a window.

The amount of averaging is specified by the window coefficients. All patterns are averaged with the same window. Map borders are extended with zeros. Resulting pattern intensities are rescaled to fill the input patterns’ data type range individually.

Averaging is accomplished by correlating the window with the extended array of patterns using scipy.ndimage.correlate().

Parameters:
deepcopy()[source]#

Return a “deep copy” of this Signal using the standard library’s deepcopy() function. Note: this means the underlying data structure will be duplicated in memory.

property detector: EBSDDetector#

An EBSDDetector describing the EBSD detector dimensions, the projection/pattern centre, and the detector-sample geometry.

Return type:

EBSDDetector

dictionary_indexing(dictionary, metric='ncc', keep_n=20, n_per_iteration=None, signal_mask=None, rechunk=False, dtype=None)[source]#

Match each experimental pattern to a dictionary of simulated patterns of known orientations to index the them .

A suitable similarity metric, the normalized cross-correlation (NormalizedCrossCorrelationMetric), is used by default, but a valid user-defined similarity metric may be used instead. The metric must be a class implementing the SimilarityMetric abstract class methods. The normalized dot product (NormalizedDotProductMetric) is available as well.

A CrystalMap with “scores” and “simulation_indices” as properties is returned.

Parameters:
• dictionary (EBSD) – EBSD signal with dictionary patterns. The signal must have a 1D navigation axis, an xmap property with crystal orientations set, and equal detector shape.

• metric (Union[SimilarityMetric, str]) – Similarity metric, by default “ncc” (normalized cross-correlation). “ndp” (normalized dot product) is also available.

• keep_n (int) – Number of best matches to keep, by default 20 or the number of dictionary patterns if fewer than 20 are available.

• n_per_iteration (Optional[int]) – Number of dictionary patterns to compare to all experimental patterns in each indexing iteration. If not given, and the dictionary is a LazyEBSD signal, it is equal to the chunk size of the first pattern array axis, while if if is an EBSD signal, it is set equal to the number of dictionary patterns, yielding only one iteration. This parameter can be increased to use less memory during indexing, but this will increase the computation time.

• signal_mask (Optional[ndarray]) – A boolean mask equal to the experimental patterns’ detector shape (n rows, n columns), where only pixels equal to False are matched. If not given, all pixels are used.

• rechunk (bool) – Whether metric is allowed to rechunk experimental and dictionary patterns before matching. Default is False. If a custom metric is passed, whatever metric.rechunk is set to will be used. Rechunking usually makes indexing faster, but uses more memory.

• dtype (Union[None, dtype, type]) – Which data type metric shall cast the patterns to before matching. If not given, float32 will be used unless a custom metric is passed and it has set the dtype attribute, which will then be used instead. float32 and float64 is allowed for the available “ncc” and “ndp” metrics.

Returns:

xmap – A crystal map with keep_n rotations per point with the sorted best matching orientations in the dictionary. The corresponding best scores and indices into the dictionary are stored in the xmap.prop dictionary as “scores” and “simulation_indices”.

Return type:

CrystalMap

Notes

Merging of single phase crystal maps into one multi phase map and calculations of an orientation similarity map can be done afterwards with merge_crystal_maps() and orientation_similarity_map(), respectively.

Changed in version 0.5: Only one dictionary can be passed, the n_per_iteration parameter replaced n_slices, and the return_merged_crystal_map and get_orientation_similarity_map parameters were removed.

New in version 0.5: The signal_mask, rechunk, and dtype parameters.

fft_filter(transfer_function, function_domain, shift=False)[source]#

Filter an EBSD scan inplace in the frequency domain.

Patterns are transformed via the Fast Fourier Transform (FFT) to the frequency domain, where their spectrum is multiplied by the transfer_function, and the filtered spectrum is subsequently transformed to the spatial domain via the inverse FFT (IFFT). Filtered patterns are rescaled to input data type range.

Note that if function_domain is “spatial”, only real valued FFT and IFFT is used.

Parameters:
• transfer_function (Union[ndarray, Window]) – Filter to apply to patterns. This can either be a transfer function in the frequency domain of pattern shape or a kernel in the spatial domain. What is passed is determined from function_domain.

• function_domain (str) – Options are “frequency” and “spatial”, indicating, respectively, whether the filter function passed to filter_function is a transfer function in the frequency domain or a kernel in the spatial domain.

• shift (bool) – Whether to shift the zero-frequency component to the centre. Default is False. This is only used when function_domain=”frequency”.

Examples

Applying a Gaussian low pass filter with a cutoff frequency of 20 to an EBSD object s:

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> pattern_shape = s.axes_manager.signal_shape[::-1]
>>> w = kp.filters.Window(
...     "lowpass", cutoff=20, shape=pattern_shape
... )
>>> s.fft_filter(
...     transfer_function=w,
...     function_domain="frequency",
...     shift=True,
... )

get_average_neighbour_dot_product_map(window=None, zero_mean=True, normalize=True, dtype_out=<class 'numpy.float32'>, dp_matrices=None)[source]#

Get a map of the average dot product between patterns and their neighbours within an averaging window.

Parameters:
• window (Optional[Window]) – Window with integer coefficients defining the neighbours to calculate the average with. If None (default), the four nearest neighbours are used. Must have the same number of dimensions as signal navigation dimensions.

• zero_mean (bool) – Whether to subtract the mean of each pattern individually to center the intensities about zero before calculating the dot products. Default is True.

• normalize (bool) – Whether to normalize the pattern intensities to a standard deviation of 1 before calculating the dot products. This operation is performed after centering the intensities if zero_mean is True. Default is True.

• dtype_out (dtype) – Data type of the output map. Default is numpy.float32.

• dp_matrices (Optional[ndarray]) – Optional pre-calculated dot product matrices, by default None. If an array is passed, the average dot product map is calculated from this array. The dp_matrices array can be obtained from get_neighbour_dot_product_matrices(). It’s shape must correspond to the signal’s navigation shape and the window’s shape.

Return type:
get_decomposition_model(components=None, dtype_out=<class 'numpy.float32'>)[source]#

Get the model signal generated with the selected number of principal components from a decomposition.

Calls HyperSpy’s hyperspy.learn.mva.MVA.get_decomposition_model(). Learning results are preconditioned before this call, doing the following: (1) set numpy.dtype to desired dtype_out, (2) remove unwanted components, and (3) rechunk, if dask.array.Array, to suitable chunks.

Parameters:
Returns:

s_model

Return type:
get_dynamic_background(filter_domain='frequency', std=None, truncate=4.0, dtype_out=None, **kwargs)[source]#

Get the dynamic background per EBSD pattern in a scan.

Parameters:
Returns:

background_signal – Signal with the large scale variations across the detector.

Return type:
get_image_quality(normalize=True)[source]#

Compute the image quality map of patterns in an EBSD scan.

The image quality is calculated based on the procedure defined by Krieger Lassen [Lassen1994].

Parameters:

normalize (bool) – Whether to normalize patterns to a mean of zero and standard deviation of 1 before calculating the image quality. Default is True.

Returns:

Image quality map of same shape as navigation axes. This is a Dask array if the signal is lazy.

Return type:

image_quality_map

References

[Lassen1994] (1,2,3)
1. Lassen, “Automated Determination of Crystal Orientations from Electron Backscattering Patterns,” Institute of Mathematical Modelling, (1994).

Examples

>>> import matplotlib.pyplot as plt
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> iq = s.get_image_quality()
>>> plt.imshow(iq)

get_neighbour_dot_product_matrices(window=None, zero_mean=True, normalize=True, dtype_out=<class 'numpy.float32'>)[source]#

Get an array with dot products of a pattern and its neighbours within a window.

Parameters:
• window (Optional[Window]) – Window with integer coefficients defining the neighbours to calculate the dot products with. If None (default), the four nearest neighbours are used. Must have the same number of dimensions as signal navigation dimensions.

• zero_mean (bool) – Whether to subtract the mean of each pattern individually to center the intensities about zero before calculating the dot products. Default is True.

• normalize (bool) – Whether to normalize the pattern intensities to a standard deviation of 1 before calculating the dot products. This operation is performed after centering the intensities if zero_mean is True. Default is True.

• dtype_out (dtype) – Data type of the output map. Default is numpy.float32.

Return type:
get_virtual_bse_intensity(roi, out_signal_axes=None)[source]#

Get a virtual backscatter electron (VBSE) image formed from intensities within a region of interest (ROI) on the detector.

Adapted from pyxem.signals.common_diffraction.CommonDiffraction.get_integrated_intensity().

Parameters:
Returns:

virtual_image – VBSE image formed from detector intensities within an ROI on the detector.

Return type:

kikuchipy.signals.VirtualBSEImage

Examples

>>> import hyperspy.api as hs
>>> import kikuchipy as kp
>>> rect_roi = hs.roi.RectangularROI(
...     left=0, right=5, top=0, bottom=5
... )
>>> s = kp.data.nickel_ebsd_small()
>>> vbse_image = s.get_virtual_bse_intensity(rect_roi)

normalize_intensity(num_std=1, divide_by_square_root=False, dtype_out=None)[source]#

Normalize image intensities in inplace to a mean of zero with a given standard deviation.

Parameters:
• num_std (int) – Number of standard deviations of the output intensities. Default is 1.

• divide_by_square_root (bool) – Whether to divide output intensities by the square root of the signal dimension size. Default is False.

• dtype_out (Optional[dtype]) – Data type of normalized images. If None (default), the input images’ data type is used.

Notes

Data type should always be changed to floating point, e.g. np.float32 with change_dtype(), before normalizing the intensities.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> np.mean(s.data)
146.0670987654321
>>> s.normalize_intensity(dtype_out=np.float32)
>>> np.mean(s.data)
2.6373216e-08


Notes

Rescaling RGB images is not possible. Use RGB channel normalization when creating the image instead.

plot_virtual_bse_intensity(roi, out_signal_axes=None, **kwargs)[source]#

Plot an interactive virtual backscatter electron (VBSE) image formed from intensities within a specified and adjustable region of interest (ROI) on the detector.

Adapted from pyxem.signals.common_diffraction.CommonDiffraction.plot_integrated_intensity().

Parameters:

Examples

>>> import hyperspy.api as hs
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> rect_roi = hs.roi.RectangularROI(
...     left=0, right=5, top=0, bottom=5
... )
>>> s.plot_virtual_bse_intensity(rect_roi)

refine_orientation(xmap, detector, master_pattern, energy, mask=None, method='minimize', method_kwargs=None, trust_region=None, compute=True, rechunk=True, chunk_kwargs=None)[source]#

Refine orientations by searching orientation space around the best indexed solution using fixed projection centers.

Refinement attempts to optimize (maximize) the similarity between patterns in this signal and simulated patterns projected from a master pattern. The only supported similarity metric is the normalized cross-correlation (NCC). The orientation, represented by three Euler angles ($$\phi_1$$, $$\Phi$$, $$\phi_2$$), is changed during projection, while the sample-detector geometry, represented by the three projection center (PC) parameters (PCx, PCy, PCz), are fixed.

A subset of the optimization methods in SciPy are available:
Parameters:
• xmap (CrystalMap) – Single phase crystal map with at least one orientation per point. The orientations are assumed to be relative to the EDAX TSL sample reference frame RD-TD-ND.

• detector (EBSDDetector) – Detector describing the detector-sample geometry with either one PC to be used for all map points or one for each point.

• master_pattern (EBSDMasterPattern) – Master pattern in the square Lambert projection of the same phase as the one in the crystal map.

• energy (Union[int, float]) – Accelerating voltage of the electron beam in kV specifying which master pattern energy to use during projection of simulated patterns.

• mask (Optional[ndarray]) – Boolean mask of signal shape to be applied to the simulated pattern before comparison. Pixels set to True are masked away. If not given, all pixels are matched.

• method (str, optional) – Name of the scipy.optimize optimization method, among “minimize”, “differential_evolution”, “dual_annealing”, “basinhopping”, and “shgo”. Default is “minimize”, which by default performs local optimization with the Nelder-Mead method unless another “minimize” method is passed to method_kwargs.

• method_kwargs (Optional[dict]) – Keyword arguments passed to the scipy.optimize method. For example, to perform refinement with the modified Powell algorithm, pass method=”minimize” and method_kwargs=dict(method=”Powell”).

• trust_region (Optional[list]) – List of +/- angular deviation in degrees as bound constraints on the three Euler angles. If not given and method requires bounds, they are set to [1, 1, 1]. If given, method is assumed to support bounds and they are passed to method.

• compute (bool) – Whether to refine now (True) or later (False). Default is True. See compute() for more details.

• rechunk (bool) – If True (default), rechunk the dask array with patterns used in refinement (not the signal data inplace) if it is returned from get_dask_array() in a single chunk. This ensures small data sets are rechunked so as to utilize multiple CPUs.

• chunk_kwargs (Optional[dict]) – Keyword arguments passed to get_chunking() if rechunk is True and the dask array with patterns used in refinement is returned from get_dask_array() in a single chunk.

Returns:

Crystal map with refined orientations and similarity metrics in a “scores” property if compute is True. If compute is False, a dask array of navigation shape + (4,) is returned, to be computed later. See compute_refine_orientation_results(). Each navigation point has the optimized score and the three Euler angles in radians in element 0, 1, 2, and 3, respectively.

Return type:
refine_orientation_projection_center(xmap, detector, master_pattern, energy, mask=None, method='minimize', method_kwargs=None, trust_region=None, compute=True, rechunk=True, chunk_kwargs=None)[source]#

Refine orientations and projection centers simultaneously by searching the orientation and PC parameter space.

Refinement attempts to optimize (maximize) the similarity between patterns in this signal and simulated patterns projected from a master pattern. The only supported similarity metric is the normalized cross-correlation (NCC). The orientation, represented by three Euler angles ($$\phi_1$$, $$\Phi$$, $$\phi_2$$), and the sample-detector geometry, represented by the three projection center (PC) parameters (PCx, PCy, PCz), are changed during projection.

A subset of the optimization methods in SciPy are available:
Parameters:
• xmap (CrystalMap) – Single phase crystal map with at least one orientation per point. The orientations are assumed to be relative to the EDAX TSL sample reference frame RD-TD-ND.

• detector (EBSDDetector) – Detector describing the detector-sample geometry with either one PC to be used for all map points or one for each point.

• master_pattern (EBSDMasterPattern) – Master pattern in the square Lambert projection of the same phase as the one in the crystal map.

• energy (Union[int, float]) – Accelerating voltage of the electron beam in kV specifying which master pattern energy to use during projection of simulated patterns.

• mask (Optional[ndarray]) – Boolean mask of signal shape to be applied to the simulated pattern before comparison. Pixels set to True are masked away. If not given, all pixels are matched.

• method (str, optional) – Name of the scipy.optimize optimization method, among “minimize”, “differential_evolution”, “dual_annealing”, “basinhopping”, and “shgo”. Default is “minimize”, which by default performs local optimization with the Nelder-Mead method unless another “minimize” method is passed to method_kwargs.

• method_kwargs (Optional[dict]) – Keyword arguments passed to the scipy.optimize method. For example, to perform refinement with the modified Powell algorithm, pass method=”minimize” and method_kwargs=dict(method=”Powell”).

• trust_region (Optional[list]) – List of +/- angular deviations in degrees as bound constraints on the three Euler angles and +/- percentage deviations as bound constraints on the PC parameters in the Bruker convention. The latter parameter range is [0, 1]. If not given and method requires bounds, they are set to [1, 1, 1, 0.05, 0.05, 0.05]. If given, method is assumed to support bounds and they are passed to method.

• compute (bool) – Whether to refine now (True) or later (False). Default is True. See compute() for more details.

• rechunk (bool) – If True (default), rechunk the dask array with patterns used in refinement (not the signal data inplace) if it is returned from get_dask_array() in a single chunk. This ensures small data sets are rechunked so as to utilize multiple CPUs.

• chunk_kwargs (Optional[dict]) – Keyword arguments passed to get_chunking() if rechunk is True and the dask array with patterns used in refinement is returned from get_dask_array() in a single chunk.

Returns:

Crystal map with refined orientations and a new EBSD detector instance with the refined PCs, if compute is True. If compute is False, a dask array of navigation shape + (7,) is returned, to be computed later. See compute_refine_orientation_projection_center_results(). Each navigation point has the optimized score, the three Euler angles in radians, and the three PC parameters in the Bruker convention in element 0, 1, 2, 3, 4, 5, and 6, respectively.

Return type:

Notes

The method attempts to refine the orientations and projection center at the same time for each map point. The optimization landscape is sloppy [PLS20], where the orientation and PC can make up for each other. Thus, it is possible that the set of parameters that yield the highest similarity is incorrect. It is left to the user to ensure that the output is reasonable.

refine_projection_center(xmap, detector, master_pattern, energy, mask=None, method='minimize', method_kwargs=None, trust_region=None, compute=True, rechunk=True, chunk_kwargs=None)[source]#

Refine projection centers by searching the parameter space using fixed orientations.

Refinement attempts to optimize (maximize) the similarity between patterns in this signal and simulated patterns projected from a master pattern. The only supported similarity metric is the normalized cross-correlation (NCC). The sample-detector geometry, represented by the three projection center (PC) parameters (PCx, PCy, PCz), is changed during projection, while the orientations are fixed.

A subset of the optimization methods in SciPy are available:
Parameters:
• xmap (CrystalMap) – Single phase crystal map with at least one orientation per point. The orientations are assumed to be relative to the EDAX TSL sample reference frame RD-TD-ND.

• detector (EBSDDetector) – Detector describing the detector-sample geometry with either one PC to be used for all map points or one for each point.

• master_pattern (EBSDMasterPattern) – Master pattern in the square Lambert projection of the same phase as the one in the crystal map.

• energy (Union[int, float]) – Accelerating voltage of the electron beam in kV specifying which master pattern energy to use during projection of simulated patterns.

• mask (Optional[ndarray]) – Boolean mask of signal shape to be applied to the simulated pattern before comparison. Pixels set to True are masked away. If not given, all pixels are matched.

• method (str, optional) – Name of the scipy.optimize optimization method, among “minimize”, “differential_evolution”, “dual_annealing”, “basinhopping”, and “shgo”. Default is “minimize”, which by default performs local optimization with the Nelder-Mead method unless another “minimize” method is passed to method_kwargs.

• method_kwargs (Optional[dict]) – Keyword arguments passed to the scipy.optimize method. For example, to perform refinement with the modified Powell algorithm, pass method=”minimize” and method_kwargs=dict(method=”Powell”).

• trust_region (Optional[list]) – List of +/- percentage deviations as bound constraints on the PC parameters in the Bruker convention. The parameter range is [0, 1]. If not given and method requires bounds, they are set to [0.05, 0.05, 0.05]. If given, method is assumed to support bounds and they are passed to method.

• compute (bool) – Whether to refine now (True) or later (False). Default is True. See compute() for more details.

• rechunk (bool) – If True (default), rechunk the dask array with patterns used in refinement (not the signal data inplace) if it is returned from get_dask_array() in a single chunk. This ensures small data sets are rechunked so as to utilize multiple CPUs.

• chunk_kwargs (Optional[dict]) – Keyword arguments passed to get_chunking() if rechunk is True and the dask array with patterns used in refinement is returned from get_dask_array() in a single chunk.

Returns:

New similarity metrics and a new EBSD detector instance with the refined PCs if compute is True. If compute is False, a dask array of navigation shape + (4,) is returned, to be computed later. See compute_refine_projection_center_results(). Each navigation point has the optimized score and the three PC parameters in the Bruker convention in element 0, 1, 2, and 3, respectively.

Return type:
remove_dynamic_background(operation='subtract', filter_domain='frequency', std=None, truncate=4.0, **kwargs)[source]#

Remove the dynamic background in an EBSD scan inplace.

The removal is performed by subtracting or dividing by a Gaussian blurred version of each pattern. Resulting pattern intensities are rescaled to fill the input patterns’ data type range individually.

Parameters:

Examples

Traditional background correction includes static and dynamic corrections:

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s.remove_static_background()
>>> s.remove_dynamic_background(operation="divide", std=5)

remove_static_background(operation='subtract', relative=False, static_bg=None, scale_bg=False)[source]#

Remove the static background inplace.

The removal is performed by subtracting or dividing by a static background pattern. Resulting pattern intensities are rescaled keeping relative intensities or not and stretched to fill the available grey levels in the patterns’ data type range.

Parameters:
• operation (str) – Whether to "subtract" (default) or "divide" by the static background pattern.

• relative (bool) –

Keep relative intensities between patterns. Default is False.

Deprecated since version 0.6: This parameter will be removed in version 0.7 due to the implementation not working well for large datasets. It was originally supported so that a virtual backscatter electron (VBSE) image with meaningful contrast could be navigated after static background removal. For an EBSD signal s, this image can be easily obtained with s_mean = s.mean(s.axes_manager.signal_indices_in_array).

• static_bg (Union[None, ndarray, Array]) – Static background pattern. If not given, the background is obtained from the EBSD.static_background property.

• scale_bg (bool) – Whether to scale the static background pattern to each individual pattern’s data range before removal. Default is False.

Examples

It is assumed that a static background pattern of the same shape and data type (e.g. 8-bit unsigned integer, uint8) as the patterns is available in signal metadata:

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s.static_background
array([[84, 87, 90, ..., 27, 29, 30],
[87, 90, 93, ..., 27, 28, 30],
[92, 94, 97, ..., 39, 28, 29],
...,
[80, 82, 84, ..., 36, 30, 26],
[79, 80, 82, ..., 28, 26, 26],
[76, 78, 80, ..., 26, 26, 25]], dtype=uint8)


The static background can be removed by subtracting or dividing this background from each pattern:

>>> s.remove_static_background(operation="divide")


If the static_background property is None, this must be passed in the static_bg parameter as a numpy or dask array.

rescale_intensity(relative=False, in_range=None, out_range=None, dtype_out=None, percentiles=None)[source]#

Rescale image intensities inplace.

Output min./max. intensity is determined from out_range or the data type range of the numpy.dtype passed to dtype_out if out_range is None.

This method is based on skimage.exposure.rescale_intensity().

Parameters:

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()


Image intensities are stretched to fill the available grey levels in the input images’ data type range or any numpy.dtype range passed to dtype_out, either keeping relative intensities between images or not:

>>> print(
...     s.data.dtype, s.data.min(), s.data.max(),
...     s.inav[0, 0].data.min(), s.inav[0, 0].data.max()
... )
uint8 23 246 26 245
>>> s2 = s.deepcopy()
>>> s.rescale_intensity(dtype_out=np.uint16)
>>> print(
...     s.data.dtype, s.data.min(), s.data.max(),
...     s.inav[0, 0].data.min(), s.inav[0, 0].data.max()
... )
uint16 0 65535 0 65535
>>> s2.rescale_intensity(relative=True)
>>> print(
...     s2.data.dtype, s2.data.min(), s2.data.max(),
...     s2.inav[0, 0].data.min(), s2.inav[0, 0].data.max()
... )
uint8 0 255 3 253


Contrast stretching can be performed by passing percentiles:

>>> s.rescale_intensity(percentiles=(1, 99))


Here, the darkest and brightest pixels within the 1% percentile are set to the ends of the data type range, e.g. 0 and 255 respectively for images of uint8 data type.

Notes

Rescaling RGB images is not possible. Use RGB channel normalization when creating the image instead.

save(filename=None, overwrite=None, extension=None, **kwargs)[source]#

Write the signal to file in the specified format.

The function gets the format from the extension: h5, hdf5 or h5ebsd for kikuchipy’s specification of the the h5ebsd format, dat for the NORDIF binary format or hspy for HyperSpy’s HDF5 specification. If no extension is provided the signal is written to a file in kikuchipy’s h5ebsd format. Each format accepts a different set of parameters.

For details see the specific format documentation under “See Also” below.

This method is a modified version of HyperSpy’s function hyperspy.signal.BaseSignal.save().

Parameters:
• filename (Optional[str]) – If None (default) and tmp_parameters.filename and tmp_parameters.folder in signal metadata are defined, the filename and path will be taken from there. A valid extension can be provided e.g. “data.h5”, see extension.

• overwrite (Optional[bool]) – If None and the file exists, it will query the user. If True (False) it (does not) overwrite the file if it exists.

• extension (Optional[str]) – Extension of the file that defines the file format. Options are “h5”/”hdf5”/”h5ebsd”/”dat”/”hspy”. “h5”/”hdf5”/”h5ebsd” are equivalent. If None, the extension is determined from the following list in this order: i) the filename, ii) tmp_parameters.extension or iii) “h5” (kikuchipy’s h5ebsd format).

• **kwargs – Keyword arguments passed to writer.

set_detector_calibration(delta)[source]#

Set detector pixel size in microns. The offset is set to the the detector centre.

Parameters:

delta (Union[int, float]) – Detector pixel size in microns.

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s.axes_manager['dx'].scale  # Default value
1.0
>>> s.set_detector_calibration(delta=70.)
>>> s.axes_manager['dx'].scale
70.0

set_experimental_parameters(detector=None, azimuth_angle=None, elevation_angle=None, sample_tilt=None, working_distance=None, binning=None, exposure_time=None, grid_type=None, gain=None, frame_number=None, frame_rate=None, scan_time=None, beam_energy=None, xpc=None, ypc=None, zpc=None, static_background=None, manufacturer=None, version=None, microscope=None, magnification=None)[source]#

[Deprecated] Set experimental parameters in signal metadata.

Parameters:
• azimuth_angle (float, optional) – Azimuth angle of the detector in degrees. If the azimuth is zero, the detector is perpendicular to the tilt axis.

• beam_energy (float, optional) – Energy of the electron beam in kV.

• binning (int, optional) – Camera binning.

• detector (str, optional) – Detector manufacturer and model.

• elevation_angle (float, optional) – Elevation angle of the detector in degrees. If the elevation is zero, the detector is perpendicular to the incident beam.

• exposure_time (float, optional) – Camera exposure time in µs.

• frame_number (float, optional) – Number of patterns integrated during acquisition.

• frame_rate (float, optional) – Frames per s.

• gain (float, optional) – Camera gain, typically in dB.

• grid_type (str, optional) – Scan grid type, only square grid is supported.

• manufacturer (str, optional) – Manufacturer of software used to collect patterns.

• microscope (str, optional) – Microscope used to collect patterns.

• magnification (int, optional) – Microscope magnification at which patterns were collected.

• sample_tilt (float, optional) – Sample tilt angle from horizontal in degrees.

• scan_time (float, optional) – Scan time in s.

• static_background (numpy.ndarray, optional) – Static background pattern.

• version (str, optional) – Version of software used to collect patterns.

• working_distance (float, optional) – Working distance in mm.

• xpc (float, optional) – Pattern centre horizontal coordinate with respect to detector centre, as viewed from the detector to the sample.

• ypc (float, optional) – Pattern centre vertical coordinate with respect to detector centre, as viewed from the detector to the sample.

• zpc (float, optional) – Specimen to scintillator distance.

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> node = kp.signals.util.metadata_nodes("ebsd")
>>> s.metadata.get_item(node + '.xpc')
-5.64
>>> s.set_experimental_parameters(xpc=0.50726)
>>> s.metadata.get_item(node + '.xpc')
0.50726


Notes

Deprecated since version 0.5: Function set_experimental_parameters() is deprecated and will be removed in version 0.6.

set_phase_parameters(number=1, atom_coordinates=None, formula=None, info=None, lattice_constants=None, laue_group=None, material_name=None, point_group=None, setting=None, source=None, space_group=None, symmetry=None)[source]#

[Deprecated] Set parameters for one phase in signal metadata.

A phase node with default values is created if none is present in the metadata when this method is called.

Parameters:
• number (int, optional) – Phase number.

• atom_coordinates (dict, optional) – Dictionary of dictionaries with one or more of the atoms in the unit cell, on the form {‘1’: {‘atom’: ‘Ni’, ‘coordinates’: [0, 0, 0], ‘site_occupation’: 1, ‘debye_waller_factor’: 0}, ‘2’: {‘atom’: ‘O’,… etc. debye_waller_factor in units of nm^2, and site_occupation in range [0, 1].

• formula (str, optional) – Phase formula, e.g. ‘Fe2’ or ‘Ni’.

• info (str, optional) – Whatever phase info the user finds relevant.

• lattice_constants (numpy.ndarray or list of floats, optional) – Six lattice constants a, b, c, alpha, beta, gamma.

• laue_group (str, optional) – Phase Laue group.

• material_name (str, optional) – Name of material.

• point_group (str, optional) – Phase point group.

• setting (int, optional) – Space group’s origin setting.

• source (str, optional) – Literature reference for phase data.

• space_group (int, optional) – Number between 1 and 230.

• symmetry (int, optional) – Phase symmetry.

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s.metadata.Sample.Phases.Number_1.atom_coordinates.Number_1
├── atom = Ni
├── coordinates = array([0, 0, 0])
├── debye_waller_factor = 0.0035
└── site_occupation = 1
>>> s.set_phase_parameters(
...     number=1,
...     atom_coordinates={'1': {
...         'atom': 'Fe',
...         'coordinates': [0, 0, 0],
...         'site_occupation': 1,
...         'debye_waller_factor': 0.005
...     }}
... )
>>> s.metadata.Sample.Phases.Number_1.atom_coordinates.Number_1
├── atom = Fe
├── coordinates = array([0, 0, 0])
├── debye_waller_factor = 0.005
└── site_occupation = 1


Notes

Deprecated since version 0.5: Function set_phase_parameters() is deprecated and will be removed in version 0.6.

set_scan_calibration(step_x=1.0, step_y=1.0)[source]#

Set the step size in microns.

Parameters:

Examples

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s.axes_manager['x'].scale
1.5
>>> s.set_scan_calibration(step_x=2)  # Microns
>>> s.axes_manager['x'].scale
2.0

property static_background: Union[None, ndarray, Array]#

Static background pattern.

Return type:
property xmap: CrystalMap#

A CrystalMap containing the phases, unit cell rotations and auxiliary properties of the EBSD data set.

Return type:

CrystalMap

These methods are exclusive to LazyEBSD instances.

 get_decomposition_model_write([components, ...]) Write the model signal generated from the selected number of principal components directly to an .hspy file.
class kikuchipy.signals.LazyEBSD(*args, **kwargs)[source]#

Lazy implementation of the EBSD class.

This class extends HyperSpy’s LazySignal2D class for EBSD patterns.

Methods inherited from HyperSpy can be found in the HyperSpy user guide.

See docstring of EBSD for attributes and methods.

compute(*args, **kwargs)[source]#

Attempt to store the full signal in memory.

Parameters:
• close_file (bool, default False) – If True, attemp to close the file associated with the dask array data if any. Note that closing the file will make all other associated lazy signals inoperative.

• show_progressbar (None or bool) – If True, display a progress bar. If None, the default from the preferences settings is used.

Return type:

None

get_decomposition_model_write(components=None, dtype_learn=<class 'numpy.float32'>, mbytes_chunk=100, dir_out=None, fname_out=None)[source]#

Write the model signal generated from the selected number of principal components directly to an .hspy file.

The model signal intensities are rescaled to the original signals’ data type range, keeping relative intensities.

Parameters:

Notes

Multiplying the learning results’ factors and loadings in memory to create the model signal cannot sometimes be done due to too large matrices. Here, instead, learning results are written to file, read into dask arrays and multiplied using dask.array.matmul(), out of core.

### EBSDMasterPattern#

All methods listed here are also available to LazyEBSDMasterPattern instances.

See Signal2D for methods inherited from HyperSpy.

 get_patterns(rotations, detector, energy[, ...]) Return a dictionary of EBSD patterns projected onto a detector from a master pattern in the square Lambert projection , for a set of crystal rotations relative to the EDAX TSL sample reference frame (RD, TD, ND) and a fixed detector-sample geometry. normalize_intensity([num_std, ...]) Normalize image intensities in inplace to a mean of zero with a given standard deviation. plot_spherical([energy, return_figure, ...]) Plot the master pattern sphere. rescale_intensity([relative, in_range, ...]) Rescale image intensities inplace.
class kikuchipy.signals.EBSDMasterPattern(*args, **kwargs)[source]#

Bases: CommonImage, Signal2D

Simulated Electron Backscatter Diffraction (EBSD) master pattern.

This class extends HyperSpy’s Signal2D class for EBSD master patterns. Methods inherited from HyperSpy can be found in the HyperSpy user guide. See the docstring of hyperspy.signal.BaseSignal for a list of additional attributes.

projection#

Which projection the pattern is in, "stereographic" or "lambert".

Type:

str

hemisphere#

Which hemisphere the data contains: "upper" (previously "north"), "lower" (previously "south") or "both".

Type:

str

phase#

Phase describing the crystal structure used in the master pattern simulation.

Type:

orix.crystal_map.Phase

as_lambert()[source]#

Return a new master pattern in the Lambert projection.

Only implemented for non-lazy signals.

Returns:

Master pattern in the Lambert projection with the same data shape but in 32-bit floating point data dtype.

Return type:

EBSDMasterPattern

Examples

>>> import kikuchipy as kp
>>> mp_sp = kp.data.nickel_ebsd_master_pattern_small()
>>> mp_sp.projection
'stereographic'
>>> mp_lp = mp_sp.as_lambert()
>>> mp_lp.projection
'lambert'

deepcopy()[source]#

Return a “deep copy” of this Signal using the standard library’s deepcopy() function. Note: this means the underlying data structure will be duplicated in memory.

get_patterns(rotations, detector, energy, dtype_out=<class 'numpy.float32'>, compute=False, **kwargs)[source]#

Return a dictionary of EBSD patterns projected onto a detector from a master pattern in the square Lambert projection , for a set of crystal rotations relative to the EDAX TSL sample reference frame (RD, TD, ND) and a fixed detector-sample geometry.

Parameters:
• rotations (Rotation) – Crystal rotations to get patterns from. The shape of this instance, a maximum of two dimensions, determines the navigation shape of the output signal.

• detector (EBSDDetector) – EBSD detector describing the detector dimensions and the detector-sample geometry with a single, fixed projection/pattern center.

• energy (Union[int, float]) – Acceleration voltage, in kV, used to simulate the desired master pattern to create a dictionary from. If only a single energy is present in the signal, this will be returned no matter its energy.

• dtype_out (Union[type, dtype]) – Data type of the returned patterns, by default np.float32.

• compute (bool) – Whether to return a lazy result, by default False. For more information see compute().

• kwargs – Keyword arguments passed to get_chunking() to control the number of chunks the dictionary creation and the output data array is split into. Only chunk_shape, chunk_bytes and dtype_out (to dtype) are passed on.

Returns:

Signal with navigation and signal shape equal to the rotation instance and detector shape, respectively.

Return type:

Notes

If the master pattern phase has a non-centrosymmetric point group, both the upper and lower hemispheres must be provided. For more details regarding the reference frame visit the reference frame user guide.

normalize_intensity(num_std=1, divide_by_square_root=False, dtype_out=None)[source]#

Normalize image intensities in inplace to a mean of zero with a given standard deviation.

Parameters:
• num_std (int) – Number of standard deviations of the output intensities. Default is 1.

• divide_by_square_root (bool) – Whether to divide output intensities by the square root of the signal dimension size. Default is False.

• dtype_out (Optional[dtype]) – Data type of normalized images. If None (default), the input images’ data type is used.

Notes

Data type should always be changed to floating point, e.g. np.float32 with change_dtype(), before normalizing the intensities.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> np.mean(s.data)
146.0670987654321
>>> s.normalize_intensity(dtype_out=np.float32)
>>> np.mean(s.data)
2.6373216e-08


Notes

Rescaling RGB images is not possible. Use RGB channel normalization when creating the image instead.

plot_spherical(energy=None, return_figure=False, style='surface', plotter_kwargs=None, show_kwargs=None)[source]#

Plot the master pattern sphere.

This requires the master pattern to be in the stereographic projection and both hemispheres to be present.

Parameters:
Returns:

pl – Only returned if return_figure is True.

Return type:

pyvista.Plotter

Notes

Requires pyvista.

Examples

>>> import kikuchipy as kp
>>> mp = kp.data.nickel_ebsd_master_pattern_small(projection="stereographic")
>>> mp.plot_spherical()

rescale_intensity(relative=False, in_range=None, out_range=None, dtype_out=None, percentiles=None)[source]#

Rescale image intensities inplace.

Output min./max. intensity is determined from out_range or the data type range of the numpy.dtype passed to dtype_out if out_range is None.

This method is based on skimage.exposure.rescale_intensity().

Parameters:

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()


Image intensities are stretched to fill the available grey levels in the input images’ data type range or any numpy.dtype range passed to dtype_out, either keeping relative intensities between images or not:

>>> print(
...     s.data.dtype, s.data.min(), s.data.max(),
...     s.inav[0, 0].data.min(), s.inav[0, 0].data.max()
... )
uint8 23 246 26 245
>>> s2 = s.deepcopy()
>>> s.rescale_intensity(dtype_out=np.uint16)
>>> print(
...     s.data.dtype, s.data.min(), s.data.max(),
...     s.inav[0, 0].data.min(), s.inav[0, 0].data.max()
... )
uint16 0 65535 0 65535
>>> s2.rescale_intensity(relative=True)
>>> print(
...     s2.data.dtype, s2.data.min(), s2.data.max(),
...     s2.inav[0, 0].data.min(), s2.inav[0, 0].data.max()
... )
uint8 0 255 3 253


Contrast stretching can be performed by passing percentiles:

>>> s.rescale_intensity(percentiles=(1, 99))


Here, the darkest and brightest pixels within the 1% percentile are set to the ends of the data type range, e.g. 0 and 255 respectively for images of uint8 data type.

Notes

Rescaling RGB images is not possible. Use RGB channel normalization when creating the image instead.

There are no methods exclusive to LazyEBSDMasterPattern instances.

class kikuchipy.signals.LazyEBSDMasterPattern(*args, **kwargs)[source]#

Lazy implementation of the EBSDMasterPattern class.

This class extends HyperSpy’s LazySignal2D class for EBSD master patterns. Methods inherited from HyperSpy can be found in the HyperSpy user guide. See docstring of EBSDMasterPattern for attributes and methods.

### VirtualBSEImage#

See Signal2D for methods inherited from HyperSpy.

 normalize_intensity([num_std, ...]) Normalize image intensities in inplace to a mean of zero with a given standard deviation. rescale_intensity([relative, in_range, ...]) Rescale image intensities inplace.
class kikuchipy.signals.VirtualBSEImage(*args, **kwargs)[source]#

Virtual backscatter electron (BSE) image(s).

This class extends HyperSpy’s Signal2D class for virtual BSE images.

Methods inherited from HyperSpy can be found in the HyperSpy user guide.

See the docstring of hyperspy.signal.BaseSignal for a list of attributes.

normalize_intensity(num_std=1, divide_by_square_root=False, dtype_out=None)[source]#

Normalize image intensities in inplace to a mean of zero with a given standard deviation.

Parameters:
• num_std (int) – Number of standard deviations of the output intensities. Default is 1.

• divide_by_square_root (bool) – Whether to divide output intensities by the square root of the signal dimension size. Default is False.

• dtype_out (Optional[dtype]) – Data type of normalized images. If None (default), the input images’ data type is used.

Notes

Data type should always be changed to floating point, e.g. np.float32 with change_dtype(), before normalizing the intensities.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> np.mean(s.data)
146.0670987654321
>>> s.normalize_intensity(dtype_out=np.float32)
>>> np.mean(s.data)
2.6373216e-08


Notes

Rescaling RGB images is not possible. Use RGB channel normalization when creating the image instead.

rescale_intensity(relative=False, in_range=None, out_range=None, dtype_out=None, percentiles=None)[source]#

Rescale image intensities inplace.

Output min./max. intensity is determined from out_range or the data type range of the numpy.dtype passed to dtype_out if out_range is None.

This method is based on skimage.exposure.rescale_intensity().

Parameters:

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()


Image intensities are stretched to fill the available grey levels in the input images’ data type range or any numpy.dtype range passed to dtype_out, either keeping relative intensities between images or not:

>>> print(
...     s.data.dtype, s.data.min(), s.data.max(),
...     s.inav[0, 0].data.min(), s.inav[0, 0].data.max()
... )
uint8 23 246 26 245
>>> s2 = s.deepcopy()
>>> s.rescale_intensity(dtype_out=np.uint16)
>>> print(
...     s.data.dtype, s.data.min(), s.data.max(),
...     s.inav[0, 0].data.min(), s.inav[0, 0].data.max()
... )
uint16 0 65535 0 65535
>>> s2.rescale_intensity(relative=True)
>>> print(
...     s2.data.dtype, s2.data.min(), s2.data.max(),
...     s2.inav[0, 0].data.min(), s2.inav[0, 0].data.max()
... )
uint8 0 255 3 253


Contrast stretching can be performed by passing percentiles:

>>> s.rescale_intensity(percentiles=(1, 99))


Here, the darkest and brightest pixels within the 1% percentile are set to the ends of the data type range, e.g. 0 and 255 respectively for images of uint8 data type.

Notes

Rescaling RGB images is not possible. Use RGB channel normalization when creating the image instead.

### util#

 Return a dictionary in HyperSpy's DictionaryTreeBrowser format with the default kikuchipy EBSD metadata. get_chunking([signal, data_shape, nav_dim, ...]) Get a chunk tuple based on the shape of the signal data. get_dask_array(signal[, dtype]) Return dask array of patterns with appropriate chunking. metadata_nodes([nodes]) Return SEM and/or EBSD metadata nodes.

Signal utilities for handling signal metadata and attributes, output from signal methods, and for controlling chunking of lazy signal data in Array.

kikuchipy.signals.util.ebsd_metadata()[source]#

Return a dictionary in HyperSpy’s DictionaryTreeBrowser format with the default kikuchipy EBSD metadata.

See set_experimental_parameters() for an explanation of the parameters.

Returns:

md

Return type:

hyperspy.misc.utils.DictionaryTreeBrowser

Notes

Deprecated since version 0.5.

kikuchipy.signals.util.get_chunking(signal=None, data_shape=None, nav_dim=None, sig_dim=None, chunk_shape=None, chunk_bytes=30000000.0, dtype=None)[source]#

Get a chunk tuple based on the shape of the signal data.

The signal dimensions will not be chunked, and the navigation dimensions will be chunked based on either chunk_shape, or be optimized based on the chunk_bytes.

This function is inspired by a similar function in pyxem.

Parameters:
Return type:

chunks

kikuchipy.signals.util.get_dask_array(signal, dtype=None, **kwargs)[source]#

Return dask array of patterns with appropriate chunking.

Parameters:
Returns:

Dask array with signal data with appropriate chunking and data type.

Return type:

dask_array

kikuchipy.signals.util.metadata_nodes(nodes=None)[source]#

Return SEM and/or EBSD metadata nodes.

This is a convenience function so that we only have to define these node strings here.

Parameters:

nodes (Union[None, str, List[str]]) – Metadata nodes to return. Options are “sem”, “ebsd”, or None. If None (default) is passed, all nodes are returned.

Returns:

nodes_to_return

Return type:

list of str or str

## simulations#

Simulations returned by a generator and handling of Kikuchi bands and zone axes.

 KikuchiPatternSimulator(reflectors) Setup and calculation of geometrical or kinematical Kikuchi pattern simulations. Collection of coordinates of Kikuchi lines and zone axes on an EBSD detector for simple plotting or creation of HyperSpy markers to plot onto kikuchipy.signals.EBSD signals. features Kikuchi bands and zone axes used in geometrical EBSD simulations. GeometricalEBSDSimulation(detector, ...) Geometrical EBSD simulation with Kikuchi bands and zone axes.

### KikuchiPatternSimulator#

 calculate_master_pattern([half_size, ...]) Calculate a kinematical master pattern in the stereographic projection. on_detector(detector, rotations) Project Kikuchi lines and zone axes onto a detector, one per crystal orientation. plot([projection, mode, hemisphere, ...]) Plot reflectors as lines or bands in the stereographic or spherical projection.
class kikuchipy.simulations.KikuchiPatternSimulator(reflectors)[source]#

Setup and calculation of geometrical or kinematical Kikuchi pattern simulations.

Parameters:

reflectors (ReciprocalLatticeVector) – Reflectors to use in the simulation, flattened to one navigation dimension.

calculate_master_pattern(half_size=500, hemisphere='upper', scaling='linear')[source]#

Calculate a kinematical master pattern in the stereographic projection.

Requires that the reflectors have structure factors (theta) calculated.

Parameters:
• half_size (Optional[int]) – Number of pixels along the x-direction of the square master pattern. Default is 500. The full size will be 2 * half_size + 1, given a master pattern of shape (1001, 1001) for the default value.

• hemisphere (Optional[str]) – Which hemisphere(s) to calculate. Options are "upper" (default), "lower" or "both".

• scaling (Optional[str]) – Intensity scaling of the band kinematical intensities, either "linear" (default), $$|F|$$, "square", $$|F|^2$$, or "None", giving all bands an intensity of 1.

Returns:

master_pattern – Kinematical master pattern in the stereographic projection.

Return type:

EBSDMasterPattern

Notes

The algorithm for selecting which unit vector is within a Kikuchi band is derived from a similar routine in EMsoft.

on_detector(detector, rotations)[source]#

Project Kikuchi lines and zone axes onto a detector, one per crystal orientation.

Parameters:
• detector (EBSDDetector) – EBSD detector describing the detector’s view of the sample. If navigation_shape is anything else than (1,), it must be equal to the shape of the input rotations.

• rotations (Rotation) – Crystal orientations assumed to be expressed with respect to the default EDAX TSL sample reference frame RD-TD-ND in the Bunge convention. Rotation shape can be 1D or 2D.

Returns:

simulations

Return type:

GeometricalKikuchiPatternSimulation

Notes

This function is not optimized for large datasets, so use with care.

property phase: Phase#

Phase with unit cell and symmetry.

Return type:

Phase

plot(projection='stereographic', mode='lines', hemisphere='upper', scaling='linear', figure=None, return_figure=False, backend='matplotlib', show_plotter=True)[source]#

Plot reflectors as lines or bands in the stereographic or spherical projection.

Parameters:
Returns:

figure – If return_figure=True, a Figure or a Plotter is returned.

Return type:
property reflectors: ReciprocalLatticeVector#

Reflectors to use in the simulation.

Return type:

ReciprocalLatticeVector

### GeometricalKikuchiPatternSimulation#

 as_collections([index, coordinates, lines, ...]) Get a single simulation as a list of Matplotlib objects. as_markers([lines, zone_axes, ...]) Return a list of simulation markers. lines_coordinates([index, coordinates, ...]) Get Kikuchi line coordinates of a single simulation. plot([index, coordinates, pattern, lines, ...]) Plot a single simulation on the detector. zone_axes_coordinates([index, coordinates, ...]) Get zone axis coordinates of a single simulation.
class kikuchipy.simulations.GeometricalKikuchiPatternSimulation(detector, rotations, reflectors, lines, zone_axes)[source]#

Collection of coordinates of Kikuchi lines and zone axes on an EBSD detector for simple plotting or creation of HyperSpy markers to plot onto kikuchipy.signals.EBSD signals.

Instances of this class are returned from kikuchipy.simulations.KikuchiPattern.Simulator.on_detector(), and not ment to be created directly.

Parameters:
• detector (EBSDDetector) – EBSD detector.

• rotations (Rotation) – Crystal orientations for which coordinates of Kikuchi lines and zone axes have been generated.

• reflectors (ReciprocalLatticeVector) – Reciprocal lattice vectors used in the simulation.

• lines (KikuchiPatternLine) – Collection of coordinates of Kikuchi lines on the detector.

• zone_axes (KikuchiPatternZoneAxis) – Collection of coordinates of zone axes on the detector.

as_collections(index=None, coordinates='detector', lines=True, zone_axes=False, zone_axes_labels=False, lines_kwargs=None, zone_axes_kwargs=None, zone_axes_labels_kwargs=None)[source]#

Get a single simulation as a list of Matplotlib objects.

Parameters:
Returns:

collections – List of Matplotlib collections.

Return type:

list

See also

as_markers(lines=True, zone_axes=False, zone_axes_labels=False, pc=False, lines_kwargs=None, zone_axes_kwargs=None, zone_axes_labels_kwargs=None, pc_kwargs=None)[source]#

Return a list of simulation markers.

Parameters:
Returns:

markers – List with all markers.

Return type:

hyperspy.drawing.marker.MarkerBase

See also

property detector: EBSDDetector#

EBSD detector onto which simulations were generated.

Return type:

EBSDDetector

lines_coordinates(index=None, coordinates='detector', exclude_nan=True)[source]#

Get Kikuchi line coordinates of a single simulation.

Parameters:
• index (Union[int, tuple, None]) – Index of the simulation to get line coordinates for. If not given, this is the first simulation.

• coordinates (str) – The type of coordinates, either "detector" (default) or "gnomonic".

• exclude_nan (bool) – Whether to exclude coordinates of Kikuchi lines not present in the pattern. Default is True. By passing False, all simulations (by varying index) returns an array of the same shape.

Returns:

coords – Kikuchi line coordinates.

Return type:

numpy.ndarray

property navigation_shape: tuple#

Navigation shape of the simulations equal to the shape of rotations.

Return type:

tuple

plot(index=None, coordinates='detector', pattern=None, lines=True, zone_axes=True, zone_axes_labels=True, pc=True, pattern_kwargs=None, lines_kwargs=None, zone_axes_kwargs=None, zone_axes_labels_kwargs=None, pc_kwargs=None, return_figure=False)[source]#

Plot a single simulation on the detector.

Parameters:
Returns:

fig – Returned if return_figure=True.

Return type:

matplotlib.figure.Figure

property reflectors: ReciprocalLatticeVector#

Reciprocal lattice vectors used in the simulations.

Return type:

ReciprocalLatticeVector

property rotations: Rotation#

Crystal orientations for which simulations were generated.

Return type:

Rotation

zone_axes_coordinates(index=None, coordinates='detector', exclude_nan=