Step-by-step guide: Virtual detectors and grain maps in 4D-STEM#

This notebook makes bright field, dark field and annular dark field images from a 4D-STEM scan with pyEMAPS, step by step, then maps the scan’s grains by comparing whole diffraction patterns. Steps 1 to 6 follow the adf.py and convert_image.py samples, one step per cell.

You’ll:

  1. download a 4D-STEM test scan and look at its diffraction patterns;

  2. make images with virtual detectors: bright field (BF), annular dark field (ADF) and dark field (DF);

  3. check pyEMAPS’ result against a sum you compute yourself;

  4. make an image with a detector mask, including one you draw yourself;

  5. compare whole patterns: a correlation map, groups of similar patterns found without a database, the groups’ average patterns, and every pattern labelled by its group;

  6. turn patterns into polar coordinates, and measure each grain’s rotation from them.

4D-STEM in brief. In scanning transmission electron microscopy (STEM), a focused electron probe is scanned across the sample. In 4D-STEM, a camera records the whole diffraction pattern at every probe position: two scan coordinates and two detector coordinates, hence 4D. A conventional STEM detector adds up the electrons that land on a fixed region of the pattern: a disk on the direct beam for bright field, a ring around it for annular dark field. With the whole pattern recorded, you choose that region after the experiment: a virtual detector. Each scan position gives one pixel of the image.

A licensed feature. The 4D-STEM functions need an activated pyEMAPS license. pyemaps -l trial, run in a terminal with an internet connection, activates a free 7-day trial; for a full license, contact support@emlabsoftware.com. Step 1 checks it.

Requirements. pyEMAPS on Windows, with Python 3.12 to 3.15, and Jupyter in the same environment. Step 2 downloads the test scan, 472 MB, once.

Step 1: Import pyEMAPS and check the license#

StackImage holds experimental images and runs the 4D-STEM analyses. Files the notebook writes go to the pyEMAPS data folder: the folder named by the PYEMAPS_DATA environment variable, or the current folder if it isn’t set.

import hashlib
import os
import shutil
import urllib.request
from importlib.metadata import version

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle

import pyemaps
from pyemaps import E_NPY, EM_INT, StackImage, stem4d

print('pyEMAPS', version('pyemaps'))
if stem4d.check_license_once() == stem4d.LICENSE_ACTIVE:
    print('License: active')
else:
    print('No active license: run "pyemaps -l trial" in a terminal for a 7-day trial, '
          'or contact support@emlabsoftware.com.')

DATA_DIR = os.environ.get('PYEMAPS_DATA') or os.getcwd()
SAMPLES = os.path.join(os.path.dirname(pyemaps.__file__), 'samples')
pyEMAPS 2.11.0
License: active

Step 2: Download the test scan#

adftest900.im3 is a 4D-STEM test scan published by EMLab Solutions on Zenodo under the CC BY 4.0 license. The cell downloads it into the data folder, unless it’s already there, and checks it against its published MD5 checksum. The download is 472 MB, so it can take a few minutes.

URL = 'https://zenodo.org/records/14028793/files/adftest900.im3?download=1'
MD5 = '81d8f8cad15f7fb51c2845505e7209a7'
IMAGE_FILE = os.path.join(DATA_DIR, 'adftest900.im3')


def md5sum(path):
    digest = hashlib.md5()
    with open(path, 'rb') as f:
        for block in iter(lambda: f.read(1 << 20), b''):
            digest.update(block)
    return digest.hexdigest()


if not os.path.exists(IMAGE_FILE):
    print('Downloading adftest900.im3, 472 MB ...')
    urllib.request.urlretrieve(URL, IMAGE_FILE + '.part')
    os.replace(IMAGE_FILE + '.part', IMAGE_FILE)

if md5sum(IMAGE_FILE) == MD5:
    print('adftest900.im3: checksum OK')
else:
    print('adftest900.im3: checksum wrong; delete the file and run this cell again')
adftest900.im3: checksum OK

Step 3: Look at the diffraction patterns#

pyemaps.read_image reads diffraction patterns from a file into a NumPy array, one pattern per scan position. It reads TIFF, DigitalMicrograph, EMD, MRC, Merlin and other files, as well as pyEMAPS’ own .im3 format used here.

An .im3 file records the pattern size and the number of patterns, but not the scan’s shape, so scan_shape gives it: 30 rows of 30 positions. The whole scan, 472 MB, is read into memory.

scan = pyemaps.read_image(IMAGE_FILE, scan_shape=(30, 30))   # (rows, columns) of the scan
print(scan)

patterns = scan.data                 # one pattern per scan position, in scan order
nstacks, height, width = patterns.shape
SCAN = scan.scan_shape[1]            # scan positions per row
print(f'{nstacks} patterns of {width} x {height} pixels, {patterns.dtype}; '
      f'scan: {scan.scan_shape[0]} rows of {SCAN} positions')
ExperimentalImage('adftest900.im3': 900 pattern(s) of 512 x 512, scan (30, 30), int16, read by pyEMAPS)
900 patterns of 512 x 512 pixels, int16; scan: 30 rows of 30 positions

Here are the pattern at the first scan position, and the average of all 900. A logarithmic colour scale shows the weak scattering next to the bright direct beam.

from matplotlib.colors import LogNorm

mean = patterns.mean(axis=0)

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
for ax, image, title in zip(axes, (patterns[0], mean), ('Scan position 1', 'Average of all 900')):
    ax.imshow(np.clip(image, 1, None), cmap='gray', norm=LogNorm())
    ax.set_title(title)
    ax.set_axis_off()
plt.show()
../_images/dce729534f478ee568713c7926189ead4ac9940a1c18c9b97deddfb3595d6923.png

Two things stand out:

  • The average shows rings of spots. The sample is made of grains in different orientations, and each grain’s pattern adds its own spots; summed over the scan, the spots of the same reflections sit on rings around the direct beam.

  • The lower-left quarter of every pattern has a higher background, with straight edges along the pattern’s center lines. That’s the camera, not the sample. A virtual detector that covers it picks up the extra background.

Every virtual detector is placed relative to the direct beam, so first find it: the brightest pixel of the average pattern. The direct beam’s radius shows in how the average intensity falls off around it.

row, col = np.unravel_index(mean.argmax(), mean.shape)
CENTER = (float(col), float(row))                 # (column, row), as pyEMAPS expects
print(f'Direct beam at column {col}, row {row}')

yy, xx = np.indices(mean.shape)
radius = np.hypot(xx - col, yy - row)                 # each pixel's distance from the beam
bins = radius.astype(int).ravel()
profile = np.bincount(bins, mean.ravel()) / np.bincount(bins)
print('Average intensity at radius 0, 4, 8, 12, 16 px:', np.round(profile[[0, 4, 8, 12, 16]]))
Direct beam at column 263, row 263
Average intensity at radius 0, 4, 8, 12, 16 px: [9187. 8061. 1764.  230.  121.]

The intensity drops by a factor of ten within about 10 pixels: that’s the edge of the direct beam. Outside it, the scattering falls off slowly, with a ring around 60 pixels.

Step 4: Bright field, annular dark field and dark field#

generateBDF adds up each pattern’s pixels inside a virtual detector: a disk or ring with the center and the inner and outer radii rads, in pixels. scol is the number of scan positions per row, which shapes the output into an image. It returns a status, 0 on success, and the image as a flat list of values.

  • Bright field (BF): a disk on the direct beam, radius 8 pixels. It records the electrons that pass the sample unscattered.

  • Annular dark field (ADF): a ring from 50 to 200 pixels, as in the adf.py sample. It records the electrons scattered to larger angles.

  • Dark field (DF): the adf.py sample’s off-axis detector, a disk of radius 200 pixels centred at the pattern’s left edge. It collects scattering on one side, but not the direct beam.

DETECTORS = {
    'Bright field':         (CENTER, (0.0, 8.0)),
    'Annular dark field':   (CENTER, (50.0, 200.0)),
    'Dark field':           ((1.0, 256.0), (0.0, 200.0)),
}

images = {}
for name, (center, rads) in DETECTORS.items():
    ret, data = StackImage(IMAGE_FILE, ndtype=EM_INT).generateBDF(center=center, rads=rads,
                                                                  scol=SCAN)
    images[name] = np.array(data, dtype=float).reshape(-1, SCAN)
    print(f'{name}: status {ret}, image {images[name].shape[0]} x {images[name].shape[1]}')
Bright field: status 0, image 30 x 30
Annular dark field: status 0, image 30 x 30
Dark field: status 0, image 30 x 30

Each detector, drawn on the average pattern, and the image it gives:

fig, axes = plt.subplots(2, 3, figsize=(12, 8))
for k, (name, (center, (r_in, r_out))) in enumerate(DETECTORS.items()):
    ax = axes[0, k]
    ax.imshow(np.clip(mean, 1, None), cmap='gray', norm=LogNorm())
    for r in (r_in, r_out):
        if r > 0:
            ax.add_patch(Circle(center, r, fill=False, color='red', linewidth=1.5))
    ax.set_title(name)
    ax.set_axis_off()

    ax = axes[1, k]
    ax.imshow(images[name], cmap='gray')
    ax.set_axis_off()
plt.tight_layout()
plt.show()

bf, adf = images['Bright field'].ravel(), images['Annular dark field'].ravel()
print(f'Correlation between the BF and ADF images: {np.corrcoef(bf, adf)[0, 1]:.2f}')
../_images/935a51f6412940f230f83ab6f2294c7b7bcccc42af1e109e938b85aa1e3ce046.png
Correlation between the BF and ADF images: -0.72

Bright field and annular dark field show largely reversed contrast, with a correlation of −0.72: where the sample scatters strongly, electrons leave the direct beam (darker in BF) and land in the ring (brighter in ADF). The dark field image depends on which part of the pattern its detector covers; try moving it in the exercises.

Step 5: Check it yourself#

A virtual detector is just a sum over pixels, so NumPy can make the same image. Here is the ADF image again, summed directly from the patterns:

ring = (radius >= 50) & (radius <= 200)
mine = np.array([pattern[ring].sum() for pattern in patterns], dtype=float).reshape(-1, SCAN)

print('Largest difference from pyEMAPS:', np.abs(mine - images['Annular dark field']).max())
Largest difference from pyEMAPS: 0.0

The two agree exactly. pyEMAPS does the same sum in compiled code, which is faster on large scans.

Step 6: Detector masks#

A detector doesn’t have to be a disk or a ring. generateMaskedImage takes a mask, an image the size of a pattern: pixels above 0.5 belong to the detector. mask.im3, which comes with pyEMAPS, is the mask of the adf.py sample:

MASK_FILE = os.path.join(SAMPLES, 'mask.im3')
mask = pyemaps.read_image(MASK_FILE).data[0]       # one pattern-sized float32 image

ret, data = StackImage(IMAGE_FILE, ndtype=EM_INT).generateMaskedImage(MASK_FILE, SCAN)
masked = np.array(data, dtype=float).reshape(-1, SCAN)

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(np.clip(mean, 1, None), cmap='gray', norm=LogNorm())
axes[0].imshow(np.ma.masked_where(mask <= 0.5, mask), cmap='autumn', alpha=0.5)
axes[0].set_title('mask.im3 on the average pattern')
axes[1].imshow(masked, cmap='gray')
axes[1].set_title('Masked image')
for ax in axes:
    ax.set_axis_off()
plt.show()
../_images/e96b6d91ec17c6ab22f948aeb9efc27057741597efa182542c2ee7edf2e0347b.png

The mask picks six spots on the ring around 60 pixels, a hexagon from one grain’s pattern. Only one region of the scan lights up: the grain whose diffraction spots fall on the mask. A mask on chosen spots gives a dark field image of the crystal regions that produce them.

A mask of your own#

Draw a mask as a NumPy array, convert it to pyEMAPS’ format with convertImage, and use it. This one is a narrow ring on the scattering around 60 pixels from the direct beam. convertImage saves the file in the sh_converted folder of the data folder, and returns its path.

own_mask = ((radius >= 55) & (radius <= 70)).astype(np.float32)
own_mask_file = StackImage.convertImage(own_mask, nformat=E_NPY)

ret, data = StackImage(IMAGE_FILE, ndtype=EM_INT).generateMaskedImage(own_mask_file, SCAN)
ring_image = np.array(data, dtype=float).reshape(-1, SCAN)

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(np.clip(mean, 1, None), cmap='gray', norm=LogNorm())
axes[0].imshow(np.ma.masked_where(own_mask <= 0.5, own_mask), cmap='autumn', alpha=0.5)
axes[0].set_title('Ring mask, 55 to 70 px')
axes[1].imshow(ring_image, cmap='gray')
axes[1].set_title('Ring image')
for ax in axes:
    ax.set_axis_off()
plt.show()
The numpy image was successfully converted to pyEMAPS image format and saved as C:\pyemaps_data\sh_converted\numpy_image_20261201_204512.im3
../_images/c5db14a67b990cbf4777343cedcf8f72b612f3786cf37111bedf38ee7448881c.png

Converting other images#

convertImage also converts raw image files: pixel data with no header, or a header of known size. You give the dimensions and where the data starts. The convert_image.py sample converts raw.img, a 256 × 256 image of 4-byte floats with no header. The converted file goes into an sh_converted folder next to the input, so the cell first copies raw.img into the data folder.

raw_file = shutil.copy(os.path.join(SAMPLES, 'raw.img'), DATA_DIR)
converted = StackImage.convertImage(raw_file,
                                    dim=(256, 256, 1),   # width, height and number of stacks
                                    noffset=0)           # bytes before the image data

image = StackImage(converted)
image.loadImage()
image.viewExpImage(title='raw.img, converted')
The image file C:\pyemaps_data\raw.img was successfully converted to pyEMAPS image format and saved as C:\pyemaps_data\sh_converted\raw.im3
../_images/531d0d491677043a90d7f8ea321efd2a966918696b0599241409d4ed950c99a0.png

Step 7: Compare whole patterns#

A virtual detector turns each pattern into a single number. The next steps compare whole patterns instead: two patterns from the same grain look alike, whatever their total intensity, so comparing patterns finds the grains without knowing the crystal. All these methods read the whole scan into memory, run in compiled code on all the processor’s cores, and return NumPy arrays. Like the virtual detectors, they need the license.

The scan’s file doesn’t record its shape, so each call gets it as scan_shape. First, the average of all the patterns, which averagePattern computes:

stack = StackImage(IMAGE_FILE, ndtype=EM_INT)
SHAPE = scan.scan_shape           # (rows, columns): the .im3 file doesn't record it

average = stack.averagePattern()
print(f'Average pattern: {average.shape[1]} x {average.shape[0]}, {average.dtype}')
print(f'Largest difference from the NumPy average: {np.abs(average - mean).max():.1e}')
Average pattern: 512 x 512, float32
Largest difference from the NumPy average: 4.9e-04

It’s the average from Step 3, to the precision of the 32-bit floats it’s returned in.

Step 8: A correlation map#

correlationMap compares every pattern with a template, here the pattern at one scan position, and gives their correlation coefficient: 1 for patterns that are the same up to brightness and background, around 0 for unrelated ones.

The comparison uses only the pixels of a mask: here a ring from 15 to 120 pixels around the direct beam. Every pattern has the bright direct beam in the same place, so with it in the mask, every pattern would look much like every other.

MASK = (radius > 15) & (radius < 120)       # leave out the direct beam and the outer pixels

ROW, COL = 16, 10                            # a scan position inside a grain
template = patterns[ROW * SCAN + COL]
similarity = stack.correlationMap(template, mask=MASK, scan_shape=SHAPE)

fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].imshow(np.clip(average, 1, None), cmap='gray', norm=LogNorm())
axes[0].imshow(np.ma.masked_where(~MASK, MASK), cmap='autumn', alpha=0.3)
axes[0].set_title('The mask on the average pattern')
axes[1].imshow(np.clip(template, 1, None), cmap='gray', norm=LogNorm())
axes[1].set_title(f'Template: row {ROW}, column {COL}')
im = axes[2].imshow(similarity, cmap='viridis', vmin=0, vmax=1)
axes[2].plot(COL, ROW, 'r+', markersize=12)
axes[2].set_title('Correlation with the template')
fig.colorbar(im, ax=axes[2], shrink=0.8)
for ax in axes:
    ax.set_axis_off()
plt.show()

print(f'{(similarity > 0.5).sum()} of {similarity.size} patterns correlate above 0.5; '
      f'the lowest correlation is {similarity.min():.2f}')
../_images/0f8c3e5de9a4a7bc6aead5ee4d19f930097ef9309e38d98aa3e2a3568dbeaf97.png
71 of 900 patterns correlate above 0.5; the lowest correlation is -0.01

The patterns that match the template form one compact region around the template’s position (the red cross): one grain, the region of the sample with the same crystal orientation. Elsewhere, the correlation drops to near 0, as the spots fall in other places.

Step 9: Find the grains#

findSimilar groups similar patterns without a template, so it finds the grains by itself. It tries a fifth of the patterns (fraction=0.2), in a random order, as seeds. A seed that isn’t in a group yet starts one and collects the patterns that correlate with it above threshold, searching along the scan in both directions. It stops searching when two scan rows of patterns in a row, 60, don’t match (reach). Each pattern’s label is its group’s seed: the pattern’s index in the scan, row * 30 + column. The random order is fixed by seed=1, so running it again gives the same groups.

groups, seed_corr = stack.findSimilar(threshold=0.5, mask=MASK, scan_shape=SHAPE)

names, counts = np.unique(groups, return_counts=True)
print(f'{len(names)} groups; {(counts == 1).sum()} patterns stayed alone')
order = np.argsort(-counts)
GRAINS = names[order][counts[order] >= 20]       # the groups of 20 patterns or more
for g in GRAINS:
    r, c = divmod(int(g), SCAN)
    print(f'  group {g:3d}: {(groups == g).sum():3d} patterns, seed at row {r}, column {c}')
46 groups; 17 patterns stayed alone
  group 594: 135 patterns, seed at row 19, column 24
  group 878: 134 patterns, seed at row 29, column 8
  group 228: 123 patterns, seed at row 7, column 18
  group 489:  63 patterns, seed at row 16, column 9
  group 478:  50 patterns, seed at row 15, column 28
  group 830:  45 patterns, seed at row 27, column 20
  group 360:  40 patterns, seed at row 12, column 0
  group 243:  39 patterns, seed at row 8, column 3
  group 888:  37 patterns, seed at row 29, column 18
  group 119:  24 patterns, seed at row 3, column 29
  group 381:  24 patterns, seed at row 12, column 21

Groups of 20 patterns or more, the larger grains, side by side with the annular dark field image from Step 4. Each x marks the group’s seed; the white positions belong to the small groups.

grain_map = np.full(groups.shape, np.nan)
for k, g in enumerate(GRAINS):
    grain_map[groups == g] = k

fig, axes = plt.subplots(1, 2, figsize=(11, 5))
axes[0].imshow(grain_map, cmap='tab20', vmin=0, vmax=19)
for k, g in enumerate(GRAINS):
    r, c = divmod(int(g), SCAN)
    axes[0].plot(c, r, 'kx')
    axes[0].text(c + 0.6, r, str(k), fontsize=9)
axes[0].set_title(f'The {len(GRAINS)} largest groups (x: seed)')
axes[1].imshow(images['Annular dark field'], cmap='gray')
axes[1].set_title('Annular dark field image')
for ax in axes:
    ax.set_axis_off()
plt.show()
../_images/283b1cd18ed27c55ff518f6c9fd50db7b7e0bda70335c8edf270312d8cbd14c5.png

The groups follow the grains’ outlines in the ADF image, where a change in contrast marks a grain boundary. Many of the white positions lie along the boundaries, where the probe can cover two grains and the patterns mix both.

Step 10: Average each group#

Each pattern is noisy, but the patterns of a grain all have the same spots. averageByLabel averages the patterns with the same label: here, each large group. Patterns labelled -1 are left out, so the small groups are. It returns the averages in increasing order of label, with those labels and the number of patterns in each; the cell puts them in the order of GRAINS, largest first.

labels = np.where(np.isin(groups, GRAINS), groups, -1)      # -1: left out of the averages
grain_avg, values, counts = stack.averageByLabel(labels, scan_shape=SHAPE)
grain_avg = grain_avg[[list(values).index(g) for g in GRAINS]]  # in the order of GRAINS

k = list(GRAINS).index(groups[ROW, COL])
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(np.clip(template, 1, None), cmap='gray', norm=LogNorm())
axes[0].set_title(f'One pattern, row {ROW}, column {COL}')
axes[1].imshow(np.clip(grain_avg[k], 1, None), cmap='gray', norm=LogNorm())
axes[1].set_title(f'Average of its group, {(groups == GRAINS[k]).sum()} patterns')
for ax in axes:
    ax.set_axis_off()
plt.show()
../_images/b2f1a20beb2ab59bd42a722db7a5561d3a0408fce30c4b4d1f24e3061419f9db.png

The average of the grain’s 63 patterns shows weak spots far from the direct beam that the noise hides in a single pattern. Here are all the groups’ averages:

fig, axes = plt.subplots(2, 6, figsize=(18, 6.5))
for k, ax in enumerate(axes.flat):
    if k < len(GRAINS):
        ax.imshow(np.clip(grain_avg[k], 1, None), cmap='gray', norm=LogNorm())
        ax.set_title(f'Group {k}: {(groups == GRAINS[k]).sum()} patterns', fontsize=10)
    ax.set_axis_off()
plt.tight_layout()
plt.show()
../_images/c1db2a7e2c8edffbfb06c06e8cb2a4203a27e6cd8697a493df6bae616a7c45c2.png

Groups 0 to 7 and 10 are grains with clear spot patterns, each in its own orientation. Groups 8 and 9, along the bottom and top edges of the scan, show only the direct beam and diffuse scattering: no crystal there is in an orientation that diffracts strongly.

Step 11: Label every pattern#

findSimilar left some patterns in small groups, or alone. classifyPatterns labels every pattern by the template it correlates with best: here, the groups’ averages. It returns the best template’s index, from 0, and the correlation.

classes, class_corr = stack.classifyPatterns(grain_avg, mask=MASK, scan_shape=SHAPE)

grouped = np.isin(groups, GRAINS)
same = (GRAINS[classes[grouped]] == groups[grouped]).mean()
print(f'Every pattern labelled; {100 * same:.0f}% of the grouped patterns keep their group')
print(f'Correlation with the best average: median {np.median(class_corr):.2f}, '
      f'lowest {class_corr.min():.2f}')

fig, axes = plt.subplots(1, 2, figsize=(11, 5))
axes[0].imshow(classes, cmap='tab20', vmin=0, vmax=19)
axes[0].set_title('Each pattern labelled by its best group average')
im = axes[1].imshow(class_corr, cmap='viridis', vmin=0, vmax=1)
axes[1].set_title('Its correlation with that average')
fig.colorbar(im, ax=axes[1], shrink=0.8)
for ax in axes:
    ax.set_axis_off()
plt.show()
Every pattern labelled; 97% of the grouped patterns keep their group
Correlation with the best average: median 0.85, lowest 0.07
../_images/36e96cd88da9dc1d7635c1f0356b5ebd4a99d221b56768e48bededd66f4185d2.png

Every scan position now belongs to one of the groups. The correlation is high inside the grains: the averages are good templates for their patterns. It drops along the grain boundaries, where the patterns are mixtures. A few patterns change group, since findSimilar compared them with a single, noisy seed pattern, and classifyPatterns with the groups’ averages.

Step 12: Polar transforms#

In a diffraction pattern, the distance of a spot from the direct beam depends on the crystal’s lattice spacing, and its angle around the beam on the crystal’s orientation. polar_transform turns a pattern into polar coordinates about a center: row r is the circle of radius r pixels, and column k the angle k degrees, counterclockwise from the pattern’s +column direction. Rings become straight rows. The transform has 249 radii here, out to the pattern’s nearest edge.

The average pattern’s rings, from Step 3, become rows of spots, and averaging over the angles gives the radial profile, with a peak for each ring:

from pyemaps import polar_transform

polar = polar_transform(average, CENTER)          # rows: radius 0, 1, ... px; columns: 0-359 deg
profile = polar.mean(axis=1)                       # the average over angles at each radius
rings = [r for r in range(20, len(profile) - 4) if profile[r] == profile[r - 4:r + 5].max()]
print(f'Polar transform: {polar.shape[0]} radii x {polar.shape[1]} angles')
print('Rings at radii (px):', rings[:4])

fig, axes = plt.subplots(1, 2, figsize=(13, 5))
axes[0].imshow(np.clip(polar, 1, None), cmap='gray', norm=LogNorm(), aspect='auto')
axes[0].set_xlabel('Angle (degrees)')
axes[0].set_ylabel('Radius (px)')
axes[0].set_title('Polar transform of the average pattern')
axes[1].semilogy(profile)
for r in rings[:4]:
    axes[1].axvline(r, color='red', linewidth=0.8, linestyle='--')
axes[1].set_xlabel('Radius (px)')
axes[1].set_ylabel('Average intensity')
axes[1].set_title('Radial profile')
plt.show()
Polar transform: 249 radii x 360 angles
Rings at radii (px): [64, 112, 131, 170]
../_images/7ca69bc6d632461cdb68c1097b5063cde86cf0919e658ed8b49806b1f7e3df0a.png

The camera’s brighter lower-left quarter (Step 3) becomes the band from 180 to 270 degrees.

On the first ring, around 64 pixels, every grain has six spots, 60 degrees apart. How far the six are rotated is the grain’s rotation about the beam. The cell below finds it from the brightest pixel at each angle between 55 and 72 pixels: sixfold_angle fits a repeat every 60 degrees to that profile with a Fourier sum, and gives its phase as an angle from 0 to 60 degrees and how strong the repeat is. Two of the group averages:

RING = slice(55, 73)          # the radii of the first ring
theta = np.arange(polar.shape[1])

def sixfold_angle(ring_profile, step=1.0):
    """The angle of the first of six spots 60 degrees apart, from 0 to 60, and how strong the
    sixfold repeat is."""
    f6 = np.sum(ring_profile * np.exp(-6j * np.radians(np.arange(len(ring_profile)) * step)))
    return np.degrees(-np.angle(f6)) / 6 % 60, abs(f6) / np.sum(ring_profile)

fig, ax = plt.subplots(figsize=(12, 4))
for k in (0, 1):
    on_ring = polar_transform(grain_avg[k], CENTER)[RING].max(axis=0)
    angle, _ = sixfold_angle(on_ring)
    ax.plot(theta, on_ring, label=f'Group {k}: spots at {angle:.0f} + 60n degrees')
ax.set_xlabel('Angle (degrees)')
ax.set_ylabel('Brightest pixel, radius 55-72 px')
ax.set_xticks(range(0, 361, 60))
ax.legend()
plt.show()
../_images/79af6ffd31c4a585b2a48115efaff6c8ef019050e78764c77866fc749b69c30f.png

The two grains’ spots are 16 degrees apart: grain 1 is rotated by 16 degrees relative to grain 0.

StackImage.polarTransform transforms every pattern of the scan at once, here in 2-degree steps. Measuring the six spots’ angle in every pattern maps the rotation across the scan. Where the sixfold repeat is weak, in groups 8 and 9, the angle means nothing, so the map greys those positions out.

scan_polar = stack.polarTransform(CENTER, dtheta=2.0)       # every pattern: 2-degree steps
print(f'{scan_polar.shape[0]} transforms of {scan_polar.shape[1]} radii x '
      f'{scan_polar.shape[2]} angles, {scan_polar.nbytes / 1e6:.0f} MB')

rotation, strength = np.zeros(SHAPE), np.zeros(SHAPE)
for n, p in enumerate(scan_polar):
    rotation.flat[n], strength.flat[n] = sixfold_angle(p[RING].max(axis=0), step=2.0)

fig, axes = plt.subplots(1, 2, figsize=(11, 5))
im = axes[0].imshow(np.ma.masked_where(strength < 0.1, rotation), cmap='twilight',
                    vmin=0, vmax=60)
fig.colorbar(im, ax=axes[0], shrink=0.8, label='degrees')
axes[0].set_title('Rotation of the six spots (grey: no sixfold pattern)')
axes[0].set_facecolor('0.6')
im = axes[1].imshow(strength, cmap='gray')
fig.colorbar(im, ax=axes[1], shrink=0.8)
axes[1].set_title('Strength of the sixfold repeat')
for ax in axes:
    ax.set_xticks([])
    ax.set_yticks([])
plt.show()

for k, g in enumerate(GRAINS):
    inside = groups == g
    print(f'Group {k}: rotation {np.median(rotation[inside]):4.1f} degrees, '
          f'sixfold strength {np.median(strength[inside]):.2f}')
900 transforms of 249 radii x 180 angles, 161 MB
../_images/606e0b005d442f54512d7c6ab5db62ce25b2ccea085e3e1ded455ef2bf5fea91.png
Group 0: rotation 31.5 degrees, sixfold strength 0.71
Group 1: rotation 47.5 degrees, sixfold strength 0.67
Group 2: rotation 10.9 degrees, sixfold strength 0.32
Group 3: rotation 20.3 degrees, sixfold strength 0.76
Group 4: rotation 36.1 degrees, sixfold strength 0.58
Group 5: rotation 32.3 degrees, sixfold strength 0.70
Group 6: rotation 18.9 degrees, sixfold strength 0.56
Group 7: rotation 19.5 degrees, sixfold strength 0.41
Group 8: rotation 31.0 degrees, sixfold strength 0.06
Group 9: rotation 17.1 degrees, sixfold strength 0.06
Group 10: rotation 31.6 degrees, sixfold strength 0.69

The rotation map shows the grains from Step 9, measured independently of them: each grain has one rotation, and it changes sharply at the boundaries. Neighbouring groups 0, 5 and 10, though, all have the same rotation, near 32 degrees. Compare their averages:

def correlation(a, b):
    """The correlation coefficient of two patterns over the mask's pixels."""
    a, b = a[MASK] - a[MASK].mean(), b[MASK] - b[MASK].mean()
    return np.sum(a * b) / np.sqrt(np.sum(a * a) * np.sum(b * b))

for j, k in ((0, 5), (0, 10), (5, 10), (0, 1), (3, 6)):
    r = correlation(grain_avg[j], grain_avg[k])
    print(f'Groups {j} and {k}: their averages correlate at {r:.2f}')
Groups 0 and 5: their averages correlate at 0.79
Groups 0 and 10: their averages correlate at 0.64
Groups 5 and 10: their averages correlate at 0.71
Groups 0 and 1: their averages correlate at 0.00
Groups 3 and 6: their averages correlate at 0.10

Groups 0, 5 and 10 correlate well with each other, unlike two different grains such as 0 and

  1. They are most likely one grain whose patterns change gradually across it, for example with a slight bend or a change in thickness. findSimilar split it because it compares single, noisy patterns, which correlate less than their averages. The polar transform’s angles, which don’t change with the spots’ intensities, keep it together.

Groups 3 and 6 are the other way round: nearly the same rotation, 20 and 19 degrees, but their averages hardly correlate. The six spots’ angle is only part of a grain’s orientation, so the rotation map doesn’t tell every grain apart; comparing whole patterns does.

Try it yourself#

  1. Detector angles. Make ADF images with inner radii of 20, 50 and 100 pixels. How does the contrast change as the detector collects only higher angles?

  2. Bright field size. Make BF images with radii of 4, 8 and 16 pixels. What happens once the detector is larger than the direct beam?

  3. Dark field. Place a small disk detector, radius 10 pixels, on the ring around 60 pixels, at different angles around the direct beam. Do the images differ?

  4. Half-disk masks. Make two masks, the left and the right halves of the direct beam, and subtract the two images. Where the sample deflects the beam, one half receives more electrons than the other: this is the idea behind differential phase contrast imaging.

  5. Threshold. Run findSimilar with thresholds of 0.4 and 0.6. How do the number and size of the groups change? What happens to the patterns along the grain boundaries?

  6. The direct beam. Use a mask without the hole for the direct beam, radius < 120, in the correlation map of Step 8. How does the map change?

  7. Another ring. Measure each grain’s rotation from the third ring, around 131 pixels, instead of the first. Is that ring sixfold too, and do the angles agree?

Next#

Further reading#

J. C. H. Spence and J. M. Zuo, Electron Microdiffraction (Plenum, New York, 1992), doi:10.1007/978-1-4899-2353-0:

  • chapter 8, Coherent Nanoprobes. STEM. Defects and Amorphous Materials, for STEM with a focused probe.

J. M. Zuo and J. C. H. Spence, Advanced Transmission Electron Microscopy (Springer, New York, 2017), doi:10.1007/978-1-4939-6607-3, a newer and broader book by the same authors:

  • chapter 9, Electron Detectors, for the cameras that record 4D-STEM data;

  • chapter 10, Instrumentation and Experimental Techniques, for the microscope side of the experiment.