Notebook to merge grain labels between stacked scanning 3DXRD layers#
Written by James Ball
Date: 15/09/2026
Run this after 7_stack_layers.ipynb.
Each layer is indexed and reconstructed on its own, so its grain labels are local to that layer. When the layers are stacked, the labels come along unchanged - a grain that is physically one grain spanning three layers still has three different labels, one per layer.
This notebook finds those cases and gives them a single label, so the labels are meaningful in 3D.
Two grains in neighbouring layers are called the same grain if:
they overlap by at least
overlap_tolvoxels in-planetheir misorientation is below
angle_tol
We only ever compare neighbouring layers. A grain that spans several layers is then recovered by taking connected components of the resulting graph, so layer 0 and layer 2 end up with the same label if they both match layer 1, without us having to compare them directly.
Source: ImageD11/nbGui/S3DXRD/8_merge_layers.ipynb. Shown as saved in git; the documentation build does not run it.
# this cell is tagged with 'parameters'
# to view the tag, select the cell, then find the settings gear icon (right or left sidebar) and look for Cell Tags
# python environment stuff
IMAGED11_PATH = None # means do not use git, otherwise "ImageD11" or "ImageD11_version_xx", etc
CHECKOUT_PATH = None # None means guess, or you can specify a folder for the checkout
# supply the path to one of the dataset files you stacked
# we only use it to find the stacked TensorMap on disk
dset_path = 'si_cube_test/processed/Si_cube/Si_cube_S3DXRD_nt_moves_dty/Si_cube_S3DXRD_nt_moves_dty_dataset.h5'
# path to the stacked TensorMap written by 7_stack_layers.ipynb
# None means look for {ds.sample}_stacked.h5 in ds.analysisroot, which is where that notebook puts it
stacked_tmap_path = None
# where to write the merged TensorMap
# None means insert _merged before the .h5 of the input path
output_path = None
# the largest misorientation (degrees) between two grains in neighbouring layers
# for them to be considered the same grain
angle_tol = 1.0
# the smallest number of voxels two grains must share in-plane
# to be considered for merging at all
overlap_tol = 10
# we plot the input layers to check them - stop after this many
max_layers_to_plot = 5
# when we annotate the label plots, label this many grains per layer (the largest ones)
# no colormap keeps thousands of grains distinct, so the numbers are what you read off the plot
max_annotations_per_layer = 25
if IMAGED11_PATH is not None:
exec(open('/data/id11/nanoscope/install_ImageD11_from_git.py').read())
PYTHONPATH=setup_ImageD11_from_git(CHECKOUT_PATH, IMAGED11_PATH)
else:
import site
PYTHONPATH = site.getsitepackages()[0]
print(PYTHONPATH)
import os
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
from tqdm.autonotebook import tqdm
import ImageD11.grain
import ImageD11.sinograms.dataset
from ImageD11.sinograms.tensor_map import TensorMap
%matplotlib ipympl
Load data#
Dataset#
ds = ImageD11.sinograms.dataset.load(dset_path)
print(ds)
Stacked TensorMap#
This is the output of 7_stack_layers.ipynb, with Z as the first axis.
if stacked_tmap_path is None:
stacked_tmap_path = os.path.join(ds.analysisroot, f'{ds.sample}_stacked.h5')
print('Reading', stacked_tmap_path)
tmap = TensorMap.from_h5(stacked_tmap_path)
print('Map shape (NZ, NY, NX):', tmap.shape)
print('Maps:', sorted(tmap.keys()))
print('Phases:', tmap.phases)
# we need per-voxel grain labels to do anything here
# tomographic TensorMaps have them, point-by-point ones may not
if 'labels' not in tmap.keys():
raise KeyError("This TensorMap has no 'labels' map, so there is nothing to merge")
if tmap.shape[0] < 2:
raise ValueError('Only one Z layer in this TensorMap - did you mean to run 7_stack_layers.ipynb first?')
if 'merged_labels' in tmap.keys():
print("This TensorMap already has a 'merged_labels' map - it will be replaced")
# phase_ids marks voxels with no data as -1, and tells us which phase each voxel belongs to
# it should always be there, but fall back to the labels if it isn't
if 'phase_ids' in tmap.keys():
phase_ids = tmap.phase_ids
else:
print("No 'phase_ids' map - assuming a single phase and using labels > -1 as the valid mask")
phase_ids = np.where(tmap.labels > -1, 0, -1)
# voxels that hold a real, indexed grain
valid = phase_ids > -1
print(f'{valid.sum()} valid voxels of {valid.size}')
# check the layers look sensible before we start
for z_layer in range(min(tmap.shape[0], max_layers_to_plot)):
tmap.plot('ipf_z', z_layer=z_layer)
Build a grain list for each layer#
We make one ImageD11.grain.grain per (layer, label) so that we can use orix to compute
misorientations later.
The UBI is taken from the first voxel of the grain. For a tomographic map every voxel of a grain
holds the same UBI, so this is exact. For a strain-refined map the UBIs vary slightly from voxel
to voxel, and this is then one representative orientation - which is fine here, because the
variation within a grain is far below any sensible angle_tol.
layers_grains = [] # list, one entry per layer, of the grains in that layer
grain_lookup = {} # (z_layer, label) -> grain
for z_layer in tqdm(range(tmap.shape[0])):
layer_grains = []
layer_labels = tmap.labels[z_layer]
layer_phases = phase_ids[z_layer]
layer_valid = valid[z_layer]
for label in np.unique(layer_labels[layer_valid]):
# plain int, so that the (layer, label) keys match the ones we build from the
# overlap counting below - numpy scalars hash the same, but mixing them is confusing
label = int(label)
label_mask = (layer_labels == label) & layer_valid
# indices of the voxels belonging to this grain, take the first one as representative
label_ijk = np.stack(np.where(label_mask))
label_ubi = tmap.UBI[z_layer][tuple(label_ijk[:, 0])]
g = ImageD11.grain.grain(label_ubi)
g.lid = z_layer
g.gid = label
g.phase_id = int(np.unique(layer_phases[label_mask])[0])
g.npx = int(label_mask.sum())
# the grain needs to know its unit cell before it can give us an orix orientation
g.ref_unitcell = tmap.phases[g.phase_id]
layer_grains.append(g)
grain_lookup[(z_layer, label)] = g
layers_grains.append(layer_grains)
print(f'{len(grain_lookup)} grains over {tmap.shape[0]} layers')
Find matching grains in neighbouring layers#
Candidate pairs from the label maps#
Rather than testing every grain in one layer against every grain in the next, we count the
in-plane overlap of every pair of labels in one pass over the two label maps. Encoding the pair
of labels as a single integer lets np.unique do the counting for us.
This is the difference between a few seconds and a very long wait once you have a few thousand grains per layer.
candidate_pairs = [] # ((lid1, gid1), (lid2, gid2), overlap in voxels)
for i in range(tmap.shape[0] - 1):
j = i + 1
# only voxels that hold a grain in BOTH layers can contribute to an overlap
both = valid[i] & valid[j]
li = tmap.labels[i][both].astype(np.int64)
lj = tmap.labels[j][both].astype(np.int64)
if li.size == 0:
continue
# pack the pair of labels into one integer so we can count pairs with np.unique
stride = np.int64(lj.max()) + 1
keys, counts = np.unique(li * stride + lj, return_counts=True)
keep = counts >= overlap_tol
for key, count in zip(keys[keep], counts[keep]):
gid1 = int(key // stride)
gid2 = int(key % stride)
candidate_pairs.append(((i, gid1), (j, gid2), int(count)))
print(f'{len(candidate_pairs)} pairs of grains overlap by at least {overlap_tol} voxels')
Misorientation filter#
Now we check the orientations of the candidates. orix_orien carries the point group of the
phase, so angle_with gives the symmetry-reduced misorientation.
Grains of different phases are never merged, however well they overlap and whatever their matrices say - a misorientation between two different point groups is meaningless.
def are_grains_similar(g1, g2, angle_tol):
"""Do these two grains have the same phase and (near enough) the same orientation?"""
if g1.phase_id != g2.phase_id:
return False
mis_angle = g1.orix_orien.angle_with(g2.orix_orien, degrees=True)[0]
return mis_angle <= angle_tol
matches = []
mis_angles = []
for key1, key2, overlap in tqdm(candidate_pairs):
g1 = grain_lookup[key1]
g2 = grain_lookup[key2]
if g1.phase_id != g2.phase_id:
continue
mis_angles.append(g1.orix_orien.angle_with(g2.orix_orien, degrees=True)[0])
if are_grains_similar(g1, g2, angle_tol):
matches.append((key1, key2))
print(f'{len(matches)} of {len(candidate_pairs)} candidate pairs are the same grain')
Real matches sit in a sharp peak near zero degrees, and everything else is a pair of grains that
happen to sit above one another. If angle_tol (red) is cutting through a populated region, the
merge is arbitrary - move it into the gap.
fig, ax = plt.subplots(layout='constrained')
ax.hist(mis_angles, bins=100)
ax.axvline(angle_tol, color='red')
ax.set(xlabel='Misorientation (degrees)', ylabel='Frequency',
title='Misorientation of overlapping grains in neighbouring layers')
plt.show()
Connected components#
Each grain is a node and each match is an edge. A connected component of that graph is then one physical grain, however many layers it spans, and gives us one new label.
Grains that never matched anything are isolated nodes, so they get a new label of their own and nothing is lost.
G = nx.Graph()
G.add_nodes_from(grain_lookup.keys())
G.add_edges_from(matches)
comps = list(nx.connected_components(G))
print(f'{len(comps)} merged grains from {len(grain_lookup)} per-layer grains')
# how far up the sample does each merged grain reach?
layers_spanned = np.array([len({lid for lid, gid in comp}) for comp in comps])
fig, ax = plt.subplots(layout='constrained')
ax.hist(layers_spanned, bins=np.arange(0.5, tmap.shape[0] + 1.5))
ax.set(xlabel='Layers spanned', ylabel='Frequency', title='Merged grains per number of layers',
yscale='log')
plt.show()
print(f'{(layers_spanned > 1).sum()} merged grains appear in more than one layer')
print(f'{(layers_spanned == tmap.shape[0]).sum()} merged grains span the whole stack')
Relabel the map#
We build a new label map where every voxel of a merged grain carries the same label, in every layer it appears in.
We also fill in tmap.merged_mapping, which TensorMap keeps for exactly this purpose: it maps
each new label back to the (layer, original label) pairs it came from, so nothing about the
original per-layer labelling is lost.
merged_labels = np.full_like(tmap.labels, -1)
tmap.merged_mapping = {}
for merged_gid, comp in enumerate(comps):
for (lid, gid) in comp:
# only relabel valid voxels - invalid ones stay at -1
merged_labels[lid][(tmap.labels[lid] == gid) & valid[lid]] = merged_gid
tmap.merged_mapping[merged_gid] = sorted(comp)
# every voxel that held a grain should still hold one, and no others should have appeared
assert (merged_labels[valid] > -1).all(), 'some valid voxels did not get a merged label'
assert (merged_labels[~valid] == -1).all(), 'some invalid voxels were given a merged label'
print('Labels before:', len(grain_lookup), 'after:', merged_labels.max() + 1)
The check to make on this plot is that a grain keeps the same number from one layer to the next in the bottom row, while the top row shows it changing.
Colour alone cannot do this once you have more than a couple of dozen grains, so the numbers are
the thing to read. Each label gets a random colour, which at least means one merged grain keeps its
colour through the stack, and only the largest max_annotations_per_layer grains in each layer are
annotated to keep the plot legible. Note that a centroid can fall outside its own grain if the
grain is concave or in more than one piece.
def label_centroids(label_image, valid_mask):
"""Centroid (x, y) and voxel count of every label present in one layer"""
rows, cols = np.nonzero(valid_mask)
lab = label_image[valid_mask].astype(np.int64)
keep = lab > -1
lab, rows, cols = lab[keep], rows[keep], cols[keep]
counts = np.bincount(lab)
ysum = np.bincount(lab, weights=rows)
xsum = np.bincount(lab, weights=cols)
ids = np.flatnonzero(counts)
return ids, xsum[ids] / counts[ids], ysum[ids] / counts[ids], counts[ids]
def plot_labels(ax, label_image, valid_mask, palette, nannotate):
# one colour per label, so a label keeps its colour from layer to layer, and white for no data
rgb = np.where(valid_mask[..., None], palette[np.clip(label_image, 0, None)], 1.0)
ax.imshow(rgb, origin='lower')
ids, xc, yc, counts = label_centroids(label_image, valid_mask)
# annotate the biggest grains first - the small ones have no room for the text anyway
for i in np.argsort(counts)[::-1][:nannotate]:
ax.text(xc[i], yc[i], str(ids[i]), ha='center', va='center', fontsize=7,
path_effects=[pe.withStroke(linewidth=2, foreground='w')])
rng = np.random.default_rng(0)
palette = rng.uniform(0.15, 0.95, size=(max(tmap.labels.max(), merged_labels.max()) + 1, 3))
nplot = min(tmap.shape[0], max_layers_to_plot)
fig, axs = plt.subplots(2, nplot, figsize=(4 * nplot, 8), sharex=True, sharey=True, layout='constrained')
axs = np.atleast_2d(axs).reshape(2, nplot)
for z_layer in range(nplot):
plot_labels(axs[0, z_layer], tmap.labels[z_layer], valid[z_layer], palette, max_annotations_per_layer)
plot_labels(axs[1, z_layer], merged_labels[z_layer], valid[z_layer], palette, max_annotations_per_layer)
axs[0, z_layer].set_title(f'Layer {z_layer}')
axs[0, 0].set_ylabel('Original labels')
axs[1, 0].set_ylabel('Merged labels')
fig.supxlabel('Lab X axis --->')
plt.show()
Export#
The merged labels go into a new merged_labels map rather than over the top of labels. That way
the original per-layer labelling is still there in the output file, next to the merged one, and you
can always go back to it or work out where a merged grain came from.
Both are ordinary entries in tmap.maps, so to_h5 writes them and from_h5 reads them back with
no special handling - those two iterate over whatever maps are present.
Note that tmap.merged_labels = merged_labels would not do what you want here:
TensorMap.__getattribute__ looks in tmap.maps before it looks at normal attributes, so the array
would be set as a plain attribute and never seen again. The array has to go into tmap.maps, which
add_map does for us.
tmap.add_map('merged_labels', merged_labels)
assert tmap.merged_labels is merged_labels
print('Maps to write:', sorted(tmap.keys()))
if output_path is None:
output_path = stacked_tmap_path.replace('.h5', '_merged.h5')
print('Writing', output_path)
# NB: to_h5 opens the file in append mode, so delete an old output first if the shape has changed
tmap.to_h5(output_path)
tmap.to_paraview(output_path)
tmap.merged_mapping itself is not written to the file - TensorMap.to_h5 only saves the maps,
the phases and the step sizes. It does not need to be: with both label maps in the file, the
mapping is just the set of (merged label, original label) pairs that occur in the same voxel, so we
can rebuild it on load. The cell below does that, and checks it against the mapping we built above.
def merged_mapping_from_maps(labels, merged_labels, valid):
"""Rebuild the {merged label: [(z_layer, original label), ...]} mapping
from a pair of label maps."""
mapping = {}
for lid in range(labels.shape[0]):
m = valid[lid]
pairs = np.unique(np.stack([merged_labels[lid][m], labels[lid][m]]), axis=1)
for merged_gid, gid in pairs.T:
mapping.setdefault(int(merged_gid), []).append((lid, int(gid)))
return {k: sorted(v) for k, v in mapping.items()}
reloaded = TensorMap.from_h5(output_path)
recovered = merged_mapping_from_maps(reloaded.labels, reloaded.merged_labels, reloaded.phase_ids > -1)
assert recovered == {k: sorted(v) for k, v in tmap.merged_mapping.items()}
print(f'Recovered the mapping for all {len(recovered)} merged grains from {output_path}')