Jupyter notebook based on ImageD11 to process 3DXRD data#
Written by Haixing Fang, Jon Wright and James Ball#
Date: 10/09/2024#
Source: ImageD11/nbGui/TDXRD/use_only_if_needed/1_3DXRD_refine_parameters.ipynb. Shown as saved in git; the documentation build does not run it.
This notebook will help you to refine the experimental parameters (such as sample to detector distance etc).
We do this by indexing a Z slice of a sample, refining the positions of the grains we find, then refining the parameters using the grain diffraction data
# 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
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 functions we need
import os, glob, pprint
import numpy as np
import h5py
from tqdm.notebook import tqdm
import matplotlib
%matplotlib widget
from matplotlib import pyplot as plt
# import utils
from ImageD11.nbGui import nb_utils as utils
import ImageD11.grain
import ImageD11.indexing
import ImageD11.columnfile
from ImageD11.sinograms import properties, dataset
from ImageD11.blobcorrector import eiger_spatial
from ImageD11.peakselect import select_ring_peaks_by_intensity
# desination of H5 files
# replace below with e.g.:
# dset_path = '/data/visitor/expt1234/20240101/PROCESSED_DATA/sample/dataset/sample_dataset.h5'
dset_path = ''
# load the dataset from file
ds = ImageD11.sinograms.dataset.load(dset_path)
sample = ds.sample
dataset = ds.dset
print(ds)
print(ds.shape)
ds.phases = ds.get_phases_from_disk()
ds.phases.unitcells
# now let's select a phase to index from our parameters json
phase_str = 'Fe'
ucell = ds.phases.unitcells[phase_str]
print(ucell.lattice_parameters, ucell.spacegroup)
# load 3d columnfile from disk
cf_3d = ds.get_cf_3d_from_disk()
ds.update_colfile_pars(cf_3d, phase_name=phase_str)
if "index" not in cf_3d.titles:
cf_3d.addcolumn(np.arange(cf_3d.nrows), "index")
# plot the 3D peaks (fewer of them) as a cake (two-theta vs eta)
# if the parameters in the par file are good, these should look like straight lines
ucell.makerings(cf_3d.ds.max())
fig, ax = plt.subplots(figsize=(16,9), layout='constrained')
ax.scatter(cf_3d.ds, cf_3d.eta, s=1)
ax.plot( ucell.ringds, [0,]*len(ucell.ringds), '|', ms=90, c="red")
ax.set_xlabel("D-star")
ax.set_ylabel("eta")
plt.show()
# here we are filtering our peaks (cf_3d) to select only the strongest ones for indexing purposes only!
# dsmax is being set to limit rings given to the indexer - 6-8 rings is normally good
# USER: modify the "frac" parameter below and re-run the cell until the orange dot sits nicely on the "elbow" of the blue line
# this indicates the fractional intensity cutoff we will select
# if the blue line does not look elbow-shaped in the logscale plot, try changing the "doplot" parameter (the y scale of the logscale plot) until it does
cf_strong = select_ring_peaks_by_intensity(cf_3d, frac=0.9850, dsmax=1.01, doplot=0.8, dstol=0.01)
print(f"Got {cf_strong.nrows} strong peaks for indexing")
cf_strong.writefile(f'{sample}_{dataset}_3d_peaks_strong.flt')
# we will also export some additional strong peaks across all rings
# this will be useful for grain refinement later (using makemap)
cf_strong_allrings = select_ring_peaks_by_intensity(cf_3d, frac=0.9855, dsmax=cf_3d.ds.max(), doplot=0.05, dstol=0.01)
print(f"Got {cf_strong_allrings.nrows} strong peaks for makemap")
cf_strong_allrings_path = f'{sample}_{dataset}_3d_peaks_strong_all_rings.flt'
cf_strong_allrings.writefile(cf_strong_allrings_path)
# now we can take a look at the intensities of the remaining peaks
fig, ax = plt.subplots(figsize=(16, 9), constrained_layout=True)
ax.plot(cf_3d.ds, cf_3d.sum_intensity,',', label='cf_3d')
ax.plot(cf_strong.ds, cf_strong.sum_intensity,',', label='cf_strong')
ax.plot( ucell.ringds, [1e4,]*len(ucell.ringds), '|', ms=90, c="red")
ax.semilogy()
ax.set_xlabel("Dstar")
ax.set_ylabel("Intensity")
ax.legend()
plt.show()
# specify our ImageD11 indexer with these peaks
indexer = ImageD11.indexing.indexer_from_colfile(cf_strong)
print(f"Indexing {cf_strong.nrows} peaks")
# USER: set a tolerance in d-space (for assigning peaks to powder rings)
indexer.ds_tol = 0.05
# change the log level so we can see what the ring assigments look like
ImageD11.indexing.loglevel = 1
# assign peaks to powder rings
indexer.assigntorings()
# change log level back again
ImageD11.indexing.loglevel = 3
# let's plot the assigned peaks
fig, ax = plt.subplots(figsize=(16, 9), layout='constrained')
# indexer.ra is the ring assignments
ax.scatter(cf_strong.ds, cf_strong.eta, c=indexer.ra, cmap='tab20', s=1)
ax.plot( ucell.ringds, [0,]*len(ucell.ringds), '|', ms=90, c="red")
ax.set_xlabel("d-star")
ax.set_ylabel("eta")
ax.set_xlim(cf_strong.ds.min()-0.05, cf_strong.ds.max()+0.05)
plt.show()
# now we are indexing!
# 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]
# 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]
# 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.75]
# the tolerance in g-vector angle
cosine_tol = np.cos(np.radians(90 - 0.25))
# the max number of UBIs we can find per pair of rings
max_grains = 1000
grains, indexer = utils.do_index(cf=cf_strong,
dstol=indexer.ds_tol,
forgen=rings_for_gen,
foridx=rings_for_scoring,
hkl_tols=hkl_tols_seq,
fracs=fracs,
cosine_tol=cosine_tol,
max_grains=max_grains
)
# create grain objects
grains = [ImageD11.grain.grain(ubi, translation=np.array([0., 0., 0.])) for ubi in indexer.ubis]
# set grain GIDs (useful if we ever delete a grain)
for i, g in enumerate(grains):
g.gid = i
tmp_ubi_path = f'{sample}_{dataset}_grains.ubi'
tmp_map_path = f'{sample}_{dataset}_grains.map'
new_flt_path = f'{sample}_{dataset}_3d_peaks_strong_all_rings.flt.new' # flt file containing assignments from makemap
unindexed_flt_path = f'{sample}_{dataset}_3d_peaks_strong_all_rings.flt.unindexed' # remaining unassigned peaks from makemap
ImageD11.grain.write_grain_file(tmp_ubi_path, grains)
omegas_sorted = np.sort(ds.omega)[0]
omega_step = np.round(np.diff(omegas_sorted).mean(), 3)
omega_slop = omega_step/2
makemap_hkl_tol_seq = [0.05, 0.025, 0.01]
# write a classic parameter file for makemap.py
from ImageD11 import parameters
oldpars = parameters.parameters()
oldpars.parameters.update(ds.phases.get_xfab_pars_dict(phase_str))
oldparfile = phase_str + '_old.par'
oldpars.saveparameters(oldparfile)
symmetry = "cubic"
for inc, makemap_tol in enumerate(makemap_hkl_tol_seq):
print(f"Running makemap {inc+1}/{len(makemap_hkl_tol_seq)}")
if inc == 0: # ubi into map
makemap_output = !makemap.py -p {oldparfile} -u {tmp_ubi_path} -U {tmp_map_path} -f {cf_strong_allrings_path} -F {unindexed_flt_path} -s {symmetry} -t {makemap_hkl_tol_seq[inc]} --omega_slop={omega_slop} --no_sort
else: # map into map
makemap_output = !makemap.py -p {oldparfile} -u {tmp_map_path} -U {tmp_map_path} -f {cf_strong_allrings_path} -F {unindexed_flt_path} -s {symmetry} -t {makemap_hkl_tol_seq[inc]} --omega_slop={omega_slop} --no_sort
grains_refined_positions = ImageD11.grain.read_grain_file(tmp_map_path)
fig, ax = plt.subplots()
ax.hist([np.mean(g.unitcell[0:3]) for g in grains_refined_positions], bins=50)
plt.show()
np.array([np.mean(g.unitcell[0:3]) for g in grains_refined_positions]).mean()
refine_output = !refine_em.py {new_flt_path} {tmp_map_path} {oldparfile} --omega_slop={omega_slop} -x wedge
# work out how many parameter files are missing
# check the missing .par files, and copy to cover the missing files
import shutil
print(f'Total number of files expected = {len(grains_refined_positions)}')
for i in range(len(grains_refined_positions)):
filename = f"{i}.par"
if not (os.path.isfile(filename)):
print(f'Missing {filename}')
if i == 0:
i = 2
print(f'Copying {i-1}.par to {filename}')
shutil.copy(str(i-1) + '.par', filename)
refined_parfile = phase_str + '_new.par'
avg_par_output = !avg_par.py {refined_parfile} {len(grains_refined_positions)}
# clean up temporary files
for i in range(len(grains_refined_positions)):
pfile = str(i) + '.par'
ffile = str(i) + '.flt'
ufile = str(i) + '.ubi'
for filename in [pfile, ffile, ufile]:
if os.path.isfile(filename):
os.remove(filename)
# refined parameter file has now been created!
!cat {refined_parfile}
# load new pars into memory
newpars = parameters.read_par_file(refined_parfile)
# strip out anything unit-cell related
parnames = list(newpars.parameters.keys())
for parname in parnames:
if parname.startswith('cell') or parname.startswith('phase'):
newpars.parameters.pop(parname)
# update ds.phases object
ds.phases.geometry_pars_obj = newpars
# update geometry file on disk
ds.phases.update_geometryfile()
# check geometry file is updated
!cat {ds.phases.geometry_pars_obj.get('filename')}