Tomographic indexing notebook#

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

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

This notebook will try to find good grain orientations from a 4D merge of your peak data.
This means your peaks have been merged across omega and dty.
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!

# 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
min_frames_per_peak = 0
cf_strong_frac = 0.9939
cf_strong_dsmax = 1.594
cf_strong_dstol = 0.005

# indexing parameters
# we have to choose which rings we want to generate orientations on
# generally we want two or three low-multiplicity rings that are isolated from other phases
# take a look at the ring assignment output from a few cells above, and choose two or three
rings_for_gen = [0, 1, 3]
# now we want to decide which rings to score our found orientations against
# generally we can just exclude dodgy rings (close to other phases, only a few peaks in etc)
rings_for_scoring = [0, 1, 2, 3, 4]
# the sequence of hkl tolerances the indexer will iterate through
hkl_tols_seq = [0.01, 0.02, 0.03, 0.04]
# the sequence of minpks fractions the indexer will iterate through
fracs = [0.9, 0.7]
# the max number of UBIs we can find per pair of rings
max_grains = 1000

peak_assign_tol = 0.05

# EXPERTS: Can specify par_file as a parameter if you want
par_file = None
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 numpy as np
from matplotlib import pyplot as plt

import ImageD11.grain
import ImageD11.indexing
import ImageD11.columnfile
from ImageD11.peakselect import select_ring_peaks_by_intensity
import ImageD11.nbGui.nb_utils as utils

%matplotlib ipympl

Load data#

Dataset#

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

Parameters#

Specify the path to your parameter file.

You can optionally set up some default parameters for either an Eiger or Frelon detector like so:

from ImageD11.parameters import AnalysisSchema
asc = AnalysisSchema.from_default(detector='eiger')  # or detector='frelon'
asc.save('./pars.json')

Please note in this case that you will still have to update the geometry.par values accordingly for your experiment.
If you haven’t already, you should run one of the calibration notebooks to determine these.

if par_file is not None:
    # only change if ds has no parfile
    if not hasattr(ds, 'parfile') or ds.parfile is None:
        ds.parfile = par_file
        ds.save()

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)
if not os.path.exists(ds.col4dfile):
    # save the 4D peaks to file so we don't have to spatially correct them again
    ImageD11.columnfile.colfile_to_hdf(cf_4d, ds.col4dfile)
# Optionally remove some noisy peaks
if min_frames_per_peak > 0:
    cf_4d.filter(cf_4d['npk2d'] > min_frames_per_peak)

Visualise data#

\(d^{*}\) vs \(\eta\)#

skip = 1  # we can skip peaks to speed up plotting if needed
ucell.makerings(cf_4d.ds.max())
fig, ax = plt.subplots(figsize=(10,5), layout='constrained')
ax.plot(cf_4d.ds[::skip], cf_4d.eta[::skip], ',')
ax.vlines(ucell.ringds, -50, 50, color='red')
ax.set(xlabel=r'$d^{*}~(\AA^{-1})$', ylabel=r'$\eta~(\degree)$', title='2D azimuthal transform')
plt.show()

Sinogram#

fig, ax = plt.subplots(layout='constrained')
im, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)
pcm = ax.pcolormesh(om_edges, dty_edges, im.T)
ax.set(xlabel=r'$\omega~(\degree)$', ylabel='dty', title='Sinogram of all peaks')
cax = fig.colorbar(pcm, ax=ax, label='log(intensity)')
plt.show()

Filtration#

Here we are filtering our peaks (cf_4d) to select only the strongest ones for indexing purposes only!
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.
dsmax: The maximum allowed peak \(d^{*}\) value. Used to limit the number of rings given to the indexer - 6-8 rings max are normally sufficient.
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, dsmax=cf_strong_dsmax, dstol=cf_strong_dstol, 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()

Indexing#

Ring assignment#

indexer = ImageD11.indexing.indexer_from_colfile_and_ucell(cf_strong, ucell)
indexer.ds_tol = cf_strong_dstol
ImageD11.indexing.loglevel = 1
indexer.assigntorings()
ImageD11.indexing.loglevel = 3
print(f"Indexing {cf_strong.nrows} peaks")
skip = 1  # we can skip peaks to speed up plotting if needed
fig, ax = plt.subplots(layout='constrained', figsize=(10,5))
ax.scatter(indexer.colfile.ds[::skip], indexer.colfile.eta[::skip], c=indexer.ra[::skip]%20, cmap='tab20', s=1)
ax.vlines(ucell.ringds, -50, 50, color='red')
ax.set(xlabel=r'$d^{*}~(\AA^{-1})$', ylabel=r'$\eta~(\degree)$', xlim=(min(ucell.ringds[0], cf_strong.ds.min()) - 0.02, cf_strong.ds.max() + 0.02), title='Ring assignments')
plt.show()
cosine_tol = np.cos(np.radians(90 - ds.ostep))
grains, indexer = utils.do_index(cf=cf_strong,
                                 unitcell=ds.phases.unitcells[phase_str],
                                 dstol=cf_strong_dstol,
                                 forgen=rings_for_gen,
                                 foridx=rings_for_scoring,
                                 hkl_tols=hkl_tols_seq,
                                 fracs=fracs,
                                 cosine_tol=cosine_tol,
                                 max_grains=max_grains,
)
for ginc, g in enumerate(grains):
    g.gid = ginc
print(f'Found {len(grains)} grains!')

Results#

unit_cell_lengths = np.array([np.sort(g.unitcell.copy()) for g in grains])
median_unit_cell = np.median(unit_cell_lengths, axis=0)
print("Median unit cell:", median_unit_cell)
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(unit_cell_lengths[:,:3])
ax.hlines(median_unit_cell[:3], 0, len(unit_cell_lengths))
ax.set(xlabel='Grain ID', ylabel='Unit cell length')
plt.show()
utils.assign_peaks_to_grains(grains, cf_strong, tol=peak_assign_tol)
utils.plot_index_results(indexer, cf_strong, 'Indexing attempt')
utils.plot_grain_sinograms(grains, cf_strong, min(len(grains), 25))

Export data#

ds.save_grains_to_disk(grains, phase_name=phase_str)
ds.save()