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):
Crystallographic computations not found (easily) elsewhere. |
|
Test data. |
|
An EBSD detector and related quantities. |
|
Creation of HyperSpy markers to add to signals. |
|
Pattern filters used on signals. |
|
Generate signals and simulations, sometimes from other signals. |
|
Tools for indexing of EBSD patterns by comparison to simulated patterns. |
|
Read and write signals from and to file. |
|
|
Load an |
Single and chunk pattern processing used by signals. |
|
Various projections and transformations relevant to EBSD. |
|
Experimental and simulated diffraction patterns and virtual backscatter electron images. |
|
Simulations returned by a generator and handling of Kikuchi bands and zone axes. |
crystallography¶
Crystallographic computations not found (easily) elsewhere.
|
Direct structure matrix as defined in EMsoft. |
|
Reciprocal metric tensor as defined in EMsoft. |
|
Reciprocal structure matrix as defined in EMsoft. |
-
kikuchipy.crystallography.
get_direct_structure_matrix
(lattice)[source]¶ Direct structure matrix as defined in EMsoft.
data¶
|
9 EBSD patterns in a (3, 3) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19]. |
|
4125 EBSD patterns in a (55, 75) navigation shape of (60, 60) detector pixels from Nickel, acquired on a NORDIF UF-1100 detector [AHvHM19]. |
|
(401, 401) uint8 square Lambert or stereographic projection of the northern and southern hemisphere of a Nickel master pattern at 20 keV accelerating voltage. |
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 [AHvHM19].
- Parameters
allow_download (bool) – Whether to allow downloading the dataset from the kikuchipy-data GitHub repository (https://github.com/pyxem/kikuchipy-data) to the local cache with the pooch Python package. Default is False.
kwargs – Keyword arguments passed to
load()
.
- Returns
signal – EBSD signal.
- Return type
-
kikuchipy.data.
nickel_ebsd_master_pattern_small
(**kwargs)[source]¶ (401, 401) uint8 square Lambert or stereographic projection of the northern and southern hemisphere of a Nickel master pattern at 20 keV accelerating voltage.
- Parameters
kwargs – Keyword arguments passed to
load()
.- Returns
signal – EBSD master pattern signal.
- Return type
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 withrescale_intensity()
, all datasets were written withdict2h5ebsdgroup()
with keyword arguments compression=”gzip” and compression_opts=9. All other HDF5 groups and datasets are the same as in the original file.
detectors¶
An EBSD detector and related quantities.
|
An EBSD detector class storing its shape, pixel size, binning factor, detector tilt, sample tilt and projection center (PC) per pattern. |
EBSDDetector¶
|
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 [BJG+16].
-
__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()
-
deepcopy
()[source]¶ Return a deep copy using
copy.deepcopy()
.
-
property
gnomonic_bounds
¶ Detector bounds [x0, x1, y0, y1] in gnomonic coordinates.
- Return type
Number of navigation dimensions of the projection center array (a maximum of 2).
- Return type
Navigation shape of the projection center array.
- Return type
-
pc_bruker
()[source]¶ Return PC in the Bruker convention.
PC conversions are calculated as presented in [JPDeGraef19]..
- Return type
-
pc_emsoft
(version=5)[source]¶ Return PC in the EMsoft convention.
PC conversions are calculated as presented in [JPDeGraef19].
-
pc_oxford
()[source]¶ Return PC in the Oxford convention.
PC conversions are calculated as presented in [JPDeGraef19].
- Return type
-
pc_tsl
()[source]¶ Return PC in the EDAX TSL convention.
PC conversions are calculated as presented in [JPDeGraef19]..
- Return type
-
plot
(coordinates=None, show_pc=True, pc_kwargs=None, pattern=None, pattern_kwargs=None, draw_gnomonic_circles=False, gnomonic_angles=None, gnomonic_circles_kwargs=None, zoom=1, return_fig_ax=False)[source]¶ Plot the detector screen.
The plotting of gnomonic circles and general style is adapted from the supplementary material to [BJG+16] by Aimo Winkelmann.
- Parameters
coordinates (
Optional
[str
]) – Which coordinates to use, “detector” or “gnomonic”. If None (default), “detector” is used.show_pc (
bool
) – Show the average projection center. Default is True.pc_kwargs (
Optional
[dict
]) – A dictionary of keyword arguments passed tomatplotlib.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 tomatplotlib.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 tomatplotlib.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
- 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
r_max
¶ Maximum distance from PC to detector edge in gnomonic coordinates.
- Return type
-
property
specimen_scintillator_distance
¶ Specimen to scintillator distance (SSD), known in EMsoft as L.
- Return type
-
draw¶
Creation of HyperSpy markers to add to signals.
markers¶
|
Return a list of line segment markers. |
|
Return a list of point markers. |
|
Return a list of text markers. |
-
kikuchipy.draw.markers.
get_line_segment_list
(lines, **kwargs)[source]¶ Return a list of line segment markers.
- Parameters
lines (
Union
[list
,ndarray
]) – On the form [[x00, y00, x01, y01], [x10, y10, x11, y11], …].kwargs – Keyword arguments allowed by
matplotlib.pyplot.axvline()
.
- Returns
marker_list – List of
hyperspy.drawing._markers.line_segment.LineSegment
.- Return type
-
kikuchipy.draw.markers.
get_point_list
(points, **kwargs)[source]¶ Return a list of point markers.
- Parameters
points (
Union
[list
,ndarray
]) – On the form [[x0, y0], [x1, y1], …].kwargs – Keyword arguments allowed by
matplotlib.pyplot.scatter()
.
- Returns
marker_list – List of
hyperspy.drawing._markers.point.Point
.- Return type
colors¶
Color palettes for plotting Kikuchi bands.
filters¶
Pattern filters used on signals.
|
Return the distance to the window origin in pixels. |
|
Return a frequency domain high-pass filter transfer function in 2D. |
|
Return a frequency domain low-pass filter transfer function in 2D. |
|
Return a 1D modified Hann window with the maximum value normalized to 1. |
|
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.
-
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
- Returns
w – 2D transfer function.
- Return type
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
- Returns
w – 2D transfer function.
- Return type
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
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¶
|
Return whether the window is in a valid state. |
Make window circular. |
|
|
Plot window values with indices relative to the origin. |
|
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 2Dnumpy.ndarray
ordask.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]]
See also
-
__init__
()¶ Initialize self. See help(type(self)) for accurate signature.
-
make_circular
()[source]¶ Make window circular.
The data of window elements who’s radial distance to the window origin is shorter or equal to the half width of the window’s longest axis are set to zero. This has no effect if the window has only one axis.
-
property
n_neighbours
¶ Maximum number of nearest neighbours in each navigation axis to the origin.
- Return type
-
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 inmatplotlib.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
- 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')
generators¶
Generate signals and simulations, sometimes from other signals.
|
A generator storing necessary parameters to simulate geometrical EBSD patterns. |
|
Generates virtual backscatter electron (BSE) images for a specified electron backscatter diffraction (EBSD) signal and a set of EBSD detector areas. |
|
Return an RGB image from three numpy arrays, with a potential alpha channel. |
Normalize an image’s intensities to a mean of 0 and a standard deviation of 1, with the possibility to also scale by a contrast factor and shift the brightness values. |
EBSDSimulationGenerator¶
Project a set of Kikuchi bands and zone axes onto the detector, one set for each rotation of the unit cell. |
-
class
kikuchipy.generators.
EBSDSimulationGenerator
(detector, phase, rotations)[source]¶ Bases:
object
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
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
Number of navigation dimensions (a maximum of 2).
- Return type
Navigation shape of the rotations and detector projection center array (maximum of 2).
- Return type
-
VirtualBSEGenerator¶
|
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. |
|
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 a pattern with the detector grid superimposed, potentially coloring the edges of three grid tiles red, green and blue. |
|
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
¶
-
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
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
Notes
HyperSpy only allows for RGB signal dimensions with data types unsigned 8 or 16 bit.
-
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
-
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).
-
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.
indexing¶
Tools for indexing of EBSD patterns by comparison to simulated patterns.
The EBSD method match_patterns()
uses
these tools for pattern matching.
|
Pattern matching of experimental patterns to simulated patterns, of known crystal orientations in pre-computed dictionaries [CPW+15,JPDeGraef19], for phase and orientation determination. |
|
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 a list of at least two single phase |
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 ofCrystalMap
Notes
Merging of crystal maps and calculations of orientation similarity maps can be done afterwards with
merge_crystal_maps()
andorientation_similarity_map()
, respectively.See also
-
-
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
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
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 a similarity metric for comparing gray-tone patterns of equal size. |
|
Describes the input parameters for a similarity metric. |
A similarity metric for calculation of the normalized cross-correlation coefficient (NCC) r [Gos12] between experimental and simulated patterns. |
|
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()
.
-
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 usesStaticPatternMatching
).- 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
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
experimental (numpy.ndarray or dask.array.Array) – Experimental patterns.
simulated (numpy.ndarray or dask.array.Array) – Simulated patterns.
- Returns
r – Correlation coefficients in range [-1, 1] for all comparisons, as
numpy.ndarray
if both experimental and simulated arenumpy.ndarray
, elsedask.array.Array
.- Return type
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()
withaxes=([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
experimental (numpy.ndarray or dask.array.Array) – Experimental patterns.
simulated (numpy.ndarray or dask.array.Array) – Simulated patterns.
- Returns
rho – Normalized dot products in range [0, 1] for all comparisons, as
numpy.ndarray
if both experimental and simulated arenumpy.ndarray
, elsedask.array.Array
.- Return type
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.
|
Load an |
Input/output plugins. |
-
kikuchipy.io._io.
load
(filename, lazy=False, **kwargs)[source]¶ Load an
EBSD
orEBSDMasterPattern
object from a supported file format.This function is a modified version of
hyperspy.io.load()
.- Parameters
filename (
str
) – Name of file to load.lazy (
bool
) – Open the data lazily without actually reading the data from disk until required. Allows opening arbitrary sized datasets. Default is False.kwargs – Keyword arguments passed to the corresponding kikuchipy reader. See their individual documentation for available options.
- Returns
- Return type
kikuchipy.signals.EBSD, kikuchipy.signals.EBSDMasterPattern, list of kikuchipy.signals.EBSD or list of kikuchipy.signals.EBSDMasterPattern
Examples
>>> import kikuchipy as kp >>> s = kp.load("patterns.h5") >>> s <EBSD, title: , dimensions: (10, 20|60, 60)>
plugins¶
Input/output plugins.
Read/write support for EBSD patterns in some HDF5 file formats. |
|
Read/write support for EBSD patterns in NORDIF’s binary format. |
|
Read support for simulated EBSD patterns in EMsoft’s HDF5 format. |
|
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
scan_group (Group) – HDF group of scan data and header.
md (hyperspy.misc.utils.DictionaryTreeBrowser) – Dictionary with empty fields from kikuchipy’s metadata.
- 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
orLazyEBSD
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
- 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
andoriginal_metadata
from an h5ebsd scan.- Parameters
- Returns
scan – Dictionary with patterns,
metadata
andoriginal_metadata
.- Return type
-
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
- 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
- Returns
dictionary – Dataset values in group (and subgroups if recursive=True).
- Return type
-
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.
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.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 asfilename
).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
orLazyEBSD
object to a NORDIF binary file.- Parameters
filename (
str
) – Full path of HDF file.signal (kikuchipy.signals.EBSD or kikuchipy.signals.LazyEBSD) – Signal instance.
-
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.
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='stereographic', 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 “stereographic” (default) or “lambert”.hemisphere (
str
) – Projection hemisphere(s) to read. Options are “north” (default), “south” or “both”. If “both”, these will be stacked in the vertical navigation axis.lazy (
bool
) – Open the data lazily without actually reading the data from disk until requested. Allows opening datasets larger than available memory. Default is False.kwargs – Keyword arguments passed to h5py.File.
- Returns
signal_dict_list – Data, axes, metadata and original metadata.
- Return type
list of dicts
pattern¶
Single and chunk pattern processing used by signals.
Functions for operating on |
|
Compute similarities between EBSD patterns. |
|
|
Compute the discrete Fast Fourier Transform (FFT) of an EBSD pattern. |
|
Filter an EBSD patterns in the frequency domain. |
|
Get the frequency vectors in a Fourier Transform spectrum. |
|
Compute the FFT spectrum of a Fourier transformed EBSD pattern. |
|
Get the dynamic background in an EBSD pattern. |
|
Return the image quality of an EBSD pattern. |
|
Compute the inverse Fast Fourier Transform (IFFT) of an FFT of an EBSD pattern. |
|
Normalize image intensities to a mean of zero and a given standard deviation. |
|
Remove the dynamic background in an EBSD pattern. |
|
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 usingscipy.fft.rfft2()
. If False (default), it is computed usingscipy.fft.fft2()
.kwargs – Keyword arguments pass to
scipy.fft.fft2()
orscipy.fft.rfft2()
.
- Returns
out – The result of the 2D FFT.
- Return type
-
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
-
kikuchipy.pattern.
fft_frequency_vectors
(shape)[source]¶ Get the frequency vectors in a Fourier Transform spectrum.
- Parameters
- Returns
frequency_vectors – Frequency vectors.
- Return type
-
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
-
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
-
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 fromfft_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
-
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 usingscipy.fft.irfft2()
. If False (default), it is computed usingscipy.fft.ifft2()
.kwargs – Keyword arguments pass to
scipy.fft.ifft()
.
- Returns
pattern – Real part of the IFFT of the EBSD pattern.
- Return type
-
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
- Returns
normalized_pattern – Normalized pattern.
- Return type
Notes
Data type should always be changed to floating point, e.g.
np.float32
withnumpy.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
-
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
chunk¶
Functions for operating on numpy.ndarray
or dask.array.Array
chunks of EBSD patterns.
|
Local contrast enhancement of a chunk of EBSD patterns with adaptive histogram equalization. |
|
Average a chunk of patterns with its neighbours within a window. |
|
Filter a chunk of EBSD patterns in the frequency domain. |
|
Obtain the dynamic background in a chunk of EBSD patterns. |
|
Compute the image quality in a chunk of EBSD patterns. |
|
Normalize intensities in a chunk of EBSD patterns to a mean of zero with a given standard deviation. |
|
Correct the dynamic background in a chunk of EBSD patterns. |
|
Remove the static background in a chunk of EBSD patterns. |
|
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
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
-
kikuchipy.pattern.chunk.
average_neighbour_patterns
(patterns, window_sums, window, dtype_out=None)[source]¶ Average a chunk of patterns with its neighbours within a window.
The amount of averaging is specified by the window coefficients. All patterns are averaged with the same window. Map borders are extended with zeros. Resulting pattern intensities are rescaled to fill the input patterns’ data type range individually.
- Parameters
- Returns
averaged_patterns – Averaged patterns.
- Return type
-
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
-
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
filter_func (
Union
[gaussian_filter
,fft_filter
]) – Function where a Gaussian convolution filter is applied, in the frequency or spatial domain. Eitherscipy.ndimage.gaussian_filter()
orkikuchipy.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
-
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
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 fromfft_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
-
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
Notes
Data type should always be changed to floating point, e.g.
np.float32
withnumpy.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
filter_func (
Union
[gaussian_filter
,fft_filter
]) – Function where a Gaussian convolution filter is applied, in the frequency or spatial domain. Eitherscipy.ndimage.gaussian_filter()
orkikuchipy.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
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
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
-
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
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
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
- Returns
coefficient – Correlation coefficient in range [-1, 1] if zero normalised, otherwise [0, 1].
- Return type
References
- Gonzalez2017
Gonzalez, R. E. Woods, “Digital Image Processing,” 4th edition, Pearson Education Limited, 2017.
projections¶
Various projections and transformations relevant to EBSD.
Rotations to align the EBSD detector with the tilted sample. |
|
Hessian normal form of a plane given by polar coordinates. |
|
Spherical projection of a cartesian vector according to the ISO 31-11 standard [SphericalWolfram]. |
ebsd_projections¶
|
Rotation U_K from detector frame D to direct crystal lattice frame K. |
|
Rotation U_Kstar from detector to reciprocal crystal lattice frame Kstar. |
|
Rotation U_S to align detector frame D with sample frame S. |
Rotations to align the EBSD detector with the tilted sample. Notation from [BJG+16].
-
kikuchipy.projections.ebsd_projections.
detector2direct_lattice
(sample_tilt, detector_tilt, lattice, rotation)[source]¶ Rotation U_K from detector frame D to direct crystal lattice frame K.
-
kikuchipy.projections.ebsd_projections.
detector2reciprocal_lattice
(sample_tilt, detector_tilt, lattice, rotation)[source]¶ Rotation U_Kstar from detector to reciprocal crystal lattice frame Kstar.
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.
-
static
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.
|
Scan of Electron Backscatter Diffraction (EBSD) patterns. |
|
Simulated Electron Backscatter Diffraction (EBSD) master pattern. |
|
Virtual backscatter electron (BSE) image(s). |
Signal utilities for handling signal metadata and attributes and for controlling chunking of |
EBSD¶
All methods listed here are also available to
LazyEBSD
objects.
Enhance the local contrast in an EBSD scan inplace using adaptive histogram equalization. |
|
|
Average patterns in an EBSD scan inplace with its neighbours within a window. |
|
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. |
|
Filter an EBSD scan inplace in the frequency domain. |
Get a map of the average dot product between patterns and their neighbours within an averaging window. |
|
|
Get the model signal generated with the selected number of principal components from a decomposition. |
|
Get the dynamic background per EBSD pattern in a scan. |
|
Compute the image quality map of patterns in an EBSD scan. |
|
Get an array with dot products of a pattern and its neighbours within a window. |
|
Get a virtual backscatter electron (VBSE) image formed from intensities within a region of interest (ROI) on the detector. |
|
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. |
|
Normalize image intensities in inplace to a mean of zero with a given standard deviation. |
|
Plot an interactive virtual backscatter electron (VBSE) image formed from intensities within a specified and adjustable region of interest (ROI) on the detector. |
|
Rebin the signal into a smaller or larger shape, based on linear interpolation. |
|
Remove the dynamic background in an EBSD scan inplace. |
|
Remove the static background in an EBSD scan inplace. |
|
Rescale image intensities inplace. |
|
Write the signal to file in the specified format. |
|
Set detector pixel size in microns. |
|
Set experimental parameters in signal metadata. |
|
Set parameters for one phase in signal metadata. |
|
Set the step size in microns. |
-
class
kikuchipy.signals.
EBSD
(*args, **kwargs)[source]¶ Bases:
kikuchipy.signals._common_image.CommonImage
,hyperspy._signals.signal2d.Signal2D
Scan of Electron Backscatter Diffraction (EBSD) patterns.
This class extends HyperSpy’s Signal2D class for EBSD patterns, with common intensity processing methods and some analysis methods.
Methods inherited from HyperSpy can be found in the HyperSpy user guide.
See the docstring of
hyperspy.signal.BaseSignal
for a list of attributes in addition to the ones listed below.-
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.
See also
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 pattern sizes, so it may be necessary to search for the optimal window size.
-
average_neighbour_patterns
(window='circular', window_shape=(3, 3), **kwargs)[source]¶ Average patterns in an EBSD scan inplace with its neighbours within a window.
The amount of averaging is specified by the window coefficients. All patterns are averaged with the same window. Map borders are extended with zeros. Resulting pattern intensities are rescaled to fill the input patterns’ data type range individually.
Averaging is accomplished by correlating the window with the extended array of patterns using
scipy.ndimage.correlate()
.- Parameters
window (
Union
[str
,ndarray
,Array
,Window
]) – Name of averaging window or an array. Available types are listed inscipy.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 2Dnumpy.ndarray
,dask.array.Array
orWindow
can also be passed.window_shape (
Tuple
[int
, …]) – Shape of averaging window. Not used if a custom window orWindow
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.
-
property
detector
¶ An
EBSDDetector
describing the EBSD detector dimensions, the projection/pattern centre, and the detector-sample geometry.- Return type
-
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
-
get_average_neighbour_dot_product_map
(window=None, zero_mean=True, normalize=True, dtype_out=<class 'numpy.float32'>, dp_matrices=None)[source]¶ Get a map of the average dot product between patterns and their neighbours within an averaging window.
- Parameters
window (
Optional
[Window
]) – Window with integer coefficients defining the neighbours to calculate the average with. If None (default), the four nearest neighbours are used. Must have the same number of dimensions as signal navigation dimensions.zero_mean (
bool
) – Whether to subtract the mean of each pattern individually to center the intensities about zero before calculating the dot products. Default is True.normalize (
bool
) – Whether to normalize the pattern intensities to a standard deviation of 1 before calculating the dot products. This operation is performed after centering the intensities if zero_mean is True. Default is True.dtype_out (
dtype
) – Data type of the output map. Default isnumpy.float32
.dp_matrices (
Optional
[ndarray
]) – Optional pre-calculated dot product matrices, by default None. If an array is passed, the average dot product map is calculated from this array. The dp_matrices array can be obtained fromget_neighbour_dot_product_matrices()
. It’s shape must correspond to the signal’s navigation shape and the window’s shape.
- Return type
-
get_decomposition_model
(components=None, dtype_out=<class 'numpy.float32'>)[source]¶ Get the model signal generated with the selected number of principal components from a decomposition.
Calls HyperSpy’s
hyperspy.learn.mva.MVA.get_decomposition_model()
. Learning results are preconditioned before this call, doing the following: (1) setnumpy.dtype
to desired dtype_out, (2) remove unwanted components, and (3) rechunk, ifdask.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 isnumpy.float32
). Note that HyperSpy casts them tonumpy.float64
.
- Returns
s_model
- Return type
-
get_dynamic_background
(filter_domain='frequency', std=None, truncate=4.0, dtype_out=None, **kwargs)[source]¶ Get the dynamic background per EBSD pattern in a scan.
- Parameters
filter_domain (
str
) – Whether to apply a Gaussian convolution filter in the “frequency” (default) or “spatial” domain.std (
Union
[None
,int
,float
]) – Standard deviation of the Gaussian window. If None (default), it is set to width/8.truncate (
Union
[int
,float
]) – Truncate the Gaussian filter at this many standard deviations. Default is 4.0.dtype_out (
Optional
[dtype
]) – Data type of the background patterns. If None (default), it is set to the same data type as the input pattern.kwargs – Keyword arguments passed to the Gaussian blurring function determined from filter_domain.
- Returns
background_signal – Signal with the large scale variations across the detector.
- Return type
-
get_image_quality
(normalize=True)[source]¶ Compute the image quality map of patterns in an EBSD scan.
The image quality is calculated based on the procedure defined by Krieger Lassen [Lassen1994].
- Parameters
normalize (
bool
) – Whether to normalize patterns to a mean of zero and standard deviation of 1 before calculating the image quality. Default is True.- Returns
image_quality_map – Image quality map of same shape as signal navigation axes.
- Return type
References
- Lassen1994(1,2,3)
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)
See also
-
get_neighbour_dot_product_matrices
(window=None, zero_mean=True, normalize=True, dtype_out=<class 'numpy.float32'>)[source]¶ Get an array with dot products of a pattern and its neighbours within a window.
- Parameters
window (
Optional
[Window
]) – Window with integer coefficients defining the neighbours to calculate the dot products with. If None (default), the four nearest neighbours are used. Must have the same number of dimensions as signal navigation dimensions.zero_mean (
bool
) – Whether to subtract the mean of each pattern individually to center the intensities about zero before calculating the dot products. Default is True.normalize (
bool
) – Whether to normalize the pattern intensities to a standard deviation of 1 before calculating the dot products. This operation is performed after centering the intensities if zero_mean is True. Default is True.dtype_out (
dtype
) – Data type of the output map. Default isnumpy.float32
.
- Return type
-
get_virtual_bse_intensity
(roi, out_signal_axes=None)[source]¶ Get a virtual backscatter electron (VBSE) image formed from intensities within a region of interest (ROI) on the detector.
Adapted from
pyxem.signals.common_diffraction.CommonDiffraction.get_integrated_intensity()
.- Parameters
- Returns
virtual_image – VBSE image formed from detector intensities within an ROI on the detector.
- Return type
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)
See also
-
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 (seemake_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()
andorientation_similarity_map()
, respectively.See also
-
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
withchange_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)
See also
-
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
orcrop=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) orNone
) – IfNone
, 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 individually.
- Parameters
operation (
str
) – Whether to “subtract” (default) or “divide” by the dynamic background pattern.filter_domain (
str
) – Whether to obtain the dynamic background by applying a Gaussian convolution filter in the “frequency” (default) or “spatial” domain.std (
Union
[None
,int
,float
]) – Standard deviation of the Gaussian window. If None (default), it is set to width/8.truncate (
Union
[int
,float
]) – Truncate the Gaussian window at this many standard deviations. Default is 4.0.kwargs – Keyword arguments passed to the Gaussian blurring function determined from filter_domain.
See also
kikuchipy.signals.EBSD.remove_static_background
,kikuchipy.signals.EBSD.get_dynamic_background
,kikuchipy.pattern.remove_dynamic_background
,kikuchipy.pattern.get_dynamic_background
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.
See also
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.
See also
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.
See also
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.
See also
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
See also
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
-
These methods are exclusive to LazyEBSD objects.
|
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:
hyperspy._signals.signal2d.LazySignal2D
,kikuchipy.signals.ebsd.EBSD
Lazy implementation of the
EBSD
class.This class extends HyperSpy’s LazySignal2D class for EBSD patterns.
Methods inherited from HyperSpy can be found in the HyperSpy user guide.
See docstring of
EBSD
for attributes and methods.-
compute
(*args, **kwargs)[source]¶ Attempt to store the full signal in memory.
- Parameters
close_file (bool, default False) – If True, attemp to close the file associated with the dask array data if any. Note that closing the file will make all other associated lazy signals inoperative.
show_progressbar (None or bool) – If
True
, display a progress bar. IfNone
, the default from the preferences settings is used.
- Returns
- Return type
-
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 isnumpy.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.
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.
|
Return a dictionary of EBSD patterns projected onto a detector from a master pattern in the square Lambert projection [CDeGraef13], for a set of crystal rotations relative to the EDAX TSL sample reference frame (RD, TD, ND) and a fixed detector-sample geometry. |
|
Normalize image intensities in inplace to a mean of zero with a given standard deviation. |
|
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.-
phase
¶ Phase describing the crystal structure used in the master pattern simulation.
-
get_patterns
(rotations, detector, energy, dtype_out=<class 'numpy.float32'>, compute=False, **kwargs)[source]¶ Return a dictionary of EBSD patterns projected onto a detector from a master pattern in the square Lambert projection [CDeGraef13], for a set of crystal rotations relative to the EDAX TSL sample reference frame (RD, TD, ND) and a fixed detector-sample geometry.
- Parameters
rotations (
Rotation
) – Set of crystal rotations to get patterns from. The shape of this object, a maximum of two dimensions, determines the navigation shape of the output signal.detector (
EBSDDetector
) – EBSD detector describing the detector dimensions and the detector-sample geometry with a single, fixed projection/pattern center.energy (
Union
[int
,float
]) – Acceleration voltage, in kV, used to simulate the desired master pattern to create a dictionary from.dtype_out (
type
) – Data type of the returned patterns, by default np.float32.compute (
bool
) – Whether to return a lazy result, by default False. For more information seecompute()
.kwargs – Keyword arguments passed to
get_chunking()
to control the number of chunks the dictionary creation and the output data array is split into. Only chunk_shape, chunk_bytes and dtype_out (to dtype) are passed on.
- Returns
Signal with navigation and signal shape equal to the rotation object’s and detector shape, respectively.
- Return type
Notes
If the master pattern phase has a non-centrosymmetric point group, both the northern and southern hemispheres must be provided. For more details regarding the reference frame visit the reference frame user guide 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
withchange_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 image intensities in inplace to a mean of zero with a given standard deviation. |
|
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
withchange_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¶
Return a dictionary in HyperSpy’s DictionaryTreeBrowser format with the default kikuchipy EBSD metadata. |
|
|
Get a chunk tuple based on the shape of the signal data. |
|
Return dask array of patterns with appropriate chunking. |
|
Return SEM and/or EBSD metadata nodes. |
Signal utilities for handling signal metadata and attributes and
for controlling chunking of dask.array.Array
.
-
kikuchipy.signals.util.
ebsd_metadata
()[source]¶ Return a dictionary in HyperSpy’s DictionaryTreeBrowser format with the default kikuchipy EBSD metadata.
See
set_experimental_parameters()
for an explanation of the parameters.- Returns
md
- Return type
-
kikuchipy.signals.util.
get_chunking
(signal=None, data_shape=None, nav_dim=None, sig_dim=None, chunk_shape=None, chunk_bytes=30000000.0, dtype=None)[source]¶ Get a chunk tuple based on the shape of the signal data.
The signal dimensions will not be chunked, and the navigation dimensions will be chunked based on either chunk_shape, or be optimized based on the chunk_bytes.
This function is inspired by a similar function in pyxem.
- Parameters
signal (kikuchipy.signals.EBSD, kikuchipy.signals.LazyEBSD or None) – If None (default), the following must be passed: data shape to be chunked data_shape, the number of navigation dimensions nav_dim, the number of signal dimensions sig_dim and the data array data type dtype.
data_shape (
Optional
[tuple
]) – Data shape, must be passed if signal is None.nav_dim (
Optional
[int
]) – Number of navigation dimensions, must be passed if signal is None.sig_dim (
Optional
[int
]) – Number of signal dimensions, must be passed if signal is None.chunk_shape (
Optional
[int
]) – Shape of navigation chunks. If None (default), this size is set automatically based on chunk_bytes. This is a square if signal has two navigation dimensions.chunk_bytes (
Union
[int
,float
,str
,None
]) – Number of bytes in each chunk. Default is 30e6, i.e. 30 MB. Only used if freedom is given to choose, i.e. if chunk_shape is None. Various parameter types are allowed, e.g. 30000000, “30 MB”, “30MiB”, or the default 30e6, all resulting in approximately 30 MB chunks.dtype (
Optional
[dtype
]) – Data type of the array to chunk. Will take precedent over the signal data type if signal is passed. Must be passed if signal is None.
- Returns
- Return type
chunks
-
kikuchipy.signals.util.
get_dask_array
(signal, dtype=None, **kwargs)[source]¶ Return dask array of patterns with appropriate chunking.
- Parameters
signal (
EBSD
orLazyEBSD
) – Signal with data to return dask array from.dtype (
Optional
[dtype
]) – Data type of returned dask array. This is also passed on toget_chunking()
.kwargs – Keyword arguments passed to
get_chunking()
to control the number of chunks the output data array is split into. Only chunk_shape, chunk_bytes and dtype are passed on.
- Returns
Dask array with signal data with appropriate chunking and data type.
- Return type
dask_array
simulations¶
Simulations returned by a generator and handling of Kikuchi bands and zone axes.
|
Geometrical EBSD simulation with Kikuchi bands and zone axes. |
Kikuchi bands and zone axes used in geometrical EBSD simulations. |
GeometricalEBSDSimulation¶
|
Return a list of all or some of the simulation markers. |
|
Return a list of Kikuchi band line segment markers. |
|
Return a list of projection center point markers. |
|
Return a list of zone axes point markers. |
|
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
-
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
bands (
bool
) – Whether to return band markers. Default is True.zone_axes (
bool
) – Whether to return zone axes markers. Default is True.zone_axes_labels (
bool
) – Whether to return zone axes label markers. Default is True.pc (
bool
) – Whether to return projection center markers. Default is True.bands_kwargs (
Optional
[dict
]) – Keyword arguments passed tokikuchipy.draw.markers.get_line_segment_list()
.zone_axes_kwargs (
Optional
[dict
]) – Keyword arguments passed tokikuchipy.draw.markers.get_point_list()
.zone_axes_labels_kwargs (
Optional
[dict
]) – Keyword arguments passed tokikuchipy.draw.markers.get_text_list()
.pc_kwargs (
Optional
[dict
]) – Keyword arguments passed tokikuchipy.draw.markers.get_point_list()
.
- Returns
markers – List with all markers.
- Return type
-
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
-
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 (y0, x0, y1, x1) on the detector.
- Return type
-
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
-
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
-
property
zone_axes_detector_coordinates
¶ Coordinates of zone axes in uncalibrated detector coordinates (a scale of 1 and offset of 0).
If GeometricalEBSDSimulation.exclude_outside_detector is True, the coordinates of the zone axes outside the detector are set to np.nan.
- Returns
za_coords – Zone axis coordinates (x, y) on the detector.
- Return type
-
property
zone_axes_label_detector_coordinates
¶ Coordinates of zone axes labels in uncalibrated detector coordinates (a scale of 1 and offset of 0).
- Returns
za_coords – Zone axes labels (x, y) placed just above the zone axes on the detector.
- Return type
-
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
-
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
-
features¶
Kikuchi bands and zone axes used in geometrical EBSD simulations.
|
Kikuchi bands used in geometrical EBSD simulations. |
|
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
-
property
hesse_alpha
¶ Hesse angle alpha. Only angles for the planes within the gnomonic_radius are returned.
- Return type
-
property
hesse_distance
¶ Distance from the PC (origin) per band, i.e. the right-angle component of the distance to the pole.
- Return type
Number of navigation dimensions (a maximum of 2).
- Return type
Navigation shape.
- Return type
-
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
-
property
within_gnomonic_radius
¶ Return whether a plane trace is within the gnomonic_radius as a boolean array.
- Return type
-
property
x_gnomonic
¶ X coordinate in the gnomonic projection plane on the detector for all bands per pattern.
- Return type
-
property
y_gnomonic
¶ Y coordinate in the gnomonic projection plane on the detector for all bands per pattern.
- Return type
-
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
Number of navigation dimensions (a maximum of 2).
- Return type
Navigation shape.
- Return type
-
property
within_gnomonic_radius
¶ Return whether a zone axis is within the gnomonic_radius as a boolean array.
- Return type
-
property
x_gnomonic
¶ X coordinate in the gnomonic projection plane on the detector for all zone axes per pattern.
- Return type
-
property
y_gnomonic
¶ X coordinate in the gnomonic projection plane on the detector for all zone axes per pattern.
- Return type
-