# 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 an alpha stage, so there will be 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. 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¶

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

Direct structure matrix as defined in EMsoft.

Parameters

lattice (Lattice) – Crystal structure lattice.

Return type

ndarray

kikuchipy.crystallography.get_reciprocal_metric_tensor(lattice)[source]

Reciprocal metric tensor as defined in EMsoft.

Parameters

lattice (Lattice) – Crystal structure lattice.

Return type

ndarray

kikuchipy.crystallography.get_reciprocal_structure_matrix(lattice)[source]

Reciprocal structure matrix as defined in EMsoft.

Parameters

lattice (Lattice) – Crystal structure lattice.

Return type

ndarray

## 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]) 4125 EBSD patterns in a (55, 75) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19]. nickel_ebsd_master_pattern_small(**kwargs) (401, 401) uint8 square Lambert or stereographic projection of the northern and southern hemisphere of a Nickel master pattern at 20 keV accelerating voltage. silicon_ebsd_moving_screen_in([allow_download]) 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.

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

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.

• kwargs – Keyword arguments passed to load().

Returns

signal – EBSD signal.

Return type

EBSD

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.

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.

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

Parameters

kwargs – Keyword arguments passed to load().

Returns

signal – EBSD signal.

Return type

EBSD

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

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.

• kwargs – Keyword arguments passed to load().

Returns

signal – EBSD signal.

Return type

EBSD

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

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.

• kwargs – Keyword arguments passed to load().

Returns

signal – EBSD signal.

Return type

EBSD

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

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.

• kwargs – Keyword arguments passed to load().

Returns

signal – EBSD signal.

Return type

EBSD

## 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¶

 deepcopy() Return a deep copy using copy.deepcopy(). Return PC in the Bruker convention. pc_emsoft([version]) Return PC in the EMsoft convention. Return PC in the Oxford convention. pc_tsl() 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)).

PC conversions are calculated as presented in .

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. X and Y are measured from the detector left and top, respectively, while Z is the distance from the sample to the detection screen divided by the detector height. 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.

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)
(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 rows divided by columns.

Return type

float

property bounds: numpy.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: numpy.ndarray

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

Return type

ndarray

property height: float

Detector height in microns.

Return type

float

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

Return type

int

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: numpy.ndarray

All projection center coordinates.

Return type

ndarray

property pc_average: numpy.ndarray

Return the overall average projection center.

Return type

ndarray

pc_bruker()[source]

Return PC in the Bruker convention.

PC conversions are calculated as presented in ..

Return type

ndarray

pc_emsoft(version=5)[source]

Return PC in the EMsoft convention.

PC conversions are calculated as presented in .

Parameters

version (int) – Which EMsoft PC convention to use. The direction of the x PC coordinate, xpc, flipped in version 5, because from then on the EBSD patterns were viewed looking from detector to sample, not the other way around.

Return type

ndarray

pc_oxford()[source]

Return PC in the Oxford convention.

PC conversions are calculated as presented in .

Return type

ndarray

pc_tsl()[source]

Return PC in the EDAX TSL convention.

PC conversions are calculated as presented in ..

Return type

ndarray

property pcx: numpy.ndarray

Projection center x coordinates.

Return type

ndarray

property pcy: numpy.ndarray

Projection center y coordinates.

Return type

ndarray

property pcz: numpy.ndarray

Projection center z coordinates.

Return type

ndarray

plot(coordinates=None, 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
• coordinates (Optional[str]) – Which coordinates to use, “detector” or “gnomonic”. If None (default), “detector” is used.

• show_pc (bool) – Show the average projection center. Default is True.

• pc_kwargs (Optional[dict]) – A dictionary of keyword arguments passed to matplotlib.axes.Axes.scatter().

• pattern (Optional[ndarray]) – A pattern to put on the detector. If None (default), no pattern is displayed. The pattern array must have the same shape as the detector.

• pattern_kwargs (Optional[dict]) – A dictionary of keyword arguments passed to matplotlib.axes.Axes.imshow().

• draw_gnomonic_circles (bool) – Draw circles for angular distances from pattern. Default is False. Circle positions are only correct when coordinates=”gnomonic”.

• gnomonic_angles (Union[None, list, ndarray]) – Which angular distances to plot if draw_gnomonic_circles is True. Default is from 10 to 80 in steps of 10.

• gnomonic_circles_kwargs (Optional[dict]) – A dictionary of keyword arguments passed to matplotlib.patches.Circle().

• zoom (float) – Whether to zoom in/out from the detector, e.g. to show the extent of the gnomonic projection circles. A zoom > 1 zooms out. Default is 1, i.e. no zoom.

• return_fig_ax (bool) – Whether to return the figure and axes object created. Default is False.

Return type

Optional[Tuple[Figure, Axes]]

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: numpy.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

Tuple[int, int]

property width: float

Detector width in microns.

Return type

float

property x_max: Union[numpy.ndarray, float]

Right bound of detector in gnomonic coordinates.

Return type
property x_min: Union[numpy.ndarray, float]

Left bound of detector in gnomonic coordinates.

Return type
property x_range: numpy.ndarray

X detector limits in gnomonic coordinates.

Return type

ndarray

property x_scale: numpy.ndarray

Width of a pixel in gnomonic coordinates.

Return type

ndarray

property y_max: Union[numpy.ndarray, float]

Bottom bound of detector in gnomonic coordinates.

Return type
property y_min: Union[numpy.ndarray, float]

Top bound of detector in gnomonic coordinates.

Return type
property y_range: numpy.ndarray

The y detector limits in gnomonic coordinates.

Return type

ndarray

property y_scale: numpy.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
• pattern_in (ndarray) – Pattern acquired with the shortest detector distance (DD) in the “in” position.

• pattern_out (ndarray) – Pattern acquired with the longer DD in the “out” position, with the camera a known distance delta_z from the “in” position.

• points_in (Union[ndarray, List[Tuple[float]]]) – Set of $$n$$ coordinates [(x1, y1), (x2, y2), …] of pattern features in pattern_in.

• points_out (Union[ndarray, List[Tuple[float]]]) – Set of $$n$$ coordinates [(x1, y1), (x2, y2), …] of pattern features, the same as in points_in, in pattern_out. They must be in the same order as in points_in.

• delta_z (float) – Known distance between the “in” and “out” camera positions in which the pattern_in and pattern_out were acquired, respectively. Default is 1. The output PCz value will be in the same unit as this value, unless px_size is provided.

• px_size (Optional[float]) – Known size of the detector pixels, in the same unit as delta_z. If this is None (default), the PCz will not be scaled to fractions of detector height.

• binning (int) – Detector pixel binning. Default is 1, meaning no binning. This is used together with px_size to scale PCz.

• convention (str) – Whether to present PCy as the value from bottom to top (TSL), or top to bottom (Bruker). Default is “tsl”.

property line_lengths: numpy.ndarray

Length of lines within the patterns in pixels.

Return type

ndarray

property lines: numpy.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: numpy.ndarray

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

Return type

ndarray

property lines_out_in: numpy.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: numpy.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: numpy.ndarray

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

Return type

ndarray

property lines_start: numpy.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: numpy.ndarray

The average PC calculated from all estimates.

Return type

ndarray

property pc_all: numpy.ndarray

All estimates of PC.

Return type

ndarray

property pcx_all: numpy.ndarray

All estimates of PCx.

Return type

ndarray

property pcy_all: numpy.ndarray

All estimates of PCy.

Return type

ndarray

property pcz_all: numpy.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

Optional[Tuple[Figure, List[Axes]]]

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: numpy.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: numpy.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

Tuple[int, int]

## draw¶

Creation of HyperSpy markers to add to signals.

### 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
• texts (Union[list, ndarray]) – A list of texts.

• coordinates (Union[ndarray, list]) – On the form [[x0, y0], [x1, y1], …].

• kwargs – Keyword arguments allowed by matplotlib.pyplot.axvline.()

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. modified_hann(Nx) Return a 1D modified Hann window with the maximum value normalized to 1. Window(window, str, numpy.ndarray, …) 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
• shape (Tuple[int, int]) – Shape of function.

• cutoff (Union[int, float]) – Cut-off frequency.

• cutoff_width (Union[None, int, float]) – Width of cut-off region. If None (default), it is set to half of the cutoff frequency.

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
• shape (Tuple[int, int]) – Shape of function.

• cutoff (Union[int, float]) – Cut-off frequency.

• cutoff_width (Union[None, int, float]) – Width of cut-off region. If None (default), it is set to half of the cutoff frequency.

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¶

 is_valid() 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: Optional[Sequence[int]] = None, **kwargs)[source]

Bases: numpy.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__()

Initialize self. See help(type(self)) for accurate signature.

circular: bool = False
property distance_to_origin: numpy.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
• grid (bool) – Whether to separate each value with a white spacing in a grid. Default is True.

• show_values (bool) – Whether to show values as text in centre of element. Default is True.

• textcolors (Optional[List[str]]) – A list of two color specifications. The first is used for values below a threshold, the second for those above. If None (default), this is set to [“white”, “black”].

• cmap (str) – A color map to color data with, available in matplotlib.colors.ListedColormap. Default is “viridis”.

• cmap_label (str) – Color map label. Default is “Value”.

• colorbar (bool) – Whether to show the colorbar. Default is True.

• return_figure (bool) – Whether to return the figure or not. Default is False.

Returns

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, …) 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. virtual_bse_generator.get_rgb_image(channels) 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

A generator storing necessary parameters to simulate geometrical EBSD patterns.

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

Returns

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

Number of navigation dimensions (a maximum of 2).

Return type

int

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

Return type

tuple

property rotations: orix.quaternion.rotation.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]

Initialize self. See help(type(self)) for accurate signature.

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
• r (Union[BaseInteractiveROI, Tuple, List[BaseInteractiveROI], List[Tuple]]) – One ROI or a list of ROIs, or one tuple or a list of tuples with detector grid indices specifying one or more ROI(s). Intensities within the specified ROI(s) are summed up to form the red color channel.

• g (Union[BaseInteractiveROI, Tuple, List[BaseInteractiveROI], List[Tuple]]) – One ROI or a list of ROIs, or one tuple or a list of tuples with detector grid indices specifying one or more ROI(s). Intensities within the specified ROI(s) are summed up to form the green color channel.

• b (Union[BaseInteractiveROI, Tuple, List[BaseInteractiveROI], List[Tuple]]) – One ROI or a list of ROIs, or one tuple or a list of tuples with detector grid indices specifying one or more ROI(s). Intensities within the specified ROI(s) are summed up to form the blue color channel.

• normalize (bool) – Whether to normalize the individual images (channels) before RGB image creation.

• alpha (Union[None, ndarray, VirtualBSEImage]) – “Alpha channel”. If None (default), no “alpha channel” is added to the image.

• percentiles (Optional[Tuple]) – Whether to apply contrast stretching with a given percentile tuple with percentages, e.g. (0.5, 99.5), after creating the RGB image. If None (default), no contrast stretching is performed.

• dtype_out (Union[uint8, uint16]) – Output data type, either np.uint16 or np.uint8 (default).

• kwargs – Keyword arguments passed to get_rgb_image().

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: numpy.ndarray

Return detector grid columns, defined by grid_shape.

Return type

ndarray

property grid_rows: numpy.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
• pattern_idx (Optional[Tuple[int, …]]) – A tuple of integers defining the pattern to superimpose the grid on. If None (default), the first pattern is used.

• rgb_channels (Union[None, List[Tuple], List[List[Tuple]]]) – A list of tuple indices defining three or more detector grid tiles which edges to color red, green and blue. If None (default), no tiles’ edges are colored.

• visible_indices (bool) – Whether to show grid indices. Default is True.

• kwargs – Keyword arguments passed to matplotlib.pyplot.axhline() and axvline, used by HyperSpy to draw lines.

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
• channels (List[ndarray]) – A list of np.ndarray for the red, green and blue channel, respectively.

• normalize (bool) – Whether to normalize the individual channels before RGB image creation.

• alpha (Optional[ndarray]) – Potential alpha channel. If None (default), no alpha channel is added to the image.

• percentiles (Optional[Tuple]) – Whether to apply contrast stretching with a given percentile tuple with percentages, e.g. (0.5, 99.5), after creating the RGB image. If None (default), no contrast stretching is performed.

• dtype_out (Union[uint8, uint16]) – Output data type, either np.uint16 or np.uint8 (default).

• kwargs – Keyword arguments passed to normalize_image().

Returns

rgb_image – RGB image.

Return type

np.ndarray

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

Parameters
• image (ndarray) – Image to normalize.

• add_bright (int) – Brightness offset. Default is 0.

• contrast (int) – Contrast factor. Default is 1.0.

• dtype_out (Union[uint8, uint16]) – Output data type, either np.uint16 or np.uint8 (default).

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
• results (list) – Results returned from refine_orientation(), which is a list of Delayed.

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

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

Returns

refined_xmap – Crystal map with refined orientations and scores.

Return type

CrystalMap

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 (list) – Results returned from refine_orientation_projection_center(), which is a list of Delayed.

• 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

• xmap_refined (CrystalMap) – Crystal map with refined orientations and scores.

• new_detector (EBSDDetector) – EBSD detector with refined projection center parameters.

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 (list) – Results returned from refine_projection_center(), which is a list of Delayed.

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

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

Returns

• new_scores (numpy.ndarray) – Score array.

• new_detector (EBSDDetector) – EBSD detector with refined projection center parameters.

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

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

Type
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
• experimental (Union[Array, ndarray]) – Experimental pattern array with as many patterns as n_experimental_patterns.

• dictionary (Union[Array, ndarray]) – Dictionary pattern array with as many patterns as n_dictionary_patterns.

Returns

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
• experimental (Union[Array, ndarray]) – Experimental pattern array with as many patterns as n_experimental_patterns.

• dictionary (Union[Array, ndarray]) – Dictionary pattern array with as many patterns as n_dictionary_patterns.

Returns

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.

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.

Returns

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.

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

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

• scan_size (Union[None, int, Tuple[int, …]]) – Scan size in number of patterns in width and height.

• 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

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='north', 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 “north” (default), “south” 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

Return type

list of dicts

#### h5ebsd¶

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

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 (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 (Group) – HDF group to write dictionary to.

• kwargs – Keyword arguments passed to Group.require_dataset.

Return scan metadata dictionaries from an EDAX TSL h5ebsd file.

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

• md (DictionaryTreeBrowser) – Dictionary with empty fields from kikuchipy’s metadata.

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.

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
• filename (str) – Full file path of the HDF file.

• scan_group_names (Union[None, str, List[str]]) – Name or a list of names of HDF5 top group(s) containing the scan(s) to return. If None, the first scan in the file is returned.

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

• kwargs – Key word arguments passed to File.

Returns

Return type

list of dicts

References

Jackson2014

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.

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
• filename (str) – Full path of HDF file.

• signal (kikuchipy.signals.EBSD or kikuchipy.signals.LazyEBSD) – Signal instance.

• add_scan (Optional[bool]) – Add signal to an existing, but not open, h5ebsd file. If it does not exist it is created and the signal is written to it.

• scan_number (int) – Scan number in name of HDF dataset when writing to an existing, but not open, h5ebsd file.

• kwargs – Keyword arguments passed to Group.require_dataset.

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

Get the desired HDF5 groups with scans within them.

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

• scan_group_names (Union[None, str, List[str]]) – Name or a list of names of the desired top HDF5 group(s). If None, the first scan group is returned.

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 (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 (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

Return type

dict

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 (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
• group (Group) – HDF group object.

• dictionary (Union[None, dict, DictionaryTreeBrowser]) – To fill dataset values into.

• recursive (bool) – Whether to add subgroups to dictionary.

• data_dset_names (Optional[list]) – List of names of HDF data sets with data to not read.

Returns

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

Return type

dict

Return scan metadata dictionaries from a kikuchipy h5ebsd file.

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

• md (DictionaryTreeBrowser) – Dictionary with empty fields from kikuchipy’s metadata.

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.

Returns

Return type

dict

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

Get manufacturer and version from h5ebsd file.

Parameters

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

Return type

Tuple[str, str]

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
• filename (str) – File path to NORDIF data file.

• mmap_mode (Optional[str]) –

• scan_size (Union[None, int, Tuple[int, …]]) – Scan size in number of patterns in width and height.

• pattern_size (Optional[Tuple[int, …]]) – Pattern size in detector pixels in width and height.

• setting_file (Optional[str]) – File path to NORDIF setting file (default is Setting.txt in same directory as filename).

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

Returns

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

• 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
• content (list) – File content to search in for the regular expression.

• expression (str) – Regular expression.

• line_no (int) – Line number to search in.

• file (file object) – File handle of open setting file.

Returns

Output string with relevant value.

Return type

str

#### nordif_calibration_patterns¶

Read support for NORDIF’s calibration patterns.

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

Parameters
• filename (str) – File path to the NORDIF settings text file.

• lazy (bool) – This parameter is not used in this reader.

Returns

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.

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

Returns

Return type

numpy.memmap

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

Tuple[int, int, int]

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

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

Parameters

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

Return type

Tuple[bool, int, int, int]

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.

Returns

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,))]
property pattern_is_present: numpy.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: numpy.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

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

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. fft_frequency_vectors(shape) 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
• pattern (ndarray) – EBSD pattern.

• apodization_window (Union[None, ndarray, Window]) – An apodization window to apply before the FFT in order to suppress streaks.

• shift (bool) – Whether to shift the zero-frequency component to the centre of the spectrum (default is False).

• real_fft_only (bool) – If True, the discrete FFT is computed for real input using scipy.fft.rfft2(). If False (default), it is computed using scipy.fft.fft2().

• kwargs – Keyword arguments pass to scipy.fft.fft2() or scipy.fft.rfft2().

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
• pattern (ndarray) – EBSD pattern.

• transfer_function (Union[ndarray, Window]) – Filter transfer function in the frequency domain.

• apodization_window (Union[None, ndarray, Window]) – An apodization window to apply before the FFT in order to suppress streaks.

• shift (bool) – Whether to shift the zero-frequency component to the centre of the spectrum. Default is False.

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
• pattern (ndarray) – EBSD pattern.

• filter_domain (str) – Whether to obtain the dynamic background by applying a Gaussian convolution filter in the “frequency” (default) or “spatial” domain.

• std (Union[None, int, float]) – Standard deviation of the Gaussian window. If None (default), a deviation of pattern width/8 is chosen.

• truncate (Union[int, float]) – Truncate the Gaussian window at this many standard deviations. Default is 4.0.

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
• pattern (ndarray) – EBSD pattern.

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

• frequency_vectors (Optional[ndarray]) – Integer 2D array assigning each FFT spectrum frequency component a weight. If None (default), these are calculated from fft_frequency_vectors(). This only depends on the pattern shape.

• inertia_max (Union[None, int, float]) – Maximum possible inertia of the FFT power spectrum of the image. If None (default), this is calculated from the frequency_vectors, which in this case must be passed. This only depends on the pattern shape.

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
• fft_pattern (ndarray) – FFT of EBSD pattern.

• shift (bool) – Whether to shift the zero-frequency component back to the corners of the spectrum (default is False).

• real_fft_only (bool) – If True, the discrete IFFT is computed for real input using scipy.fft.irfft2(). If False (default), it is computed using scipy.fft.ifft2().

• kwargs – Keyword arguments pass to scipy.fft.ifft().

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
• pattern (ndarray) – EBSD pattern.

• operation (str) – Whether to “subtract” (default) or “divide” by the dynamic background pattern.

• filter_domain (str) – Whether to obtain the dynamic background by applying a Gaussian convolution filter in the “frequency” (default) or “spatial” domain.

• std (Union[None, int, float]) – Standard deviation of the Gaussian window. If None (default), it is set to width/8.

• truncate (Union[int, float]) – Truncate the Gaussian window at this many standard deviations. Default is 4.0.

• dtype_out (Union[None, dtype, type, Tuple[int, int], Tuple[float, float]]) – Data type of corrected pattern. If None (default), it is set to input patterns’ data type.

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
• pattern (ndarray) – EBSD pattern.

• in_range (Optional[Tuple[Union[int, float], …]]) – Min./max. intensity values of the input pattern. If None (default), it is set to the pattern’s min./max intensity.

• out_range (Optional[Tuple[Union[int, float], …]]) – Min./max. intensity values of the rescaled pattern. If None (default), it is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, type]) – Data type of the rescaled pattern. If None (default), it is set to the same data type as the input pattern.

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[, …]) 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, …[, …]) Correct the dynamic background in a chunk of EBSD patterns. remove_static_background(patterns, …[, …]) 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.

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

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

Parameters
• patterns (Union[ndarray, Array]) – EBSD patterns.

• kernel_size (Union[Tuple[int, int], List[int]]) – Shape of contextual regions for adaptive histogram equalization.

• clip_limit (Union[int, float]) – Clipping limit, normalized between 0 and 1 (higher values give more contrast). Default is 0.

• nbins (int) – Number of gray bins for histogram. Default is 128.

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
• patterns (ndarray) – Patterns to average, with some overlap with surrounding chunks.

• window_sums (ndarray) – Sum of window data for each image.

• window (Union[ndarray, Window]) – Averaging window.

• dtype_out (Optional[dtype]) – Data type of averaged patterns. If None (default), it is set to the same data type as the input patterns.

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
• patterns (ndarray) – EBSD patterns.

• filter_func (Union[fft_filter, _fft_filter]) – Function to apply transfer_function with.

• transfer_function (Union[ndarray, Window]) – Filter transfer function in the frequency domain.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of output patterns. If None (default), it is set to the input patterns’ data type.

• kwargs – Keyword arguments passed to the filter_func.

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
• patterns (Union[ndarray, Array]) – EBSD patterns.

• filter_func (Union[gaussian_filter, fft_filter]) – Function where a Gaussian convolution filter is applied, in the frequency or spatial domain. Either scipy.ndimage.gaussian_filter() or kikuchipy.util.barnes_fftfilter.fft_filter().

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of background patterns. If None (default), it is set to input patterns’ data type.

• kwargs – Keyword arguments passed to the Gaussian blurring function passed to filter_func.

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]

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
• patterns (Union[ndarray, Array]) – EBSD patterns.

• frequency_vectors (Optional[ndarray]) – Integer 2D array with values corresponding to the weight given each FFT spectrum frequency component. If None (default), these are calculated from fft_frequency_vectors().

• inertia_max (Union[None, int, float]) – Maximum inertia of the FFT power spectrum of the image. If None (default), this is calculated from the frequency_vectors.

• 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_chunk – Image quality of patterns.

Return type

numpy.ndarray

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
• patterns (Union[ndarray, Array]) – Patterns to normalize the intensity in.

• 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 pattern size. Default is False.

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

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]

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
• patterns (Union[ndarray, Array]) – EBSD patterns.

• filter_func (Union[gaussian_filter, fft_filter]) – Function where a Gaussian convolution filter is applied, in the frequency or spatial domain. Either scipy.ndimage.gaussian_filter() or kikuchipy.util.barnes_fftfilter.fft_filter().

• operation_func (Union[<ufunc ‘subtract’>, <ufunc ‘true_divide’>]) – Function to subtract or divide by the dynamic background pattern.

• out_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity values of the output patterns. If None (default), out_range is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of corrected patterns. If None (default), it is set to input patterns’ data type.

• kwargs – Keyword arguments passed to the Gaussian blurring function passed to filter_func.

Returns

corrected_patterns – Dynamic background corrected patterns.

Return type

numpy.ndarray

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

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

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
• patterns (Union[ndarray, Array]) – EBSD patterns.

• static_bg (Union[ndarray, Array]) – Static background pattern. If None is passed (default) we try to read it from the signal metadata.

• operation_func (Union[<ufunc ‘subtract’>, <ufunc ‘true_divide’>]) – Function to subtract or divide by the dynamic background pattern.

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

• in_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity values of input and output patterns. If None (default), it is set to the overall pattern min./max, losing relative intensities between patterns.

• out_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity values of the output patterns. If None (default), out_range is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of corrected patterns. If None (default), it is set to input patterns’ data type.

Returns

corrected_patterns – Patterns with the static background removed.

Return type

numpy.ndarray

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
• patterns (Union[ndarray, Array]) – EBSD patterns.

• in_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of input patterns. If None (default), in_range is set to pattern min./max. Contrast stretching is performed when in_range is set to a narrower intensity range than the input patterns.

• out_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of output patterns. If None (default), out_range is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of rescaled patterns. If None (default), it is set to the same data type as the input patterns.

• percentiles (Union[None, Tuple[int, int], Tuple[float, float]]) – Disregard intensities outside these percentiles. Calculated per pattern. Must be None if in_range is passed (default is None).

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
• sample_tilt (float) – Sample tilt in degrees.

• detector_tilt (float) – Detector tilt in degrees.

• lattice (Lattice) – Crystal lattice.

• rotation (Rotation) – Unit cell rotation from the sample frame S.

Returns

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
• sample_tilt (float) – Sample tilt in degrees.

• detector_tilt (float) – Detector tilt in degrees.

• lattice (Lattice) – Crystal lattice.

• rotation (Rotation) – Unit cell rotation from the sample frame S.

Returns

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
• sample_tilt (float) – Sample tilt in degrees.

• detector_tilt (float) – Detector tilt in degrees.

• convention (Optional[str]) – Which sample reference frame to use, either the one used by EDAX TSL (default), “tsl”, or the one used by Bruker, “bruker”.

Returns

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.

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

Parameters
• cartesian (ndarray) – Cartesian coordinates x, y, z.

Returns

Hesse normal form coordinates distance and angle.

Return type

hesse

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

Parameters
• polar (ndarray) – The polar, azimuthal and radial spherical coordinates.

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 ̃hyperspy._signals.signal2d.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 in an EBSD scan 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_orientation_projection_center(xmap, …) 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 in an EBSD scan 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_calibration(delta) 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: kikuchipy.signals._common_image.CommonImage, hyperspy._signals.signal2d.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.

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

Parameters
• kernel_size (Union[Tuple[int, int], List[int], None]) – Shape of contextual regions for adaptive histogram equalization, default is 1/4 of image height and 1/4 of image width.

• clip_limit (Union[int, float]) – Clipping limit, normalized between 0 and 1 (higher values give more contrast). Default is 0.

• nbins (int) – Number of gray bins for histogram (“data range”), default is 128.

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

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

Average patterns in an EBSD scan 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
• window (Union[str, ndarray, Array, Window]) – Name of averaging window or an array. Available types are listed in scipy.signal.windows.get_window(), in addition to a “circular” window (default) filled with ones in which corner coefficients are set to zero. 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 window’s longest axis. A 1D or 2D numpy.ndarray, dask.array.Array or Window can also be passed.

• window_shape (Tuple[int, …]) – Shape of averaging window. Not used if a custom window or Window object is passed to window. This can be either 1D or 2D, and can be asymmetrical. Default is (3, 3).

• **kwargs – Keyword arguments passed to the available window type listed in scipy.signal.windows.get_window(). If none are passed, the default values of that particular window are used.

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.

copy()

property detector: kikuchipy.detectors.ebsd_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,
... )

Window

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
• components (Union[None, int, List[int]]) – If None (default), rebuilds the signal from all components. If int, rebuilds signal from components in range 0-given int. If list of ints, rebuilds signal from only components in given list.

• dtype_out (dtype) – Data type to cast learning results to (default is numpy.float32). Note that HyperSpy casts them to numpy.float64.

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
• filter_domain (str) – Whether to apply a Gaussian convolution filter in the “frequency” (default) or “spatial” domain.

• std (Union[None, int, float]) – Standard deviation of the Gaussian window. If None (default), it is set to width/8.

• truncate (Union[int, float]) – Truncate the Gaussian filter at this many standard deviations. Default is 4.0.

• dtype_out (Optional[dtype]) – Data type of the background patterns. If None (default), it is set to the same data type as the input pattern.

• kwargs – Keyword arguments passed to the Gaussian blurring function determined from filter_domain.

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 – Image quality map of same shape as signal navigation axes.

Return type

numpy.ndarray

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(normalize=True)
>>> 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.

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

• out_signal_axes (Union[None, Iterable[int], Iterable[str]]) – Which navigation axes to use as signal axes in the virtual image. If None (default), the first two navigation axes are used.

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.

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

• out_signal_axes (Union[None, Iterable[int], Iterable[str]]) – Which navigation axes to use as signal axes in the virtual image. If None (default), the first two navigation axes are used.

• **kwargs – Keyword arguments passed to the plot method of the virtual image.

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)[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:
• Local optimization:
• Global optimization:
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.

Returns

Crystal map with refined orientations and similarity metrics in a “scores” property if compute is True. If compute is False, a list of Delayed instances, one per experimental pattern, is returned, to be computed later. See compute_refine_orientation_results(). One delayed instance has the optimized score and the three Euler angles in radians in element 0, 1, 2, and 3, respectively.

Return type

CrystalMap or list of Delayed

refine_orientation_projection_center(xmap, detector, master_pattern, energy, mask=None, method='minimize', method_kwargs=None, trust_region=None, compute=True)[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:
• Local optimization:
• Global optimization:
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.

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 list of Delayed instances, one per experimental pattern, is returned, to be computed later. See compute_refine_orientation_projection_center_results(). One delayed instance 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

CrystalMap and EBSDDetector, or list of Delayed

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)[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:
• Local optimization:
• Global optimization:
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.

Returns

New similarity metrics and a new EBSD detector instance with the refined PCs if compute is True. If compute is False, a list of Delayed instances, one per experimental pattern, is returned, to be computed later. See compute_refine_projection_center_results(). One delayed instance has the optimized score and the three PC parameters in the Bruker convention in element 0, 1, 2, and 3, respectively.

Return type

numpy.ndarray and EBSDDetector, or list of Delayed

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
• operation (str) – Whether to “subtract” (default) or “divide” by the dynamic background pattern.

• filter_domain (str) – Whether to obtain the dynamic background by applying a Gaussian convolution filter in the “frequency” (default) or “spatial” domain.

• std (Union[None, int, float]) – Standard deviation of the Gaussian window. If None (default), it is set to width/8.

• truncate (Union[int, float]) – Truncate the Gaussian window at this many standard deviations. Default is 4.0.

• kwargs – Keyword arguments passed to the Gaussian blurring function determined from filter_domain.

Examples

Traditional background correction includes static and dynamic corrections, loosing relative intensities between patterns after dynamic corrections (whether relative is set to True or False in remove_static_background()):

>>> import kikuchipy as kp
>>> s = kp.data.nickel_ebsd_small()
>>> s.remove_static_background(operation="subtract")
>>> s.remove_dynamic_background(
...     operation="subtract",  # Default
...     filter_domain="frequency",  # Default
...     truncate=4.0,  # Default
...     std=5,
... )
remove_static_background(operation='subtract', relative=True, static_bg=None, scale_bg=False)[source]

Remove the static background in an EBSD scan 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 True.

• static_bg (Union[None, ndarray, Array]) – Static background pattern. If None is passed (default) we try to read it from the signal metadata.

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

Examples

We assume that a static background pattern with 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()
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 while keeping relative intensities between patterns (or not):

>>> s.remove_static_background(
...     operation='subtract', relative=True
... )

If the metadata has no background pattern, 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
• relative (bool) – Whether to keep relative intensities between images (default is False). If True, in_range must be None, because in_range is in this case set to the global min./max. intensity.

• in_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of input images. If None (default), in_range is set to pattern min./max intensity. Contrast stretching is performed when in_range is set to a narrower intensity range than the input patterns. Must be None if relative is True or percentiles are passed.

• out_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of output images. If None (default), out_range is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of rescaled images, default is input images’ data type.

• percentiles (Union[None, Tuple[int, int], Tuple[float, float]]) – Disregard intensities outside these percentiles. Calculated per image. Must be None if in_range or relative is passed. Default is None.

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.

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()
-5.64
>>> s.set_experimental_parameters(xpc=0.50726)
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()
├── 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
...     }}
... )
├── 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
• step_x (Union[int, float]) – Scan step size in um per pixel in horizontal direction.

• step_y (Union[int, float]) – Scan step size in um per pixel in vertical direction.

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 xmap: orix.crystal_map.crystal_map.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.

Returns

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
• components (Union[None, int, List[int]]) – If None (default), rebuilds the signal from all components. If int, rebuilds signal from components in range 0-given int. If list of ints, rebuilds signal from only components in given list.

• dtype_learn (dtype) – Data type to set learning results to (default is numpy.float32) before multiplication.

• mbytes_chunk (int) – Size of learning results chunks in MB, default is 100 MB as suggested in the Dask documentation.

• dir_out (Optional[str]) – Directory to place output signal in.

• fname_out (Optional[str]) – Name of output signal file.

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. rescale_intensity([relative, in_range, …]) Rescale image intensities inplace.
class kikuchipy.signals.EBSDMasterPattern(*args, **kwargs)[source]

Bases: kikuchipy.signals._common_image.CommonImage, hyperspy._signals.signal2d.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: “north”, “south” or “both”.

Type

str

phase

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

Type

orix.crystal_map.phase_list.Phase

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.

copy()

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 northern and southern 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.

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
• relative (bool) – Whether to keep relative intensities between images (default is False). If True, in_range must be None, because in_range is in this case set to the global min./max. intensity.

• in_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of input images. If None (default), in_range is set to pattern min./max intensity. Contrast stretching is performed when in_range is set to a narrower intensity range than the input patterns. Must be None if relative is True or percentiles are passed.

• out_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of output images. If None (default), out_range is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of rescaled images, default is input images’ data type.

• percentiles (Union[None, Tuple[int, int], Tuple[float, float]]) – Disregard intensities outside these percentiles. Calculated per image. Must be None if in_range or relative is passed. Default is None.

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
• relative (bool) – Whether to keep relative intensities between images (default is False). If True, in_range must be None, because in_range is in this case set to the global min./max. intensity.

• in_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of input images. If None (default), in_range is set to pattern min./max intensity. Contrast stretching is performed when in_range is set to a narrower intensity range than the input patterns. Must be None if relative is True or percentiles are passed.

• out_range (Union[None, Tuple[int, int], Tuple[float, float]]) – Min./max. intensity of output images. If None (default), out_range is set to dtype_out min./max according to skimage.util.dtype.dtype_range.

• dtype_out (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – Data type of rescaled images, default is input images’ data type.

• percentiles (Union[None, Tuple[int, int], Tuple[float, float]]) – Disregard intensities outside these percentiles. Calculated per image. Must be None if in_range or relative is passed. Default is None.

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.

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
• signal (kikuchipy.signals.EBSD, kikuchipy.signals.LazyEBSD or None) – If None (default), the following must be passed: data shape to be chunked data_shape, the number of navigation dimensions nav_dim, the number of signal dimensions sig_dim and the data array data type dtype.

• data_shape (Optional[tuple]) – Data shape, must be passed if signal is None.

• nav_dim (Optional[int]) – Number of navigation dimensions, must be passed if signal is None.

• sig_dim (Optional[int]) – Number of signal dimensions, must be passed if signal is None.

• chunk_shape (Optional[int]) – Shape of navigation chunks. If None (default), this size is set automatically based on chunk_bytes. This is a square if signal has two navigation dimensions.

• chunk_bytes (Union[int, float, str, None]) – Number of bytes in each chunk. Default is 30e6, i.e. 30 MB. Only used if freedom is given to choose, i.e. if chunk_shape is None. Various parameter types are allowed, e.g. 30000000, “30 MB”, “30MiB”, or the default 30e6, all resulting in approximately 30 MB chunks.

• dtype (Union[None, dtype, type]) – Data type of the array to chunk. Will take precedent over the signal data type if signal is passed. Must be passed if signal is None.

Returns

Return type

chunks

Return dask array of patterns with appropriate chunking.

Parameters
• signal (EBSD or LazyEBSD) – Signal with data to return dask array from.

• dtype (Optional[type]) – Data type of returned dask array. This is also passed on to get_chunking().

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

Returns

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

Return type

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.

 GeometricalEBSDSimulation(detector, …) Geometrical EBSD simulation with Kikuchi bands and zone axes. features Kikuchi bands and zone axes used in geometrical EBSD simulations.

### GeometricalEBSDSimulation¶

 as_markers([bands, zone_axes, …]) Return a list of all or some of the simulation markers. bands_as_markers([family_colors]) Return a list of Kikuchi band line segment markers. pc_as_markers(**kwargs) Return a list of projection center point markers. zone_axes_as_markers(**kwargs) Return a list of zone axes point markers. zone_axes_labels_as_markers(**kwargs) Return a list of zone axes label text markers.
class kikuchipy.simulations.GeometricalEBSDSimulation(detector, rotations, bands, zone_axes)[source]

Bases: object

Geometrical EBSD simulation with Kikuchi bands and zone axes.

__init__(detector, rotations, bands, zone_axes)[source]

Create a geometrical EBSD simulation storing a set of center positions of Kikuchi bands and zone axes on the detector, one set for each orientation of the unit cell.

Parameters
• detector (EBSDDetector) – An EBSD detector with a shape, pixel size, binning, and projection center(s) (PC(s)).

• rotations (Rotation) – Orientations of the unit cell.

• bands (KikuchiBand) – Kikuchi bands projected onto the detector. Default is None.

• zone_axes (ZoneAxis) – Zone axes projected onto the detector. Default is None.

Returns

Return type

GeometricalEBSDSimulation

as_markers(bands=True, zone_axes=True, zone_axes_labels=True, pc=True, bands_kwargs=None, zone_axes_kwargs=None, zone_axes_labels_kwargs=None, pc_kwargs=None)[source]

Return a list of all or some of the simulation markers.

Parameters
Returns

markers – List with all markers.

Return type

hyperspy.drawing.marker.MarkerBase

bands_as_markers(family_colors=None, **kwargs)[source]

Return a list of Kikuchi band line segment markers.

Parameters
• family_colors (Optional[List[str]]) – A list of at least as many colors as unique HKL families, either as RGB iterables or colors recognizable by Matplotlib, used to color each unique family of bands. If None (default), this is determined from a list similar to the one used in EDAX TSL’s software.

• kwargs – Keyword arguments passed to get_line_segment_list().

Returns

List with line segment markers.

Return type

list

property bands_detector_coordinates: numpy.ndarray

Start and end point coordinates of bands in uncalibrated detector coordinates (a scale of 1 and offset of 0).

Returns

band_coords_detector – Band coordinates (y0, x0, y1, x1) on the detector.

Return type

numpy.ndarray

exclude_outside_detector = True
pc_as_markers(**kwargs)[source]

Return a list of projection center point markers.

Parameters

kwargs – Keyword arguments passed to get_point_list().

Returns

List of point markers.

Return type

list

zone_axes_as_markers(**kwargs)[source]

Return a list of zone axes point markers.

Parameters

kwargs – Keyword arguments passed to get_point_list().

Returns

List with point markers.

Return type

list

property zone_axes_detector_coordinates: numpy.ndarray

Coordinates of zone axes in uncalibrated detector coordinates (a scale of 1 and offset of 0).

If GeometricalEBSDSimulation.exclude_outside_detector is True, the coordinates of the zone axes outside the detector are set to np.nan.

Returns

za_coords – Zone axis coordinates (x, y) on the detector.

Return type

numpy.ndarray

property zone_axes_label_detector_coordinates: numpy.ndarray

Coordinates of zone axes labels in uncalibrated detector coordinates (a scale of 1 and offset of 0).

Returns

za_coords – Zone axes labels (x, y) placed just above the zone axes on the detector.

Return type

numpy.ndarray

zone_axes_labels_as_markers(**kwargs)[source]

Return a list of zone axes label text markers.

Parameters

kwargs – Keyword arguments passed to get_text_list().

Returns

List of text markers.

Return type

list

property zone_axes_within_gnomonic_bounds: numpy.ndarray

Return a boolean array with True for the zone axes within the detector’s gnomonic bounds.

Returns

within_gnomonic_bounds – Boolean array with True for zone axes within the detector’s gnomonic bounds.

Return type

numpy.ndarray

### features¶

Kikuchi bands and zone axes used in geometrical EBSD simulations.

 KikuchiBand(phase, hkl, hkl_detector, in_pattern) Kikuchi bands used in geometrical EBSD simulations. ZoneAxis(phase, uvw, uvw_detector, in_pattern) Zone axes used in geometrical EBSD simulations.

#### KikuchiBand¶

class kikuchipy.simulations.features.KikuchiBand(phase, hkl, hkl_detector, in_pattern, gnomonic_radius=10)[source]

Kikuchi bands used in geometrical EBSD simulations.

Center positions of Kikuchi bands on the detector for n simulated patterns.

This class extends the ReciprocalLatticePoint class with EBSD detector pixel and gnomonic coordinates for each band (or point).

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

• hkl (Union[Vector3d, ndarray, tuple]) – All Miller indices present in any of the n patterns.

• hkl_detector (Union[Vector3d, ndarray, list, tuple]) – Detector coordinates for all Miller indices per pattern, in the shape navigation_shape + (n_hkl, 3).

• in_pattern (Union[ndarray, list, tuple]) – Boolean array of shape navigation_shape + (n_hkl,) indicating whether an hkl is visible in a pattern.

• gnomonic_radius (Union[float, ndarray]) – Only plane trace coordinates of bands with Hesse normal form distances below this radius is returned when called for.

Examples

This class is ment to be part of a GeometricalEBSDSimulation generated from an EBSDSimulationGenerator object. However, a KikuchiBand object with no navigation shape and two bands can be created in the following way:

>>> import numpy as np
>>> from orix.crystal_map import Phase
>>> from kikuchipy.simulations.features import KikuchiBand
>>> p = Phase(name="ni", space_group=225)
>>> p.structure.lattice.setLatPar(3.52, 3.52, 3.52, 90, 90, 90)
>>> bands = KikuchiBand(
...     phase=p,
...     hkl=np.array([[-1, 1, 1], [-2, 0, 0]]),
...     hkl_detector=np.array(
...         [[0.26, 0.32, 0.26], [-0.21, 0.45, 0.27]]
...     ),
...     in_pattern=np.ones(2, dtype=bool),
... )
>>> bands
KikuchiBand (|2)
Phase: ni (m-3m)
[[-1  1  1]
[-2  0  0]]
__getitem__(key)[source]

Get a deepcopy subset of the KikuchiBand object.

Properties have different shapes, so care must be taken when slicing. As an example, consider a 2 x 3 map with 4 bands. Three data shapes are considered: * navigation shape (2, 3) (gnomonic_radius) * band shape (4,) (hkl, structure_factor, theta) * full shape (2, 3, 4) (hkl_detector, in_pattern)

Only plane trace coordinates of bands with Hesse normal form distances below this radius are returned when called for. Per navigation point.

Return type

ndarray

property hesse_alpha: numpy.ndarray

Hesse angle alpha. Only angles for the planes within the gnomonic_radius are returned.

Return type

ndarray

property hesse_distance: numpy.ndarray

Distance from the PC (origin) per band, i.e. the right-angle component of the distance to the pole.

Return type

ndarray

property hesse_line_x: numpy.ndarray
Return type

ndarray

property hesse_line_y: numpy.ndarray
Return type

ndarray

property hkl_detector: orix.vector.vector3d.Vector3d

Detector coordinates for all bands per pattern.

Return type

Vector3d

property in_pattern: numpy.ndarray

Which bands are visible in which patterns.

Return type

ndarray

Number of navigation dimensions (a maximum of 2).

Return type

int

Return type

tuple

property plane_trace_coordinates: numpy.ndarray

Plane trace coordinates P1, P2 on the form [y0, x0, y1, x1] per band in the plane of the detector in gnomonic coordinates.

Coordinates for the planes outside the gnomonic_radius are set to NaN.

Return type

ndarray

Return whether a plane trace is within the gnomonic_radius as a boolean array.

Return type

ndarray

property x_detector: numpy.ndarray

X detector coordinate for all bands per pattern.

Return type

ndarray

property x_gnomonic: numpy.ndarray

X coordinate in the gnomonic projection plane on the detector for all bands per pattern.

Return type

ndarray

property y_detector: numpy.ndarray

Y detector coordinate for all bands per pattern.

Return type

ndarray

property y_gnomonic: numpy.ndarray

Y coordinate in the gnomonic projection plane on the detector for all bands per pattern.

Return type

ndarray

property z_detector: numpy.ndarray

Z detector coordinate for all bands per pattern.

Return type

ndarray

#### ZoneAxis¶

class kikuchipy.simulations.features.ZoneAxis(phase, uvw, uvw_detector, in_pattern, gnomonic_radius=10)[source]

Zone axes used in geometrical EBSD simulations.

Positions of zone axes on the detector.

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

• uvw (Union[Vector3d, ndarray, list, tuple]) – Miller indices.

• uvw_detector (Union[Vector3d, ndarray, list, tuple]) – Zone axes coordinates on the detector.

• in_pattern (Union[ndarray, list, tuple]) – Boolean array of shape (n, n_hkl) indicating whether an hkl is visible in a pattern.

• gnomonic_radius (Union[float, ndarray]) – Only plane trace coordinates of bands with Hesse normal form distances below this radius is returned when called for.

__getitem__(key)[source]

Get a deepcopy subset of the ZoneAxis object.

Properties have different shapes, so care must be taken when slicing. As an example, consider a 2 x 3 map with 4 zone axes. Three data shapes are considered: * navigation shape (2, 3) (gnomonic_radius) * zone axes shape (4,) (hkl, structure_factor, theta) * full shape (2, 3, 4) (uvw_detector, in_pattern)

Only zone axes within this distance from the PC are returned when called for. Per navigation point.

Return type

ndarray

property in_pattern: numpy.ndarray

Which bands are visible in which patterns.

Return type

ndarray

Number of navigation dimensions (a maximum of 2).

Return type

int

Return type

tuple

property r_gnomonic: numpy.ndarray

Gnomonic radius for all zone axes per pattern.

Return type

ndarray

property uvw_detector: orix.vector.vector3d.Vector3d

Detector coordinates for all zone axes per pattern.

Return type

Vector3d

Return whether a zone axis is within the gnomonic_radius as a boolean array.

Return type

ndarray

property x_detector: numpy.ndarray

X detector coordinate for all zone axes per pattern.

Return type

ndarray

property x_gnomonic: numpy.ndarray

X coordinate in the gnomonic projection plane on the detector for all zone axes per pattern.

Return type

ndarray

property y_detector: numpy.ndarray

Y detector coordinate for all zone axes per pattern.

Return type

ndarray

property y_gnomonic: numpy.ndarray

X coordinate in the gnomonic projection plane on the detector for all zone axes per pattern.

Return type

ndarray

property z_detector: numpy.ndarray

Z detector coordinate for all zone axes per pattern.

Return type

ndarray