Point-by-point mapping notebook#
Written by Haixing Fang, Jon Wright and James Ball
Date: 21/02/2025
Source: ImageD11/nbGui/S3DXRD/pbp_1_indexing.ipynb. Shown as saved in git; the documentation build does not run it.
This notebook will try to perform a point-by-point index of the 2D peaks you segmented.
The point-by-point results (usually saved to a .txt file in the sample PROCESSED_DATA folder) are multi-valued (we can find multiple UBIs at each map voxel).
You can view the results of the point-by-point process ‘live’ by running the next notebook (pbp_2_visualise).
That notebook will also allow you to save a single-valued version of the pbp map to H5, ParaView XDMF and MTEX CTF.
The UBIs we find from the PBP index should have reasonably accurate orientations, but the strains are likely to be poor.
To get much better strains, slightly better orientations and possibly better grain shapes, you should run pbp_3_refinement
Then run 4_visualise to convert the refinement results to an accurate single-valued map with good strains.
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'
# filter the columnfile to discard weak peaks
minpkint = 5
# 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)
is_half_scan = False
# need to know for automatic y0 guessing from scan ranges.
# point-by-point parameters
hkl_tol = 0.025
fpks = 0.9
ds_tol = 0.004
etacut = 0.1
ifrac = 5e-3
drop_input_peaks = False
# ^ for large datasets, delete cf_2d from memory after choosing peaks to refine with
symmetry = "cubic"
foridx = [0, 1, 3, 5, 7]
forgen = [1, 5, 7]
uniqcut = 0.85
uniqueness = 0.5
# ^ an orientation is kept at a point only if more than this fraction of its peaks are unclaimed.
# 0.5 rejects duplicates but can also reject one member of a twin pair (they share ~1/3 of reflections)
# should we mask based on whole-sample sinogram before indexing? helps get clean sample edges
mask_before_indexing = True
# 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
# cluster indexing
use_cluster = False
n_chunks = 4
cpus_per_chunk = 24
time_h = 8
partition = 'nice'
# ^ can be nice-long
mem_G = 32
# 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 numpy as np
from matplotlib import pyplot as plt
try:
from ImageD11.nbGui.S3DXRD.run_pbp_recon_chunk import merge_chunk_outputs
except:
merge_chunk_outputs = None # Old version
import ImageD11.sinograms.point_by_point
import ImageD11.sinograms.tensor_map # trigger tensor_map computation so chunked version doesn't crash (try to fix #571)
import ImageD11.sinograms.dataset
import ImageD11.columnfile
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()
# 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 = y0_manual
else:
if hasattr(ds, 'y0') and ds.y0 is not None:
print('Using ds.y0')
y0 = ds.y0
else:
# not using manual y0, and couldn't find one. guess it from ymax/ymin
if not is_half_scan:
print('Guessing y0 from ymax/ymin')
y0 = (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)
# if we got here, save to ds.y0 - future refinements should use the same one
ds.y0 = y0
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_2d = ds.get_cf_2d()
ds.update_colfile_pars(cf_2d, phase_name=phase_str)
if not os.path.exists(ds.col2dfile):
# save the 2D peaks to file so we don't have to spatially correct them again
ImageD11.columnfile.colfile_to_hdf(cf_2d, ds.col2dfile)
# filter the columnfile to discard weak peaks
cf_2d.filter(cf_2d.Number_of_pixels > minpkint)
cosine_tol=np.cos(np.radians(90 - ds.ostep))
pbp_object = ImageD11.sinograms.point_by_point.PBP(ds.parfile,
ds,
hkl_tol=hkl_tol,
fpks=fpks,
ds_tol=ds_tol,
etacut=etacut,
ifrac=ifrac,
cosine_tol=cosine_tol,
y0=y0,
symmetry=symmetry,
foridx=foridx,
forgen=forgen,
uniqcut=uniqcut,
uniqueness=uniqueness,
phase_name=phase_str)
# make icolf filename phase-aware
icolf_filename = ds.icolfile.replace('.h5', f'_{phase_str}.h5')
grains_filename = ds.pbpfile.replace('.txt', f'_{phase_str}.txt')
pbp_object.setpeaks(cf_2d, icolf_filename=icolf_filename, keep_colf=not drop_input_peaks)
if drop_input_peaks:
del cf_2d
import gc; gc.collect()
print("released input peaks")
fig, ax = pbp_object.iplot(skip=1) # increase skip to make plot faster
if mask_before_indexing:
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()
if mask_before_indexing:
from ImageD11 import cImageD11
from ImageD11.sinograms.roi_iradon import run_iradon
from ImageD11.sinograms.geometry import sino_shift_and_pad, recon_to_step, step_grid_from_ybincens
from ImageD11.nbGui.draw_mask import InteractiveMask, threshold_mask
is_half_scan = False # change to True for half-acquisition
shift, pad = sino_shift_and_pad(y0, len(ds.ybincens), min(ds.ybincens), ds.ystep)
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)
# Now we generate a whole-sample mask for the image
if mask_before_indexing:
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_before_indexing:
if draw_mask_interactive:
whole_sample_mask = masker.get_mask(doplot=True)
if mask_before_indexing:
# determine points to index
# add the corners back into the mask to keep a consistent shape
whole_sample_mask[0, 0] = 1
whole_sample_mask[0, -1] = 1
whole_sample_mask[-1, 0] = 1
whole_sample_mask[-1, -1] = 1
ri, rj = np.where(whole_sample_mask)
si, sj = recon_to_step(ri, rj, whole_sample_mask.shape)
debugpoints = np.array((si, sj)).T
debugpoints = [tuple(row) for row in debugpoints]
print(debugpoints[:2], debugpoints[-2:]) # limits
else:
debugpoints = None
Indexing#
if merge_chunk_outputs is not None and use_cluster:
grains_prefix = ds.pbpfile.replace(ds.analysispath, os.path.join(ds.analysispath, 'slurm_pbp')).replace('.txt', f'_{phase_str}_')
bash_script_path, grains_files = pbp_object.submit_slurm_chunks(grains_prefix,
PYTHONPATH,
n_chunks=n_chunks,
cpus_per_chunk=cpus_per_chunk,
time_h=time_h,
partition=partition,
mem_G=mem_G,
debugpoints=debugpoints) # (N, 2) array. these can be supplied then chunked if you want
utils.slurm_submit_and_wait(bash_script_path, 15)
merge_chunk_outputs(grains_files, grains_filename)
else:
pbp_object.point_by_point(grains_filename, loglevel=3, debugpoints=debugpoints)
ds.save()