KikuchiPy reference

This reference manual details all EBSD class methods, utility functions and readers of EBSD patterns included in KikuchiPy, as generated from their docstrings. For learning how to use KikuchiPy, see the user guide pages in the sidebar.

EBSD

While some methods listed here are only available to LazyEBSD objects, all methods available to EBSD objects, apart from as_lazy(), are also available to LazyEBSD objects.

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

Bases: hyperspy._signals.signal2d.Signal2D

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

Local contrast enhancement inplace with adaptive histogram equalization.

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

Parameters
  • kernel_size (int or list-like, optional) – Shape of contextual regions for adaptive histogram equalization, default is 1/4 of pattern height and 1/4 of pattern width.

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

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

Examples

To best understand how adaptive histogram equalization works, we plot the histogram of the same pattern 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 kernel size might not fit all pattern sizes, so it may be necessary to search for the optimal kernel size.

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

Create a LazyEBSD object from an EBSD object.

Returns

lazy_signal – Lazy signal.

Return type

LazyEBSD

change_dtype(dtype, rechunk=True)[source]

Change the data type of a Signal.

Parameters
  • dtype (str or numpy.dtype) – Typecode string or data-type to which the Signal’s data array is cast. In addition to all the standard numpy Data type objects (dtype), HyperSpy supports four extra dtypes for RGB images: 'rgb8', 'rgba8', 'rgb16', and 'rgba16'. Changing from and to any rgb(a) dtype is more constrained than most other dtype conversions. To change to an rgb(a) dtype, the signal_dimension must be 1, and its size should be 3 (for rgb) or 4 (for rgba) dtypes. The original dtype should be uint8 or uint16 if converting to rgb(a)8 or rgb(a))16, and the navigation_dimension should be at least 2. After conversion, the signal_dimension becomes 2. The dtype of images with original dtype rgb(a)8 or rgb(a)16 can only be changed to uint8 or uint16, and the signal_dimension becomes 1.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Examples

>>> s = hs.signals.Signal1D([1,2,3,4,5])
>>> s.data
array([1, 2, 3, 4, 5])
>>> s.change_dtype('float')
>>> s.data
array([ 1.,  2.,  3.,  4.,  5.])
decomposition(*args, **kwargs)[source]

Decomposition with a choice of algorithms

The results are stored in self.learning_results

Parameters
  • normalize_poissonian_noise (bool) – If True, scale the SI to normalize Poissonian noise

  • algorithm ('svd' | 'fast_svd' | 'mlpca' | 'fast_mlpca' | 'nmf' |) – ‘sparse_pca’ | ‘mini_batch_sparse_pca’ | ‘RPCA_GoDec’ | ‘ORPCA’

  • output_dimension (None or int) – number of components to keep/calculate

  • centre (None | 'variables' | 'trials') – If None no centring is applied. If ‘variable’ the centring will be performed in the variable axis. If ‘trials’, the centring will be performed in the ‘trials’ axis. It only has effect when using the svd or fast_svd algorithms

  • auto_transpose (bool) – If True, automatically transposes the data to boost performance. Only has effect when using the svd of fast_svd algorithms.

  • navigation_mask (boolean numpy array) – The navigation locations marked as True are not used in the decompostion.

  • signal_mask (boolean numpy array) – The signal locations marked as True are not used in the decomposition.

  • var_array (numpy array) – Array of variance for the maximum likelihood PCA algorithm

  • var_func (function or numpy array) – If function, it will apply it to the dataset to obtain the var_array. Alternatively, it can a an array with the coefficients of a polynomial.

  • reproject (None | signal | navigation | both) – If not None, the results of the decomposition will be projected in the selected masked area.

  • return_info (bool, default False) – The result of the decomposition is stored internally. However, some algorithms generate some extra information that is not stored. If True (the default is False) return any extra information if available

Returns

(X, E) – If ‘algorithm’ == ‘RPCA_GoDec’ or ‘ORPCA’ and ‘return_info’ is True, returns the low-rank (X) and sparse (E) matrices from robust PCA.

Return type

(numpy array, numpy array)

See also

plot_decomposition_factors(), plot_decomposition_loadings(), plot_lev()

dynamic_background_correction(operation='subtract', sigma=None)[source]

Correct dynamic background inplace by subtracting or dividing by a blurred version of each pattern.

Resulting pattern intensities are rescaled to fill the available grey levels in the patterns’ numpy.dtype range.

Parameters
  • operation ('subtract' or 'divide', optional) – Subtract (default) or divide by dynamic background pattern.

  • sigma (int, float or None, optional) – Standard deviation of the gaussian kernel. If None (default), a deviation of pattern width/30 is chosen.

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

>>> s.static_background_correction(operation='subtract')
>>> s.dynamic_background_correction(
        operation='subtract', sigma=2.0)
get_decomposition_model(components=None, dtype_out=<class 'numpy.float16'>)[source]

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

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

Parameters
  • components (None, int or list of ints, optional) – 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 (numpy.float16, numpy.float32, numpy.float64, optional) – Data to cast learning results to (default is numpy.float16). Note that HyperSpy casts them to numpy.float64.

Returns

s_model

Return type

EBSD or LazyEBSD

get_virtual_image(roi)[source]

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

Adapted from pyxem.signals.diffraction2d.Diffraction2D.get_virtual_image().

Parameters

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

Returns

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

Return type

hyperspy.signal.BaseSignal

Examples

>>> import hyperspy.api as hs
>>> roi = hs.roi.RectangularROI(
        left=0, right=5, top=0, bottom=5)
>>> vbse_image = s.get_virtual_image(roi)
rebin(new_shape=None, scale=None, crop=True, out=None)[source]

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

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

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

  • crop (bool) –

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

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

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

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

Returns

s – The resulting cropped signal.

Return type

BaseSignal (or subclass)

Examples

>>> spectrum = hs.signals.EDSTEMSpectrum(np.ones([4, 4, 10]))
>>> spectrum.data[1, 2, 9] = 5
>>> print(spectrum)
<EDXTEMSpectrum, title: dimensions: (4, 4|10)>
>>> print ('Sum = ', sum(sum(sum(spectrum.data))))
Sum = 164.0
>>> scale = [2, 2, 5]
>>> test = spectrum.rebin(scale)
>>> print(test)
<EDSTEMSpectrum, title: dimensions (2, 2|2)>
>>> print('Sum = ', sum(sum(sum(test.data))))
Sum =  164.0
rescale_intensities(relative=False, dtype_out=None)[source]

Rescale pattern intensities inplace to desired numpy.dtype range specified by dtype_out keeping relative intensities or not.

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

Parameters
  • relative (bool, optional) – Keep relative intensities between patterns, default is False.

  • dtype_out (numpy.dtype, optional) – Data type of rescaled patterns, default is input patterns’ data type.

Examples

Pattern intensities are stretched to fill the available grey levels in the input patterns’ data type range or any numpy.dtype range passed to dtype_out, either keeping relative intensities between patterns 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_intensities(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_intensities(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
save(filename=None, overwrite=None, extension=None, **kwargs)[source]

Write signal to 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 (str or None, optional) – 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 (None or bool, optional) – If None and the file exists, it will query the user. If True (False) it (does not) overwrite the file if it exists.

  • extension (None, 'h5', 'hdf5', 'h5ebsd', 'dat' or 'hspy', optional) – Extension of the file that defines the file format. ‘h5’, ‘hdf5’ and ‘h5ebsd’ are equivalent. If None, the extension is determined from the following list in this order: i) the filename, ii) tmp_parameters.extension or iii) ‘h5’ (KikuchiPy’s h5ebsd format).

  • **kwargs – Keyword arguments passed to writer.

set_detector_calibration(delta)[source]

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

Parameters

delta (float) – Detector pixel size in microns.

Examples

>>> print(s.axes_manager['dx'].scale)  # Default value
1.0
>>> s.set_detector_calibration(delta=70.)
>>> print(s.axes_manager['dx'].scale)
70.0
set_experimental_parameters(detector=None, azimuth_angle=None, elevation_angle=None, sample_tilt=None, working_distance=None, binning=None, exposure_time=None, grid_type=None, gain=None, frame_number=None, frame_rate=None, scan_time=None, beam_energy=None, xpc=None, ypc=None, zpc=None, static_background=None, manufacturer=None, version=None, microscope=None, magnification=None)[source]

Set experimental parameters in signal metadata.

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

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

  • binning (int, optional) – Camera binning.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Examples

>>> import kikuchipy as kp
>>> ebsd_node = kp.util.io.metadata_nodes(sem=False)
>>> print(s.metadata.get_item(ebsd_node + '.xpc')
1.0
>>> s.set_experimental_parameters(xpc=0.50726)
>>> print(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, space_group=None, symmetry=None)[source]

Set parameters for one phase in signal metadata, using the International Tables for Crystallography, Volume A.

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.

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

  • symmetry (int, optional) – Phase symmetry.

Examples

>>> print(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}})
>>> print(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 um.

Parameters
  • step_x (float) – Scan step size in um per pixel in horizontal direction.

  • step_y (float) – Scan step size in um per pixel in vertical direction.

Examples

>>> print(s.axes_manager.['x'].scale)  # Default value
1.0
>>> s.set_scan_calibration(step_x=1.5)  # Microns
>>> print(s.axes_manager['x'].scale)
1.5
static_background_correction(operation='subtract', relative=False, static_bg=None)[source]

Correct static background inplace by subtracting/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’ numpy.dtype range.

Parameters
  • operation ('subtract' or 'divide', optional) – Subtract (default) or divide by static background pattern.

  • relative (bool, optional) – Keep relative intensities between patterns (default is False).

  • static_bg (numpy.ndarray, dask.array.Array or None, optional) – Static background pattern. If not passed we try to read it from the signal metadata.

Examples

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

>>> import kikuchipy as kp
>>> ebsd_node = kp.util.io.metadata_nodes(sem=False)
>>> print(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]]

Static background can be corrected by subtracting or dividing this background from each pattern while keeping relative intensities between patterns (or not).

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

If metadata has no background pattern, this must be passed in the static_bg parameter as a numpy or dask array.

virtual_backscatter_electron_imaging(roi, **kwargs)[source]

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

Adapted from meth:pyxem.signals.diffraction2d.Diffraction2D.plot_interactive_virtual_image.

Parameters

Examples

>>> import hyperspy.api as hs
>>> roi = hs.roi.RectangularROI(
        left=0, right=5, top=0, bottom=5)
>>> s.virtual_backscatter_electron_imaging(roi)
class kikuchipy.signals.ebsd.LazyEBSD(*args, **kwargs)[source]

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

change_dtype(dtype, rechunk=True)[source]

Change the data type of a Signal.

Parameters
  • dtype (str or numpy.dtype) – Typecode string or data-type to which the Signal’s data array is cast. In addition to all the standard numpy Data type objects (dtype), HyperSpy supports four extra dtypes for RGB images: 'rgb8', 'rgba8', 'rgb16', and 'rgba16'. Changing from and to any rgb(a) dtype is more constrained than most other dtype conversions. To change to an rgb(a) dtype, the signal_dimension must be 1, and its size should be 3 (for rgb) or 4 (for rgba) dtypes. The original dtype should be uint8 or uint16 if converting to rgb(a)8 or rgb(a))16, and the navigation_dimension should be at least 2. After conversion, the signal_dimension becomes 2. The dtype of images with original dtype rgb(a)8 or rgb(a)16 can only be changed to uint8 or uint16, and the signal_dimension becomes 1.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Examples

>>> s = hs.signals.Signal1D([1,2,3,4,5])
>>> s.data
array([1, 2, 3, 4, 5])
>>> s.change_dtype('float')
>>> s.data
array([ 1.,  2.,  3.,  4.,  5.])
compute(*args, **kwargs)[source]

Attempt to store the full signal in memory.

close_file: bool

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.

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

Perform Incremental (Batch) decomposition on the data, keeping n significant components.

Parameters
  • normalize_poissonian_noise (bool) – If True, scale the SI to normalize Poissonian noise

  • algorithm (str) – One of (‘svd’, ‘PCA’, ‘ORPCA’, ‘ONMF’). By default ‘svd’, lazy SVD decomposition from dask.

  • output_dimension (int) – the number of significant components to keep. If None, keep all (only valid for SVD)

  • get (dask scheduler) – the dask scheduler to use for computations; default dask.threaded.get

  • num_chunks (int) – the number of dask chunks to pass to the decomposition model. More chunks require more memory, but should run faster. Will be increased to contain atleast output_dimension signals.

  • navigation_mask ({BaseSignal, numpy array, dask array}) – The navigation locations marked as True are not used in the decompostion.

  • signal_mask ({BaseSignal, numpy array, dask array}) – The signal locations marked as True are not used in the decomposition.

  • reproject (bool) – Reproject data on the learnt components (factors) after learning.

  • **kwargs – passed to the partial_fit/fit functions.

Notes

Various algorithm parameters and their default values:
ONMF:

lambda1=1, kappa=1, robust=False, store_r=False batch_size=None

ORPCA:

fast=True, lambda1=None, lambda2=None, method=None, learning_rate=None, init=None, training_samples=None, momentum=None

PCA:

batch_size=None, copy=True, white=False

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

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

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

Parameters
  • components (None, int or list of ints, optional) – 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 (numpy.float16, numpy.float32 or numpy.float64, optional) – Data type to set learning results to (default is numpy.float16) before multiplication.

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

  • dir_out (str, optional) – Directory to place output signal in.

  • fname_out (str, optional) – Name of output signal file.

Notes

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

Utilities

Experimental utilities

kikuchipy.util.experimental.normalised_correlation_coefficient(pattern, template, zero_normalised=True)[source]

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

Parameters
Returns

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

Return type

float

References

Gonzalez2008

Gonzalez, Rafael C, Woods, Richard E: Digital Image Processing, 3rd edition, Pearson Education, 954, 2008.

Input/output utilities

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

Load an EBSD object from a supported file.

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

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

  • lazy (bool, optional) – 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.

kikuchipy.io._io.save(filename, signal, overwrite=None, add_scan=None, **kwargs)[source]

Write signal to a file in a supported format.

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

Parameters
  • filename (str) – File path including name of new file.

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

  • overwrite (bool or None, optional) – Whether to overwrite file or not if it already exists.

  • add_scan (bool or None, optional) – Whether to add the signal to an already existing h5ebsd file or not. If the file does not exist the signal is written to a new file.

  • **kwargs – Keyword arguments passed to the writer.

kikuchipy.util.io.kikuchipy_metadata()[source]

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

See set_experimental_parameters() for an explanation of the parameters.

Returns

md

Return type

hyperspy.misc.utils.DictionaryTreeBrowser

kikuchipy.util.io.metadata_nodes(sem=True, ebsd=True)[source]

Return SEM and EBSD metadata nodes.

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

Parameters
  • sem (bool, optional) – Whether to return the SEM node string (default is True).

  • ebsd (bool, optional) – Whether to return the EBSD node string (default is True).

Returns

  • sem_node (str)

  • ebsd_node (str)

Input/output plugins

These plugin functions import patterns and parameters from vendor file formats into EBSD (or LazyEBSD if loading lazily) objects.

h5ebsd

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

Return scan metadata dictionaries from a Bruker h5ebsd file.

Parameters
Returns

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
Returns

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

Read electron backscatter patterns from an h5ebsd file [Jackson2014]. A valid h5ebsd file has at least one group with the name ‘/Scan x/EBSD’ with the groups ‘Data’ (patterns etc.) and ‘Header’ (metadata etc.) , where ‘x’ is the scan_number.

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

  • scans (int or list of ints) – Integer of scan to return, or list of integers of scans to return. If None is passed the first scan in the file is returned.

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

Returns

scan_dict_list – Data, axes, metadata and original metadata.

Return type

list of dicts

References

Jackson2014

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

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

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

Only writing to KikuchiPy’s h5ebsd format is supported.

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

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

  • add_scan (None, bool, optional) – 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, optional) – 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.h5ebsd2signaldict(scan_group, manufacturer, version, lazy=False)[source]

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

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

  • manufacturer ('KikuchiPy', 'EDAX' or 'Bruker Nano') – Manufacturer of file.

  • version (str) – Version of manufacturer software.

  • lazy (bool, optional) – Read dataset lazily.

Returns

scan – Dictionary with patterns, metadata and original_metadata.

Return type

dict

kikuchipy.io.plugins.h5ebsd.h5ebsdgroup2dict(group, dictionary=None, recursive=False, lazy=False)[source]

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

Parameters
Returns

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

Return type

dict

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

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

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

  • manufacturer ('KikuchiPy', 'EDAX' or 'Bruker Nano') – Manufacturer of file.

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

  • lazy (bool, optional) – Read dataset lazily.

Returns

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

Return scan metadata dictionaries from a KikuchiPy h5ebsd file.

Parameters
Returns

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

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

Returns

Return type

dict

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

Get manufacturer and version from h5ebsd file.

Parameters

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

Returns

  • manufacturer (str)

  • version (str)

NORDIF

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

Read electron backscatter patterns from a NORDIF data file.

Parameters
  • filename (str) – File path to NORDIF data file.

  • mmap_mode (str, optional) –

  • scan_size (None, int, or tuple, optional) – Scan size in number of patterns in width and height.

  • pattern_size (None or tuple, optional) – Pattern size in detector pixels in width and height.

  • setting_file (None or str, optional) – File path to NORDIF setting file (default is Setting.txt in same directory as filename).

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

Returns

scan – Data, axes, metadata and original metadata.

Return type

list of dicts

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

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

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

Return metadata with parameters from NORDIF setting file.

Parameters

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

Returns

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

Get relevant part of string using regular expression.

Parameters
  • content (list) – File content to search in for the regular expression.

  • expression (str) – Regular expression.

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

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

Returns

Output string with relevant value.

Return type

str