Point-by-point refinement notebook#
Written by Haixing Fang, Jon Wright and James Ball
Date: 21/02/2025
Source: ImageD11/nbGui/S3DXRD/pbp_3_refinement.ipynb. Shown as saved in git; the documentation build does not run it.
This notebook will try to perform a point-by-point strain refinement of your pbp index results.
As with the pbp index, the results of this process are multi-valued.
You can run 4_visualise to convert the refinement results to an accurate single-valued map.
NOTE: It is highly recommended to run this notebook on a Jupyter server with many cores and a lot of RAM.#
The compute_origins() function in particular runs locally and can be compute-intensive for large datasets.
If this is a big scan (e.g 100 million + 2D peaks), you should definitely refine on the cluster rather than locally.
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 refine
phase_str = 'Si'
# the minimum number of peaks you want a pixel to have to be counted
min_unique = 20
# threshold for whole-sample mask binarisation
manual_threshold = None
# refinement parameters
# 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)
# refinement tolerances
hkl_tol_origins = 0.05
# ^ we forgot to square this before!
hkl_tol_refine = 0.1
hkl_tol_refine_merged = 0.05
ds_tol = 0.006
ifrac = 1e-4
rings_to_refine = None
# ^ can be a list of rings
drop_input_peaks = False
# ^ for large datasets, delete cf_2d from memory after choosing peaks to refine with
use_origin_found_only=True
set_mask_from_input = False # do we mask just from the min_unique value?
use_cluster = False
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
from ImageD11.grain import grain
from ImageD11 import unitcell
import ImageD11.sinograms.dataset
from ImageD11.sinograms.point_by_point import PBPMap
from ImageD11.sinograms.pbp_refine import PBPRefine
from ImageD11.sinograms.tensor_map import TensorMap
from ImageD11.nbGui import nb_utils as utils
%matplotlib ipympl
Load data#
Dataset#
ds = ImageD11.sinograms.dataset.load(dset_path)
print(ds)
y0 = ds.y0
print(y0)
Phases#
If the parameter file was a json, we can access the unit cells via ds.phases.unitcells
# load phases from parameter file
ds.phases = ds.get_phases_from_disk()
ds.phases.unitcells
ref_ucell = ds.phases.unitcells[phase_str]
print(ref_ucell)
Point-by-point map#
pmap = PBPMap(ds.pbpfile.replace('.txt', f'_{phase_str}.txt'))
pmap.plot_nuniq_hist()
# choose the minimum number of peaks you want a pixel to have to be counted
pmap.choose_best(min_unique)
pmap.plot_best(min_unique)
Peaks#
cf_2d = ds.get_cf_2d()
ds.update_colfile_pars(cf_2d)
print(f"Read {cf_2d.nrows} 2D peaks")
# 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:
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()
Refinement#
# set up a refinement manager object
refine = PBPRefine(dset=ds,
y0=y0, hkl_tol_origins=hkl_tol_origins, hkl_tol_refine=hkl_tol_refine, hkl_tol_refine_merged=hkl_tol_refine_merged,
ds_tol=ds_tol, ifrac=ifrac, phase_name=phase_str, forref=rings_to_refine,
beam_size=None) # use step size as beam size - important for regularisation
# change the default paths of the refinement manager to append the phase name
refine.own_filename = os.path.splitext(refine.own_filename)[0] + f'_{phase_str}.h5'
refine.icolf_filename = os.path.splitext(refine.icolf_filename)[0] + f'_{phase_str}.h5'
refine.pbpmap_filename = os.path.splitext(refine.pbpmap_filename)[0] + f'_{phase_str}.h5'
refine.refinedmap_filename = os.path.splitext(refine.refinedmap_filename)[0] + f'_{phase_str}.h5'
# tell it which point-by-point map we are refining
refine.setmap(pmap)
# or load from disk:
# refine.loadmap()
# choose 2D peaks to refine with
refine.setpeaks(cf_2d, keep_colf=not drop_input_peaks)
# or load from disk:
# refine.loadpeaks()
if drop_input_peaks:
del cf_2d
import gc; gc.collect()
print("released input peaks")
# plot the peaks you selected
refine.iplot()
# generate a single-valued map to refine on
refine.setsingle(refine.pbpmap, minpeaks=min_unique)
# set whole-sample mask to choose where to refine
# if use_singlemap is true, we will generate a mask simply based on where self.singlemap > min_unique
refine.setmask(manual_threshold=manual_threshold, doplot=True, use_singlemap=set_mask_from_input)
Compute peak diffraction origins#
# compute diffraction origins - these will be added as a column to refine.icolf
# will then save the new column to disk to avoid re-computation
refine.get_origins()
# after refine.get_origins()
if use_origin_found_only:
n0 = refine.icolf.nrows
refine.icolf = refine.icolf.copyrows(refine.icolf.origin_found == 1)
print(f"origin_found filter: kept {refine.icolf.nrows} / {n0} peaks")
Run refinement#
# run the refinement
# if compute_origins took more than a couple of minutes to run, I suggest setting use_cluster=True below
# otherwise if you asked for lots of cores and RAM on this Jupyter instance, you can run it locally (use_cluster=False)
refine.run_refine(use_cluster=use_cluster, pythonpath=PYTHONPATH)
Export#
# make sure refinement is saved to disk
if not use_cluster:
refine.to_h5(save_peaks=False)
ds.save()