Tomographic mapping notebook, with optimizations for minor phases#

Written by Haixing Fang, Jon Wright and James Ball
Date: 21/02/2025

Source: ImageD11/nbGui/S3DXRD/tomo_2_map_minor_phase.ipynb. Shown as saved in git; the documentation build does not run it.

This notebook will try to reconstruct grain shapes and positions from the grain orientations you found in the first notebook.
This notebook is optimised for weak and noisy minor phase data.
This notebook (and the tomo route in general) works best for low levels of deformation.
If it doesn’t seem to work well, try the point-by-point route instead!

import os

os.environ['OMP_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
# 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

# dataset file to import
dset_path = 'si_cube_test/processed/Si_cube/Si_cube_S3DXRD_nt_moves_dty/Si_cube_S3DXRD_nt_moves_dty_dataset.h5'

# phase names to look at
major_phase_strs = ['Fe']
minor_phase_str = 'Au'

# peak filtration parameters
# whether to filter out major phase peaks before trying to build sinograms
remove_major_phase_peaks = True
major_phase_cf_dstol = 0.005
minor_phase_cf_frac = 0.9975
minor_phase_cf_dstol = 0.005

# We can interactively draw a mask
draw_mask_interactive = True
# or we can threshold with Otsu, or a manual threshold value:
# e.g. manual_threshold = 0.006
manual_threshold = None

# If the sinograms are only half-sinograms (we scanned dty across half the sample rather than the full sample), set the below to true:
is_half_scan = False
# If we did halfmask, choose the radius to mask in the centre of the reconstruction (normally hot pixels)
halfmask_radius = 25

# assign peaks to the grains with hkl tolerance peak_assign_tol
peak_assign_tol = 0.05

# tolerance for building sinograms from assigned peaks
hkltol = 0.25

# We can optionally correct each row of the sinogram by the ring current of that rotation
# This helps remove artifacts in the reconstruction
correct_sinos_with_ring_current = False

# optional twin-friendly assignment
# allows grains to share reflections
twin_assign = False

# optional structure factor correction
# needs CIF!
struc_factor_correction = False
cif_for_sf_path = '/path/to/cif.cif'

# use astra to run a second cycle of sinogram reconstructions?
run_astra = True
# run astra locally or on the cluster?
run_astra_on_cluster = True
# which ASTRA method?
astra_method = 'EM_CUDA'
# or 'FBP' if you run locally without CUDA
# how many iterations for Astra reconstruction?
niter = 500

if struc_factor_correction:
    first_tmap_cutoff_level = 0.01
    second_tmap_cutoff_level = 0.01
else:
    first_tmap_cutoff_level = 0.4
    second_tmap_cutoff_level = 0.5

# filter out grains with more than grain_too_many_px pixels in the label map
# this normally indicates a dodgy reconstruction for this grain
# only really applies if the grains are very small!
grain_too_many_px = 10
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 concurrent.futures

import h5py
import hdf5plugin
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from tqdm.notebook import tqdm

from ImageD11 import cImageD11
from ImageD11.peakselect import select_ring_peaks_by_intensity, remove_peaks_from_phases
import ImageD11.sinograms.dataset
from ImageD11.sinograms.sinogram import GrainSinogram, write_h5, read_h5, get_2d_peaks_from_4d_peaks, counting_sort, save_array
from ImageD11.sinograms.roi_iradon import run_iradon
from ImageD11.sinograms.tensor_map import TensorMap
from ImageD11.sinograms.geometry import sino_shift_and_pad
import ImageD11.nbGui.nb_utils as utils
from ImageD11.nbGui.draw_mask import plot_mask_result, InteractiveMask, threshold_mask

%matplotlib ipympl

Load data#

Dataset#

ds = ImageD11.sinograms.dataset.load(dset_path)
print(ds)

Phases#

If the parameter file was a json, we can access the unit cells via ds.phases.unitcells

ds.phases = ds.get_phases_from_disk()
ds.phases.unitcells

Now we need to decide which are our ‘major’ phases, which we will remove from our peaks before indexing.

major_phase_unitcells = [ds.phases.unitcells[mps] for mps in major_phase_strs]
print(*major_phase_unitcells)
minor_phase_unitcell = ds.phases.unitcells[minor_phase_str]
print(minor_phase_unitcell)

Peaks#

cf_4d = ds.get_cf_4d()
ds.update_colfile_pars(cf_4d)  # computes geometry, needed for filtration
for major_phase_unitcell in major_phase_unitcells:
    major_phase_unitcell.makerings(cf_4d.ds.max())
minor_phase_unitcell.makerings(cf_4d.ds.max())

Grains#

grains = ds.get_grains_from_disk(minor_phase_str)
grainsinos = [GrainSinogram(g, ds) for g in grains]
utils.get_rgbs_for_grains(grains)
print(f"{len(grains)} grains imported")
utils.plot_all_ipfs(grains)

Inherit the reconstruction parameters#

if is_half_scan:
    ds.correct_bins_for_half_scan(y0=ds.y0)

# try to automatically determine the sinogram shift and the padding from the y0 values
shift, pad = sino_shift_and_pad(ds.y0, len(ds.ybincens), min(ds.ybincens), ds.ystep)

print(shift, ds.y0, pad)

Filtration#

(optional) remove major phase peaks#

if remove_major_phase_peaks:
    cf_4d = remove_peaks_from_phases(cf_4d, major_phase_cf_dstol, major_phase_unitcells)

Filter by intensity#

Now we are filtering our peaks (cf_4d) to select only the strongest ones . This time, we don’t clip via dsmax, because we need the higher-angle projections for complete sinograms.
We first filter the peaks in \(d^{*}\) to keep only those close to the predicted peaks from the unit cell.
We then sort our peaks by intensity, and take a certain intensity-weighted fraction of them.
dstol: The tolerance in \(d^{*}\) between a peak and a predicted reflection.
frac: The intensity fraction: frac=0.9 keeps 90% of the peak intensity. We recommend that you choose a value close to the ‘elbow’ of the plot.

cf_strong = select_ring_peaks_by_intensity(cf_4d, frac=minor_phase_cf_frac, dstol=minor_phase_cf_dstol, dsmax=cf_4d.ds.max(), ucell=minor_phase_unitcell, doplot=0.5)
minor_phase_unitcell.makerings(cf_strong.ds.max())
skip = 1  # we can skip peaks to speed up plotting if needed
fig, ax = plt.subplots(figsize=(10, 5), constrained_layout=True)
ax.plot(cf_4d.ds[::skip], cf_4d.sum_intensity[::skip],',', label='cf_4d',c='blue')
ax.plot(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='minor phase',c='orange')
ax.vlines(minor_phase_unitcell.ringds, 1e3, 3e3, color='red', label=minor_phase_unitcell.name)
for inc, major_phase_unitcell in enumerate(major_phase_unitcells):
    ax.vlines(major_phase_unitcell.ringds, 3e3*(3**inc), 3e3*(2**inc)*3, color=plt.color_sequences['tab20'][inc], label=major_phase_unitcell.name)
ax.set(xlabel=r'$d^{*}~(\AA^{-1})$', ylabel='Intensity', yscale='log', title='Peak filtration')
ax.legend(loc='upper right')
plt.show()

Peak assignment#

utils.assign_peaks_to_grains(grains, cf_strong, peak_assign_tol)
gid = cf_strong.grain_id.astype(int)
npks_4d = np.bincount(gid[gid >= 0], minlength=len(grains))
for grain_label, g in enumerate(grains):
    g.gid = grain_label
    g.npks_4d = npks_4d[grain_label]
utils.plot_grain_sinograms(grains, cf_strong, min(len(grains), 25))

Grain position refinement#

# sort peaks by grain once, then slice per grain (stable: same peak order as a mask)
gid = cf_strong.grain_id.astype(int)
order = np.argsort(gid, kind='stable')
bounds = np.searchsorted(gid[order], np.arange(len(grainsinos) + 1))
for grain_label, gs in enumerate(grainsinos):
    sel = order[bounds[grain_label]:bounds[grain_label + 1]]
    sx, sy, y0 = ImageD11.sinograms.geometry.sx_sy_y0_from_dty_omega(
        cf_strong.dty[sel], cf_strong.omega[sel], ds.y0)
    gs.grain.translation = np.array([sx, sy, 0])
    gs.recon_y0 = y0
# plt.style.use('dark_background')
fig, ax = plt.subplots(2,2, figsize=(12,12), layout='constrained')
a = ax.ravel()
x = [g.translation[0] for g in grains]
y = [g.translation[1] for g in grains]
s = [g.npks_4d/10 for g in grains]
a[0].scatter(y, x, c=[g.rgb_z for g in grains], s=s)
a[0].set(title='IPF color Z',  aspect='equal')
a[1].scatter(y, x, c=[g.rgb_y for g in grains], s=s)
a[1].set(title='IPF color Y', aspect='equal')
a[2].scatter(y, x, c=[g.rgb_x for g in grains], s=s)
a[2].set(title='IPF color X',  aspect='equal')
a[3].scatter(y, x, c=s)
a[3].set(title='Number of 4D peaks', aspect='equal')
fig.supxlabel("<- Sample y (transverse)")
fig.supylabel("Sample x (beam) ->")
fig.suptitle("Grain centre-of-mass positions from 4D peaks")

a[0].invert_xaxis()
plt.show()

Masking#

fig, ax = plt.subplots(layout='constrained')
whole_sample_sino, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)
whole_sample_sino = whole_sample_sino.T
pcm = ax.pcolormesh(om_edges, dty_edges, whole_sample_sino)
ax.set(xlabel=r'$\omega~(\degree)$', ylabel='dty', title='Sinogram of all peaks')
cax = fig.colorbar(pcm, ax=ax, label='log(intensity)')
plt.show()
nthreads = cImageD11.cores_available()
whole_sample_recon = run_iradon(whole_sample_sino, ds.obincens, pad, shift, workers=nthreads, apply_halfmask=is_half_scan, mask_central_zingers=is_half_scan)
mask_on_disk = False

with h5py.File(ds.grainsfile, "r") as hin:
    mask_path = f'masks/{minor_phase_str}' 
    if mask_path in hin:
        whole_sample_mask = hin[mask_path][:]
        mask_on_disk = True

if not mask_on_disk:
    if draw_mask_interactive:
        masker = InteractiveMask(whole_sample_recon)
    else:
        whole_sample_mask = threshold_mask(whole_sample_recon, manual_threshold=manual_threshold, doplot=True)
if mask_on_disk:
    plot_mask_result(whole_sample_recon, whole_sample_mask)
else:
    if draw_mask_interactive:
        whole_sample_mask = masker.get_mask(doplot=True)

    # write mask to disk
    with h5py.File(ds.grainsfile, "a") as hout:
        mask_group = hout.require_group("masks")
        save_array(mask_group, minor_phase_str, whole_sample_mask)

Grain sinogram generation#

corrector = ds.get_spatial_corrector()

if twin_assign:
    # assign from 4D peaks
    # allow grains to share reflections
    p2d = ds.pk2d
    # sort the 2D peaks by spot3d_id once; per grain we then look up only that grain's spots
    numba_order, numba_histo = counting_sort(p2d['spot3d_id'])
    sid2d_sorted = p2d['spot3d_id'][numba_order]
    gves = np.column_stack((cf_strong.gx, cf_strong.gy, cf_strong.gz))

    for grain_label, gs in enumerate(tqdm(grainsinos[:])):
        labels = np.full(cf_strong.nrows, fill_value=-1, dtype='i')
        drlv2 = np.full(cf_strong.nrows, fill_value=1, dtype='d')
        npks = ImageD11.cImageD11.score_and_assign(
            ubi=gs.grain.ubi,
            gv=gves,
            tol=peak_assign_tol,
            drlv2=drlv2,
            labels=labels,
            label=0
        )

        # 3D spot ids of this grain's 4D peaks -> runs of 2D peaks in the sorted order
        sel = np.unique(cf_strong.spot3d_id[labels == 0]).astype(sid2d_sorted.dtype)
        lo = np.searchsorted(sid2d_sorted, sel, side='left')
        hi = np.searchsorted(sid2d_sorted, sel, side='right')
        n = hi - lo
        pos = np.arange(n.sum()) + np.repeat(lo - (np.cumsum(n) - n), n)
        idx = np.sort(numba_order[pos])  # ascending 2D peak index, as before

        gs.prepare_peaks_from_4d(cf_strong, idx, np.array([0, 0, len(idx)]), 0, corrector, hkltol)

else:
    gord, inds = get_2d_peaks_from_4d_peaks(ds.pk2d, cf_strong)
    
    for grain_label, gs in enumerate(tqdm(grainsinos)):
        gs.prepare_peaks_from_4d(cf_strong, gord, inds, grain_label, corrector, hkltol)
# ^ if you segmented frelon data for scanning, the above cell won't work, because we don't have a 2d peaks table
# you can instead try the below to prepare the peaks from the 2D peaks:

# cf_2d = ds.get_cf_2d()
# ds.update_colfile_pars(cf_2d, phase_str)

# gv = np.ascontiguousarray(np.array((cf_2d.gx, cf_2d.gy, cf_2d.gz), dtype=float).T)

# for grain_label, gs in enumerate(tqdm(grainsinos)):
#     gs.prepare_peaks_from_2d(cf_2d, grain_label, 0.02, gv=gv)
if struc_factor_correction:
    # |F|^2 of every reflection from the CIF (needs Dans_Diffraction)
    sfc = ImageD11.sinograms.sinogram.StructureFactorCorrection.from_cif(
        cif_for_sf_path,
        wavelength=cf_4d.parameters.get('wavelength'),
        tth_max=cf_4d.tth.max(),
    )

    # correct intensity
    for gs in tqdm(grainsinos):
        gs.filter_valid_hkls(sfc)
        intensity_column = gs.compute_corrected_intensity(sf_correction=sfc, apply_lf_pol=True)

else:
    intensity_column = "sum_intensity"
for gs in tqdm(grainsinos):
    gs.build_sinogram(intensity_column=intensity_column, normalise=not struc_factor_correction)  # normalises if no structure factors
# optionally correct the halfmask:
if is_half_scan:
    for gs in grainsinos:
        gs.correct_halfmask()
gs = grainsinos[0]
fig, ax = plt.subplots(figsize=(7, 7), layout='constrained')
ax.pcolormesh(gs.sinoangles, ds.ybincens, gs.ssino)
ax.set(xlabel=r'Projection angle ($\degree$)', ylabel='dty', title='Grain sinogram')
plt.show()
# We can optionally correct each row of the sinogram by the ring current of that rotation
# This helps remove artifacts in the reconstruction
if correct_sinos_with_ring_current:
    ds.get_ring_current_per_scan()
    for gs in grainsinos:
        gs.correct_ring_current(is_half_scan=is_half_scan)

    gs = grainsinos[0]
    fig, ax = plt.subplots(figsize=(7, 7), layout='constrained')
    ax.pcolormesh(gs.sinoangles, ds.ybincens, gs.ssino)
    ax.set(xlabel=r'Projection angle ($\degree$)', ylabel='dty', title='Grain sinogram')
    plt.show()

Grain shape reconstruction#

iradon#

First grain as example#

gs.update_recon_parameters(pad=pad, shift=shift, mask=whole_sample_mask, y0=ds.y0)
gs.recon()
if is_half_scan:
    gs.mask_central_zingers("iradon", radius=halfmask_radius)
fig, axs = plt.subplots(1,2, figsize=(10,5), layout="constrained")
axs[0].pcolormesh(gs.sinoangles, ds.ybincens, gs.ssino)
axs[0].set(xlabel=r'Projection angle ($\degree$)', ylabel='dty', title='Grain sinogram')
axs[1].imshow(gs.recons["iradon"], vmin=0, origin="lower")
axs[1].set(title="ID11 iradon", xlabel="<-- Sample Y", ylabel="Sample X")
plt.show()
for gs in grainsinos:
    gs.update_recon_parameters(pad=pad, shift=shift, mask=whole_sample_mask, y0=ds.y0)

Reconstruct all grains#

nthreads = cImageD11.cores_available()
with concurrent.futures.ThreadPoolExecutor(max_workers= max(1,nthreads-1)) as pool:
    for i in tqdm(pool.map(GrainSinogram.recon, grainsinos), total=len(grainsinos)):
        pass
if is_half_scan:
    for gs in grainsinos:
        gs.mask_central_zingers("iradon", radius=halfmask_radius)

View outputs#

def update_frame(i):
    rec.set_array(grainsinos[i].recons["iradon"])
    sin = a[1].pcolormesh(grainsinos[i].sinoangles, ds.ybincens, grainsinos[i].ssino)
    fig.suptitle("Grain " + str(i))
    fig.canvas.draw()
frame_slider = widgets.IntSlider(
    value=0,
    min=0,
    max=len(grains) - 1,
    step=1,
    description='Grain:'
)
fig, a = plt.subplots(1,2,figsize=(10,5), constrained_layout=True)
rec = a[0].imshow(grainsinos[0].recons["iradon"], vmin=0, origin="lower")
sin = a[1].pcolormesh(grainsinos[0].sinoangles, ds.ybincens, grainsinos[0].ssino)
a[0].set(xlabel="<-- Sample Y", ylabel="Sample X", title="iradon Reconstruction")
a[1].set(xlabel=r'Projection angle ($\degree$)', ylabel='dty', title='Grain sinogram')
widgets.interact(update_frame, i=frame_slider)
plt.show()

Assemble TensorMap#

tensor_map = TensorMap.from_grainsinos(grainsinos, cutoff_level=first_tmap_cutoff_level,
                                       sf_normalisation=struc_factor_correction, sf_norm_percentile=50,
                                       smooth_labels=False, smooth_size=5)
tensor_map.plot("ipf_z")
tensor_map.plot("labels")
tensor_map.plot("intensity")

ASTRA#

We can clean up these reconstructions using an MLEM iterative recon.
We will carry this out using ASTRA on the GPU on the SLURM cluster.

if run_astra:
    for gs in grainsinos:
        gs.update_recon_parameters(pad=pad, shift=shift, mask=whole_sample_mask, niter=niter, y0=ds.y0)

    if run_astra_on_cluster:
        # save to disk and send slurm job
        write_h5(ds.grainsfile, grainsinos, overwrite_grains=True, group_name=minor_phase_str)
        bash_script_path = utils.prepare_astra_bash(ds, ds.grainsfile, PYTHONPATH, group_name=minor_phase_str, method=astra_method)
        utils.slurm_submit_and_wait(bash_script_path, 10)

        grainsinos = read_h5(ds.grainsfile, ds, group_name=minor_phase_str)
        for gs, g in zip(grainsinos, grains):
            gs.grain = g
            gs.ds = ds

    else:
        # run astra locally
        # first check if we have CUDA
        import astra
        if astra.use_cuda():
            # we have a local CUDA-enabled GPU
            print('ASTRA will run with GPU!')
        else:
            # we don't have a CUDA-enabled GPU
            if 'CUDA' in astra_method:
                print('ASTRA method requested:', astra_method)
                raise ValueError("You want to run ASTRA locally with a CUDA method, but you don't have a CUDA GPU available!")

        # go ahead and run it
        for gs in tqdm(grainsinos):
            gs.recon(method='astra', astra_method=astra_method, niter=niter)

    utils.plot_grain_recons(grainsinos, method='astra')

    tensor_map_astra = TensorMap.from_grainsinos(grainsinos, cutoff_level=second_tmap_cutoff_level, method='astra',
                                           sf_normalisation=struc_factor_correction, sf_norm_percentile=99,
                                           smooth_labels=False, smooth_size=5)
    tensor_map_astra.plot("ipf_z")
    tensor_map_astra.plot("labels")
    tensor_map_astra.plot("intensity")

else:
    tensor_map_astra = tensor_map

Filter by reconstruction quality#

For weak grains, there will likely be many streaks, indicating a few grains have dodgy reconstructions and are probably not to be trusted.
To fix this, we can count how many pixels in the grain labels array each grain has.
It can be helpful to run this filtration more than once.

labels, counts = np.unique(tensor_map_astra["labels"], return_counts=True)
fig, ax = plt.subplots(constrained_layout=True, figsize=(6, 6))
ax.plot(labels[labels > 0], counts[labels > 0])
ax.set(xlabel='Grain ID', ylabel='Pixels in TensorMap')
plt.show()

Filter out grains with more than grain_too_many_px pixels in the label map.
This normally indicates a dodgy reconstruction for this grain.
Only really applies if the grains are very small!

bad_gids = [int(label) for (label, count) in zip(labels, counts) if count > grain_too_many_px and label > 0]
print(f"{len(grainsinos)} grains before filtration")
grainsinos_clean = [gs for (inc, gs) in enumerate(grainsinos) if inc not in bad_gids]
grain_labels_clean = [inc for (inc, gs) in enumerate(grainsinos) if inc not in bad_gids]
print(f"{len(grainsinos_clean)} grains after filtration")
for gs, label in zip(grainsinos_clean, grain_labels_clean):
    gs.grain.gid = label

Assemble cleaned TensorMap#

tensor_map_astra_clean = TensorMap.from_grainsinos(grainsinos_clean, cutoff_level=second_tmap_cutoff_level, method='astra',
                                           sf_normalisation=struc_factor_correction, sf_norm_percentile=50,
                                           smooth_labels=False, smooth_size=5)
tensor_map_astra_clean.plot("ipf_z")
tensor_map_astra_clean.plot("labels")
tensor_map_astra_clean.plot("intensity")

Re-fit grain positions from reconstructions#

for gs in tqdm(grainsinos):
    gs.update_lab_position_from_recon()
for gs in grainsinos:
    gs.update_recon_parameters(y0=ds.y0)
# plt.style.use('dark_background')
fig, ax = plt.subplots(2,2, figsize=(12,12), layout='constrained')
a = ax.ravel()
x = [gs.grain.translation[0] for gs in grainsinos_clean]
y = [gs.grain.translation[1] for gs in grainsinos_clean]
s = [gs.grain.npks_4d/10 for gs in grainsinos_clean]
a[0].scatter(y, x, c=[gs.grain.rgb_z for gs in grainsinos_clean], s=s)
a[0].set(title='IPF color Z',  aspect='equal')
a[1].scatter(y, x, c=[gs.grain.rgb_y for gs in grainsinos_clean], s=s)
a[1].set(title='IPF color Y', aspect='equal')
a[2].scatter(y, x, c=[gs.grain.rgb_x for gs in grainsinos_clean], s=s)
a[2].set(title='IPF color X',  aspect='equal')
a[3].scatter(y, x, c=s)
a[3].set(title='Number of 4D peaks', aspect='equal')
fig.supxlabel("<- Sample y (transverse)")
fig.supylabel("Sample x (beam) ->")
fig.suptitle("Grain centre-of-mass positions from 4D peaks")

a[0].invert_xaxis()
plt.show()

Export#

Grains#

write_h5(ds.grainsfile, grainsinos, overwrite_grains=True, group_name=minor_phase_str)

TensorMap#

tensor_map_astra.to_h5(ds.grainsfile, h5group='TensorMap_' + minor_phase_str)

XDMF#

tensor_map_astra.to_paraview(ds.grainsfile, h5group='TensorMap_' + minor_phase_str)
ds.save()