Tomographic mapping notebook#

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

Source: ImageD11/nbGui/S3DXRD/tomo_2_map.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 (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'

# which phase to index
phase_str = 'Si'

# peak filtration parameters
cf_strong_frac = 0.993
cf_strong_dstol = 0.005

# 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

# 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

# tolerance for building sinograms from assigned peaks
hkltol = 0.25

# manual override of y0 (ignores any value saved in dataset)
y0_manual = None
# or y0_manual = 0.0 (typical NSCOPE) or 13.5 (typical TDXRD)

# set to True if you want to update ds.y0 with the value from the sinograms
update_y0 = True

# We can optionally correct each row of the sinogram by the ring current of that rotation
# This helps remove artifacts in the reconstruction. Not needed if you had a monitor column
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'

first_tmap_cutoff_level = 0.4

# 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

second_tmap_cutoff_level = 0.05
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
import ImageD11.sinograms.dataset
from ImageD11.sinograms.sinogram import GrainSinogram, read_h5, write_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
ucell = ds.phases.unitcells[phase_str]
print(ucell)

Peaks#

cf_4d = ds.get_cf_4d()
ds.update_colfile_pars(cf_4d)
ucell.makerings(cf_4d.ds.max())
print(f"Read {cf_4d.nrows} 4D peaks")

Grains#

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

Filtration#

Here 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=cf_strong_frac, dstol=cf_strong_dstol, dsmax=cf_4d.ds.max(), ucell=ucell, doplot=0.5)
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')
ax.plot(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='cf_strong')
ax.vlines(ucell.ringds, 1e3, 1e4, color='red')
ax.set(xlabel=r'$d^{*}~(\AA^{-1})$', ylabel='Intensity', yscale='log', title='Peak filtration')
ax.legend()
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#

# Priority order (decreasing)
# manual override in first cell
# ds attribute

# fails if no y0 provided at all

if y0_manual is not None:
    print('Using manually supplied y0')
    y0_guess = y0_manual
else:
    if hasattr(ds, 'y0') and ds.y0 is not None:
        print('Using ds.y0')
        y0_guess = ds.y0
    else:
        # not using manual y0, and couldn't find one. guess it from ymax/ymin
        if not is_half_scan:
            y0_guess = (ds.ymax + ds.ymin)/2
        else:
            # half scan, not sure
            raise ValueError('You must manually supply a y0 value in the first cell to continue.')
print('Using y0:', y0_guess)
# 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], y0_guess)
    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")
for a in ax.ravel():
    a.invert_xaxis()
plt.show()

\(y_0\) refinement#

We need to determine what the value of dtymotor is where the rotation axis intercepts the beam.
This should be close to zero for the NSCOPE station, and somewhere around 14 mm for the TDXRD station.

sample_y0s = [gs.recon_y0 for gs in grainsinos]
y0_fit = np.median(sample_y0s)
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(sample_y0s)
ax.hlines(y0_fit, 0, len(grainsinos), color='red', label='y0 fit from sinograms')
ax.hlines(y0_guess, 0, len(grainsinos), color='green', label='y0 guess')
ax.set(xlabel='Grain ID', ylabel=r'$y_0$')
ax.legend()
plt.show()
print('y0_guess is', y0_guess)
print('fitted y0 from sinograms is', y0_fit)

if update_y0:
    print('Updating y0 to', y0_fit)
    ds.y0 = y0_fit
else:
    ds.y0 = y0_guess

ds.save()

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 is', shift)
print('pad is', pad)
# update the grainsinogram parameters accordingly:
for gs in grainsinos:
    gs.update_recon_parameters(y0=ds.y0, shift=shift, pad=pad)

Whole-sample mask#

Our next task is to determine a reconstruction mask for the entire sample.

This should adequately differentiate between sample and air.

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/{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, 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, hkl_tol, 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#

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#

utils.plot_grain_recons(grainsinos)

Assemble TensorMap#

tensor_map = TensorMap.from_grainsinos(grainsinos, cutoff_level=first_tmap_cutoff_level,
                                       sf_normalisation=struc_factor_correction, sf_norm_percentile=99,
                                       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.
The ASTRA EM_CUDA method will be used.

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=phase_str)
        bash_script_path = utils.prepare_astra_bash(ds, ds.grainsfile, PYTHONPATH, group_name=phase_str, method=astra_method)
        utils.slurm_submit_and_wait(bash_script_path, 10)

        grainsinos = read_h5(ds.grainsfile, ds, group_name=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

Export#

Grains#

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

TensorMap#

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

XDMF#

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