This page was generated from doc/pattern_matching.ipynb. Interactive online version: Binder badge.

Pattern matching

Crystal orientations can be determined from experimental EBSD patterns by matching them to a dictionary of simulated patterns of known orientations [CPW+15], [NWB16], [FCWB19].

Here, we will demonstrate pattern matching using a small Ni data set of nine EBSD patterns from two grains and a dynamically simulated master pattern from EMsoft, both of low resolution and found in the kikuchipy.data module.

Warning

The generated pattern dictionary is discrete, but no refinement of the best matching orientation is provided. The need for the latter is discussed in e.g. [SRDeGraef17].

Before we can generate a dictionary of simulated patterns, we need a master pattern containing all possible scattering vectors for a candidate phase. This can simulated done using EMsoft [CDeGraef13] [JGU+14], and then read into kikuchipy.

First, we import libraries and load the small experimental Nickel test data.

[1]:
# exchange inline for qt5 for interactive plotting from the pyqt package
%matplotlib inline

import tempfile
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 15
import hyperspy.api as hs
import numpy as np
from orix import sampling, plot, io
import kikuchipy as kp


s = kp.data.nickel_ebsd_small()  # Use kp.load("data.h5") to load your own data
s
WARNING:hyperspy.api:The ipywidgets GUI elements are not available, probably because the hyperspy_gui_ipywidgets package is not installed.
WARNING:hyperspy.api:The traitsui GUI elements are not available, probably because the hyperspy_gui_traitsui package is not installed.
[1]:
<EBSD, title: patterns My awes0m4 ..., dimensions: (3, 3|60, 60)>

To obtain a good match, we must increase the signal-to-noise ratio. In this pattern matching analysis, the Kikuchi bands are considered the signal, and the angle-dependent backscatter intensity, along with unwanted detector effects, are considered to be noise. See the pattern processing guide for further details.

[2]:
s.remove_static_background()
s.remove_dynamic_background()
Removing the static background:
[########################################] | 100% Completed |  0.8s
Removing the dynamic background:
[########################################] | 100% Completed |  0.4s

Next, we load a dynamically simulated Nickel master pattern generated with EMsoft, in the northern hemisphere projection of the square Lambert projection for an accelerating voltage of 20 keV.

[3]:
mp = kp.data.nickel_ebsd_master_pattern_small(projection="lambert", energy=20)
mp
[3]:
<EBSDMasterPattern, title: ni_mc_mp_20kv_uint8_gzip_opts9, dimensions: (|401, 401)>
[4]:
mp.plot()
_images/pattern_matching_8_0.png

The Nickel phase information, specifically the crystal symmetry, asymmetric atom positions, and crystal lattice, is conveniently stored in an orix.crystal_map.Phase.

[5]:
ni = mp.phase
ni
[5]:
<name: ni. space group: Fm-3m. point group: m-3m. proper point group: 432. color: tab:blue>
[6]:
ni.structure  # Element, x, y, z, site occupation
[6]:
[28   0.000000 0.000000 0.000000 1.0000]
[7]:
ni.structure.lattice  # nm and degrees
[7]:
Lattice(a=0.35236, b=0.35236, c=0.35236, alpha=90, beta=90, gamma=90)

If we don’t know anything about the possible crystal (unit cell) orientations in our sample, the safest thing to do is to generate a dictionary of orientations uniformly distributed in a candidate phase’s orientation space. To achieve this, we sample the Rodrigues Fundamental Zone of the proper point group 432 with a 5\(^{\circ}\) characteristic distance between orientations (we can either pass in the proper point group, or the space group, which is a subgroup of the proper point group) using orix.sampling.get_sample_fundamental().

[8]:
r = sampling.get_sample_fundamental(
    resolution=5, space_group=ni.space_group.number
)
r
[8]:
Rotation (7467,)
[[ 1.     -0.     -0.     -0.    ]
 [ 0.986  -0.1667 -0.     -0.    ]
 [ 0.9718 -0.2357 -0.     -0.    ]
 ...
 [ 0.9538 -0.2887 -0.      0.0834]
 [ 0.9392 -0.3333 -0.      0.0822]
 [ 0.9244 -0.3727 -0.      0.0809]]

This sampling resulted in 7 467 crystal orientations.

Note

A characteristic distance of 5\(^{\circ}\) results in a course sampling of orientation space; a shorter distance should be used for real experimental work.

Now that we have our master pattern and crystal orientations, we need to describe the EBSD detector’s position with respect to the sample (interaction volume). This ensures that projecting parts of the master pattern onto our detector yields dynamically simulated patterns resembling our experimental ones. See the reference frames user guide and the EBSDDetector class for further details.

[9]:
detector = kp.detectors.EBSDDetector(
    shape=s.axes_manager.signal_shape[::-1],
    pc=[0.421, 0.7794, 0.5049],
    sample_tilt=70,
    convention="tsl",
)
detector
[9]:
EBSDDetector (60, 60), px_size 1 um, binning 1, tilt 0, pc (0.421, 0.221, 0.505)

Let’s double check the projection/pattern center (PC) position on the detector using plot().

[10]:
detector.plot(coordinates="gnomonic", pattern=s.inav[0, 0].data)
_images/pattern_matching_19_0.png

Now we’re ready to generate our dictionary of simulated patterns by projecting parts of the master pattern onto our detector for all sampled orientations, using the get_patterns() method. The method assumes the crystal orientations are represented with respect to the EDAX TSL sample reference frame RD-TD-ND.

[11]:
sim = mp.get_patterns(
    rotations=r,
    detector=detector,
    energy=20,
    dtype_out=s.data.dtype,
    compute=True
)
sim
Creating a dictionary of (7467,) simulated patterns:
[########################################] | 100% Completed | 13.7s
[11]:
<EBSD, title: , dimensions: (7467|60, 60)>

Let’s inspect the three first of the 7 467 simulated patterns.

[12]:
#sim.plot()  # Plot the patterns with a navigator for easy inspection
fig, ax = plt.subplots(ncols=3, figsize=(18, 6))
for i in range(3):
    ax[i].imshow(sim.inav[i].data, cmap="gray")
    euler = np.rad2deg(sim.xmap[i].rotations.to_euler())[0]
    ax[i].set_title(
        f"($\phi_1, \Phi, \phi_2)$ = {np.array_str(euler, precision=1)}"
    )
    ax[i].axis("off")
fig.tight_layout()
_images/pattern_matching_23_0.png

Finally, let’s use the match_patterns() method to match the 7 467 simulated patterns to our nine experimental patterns, using the zero-mean normalized cross correlation (NCC) coefficient \(r\) [GW17], which is the default similarity metric. Let’s keep the 10 best matching orientations. A number of 9 * 7467 comparisons is quite small, which we can do in memory all at once. However, in cases where the number of comparisons are too big for our memory to handle, we can slice our simulated pattern data into \(n\) slices. To demonstrate this, we use 10 slices here. The results are returned as a orix.crystal_map.CrystalMap.

[13]:
xmap = s.match_patterns(sim, n_slices=10, keep_n=10)
xmap
Matching ni patterns: 100%|██████████| 10/10 [00:00<00:00, 19.96slice/s, mem=38.3%]
[13]:
Phase  Orientations  Name  Space group  Point group  Proper point group     Color
    0    9 (100.0%)    ni        Fm-3m         m-3m                 432  tab:blue
Properties: scores, simulation_indices
Scan unit: um

The results can be exported to an HDF5 file re-readable by orix.

[14]:
temp_dir = tempfile.mkdtemp()
xmap_file = temp_dir + "ni.h5"
io.save(xmap_file, xmap)

Let’s inspect our matching results by plotting a map of the highest \(r\) (stored in the scores property).

[15]:
fig, ax = plt.subplots(subplot_kw=dict(projection="plot_map"))
ax.plot_map(xmap, xmap.scores[:, 0], scalebar=False)
ax.add_colorbar(label=r"$r$")
_ = ax.axis("off")
_images/pattern_matching_29_0.png

We can use the crystal map property simulation_indices to get the best matching simulated patterns from the dictionary of simulated patterns.

[16]:
best_patterns = sim.data[xmap.simulation_indices[:, 0]].reshape(s.data.shape)
s_best = kp.signals.EBSD(best_patterns)
s_best
[16]:
<EBSD, title: , dimensions: (3, 3|60, 60)>

The simplest way to visually compare the experimental and best matching simulated patterns are to plot them in the same navigator. Here, we use the highest \(r\) as a navigator. When using an interactive backend like Qt5Agg, we can then move the red square around to look at the patterns in each point.

[17]:
ncc_navigator = hs.signals.Signal2D(xmap.get_map_data(xmap.scores[:, 0]))
hs.plot.plot_signals([s, s_best], navigator=hs.signals.Signal2D(ncc_navigator))
_images/pattern_matching_33_0.png
_images/pattern_matching_33_1.png
_images/pattern_matching_33_2.png

Let’s also plot the best matches for patterns from the two grains.

[18]:
fig, ax = plt.subplots(ncols=2, nrows=2, figsize=(10, 10))
ax[0, 0].imshow(s.inav[0, 0].data, cmap="gray")
ax[0, 0].axis("off")
ax[0, 1].imshow(s_best.inav[0, 0].data, cmap="gray")
ax[0, 1].axis("off")
ax[1, 0].imshow(s.inav[2, 0].data, cmap="gray")
ax[1, 0].axis("off")
ax[1, 1].imshow(s_best.inav[2, 0].data, cmap="gray")
ax[1, 1].axis("off")
fig.tight_layout(h_pad=0.5, w_pad=1)
_images/pattern_matching_35_0.png