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