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 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 comparison to simulated patterns.

io

Read and write signals from and to file.

load(filename[, lazy])

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

pattern

Single and chunk pattern processing used by signals.

projections

Various projections and transformations relevant to EBSD.

signals

Experimental and simulated diffraction patterns and virtual backscatter electron images.

simulations

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


crystallography

Crystallographic computations not found (easily) elsewhere.

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.

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.

nickel_ebsd_master_pattern_small(**kwargs)

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

Test data.

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

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

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

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

Parameters

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.

EBSDDetector

plot([coordinates, show_pc, pc_kwargs, …])

Plot the detector screen.

class kikuchipy.detectors.ebsd_detector.EBSDDetector(shape=(1, 1), px_size=1, binning=1, tilt=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 [Britton2016].

References

Britton2016(1,2,3)

T. B. Britton, J. Jiang, Y. Guo, A. Vilalta-Clemente, D. Wallis, L. N. Hansen, A. Winkelmann, A. J. Wilkinson, “Tutorial: Crystal orientations and EBSD - Or which way is up?,” Materials Characterization 117 (2016), doi: https://doi.org/10.1016/j.matchar.2016.04.008.

__init__(shape=(1, 1), px_size=1, binning=1, tilt=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 [JPDeGraef19].

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.

  • 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

>>> from kikuchipy.detectors import EBSDDetector
>>> det = EBSDDetector(
...     shape=(60, 60),
...     pc=np.ones((149, 200)) * [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 0, pc
 (0.421, 0.221, 0.505)
>>> det.navigation_shape  # (nrows, ncols)
(149, 200)
>>> det.bounds
array([ 0, 60,  0, 60])
>>> det.gnomonic_bounds
array([-0.83366337,  1.14653465, -1.54257426,  0.43762376])
>>> det.plot()
property aspect_ratio

Number of detector rows divided by columns.

Return type

float

property bounds

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

Return type

ndarray

deepcopy()[source]

Return a deep copy using copy.deepcopy().

property gnomonic_bounds

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

Return type

ndarray

property height

Detector height in microns.

Return type

float

property navigation_dimension

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

Return type

int

property navigation_shape

Navigation shape of the projection center array.

Return type

tuple

property ncols

Number of detector pixel columns.

Return type

int

property nrows

Number of detector pixel rows.

Return type

int

property pc

All projection center coordinates.

Return type

ndarray

property pc_average

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

Return type

ndarray

pc_emsoft(version=5)[source]

Return PC in the EMsoft convention.

PC conversions are calculated as presented in [JPDeGraef19].

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

Return type

ndarray

pc_tsl()[source]

Return PC in the EDAX TSL convention.

PC conversions are calculated as presented in [JPDeGraef19]..

Return type

ndarray

property pcx

Projection center x coordinates.

Return type

ndarray

property pcy

Projection center y coordinates.

Return type

ndarray

property pcz

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 [Britton2016] 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)) * [0.421, 0.779, 0.505],
...     convention="tsl",
...     pixel_size=70,
...     binning=8,
...     tilt=5,
...     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

Binned pixel size in microns.

Return type

float

property r_max

Maximum distance from PC to detector edge in gnomonic coordinates.

property size

Number of detector pixels.

Return type

int

property specimen_scintillator_distance

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

Return type

float

property unbinned_shape

Unbinned detector shape in pixels.

Return type

Tuple[int, int]

property width

Detector width in microns.

Return type

float

property x_max

Right bound of detector in gnomonic coordinates.

Return type

Union[ndarray, float]

property x_min

Left bound of detector in gnomonic coordinates.

Return type

Union[ndarray, float]

property x_range

X detector limits in gnomonic coordinates.

Return type

ndarray

property x_scale

Width of a pixel in gnomonic coordinates.

Return type

ndarray

property y_max

Bottom bound of detector in gnomonic coordinates.

Return type

Union[ndarray, float]

property y_min

Top bound of detector in gnomonic coordinates.

Return type

Union[ndarray, float]

property y_range

The y detector limits in gnomonic coordinates.

Return type

ndarray

property y_scale

Height of a pixel in gnomonic coordinates.

Return type

ndarray


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.window.distance_to_origin(shape, origin=None)[source]

Return the distance to the window origin in pixels.

Parameters
Return type

ndarray

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

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

Used in [Wilkinson2006].

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 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.window.lowpass_fft_filter(shape, cutoff, cutoff_width=None)[source]

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

Used in [Wilkinson2006].

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 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 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.window.modified_hann(Nx)[source]

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

Used in [Wilkinson2006].

Parameters

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

Returns

w – 1D Hann window.

Return type

numpy.ndarray

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.

References

Wilkinson2006(1,2,3)

A. J. Wilkinson, G. Meaden, D. J. Dingley, “High resolution mapping of strains and rotations using electron backscatter diffraction,” Materials Science and Technology 22(11), (2006), doi: https://doi.org/10.1179/174328406X130966.

Examples

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

Make window circular.

plot([grid, show_values, cmap, textcolors, …])

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(window: Union[None, str, numpy.ndarray, dask.array.core.Array] = 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 – Keyword arguments passed to the window type. If none are passed, the default values of that particular window are used.

Examples

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

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.77880078, 0.8824969 , 0.77880078]
 [0.8824969 , 1.        , 0.8824969 ]
 [0.77880078, 0.8824969 , 0.77880078]]
__init__()

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

circular: bool = False
property distance_to_origin

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.

name: str = None
property origin

Window origin.

Return type

tuple

plot(grid=True, show_values=True, cmap='viridis', textcolors=None, cmap_label='Value')[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.

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

  • 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_label (str) – Color map label. Default is “Value”.

Return type

Tuple[Figure, AxesImage, Colorbar]

Returns

  • fig

  • image

  • colorbar

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

>>> figure, image, colorbar = w.plot(
...     cmap="inferno", grid=True, show_values=True)
>>> figure.savefig('my_kernel.png')
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.

virtual_bse_generator.normalize_image(image)

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

geometrical_simulation([…])

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.crystal_map import Phase
>>> from orix.quaternion import Rotation
>>> from kikuchipy.detectors import EBSDDetector
>>> from kikuchipy.generators import EBSDSimulationGenerator
>>> det = EBSDDetector(
...     shape=(60, 60), sample_tilt=70, pc=[0.5,] * 3
... )
>>> p = Phase(name="ni", space_group=225)
>>> p.structure.lattice.setLatPar(3.52, 3.52, 3.52, 90, 90, 90)
>>> simgen = EBSDSimulationGenerator(
...     detector=det,
...     phase=p,
...     rotations=Rotation.from_euler([90, 45, 90])
... )
>>> simgen
EBSDSimulationGenerator (1,)
EBSDDetector (60, 60), px_size 1 um, binning 1, tilt 0, pc
(0.5, 0.5, 0.5)
<name: . space group: None. point group: None. proper point
group: None. 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
>>> simgen
EBSDSimulationGenerator (1,)
EBSDDetector (60, 60), px_size 1 um, binning 1, tilt 0, pc
(0.5, 0.5, 0.5)
<name: . space group: None. point group: None. proper point
group: None. color: tab:blue>
Rotation (1,)
>>> sim1 = simgen.geometrical_simulation()
>>> sim1.bands.size
94
>>> rlp = ReciprocalLatticePoint(
...     phase=simgen.phase, hkl=[[1, 1, 1], [2, 0, 0]]
... )
>>> sim2 = simgen.geometrical_simulation()
>>> sim2.bands.size
13
property navigation_dimension

Number of navigation dimensions (a maximum of 2).

Return type

int

property navigation_shape

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

Return type

tuple

property rotations

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

>>> s
<EBSD, title: Pattern, dimensions: (200, 149|60, 60)>
>>> vbse_gen = VirtualBSEGenerator(s)
>>> vbse_gen.grid_shape = (5, 5)
>>> vbse = vbse_gen.get_images_from_grid()
>>> vbse
<VirtualBSEImage, title: , dimensions: (5, 5|200, 149)>
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

Return detector grid columns, defined by grid_shape.

Return type

ndarray

property grid_rows

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

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

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

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

Adapted from the aloe/xcdskd package.

Parameters
  • 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 comparison to simulated patterns.

The EBSD method match_patterns() uses these tools for pattern matching.

StaticPatternMatching(dictionaries)

Pattern matching of experimental patterns to simulated patterns, of known crystal orientations in pre-computed dictionaries [CPW+15][JPDeGraef19], for phase and orientation determination.

orientation_similarity_map(xmap[, n_best, …])

Compute an orientation similarity map following [MDeGraefS+17], where the ranked list of the array 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 gray-tone patterns.

class kikuchipy.indexing.StaticPatternMatching(dictionaries)[source]

Bases: object

Pattern matching of experimental patterns to simulated patterns, of known crystal orientations in pre-computed dictionaries [CPW+15][JPDeGraef19], for phase and orientation determination.

__init__(dictionaries)[source]

Set up pattern matching with one or more dictionaries of pre-computed simulated patterns of known crystal orientations.

Parameters

dictionaries (EBSD or list of EBSD) – Dictionaries as EBSD signals with a 1D navigation axis and the xmap property with known crystal orientations set.

__call__(signal, metric='ncc', keep_n=50, n_slices=1, return_merged_crystal_map=False, get_orientation_similarity_map=False)[source]

Match each experimental pattern to all simulated patterns, of known crystal orientations in pre-computed dictionaries [CPW+15][JPDeGraef19], to determine their phase and orientation.

A suitable similarity metric, the normalized cross-correlation (ncc()), is used by default, but a valid user-defined similarity metric may be used instead.

CrystalMap’s for each dictionary with “scores” and “simulation_indices” as properties are returned.

Parameters
  • signal (EBSD) – EBSD signal with experimental patterns.

  • metric (str or SimilarityMetric, optional) – Similarity metric, by default “ncc” (normalized cross-correlation).

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

  • n_slices (int, optional) – Number of simulation slices to process sequentially, by default 1 (no slicing).

  • return_merged_crystal_map (bool, optional) – Whether to return a merged crystal map, the best matches determined from the similarity scores, in addition to the single phase maps. By default False.

  • get_orientation_similarity_map (bool, optional) – Add orientation similarity maps to the returned crystal maps’ properties named “osm”. By default False.

Returns

xmaps – A crystal map for each dictionary loaded and one merged map if return_merged_crystal_map = True.

Return type

CrystalMap or list of CrystalMap

Notes

Merging of crystal maps and calculations of orientation similarity maps can be done afterwards with merge_crystal_maps() and orientation_similarity_map(), respectively.

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

Compute an orientation similarity map following [MDeGraefS+17], where the ranked list of the array 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 (int, optional) – Number of ranked indices to compare. If None (default), all indices are compared.

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

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

  • from_n_best (int, optional) – 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 (numpy.ndarray, optional) – Boolean 2D array specifying which neighbouring points to compare lists with, by default the four nearest neighbours.

  • center_index (int, optional) – 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

numpy.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).\]
kikuchipy.indexing.merge_crystal_maps(crystal_maps, mean_n_best=1, metric=None, simulation_indices_prop='simulation_indices', scores_prop='scores')[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 there are at least as many simulation indices as scores per point, and that all maps have the same number of rotations, scores and simulation indices per point.

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

  • mean_n_best (int, optional) – Number of best metric results to take the mean of before comparing. Default is 1.

  • metric (str or SimilarityMetric, optional) – Similarity metric, default is None.

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

  • scores_prop (str, optional) – Name of scores array in the crystal maps’ properties. Default is “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 simulation indices and scores, merge sorted, are added to its properties with names equal to whatever passed to scores_prop and simulation_indices_prop with “merged” as a suffix, respectively.

Return type

CrystalMap

Notes

mean_n_best can be given with a negative sign if metric is not given, in order to choose the lowest valued metric results.

similarity_metrics

make_similarity_metric(metric_func[, …])

Make a similarity metric for comparing gray-tone patterns of equal size.

MetricScope(value)

Describes the input parameters for a similarity metric.

ncc

A similarity metric for calculation of the normalized cross-correlation coefficient (NCC) r [Gos12] between experimental and simulated patterns.

ndp

A similarity metric for calculation of the normalized dot product (NDP) \(\rho\) [CPW+15] between experimental and simulated patterns.

Similarity metrics for comparing gray-tone patterns.

class kikuchipy.indexing.similarity_metrics.FlatSimilarityMetric(metric_func, sign, scope, flat, make_compatible_to_lower_scopes, dtype_out=<class 'numpy.float32'>)[source]

Bases: kikuchipy.indexing.similarity_metrics.SimilarityMetric

Similarity metric between 2D gray-tone images where the navigation and signal axes are flattened before sent to metric_func.

class kikuchipy.indexing.similarity_metrics.MetricScope(value)[source]

Bases: enum.Enum

Describes the input parameters for a similarity metric. See make_similarity_metric().

MANY_TO_MANY = 'many_to_many'[source]
MANY_TO_ONE = 'many_to_one'[source]
ONE_TO_MANY = 'one_to_many'[source]
ONE_TO_ONE = 'one_to_one'[source]
SOME_TO_MANY = 'some_to_many'[source]
SOME_TO_ONE = 'some_to_one'[source]
class kikuchipy.indexing.similarity_metrics.SimilarityMetric(metric_func, sign, scope, flat, make_compatible_to_lower_scopes, dtype_out=<class 'numpy.float32'>)[source]

Bases: object

Similarity metric between 2D gray-tone patterns.

kikuchipy.indexing.similarity_metrics.make_similarity_metric(metric_func, greater_is_better=True, scope=<MetricScope.MANY_TO_MANY: 'many_to_many'>, flat=False, make_compatible_to_lower_scopes=False, dtype_out=<class 'numpy.float32'>)[source]

Make a similarity metric for comparing gray-tone patterns of equal size.

This factory function wraps metric functions for use in match_patterns() (which uses StaticPatternMatching).

Parameters
  • metric_func (Callable) – Metric function with signature metric_func(experimental, simulated), which computes the similarity or a distance matrix between experimental and simulated pattern(s)).

  • greater_is_better (bool, optional) – Whether greater values correspond to more similar patterns, by default True. Used for choosing keep_n metric results in pattern_match.

  • scope (MetricScope, optional) – Describes the shapes of the metric_func’s input parameters experimental and simulated, by default MetricScope.MANY_TO_MANY.

  • flat (bool, optional) – Whether experimental and simulated patterns are to be flattened before sent to metric_func when the similarity metric is called, by default False.

  • make_compatible_to_lower_scopes (bool, optional) – Whether to reshape experimental and simulated data by adding single dimensions to match the given scope, by default False.

  • dtype_out (numpy.dtype, optional) – The data type used and returned by the metric, by default numpy.float32.

Returns

metric_class – A callable class instance computing a similarity matrix with signature metric_func(experimental, simulated).

Return type

SimilarityMetric or FlatSimilarityMetric

Notes

The metric function must take the arrays experimental and simulated as arguments, in that order. The scope and whether the metric is flat defines the intended data shapes. In the following table, (ny, nx) and (sy, sx) correspond to the navigation and signal shapes (row, column), respectively, with N number of simulations:

MetricScope

flat = False

flat = True

experimental

simulated

returns

experimental

simulated

returns

MANY_TO_MANY

(ny,nx,sy,sx)

(N,sy,sx)

(ny,nx,N)

(ny*nx,sy*sx)

(N,sy*sx)

(ny*nx,N)

SOME_TO_MANY

(nx,sy,sx)

(N,sy,sx)

(nx,N)

ONE_TO_MANY

(sy,sx)

(N,sy,sx)

(N,)

(sy*sx,)

(N,sy*sx)

(N,)

MANY_TO_ONE

(ny,nx,sy,sx)

(sy,sx)

(ny,nx)

(ny*nx,sy*sx)

(sy*sx,)

(ny*nx)

SOME_TO_ONE

(nx,sy,sx)

(sy,sx)

(nx,)

ONE_TO_ONE

(sy,sx)

(sy,sx)

(1,)

(sy*sx,)

(sy*sx,)

(1,)

If a scope of SOME_TO_MANY or SOME_TO_ONE and flat=True is desired, the returned similarity metric has the scope MANY_TO_MANY or MANY_TO_ONE, respectively.

kikuchipy.indexing.similarity_metrics.ncc(experimental: Union[numpy.ndarray, dask.array.core.Array], simulated: Union[numpy.ndarray, dask.array.core.Array]) → Union[numpy.ndarray, dask.array.core.Array][source]

A similarity metric for calculation of the normalized cross-correlation coefficient (NCC) r [Gos12] between experimental and simulated patterns.

Parameters
Returns

r – Correlation coefficients in range [-1, 1] for all comparisons, as numpy.ndarray if both experimental and simulated are numpy.ndarray, else dask.array.Array.

Return type

numpy.ndarray or dask.array.Array

Notes

The NCC, or Pearson Correlation Coefficient, is defined as

\[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.

kikuchipy.indexing.similarity_metrics.ndp(experimental: Union[numpy.ndarray, dask.array.core.Array], simulated: Union[numpy.ndarray, dask.array.core.Array]) → Union[numpy.ndarray, dask.array.core.Array][source]

A similarity metric for calculation of the normalized dot product (NDP) \(\rho\) [CPW+15] between experimental and simulated patterns.

Parameters
Returns

rho – Normalized dot products in range [0, 1] for all comparisons, as numpy.ndarray if both experimental and simulated are numpy.ndarray, else dask.array.Array.

Return type

numpy.ndarray or dask.array.Array

Notes

The NDP is defined as

\[\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}\).


io

Read and write signals from and to file.

_io.load(filename[, lazy])

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

plugins

Input/output plugins.

kikuchipy.io._io.load(filename, lazy=False, **kwargs)[source]

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

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

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

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

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

Examples

>>> import kikuchipy as kp
>>> s = kp.load("patterns.h5")
>>> s
<EBSD, title: , dimensions: (10, 20|60, 60)>

plugins

Input/output plugins.

h5ebsd

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

nordif

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

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.

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

h5ebsd

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

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

Return scan metadata dictionaries from a Bruker h5ebsd file.

Parameters
Return type

Tuple[DictionaryTreeBrowser, DictionaryTreeBrowser, DictionaryTreeBrowser]

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.

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

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

Tuple[DictionaryTreeBrowser, DictionaryTreeBrowser, DictionaryTreeBrowser]

Returns

  • md – kikuchipy metadata elements available in EDAX file.

  • omd – All metadata available in EDAX file.

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

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

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

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

scan_dict_list – Data, axes, metadata and original metadata.

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.

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

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

Only writing to kikuchipy’s h5ebsd format is supported.

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

scan – Dictionary with patterns, metadata and original_metadata.

Return type

dict

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

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

Parameters
  • scan_group (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

Tuple[DictionaryTreeBrowser, DictionaryTreeBrowser, DictionaryTreeBrowser]

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

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

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

Tuple[DictionaryTreeBrowser, DictionaryTreeBrowser, DictionaryTreeBrowser]

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

scan – Data, axes, metadata and original metadata.

Return type

list of dicts

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

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

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

Return metadata with parameters from NORDIF setting file.

Parameters

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

Return type

Tuple[DictionaryTreeBrowser, DictionaryTreeBrowser, DictionaryTreeBrowser]

Returns

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

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

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

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

Get relevant part of string using regular expression.

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

emsoft_ebsd

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

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

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

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

signal_dict_list – Data, axes, metadata and original metadata.

Return type

list of dicts

emsoft_ebsd_master_pattern

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

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

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

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 “spherical” (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

signal_dict_list – Data, axes, metadata and original metadata.

Return type

list of dicts


pattern

Single and chunk pattern processing used by signals.

chunk

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

correlate

Compute similarities between 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 numpy.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, 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 (Optional[dtype]) – 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 numpy.ndarray or dask.array.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.

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

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

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

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

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 (Union[None, dtype, Tuple[int, int], Tuple[float, float]]) – 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

See also

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


correlate

Compute similarities between EBSD patterns.

kikuchipy.pattern.correlate.normalized_correlation_coefficient(pattern, template, zero_normalised=True)[source]

Calculate the normalized or zero-normalized correlation coefficient between a pattern and a template following [Gonzalez2017].

Parameters
  • pattern (Union[ndarray, Array]) – Pattern to compare the template to.

  • template (Union[ndarray, Array]) – Template image.

  • zero_normalised (bool) – Subtract local mean value of intensities. Default is True.

Returns

coefficient – Correlation coefficient in range [-1, 1] if zero normalised, otherwise [0, 1].

Return type

float

References

Gonzalez2017
    1. Gonzalez, R. E. Woods, “Digital Image Processing,” 4th edition, Pearson Education Limited, 2017.


projections

Various projections and transformations relevant to EBSD.

ebsd_projections

Rotations to align the EBSD detector with the tilted sample.

hesse_normal_form.HesseNormalForm()

Hessian normal form of a plane given by polar coordinates.

spherical_projection.SphericalProjection()

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

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

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.

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

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

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

  • radius (Optional[float]) – Hesse radius. Default is 10.

Returns

Hesse normal form coordinates distance and angle.

Return type

hesse

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

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

Parameters
  • polar (ndarray) – Spherical coordinates theta, phi, r.

  • radius (Optional[float]) – Hesse radius. Default is 10.

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

classmethod project(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.project(v)
>>> np.allclose(np.arccos(v[: 2] / r), theta)
True
>>> np.allclose(np.arctan2(v[:, 1], v[:, 2]), phi)
True
spherical_region = SphericalRegion (1,) [[0 0 1]]

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, mostly for handling signal metadata and attributes.

EBSD

All methods listed here are also available to LazyEBSD objects.

adaptive_histogram_equalization([…])

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.

match_patterns(simulations[, metric, …])

Match each experimental pattern to all simulated patterns, of known crystal orientations in pre-computed dictionaries [CPW+15][JPDeGraef19], to determine their phase and orientation.

fft_filter(transfer_function, function_domain)

Filter an EBSD scan inplace in the frequency domain.

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

rebin([new_shape, scale, crop, out])

Rebin the signal into a smaller or larger shape, based on linear interpolation.

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

Set experimental parameters in signal metadata.

set_phase_parameters([number, …])

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.

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

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

This method uses skimage.exposure.equalize_adapthist().

Parameters
  • 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
>>> s2 = s.inav[0, 0]
>>> s2.adaptive_histogram_equalization()
>>> imin = np.iinfo(s.data.dtype_out).min
>>> imax = np.iinfo(s.data.dtype_out).max + 1
>>> hist, _ = np.histogram(
...     s.inav[0, 0].data, bins=imax, range=(imin, imax))
>>> hist2, _ = np.histogram(
...     s2.inav[0, 0].data, bins=imax, range=(imin, imax))
>>> 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.inav[0, 0].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 image 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.

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.

Examples

>>> import numpy as np
>>> import kikuchipy as kp
>>> s = kp.signals.EBSD(np.ones((4, 4, 1, 1)))
>>> k = 1
>>> for i in range(4):
...     for j in range(4):
...         s.inav[j, i].data *= k
...         k += 1
>>> s.data[:, :, 0, 0]
array([[ 1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.],
       [ 9., 10., 11., 12.],
       [13., 14., 15., 16.]])
>>> s2 = s.deepcopy()  # For use below
>>> s.average_neighbour_patterns(
...     window="circular", shape=(3, 3))
>>> s.data[:, :, 0, 0]
array([[ 2.66666667,  3.        ,  4.        ,  5.        ],
       [ 5.25      ,  6.        ,  7.        ,  7.75      ],
       [ 9.25      , 10.        , 11.        , 11.75      ],
       [12.        , 13.        , 14.        , 14.33333333]])

A window object can also be passed

>>> 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]]
>>> s2.average_neighbour_patterns(w)
>>> s2.data[:, :, 0, 0]
array([[ 3.34395304,  3.87516243,  4.87516264,  5.40637176],
       [ 5.46879047,  5.99999985,  6.99999991,  7.53120901],
       [ 9.46879095,  9.99999959, 11.00000015, 11.53120913],
       [11.59362845, 12.12483732, 13.1248368 , 13.65604717]])

This window can subsequently be plotted and saved

>>> figure, image, colorbar = w.plot()
>>> figure.savefig('averaging_window.png')
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:

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

See also

Window

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

EBSD or LazyEBSD

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

EBSD or LazyEBSD

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

>>> iq = s.get_image_quality(normalize=True)  # Default
>>> plt.imshow(iq)
get_virtual_bse_intensity(roi, out_signal_axes=None)[source]

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

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

Parameters
  • 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
>>> roi = hs.roi.RectangularROI(
...     left=0, right=5, top=0, bottom=5)
>>> vbse_image = s.get_virtual_bse_intensity(roi)
match_patterns(simulations, metric='ncc', keep_n=50, n_slices=1, return_merged_crystal_map=False, get_orientation_similarity_map=False)[source]

Match each experimental pattern to all simulated patterns, of known crystal orientations in pre-computed dictionaries [CPW+15][JPDeGraef19], to determine their phase and orientation.

A suitable similarity metric, the normalized cross-correlation (ncc()), is used by default, but a valid user-defined similarity metric may be used instead (see make_similarity_metric()).

CrystalMap’s for each dictionary with “scores” and “simulation_indices” as properties are returned.

Parameters
  • simulations (EBSD or list of EBSD) – An EBSD signal or a list of EBSD signals with simulated patterns (dictionaries). The signals must have a 1D navigation axis and the xmap property with crystal orientations set.

  • metric (str or SimilarityMetric, optional) – Similarity metric, by default “ncc” (normalized cross-correlation).

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

  • n_slices (int, optional) – Number of simulation slices to process sequentially, by default 1 (no slicing).

  • return_merged_crystal_map (bool, optional) – Whether to return a merged crystal map, the best matches determined from the similarity scores, in addition to the single phase maps. By default False.

  • get_orientation_similarity_map (bool, optional) – Add orientation similarity maps to the returned crystal maps’ properties named “osm”. By default False.

Returns

xmaps – A crystal map for each dictionary loaded and one merged map if return_merged_crystal_map = True.

Return type

CrystalMap or list of ~orix.crystal_map.crystal_map.CrystalMap

Notes

Merging of crystal maps and calculations of orientation similarity maps can be done afterwards with merge_crystal_maps() and orientation_similarity_map(), respectively.

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

>>> np.mean(s.data)
146.0670987654321
>>> s.change_dtype(np.float32)  # Or passing dtype_out=np.float32
>>> s.normalize_intensity()
>>> np.mean(s.data)
2.6373216e-08

Notes

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

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

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

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

Parameters
  • 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
>>> roi = hs.roi.RectangularROI(
...     left=0, right=5, top=0, bottom=5)
>>> s.plot_virtual_bse_intensity(roi)
rebin(new_shape=None, scale=None, crop=True, out=None)[source]

Rebin the signal into a smaller or larger shape, based on linear interpolation. Specify either new_shape or scale.

Parameters
  • new_shape (list (of floats or integer) or None) – For each dimension specify the new_shape. This will internally be converted into a scale parameter.

  • scale (list (of floats or integer) or None) – For each dimension, specify the new:old pixel ratio, e.g. a ratio of 1 is no binning and a ratio of 2 means that each pixel in the new spectrum is twice the size of the pixels in the old spectrum. The length of the list should match the dimension of the Signal’s underlying data array. Note : Only one of `scale` or `new_shape` should be specified, otherwise the function will not run

  • crop (bool) –

    Whether or not to crop the resulting rebinned data (default is True). When binning by a non-integer number of pixels it is likely that the final row in each dimension will contain fewer than the full quota to fill one pixel.

    • e.g. a 5*5 array binned by 2.1 will produce two rows containing 2.1 pixels and one row containing only 0.8 pixels. Selection of crop=True or crop=False determines whether or not this “black” line is cropped from the final binned array or not.

    Please note that if crop=False is used, the final row in each dimension may appear black if a fractional number of pixels are left over. It can be removed but has been left to preserve total counts before and after binning.

  • out (BaseSignal (or subclasses) or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

Returns

s – The resulting cropped signal.

Return type

BaseSignal (or subclass)

Examples

>>> spectrum = hs.signals.EDSTEMSpectrum(np.ones([4, 4, 10]))
>>> spectrum.data[1, 2, 9] = 5
>>> print(spectrum)
<EDXTEMSpectrum, title: dimensions: (4, 4|10)>
>>> print ('Sum = ', sum(sum(sum(spectrum.data))))
Sum = 164.0
>>> scale = [2, 2, 5]
>>> test = spectrum.rebin(scale)
>>> print(test)
<EDSTEMSpectrum, title: dimensions (2, 2|2)>
>>> print('Sum = ', sum(sum(sum(test.data))))
Sum =  164.0
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.

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

>>> 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
>>> ebsd_node = kp.signals.util.metadata_nodes("ebsd")
>>> s.metadata.get_item(ebsd_node + '.static_background')
[[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]]

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

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_out, s.data.min(), s.data.max(),
...       s.inav[0, 0].data.min(), s.inav[0, 0].data.max())
uint8 20 254 24 233
>>> s2 = s.deepcopy()
>>> s.rescale_intensity(dtype_out=np.uint16)
>>> print(s.data.dtype_out, 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_out, s2.data.min(), s2.data.max(),
...       s2.inav[0, 0].data.min(), s2.inav[0, 0].data.max())
uint8 0 255 4 232

Contrast stretching can be performed by passing percentiles:

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

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

Notes

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

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

Write the signal to file in the specified format.

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

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

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

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

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

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

  • **kwargs – Keyword arguments passed to writer.

set_detector_calibration(delta)[source]

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

Parameters

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

Examples

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

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
>>> ebsd_node = metadata_nodes("ebsd")
>>> s.metadata.get_item(ebsd_node + '.xpc')
1.0
>>> s.set_experimental_parameters(xpc=0.50726)
>>> s.metadata.get_item(ebsd_node + '.xpc')
0.50726
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]

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

>>> s.metadata.Sample.Phases.Number_1.atom_coordinates.Number_1
├── atom =
├── coordinates = array([0., 0., 0.])
├── debye_waller_factor = 0.0
└── site_occupation = 0.0
>>> s.set_phase_parameters(
...     number=1, atom_coordinates={
...         '1': {'atom': 'Ni', 'coordinates': [0, 0, 0],
...         'site_occupation': 1,
...         'debye_waller_factor': 0.0035}})
>>> s.metadata.Sample.Phases.Number_1.atom_coordinates.Number_1
├── atom = Ni
├── coordinates = array([0., 0., 0.])
├── debye_waller_factor = 0.0035
└── site_occupation = 1
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

>>> s.axes_manager.['x'].scale  # Default value
1.0
>>> s.set_scan_calibration(step_x=1.5)  # Microns
>>> s.axes_manager['x'].scale
1.5
property xmap

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

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]

Bases: kikuchipy.signals.ebsd.EBSD, hyperspy._signals.signal2d.LazySignal2D

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.

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

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: “spherical” 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

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

Creates a dictionary of EBSD patterns for a sample in the EDAX TSL (RD, TD, ND) reference frame, given a set of local crystal lattice rotations and a detector model from a master pattern in the Lambert projection.

Parameters
  • rotations (Rotation) – Set of unit cell rotations to get patterns from.

  • detector (EBSDDetector) – EBSDDetector object describing the detector geometry with a single, fixed projection/pattern center.

  • energy (int) – The wanted energy in the master pattern.

  • n_chunk (int, optional) – The number of chunks the data should be split up into. By default, this is set so each chunk is around 100 MB.

  • dtype_out (type, optional) – Data type of the returned patterns, by default np.float32.

  • compute (bool, optional) – Whether or not the dask.compute() function should be called and read the patterns into memory, by default false. For more information see: dask.array.Array.compute().

Returns

All the simulated EBSD patterns with the shape (number of rotations, detector pixels in x direction, detector pixels in y direction).

Return type

EBSD or LazyEBSD

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 at: https://kikuchipy.org/en/latest/reference_frames.html.

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

>>> np.mean(s.data)
146.0670987654321
>>> s.change_dtype(np.float32)  # Or passing dtype_out=np.float32
>>> s.normalize_intensity()
>>> 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

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_out, s.data.min(), s.data.max(),
...       s.inav[0, 0].data.min(), s.inav[0, 0].data.max())
uint8 20 254 24 233
>>> s2 = s.deepcopy()
>>> s.rescale_intensity(dtype_out=np.uint16)
>>> print(s.data.dtype_out, 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_out, s2.data.min(), s2.data.max(),
...       s2.inav[0, 0].data.min(), s2.inav[0, 0].data.max())
uint8 0 255 4 232

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

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

Bases: kikuchipy.signals.ebsd_master_pattern.EBSDMasterPattern, hyperspy._signals.signal2d.LazySignal2D

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

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

>>> np.mean(s.data)
146.0670987654321
>>> s.change_dtype(np.float32)  # Or passing dtype_out=np.float32
>>> s.normalize_intensity()
>>> 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

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_out, s.data.min(), s.data.max(),
...       s.inav[0, 0].data.min(), s.inav[0, 0].data.max())
uint8 20 254 24 233
>>> s2 = s.deepcopy()
>>> s.rescale_intensity(dtype_out=np.uint16)
>>> print(s.data.dtype_out, 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_out, s2.data.min(), s2.data.max(),
...       s2.inav[0, 0].data.min(), s2.inav[0, 0].data.max())
uint8 0 255 4 232

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

ebsd_metadata()

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

metadata_nodes([nodes])

Return SEM and/or EBSD metadata nodes.

Signal utilities, mostly for handling signal metadata and attributes.

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

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

See set_experimental_parameters() for an explanation of the parameters.

Returns

md

Return type

hyperspy.misc.utils.DictionaryTreeBrowser

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

Return SEM and/or EBSD metadata nodes.

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

Parameters

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

Returns

nodes_to_return

Return type

list of str or str


simulations

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

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

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

Coordinates of zone axes in uncalibrated detector coordinates.

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 on the detector.

Return type

numpy.ndarray

property zone_axes_label_detector_coordinates

Coordinates of zone axes labels in uncalibrated detector coordinates.

Returns

za_coords – Zone axes labels placed just above the zone axes.

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

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]

Bases: diffsims.crystallography.reciprocal_lattice_point.ReciprocalLatticePoint

Kikuchi bands used in geometrical EBSD simulations.

__init__(phase, hkl, hkl_detector, in_pattern, gnomonic_radius=10)[source]

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),
...     gnomonic_radius=10,
... )
>>> bands
KikuchiBand (|2)
Phase: ni (m-3m)
[[-1  1  1]
 [ 0 -2  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)

property gnomonic_radius

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

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

Return type

ndarray

property hesse_distance

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
Return type

ndarray

property hesse_line_y
Return type

ndarray

property hkl_detector

Detector coordinates for all bands per pattern.

Return type

Vector3d

property in_pattern

Which bands are visible in which patterns.

Return type

ndarray

property navigation_dimension

Number of navigation dimensions (a maximum of 2).

Return type

int

property navigation_shape

Navigation shape.

Return type

tuple

property plane_trace_coordinates

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

property within_gnomonic_radius

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

Return type

ndarray

property x_detector

X detector coordinate for all bands per pattern.

Return type

ndarray

property x_gnomonic

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

Return type

ndarray

property y_detector

Y detector coordinate for all bands per pattern.

Return type

ndarray

property y_gnomonic

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

Return type

ndarray

property z_detector

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]

Bases: diffsims.crystallography.reciprocal_lattice_point.ReciprocalLatticePoint

Zone axes used in geometrical EBSD simulations.

__init__(phase, uvw, uvw_detector, in_pattern, gnomonic_radius=10)[source]

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)

property gnomonic_radius

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

Return type

ndarray

property in_pattern

Which bands are visible in which patterns.

Return type

ndarray

property navigation_dimension

Number of navigation dimensions (a maximum of 2).

Return type

int

property navigation_shape

Navigation shape.

Return type

tuple

property r_gnomonic

Gnomonic radius for all zone axes per pattern.

Return type

ndarray

property uvw_detector

Detector coordinates for all zone axes per pattern.

Return type

Vector3d

property within_gnomonic_radius

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

Return type

ndarray

property x_detector

X detector coordinate for all zone axes per pattern.

Return type

ndarray

property x_gnomonic

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

Return type

ndarray

property y_detector

Y detector coordinate for all zone axes per pattern.

Return type

ndarray

property y_gnomonic

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

Return type

ndarray

property z_detector

Z detector coordinate for all zone axes per pattern.

Return type

ndarray