Friedel pair indexing notebook#
Written by Jon Wright and James Ball
Date: 15/09/2026
Source: ImageD11/nbGui/S3DXRD/friedel_1_index.ipynb. Shown as saved in git; the documentation build does not run it.
This notebook is an alternative to tomo_1_index.ipynb for finding grain orientations.
Instead of indexing the whole dataset at once, we use Friedel pairs to work out where in the sample each peak came from, then index each position in the sample separately.
The pairs we use are related by:
eta -> -eta
tth -> tth
gve -> -gve
Both peaks of a pair come from the same point in the sample, so their two (omega, dty) values
give us two equations for the two unknowns (sx, sy), which we solve directly.
See fit_y0.ipynb and friedel_pair_map.ipynb for more about the pairing itself.
Because each position is indexed on its own, with the diffraction origin moved to that position,
this route copes better with many grains and with grains far from the rotation axis than
indexing everything together does. It needs a good y0 and reasonably clean Friedel pairs.
The output is a list of grains saved to ds.grainsfile, exactly like tomo_1_index.ipynb,
so you can carry straight on with tomo_2_map.ipynb afterwards.
import os
# the indexer and the iradon below are already parallel
# stop the BLAS libraries from oversubscribing the machine on top of that
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
# drop peaks that were only seen on this many frames or fewer (0 keeps everything)
min_frames_per_peak = 2
# keep the rings holding at least this fraction of the total intensity
cf_strong_ifrac = 5e-5
# tolerance in d* between a peak and a predicted reflection
cf_strong_dstol = 0.003
# Friedel pair matching tolerance, in g-vector units (1/Angstrom)
# look at the histogram of pair distances below - you want to cut before the flat background
gvtol = 0.0015
# 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)
# if you don't know y0, run fit_y0.ipynb first - the pair positions are very sensitive to it
# 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
# 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
# threshold in Friedel pairs per pixel, used to segment the pair-position map into grains
# choose this using the threshold scan below
hist_threshold = 10
# how far (in sample units) either side of a segmented position we collect pairs from
# None means 2 * ds.ystep
ytol = None
# indexing parameters, applied at each candidate grain position
index_ds_tol = 0.005
index_hkl_tol = 0.025
index_minpks = 20
index_max_grains = 50
# maximum number of pairs of rings to try per position
index_npairs = 20
# optionally generate the sigma-3 twins of every grain we find
# WARNING: only sigma-3 twins (60 degrees about <111>) of cubic phases are supported
generate_twins = False
# merging duplicate orientations
uniq_symmetry = 'cubic'
# distance tolerance for merging, in sample units
# None means 2000 * ytol, i.e. merge on orientation alone and ignore position entirely
uniq_toldist = None
uniq_tolangle = 0.5
# final peak assignment
cf_strong_frac = 0.997
peak_assign_tol = 0.05
# grain quality cutoffs - set these after looking at the histograms below
min_nuniq = 140
min_npks = 350
# 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 h5py
import numpy as np
import scipy.spatial
import scipy.spatial.transform
import matplotlib.pyplot as plt
from tqdm.autonotebook import tqdm
import ImageD11.cImageD11
import ImageD11.columnfile
import ImageD11.grain
import ImageD11.grid_index_parallel
import ImageD11.indexing
import ImageD11.sinograms.dataset
import ImageD11.nbGui.nb_utils as utils
from ImageD11.forward_model.forward_projector import clean_frms, get_opts_seg
from ImageD11.nbGui.draw_mask import InteractiveMask, plot_mask_result, threshold_mask
from ImageD11.peakselect import select_ring_peaks_by_intensity, select_rings_by_ifrac
from ImageD11.sinograms.geometry import recon_bins, sino_shift_and_pad
from ImageD11.sinograms.lima_segmenter import frmtosparse
from ImageD11.sinograms.roi_iradon import run_iradon
from ImageD11.sinograms.sinogram import save_array
from ImageD11.sparseframe import sparse_connected_pixels, sparse_moments
%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, phase_str)
ucell.makerings(cf_4d.ds.max())
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)
print(f"Read {cf_4d.nrows} 4D peaks")
# Optionally remove some noisy peaks
# peaks seen on only one or two frames are usually junk, and they pair up badly
if min_frames_per_peak > 0:
cf_4d.filter(cf_4d['npk2d'] > min_frames_per_peak)
print(f"{cf_4d.nrows} peaks left")
Filtration#
The Friedel pair search is a nearest-neighbour search in g-vector space, so its cost grows with the number of peaks. We therefore keep only the peaks that lie on the strongest rings of our phase.
select_rings_by_ifrac keeps whole rings rather than individual peaks: any ring holding at least
ifrac of the total intensity survives, and every peak on it is kept. That matters here, because
Friedel pairing needs both halves of a pair to be present - filtering peak-by-peak on intensity
(as tomo_1_index.ipynb does) would break pairs where one half happens to be weaker.
cring = select_rings_by_ifrac(cf_4d, dstol=cf_strong_dstol, dsmax=cf_4d.ds.max(), ifrac=cf_strong_ifrac, uc=ucell)
print(f"{cring.nrows} peaks on the selected rings")
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(cring.ds[::skip], cring.sum_intensity[::skip],',', label='cring')
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()
Geometry#
\(y_0\)#
We need the value of dtymotor where the rotation axis intercepts the beam.
Everything below (pair positions, reconstruction grid, mask) is referenced to it, and the pair
positions are very sensitive to it, so it is worth getting right with fit_y0.ipynb first.
# 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
elif hasattr(ds, 'y0') and ds.y0 is not None:
print('Using ds.y0')
y0 = ds.y0
else:
raise ValueError('You must supply a y0 value in the first cell to continue. Try running fit_y0.ipynb!')
print('Using y0:', y0)
ds.y0 = y0
ds.save()
Reconstruction grid#
A half-scan only covers dty from the rotation axis out to one side of the sample.
correct_bins_for_half_scan pads ds.ybincens with virtual bins on the short side, so that the
dty range becomes symmetric about y0. Everything downstream (sinohist, sino_shift_and_pad,
recon_bins) then sees the padded bins.
This is exactly what tomo_2_map.ipynb does, and it matters here because the whole-sample mask we
draw below is shared with that notebook - if we padded differently, the mask would be the wrong shape.
if is_half_scan:
ds.correct_bins_for_half_scan(y0=ds.y0)
# y0 is rarely exactly at the centre of the scanned dty range, so the rotation axis is not on the
# middle row of the sinogram. shift moves it there, and pad grows the reconstruction so the whole
# sample fits (it also keeps the output odd-sized, which puts the axis on a pixel centre)
shift, pad = sino_shift_and_pad(ds.y0, len(ds.ybincens), ds.ymin, ds.ystep)
print('shift is', shift)
print('pad is', pad)
Friedel pairs#
The next two functions are the same ones used in fit_y0.ipynb and friedel_pair_map.ipynb.
find_pairs_minus_eta builds a KD-tree of the eta > 0 peaks and another of the negated eta < 0
peaks, then looks for coincidences within gvtol.
locate_pairs solves the geometry for each pair. ImageD11.sinograms.geometry gives us
dty - y0 = -sx.sin(omega) - sy.cos(omega), so two peaks of a pair give a 2x2 system for (sx, sy).
It is written in the affine form s(y0) = s0 - y0.v, so the linear solve happens once and
re-evaluating at a different y0 is just a multiply and subtract.
def find_pairs_minus_eta(cf, gvtol=0.002, doplot=False):
"""
Locate Friedel pairs with eta -> -eta and g -> -g.
Returns ip, im == indices for eta+ and eta- pairs.
"""
fp = np.flatnonzero(cf.eta > 0)
fm = np.flatnonzero(cf.eta < 0)
kdp = scipy.spatial.cKDTree( np.transpose((cf.gx[fp], cf.gy[fp], cf.gz[fp])) )
kdm = scipy.spatial.cKDTree( -np.transpose((cf.gx[fm], cf.gy[fm], cf.gz[fm])) )
coo = kdp.sparse_distance_matrix(kdm, gvtol, output_type='coo_matrix')
if doplot:
fig, ax = plt.subplots(layout='constrained')
ax.hist(coo.data.flat, bins=500)
ax.set(xlabel='gvtol', ylabel='count', title='Friedel pair g-vector distances')
plt.show()
return fp[coo.row], fm[coo.col]
def locate_pairs_affine(cf, pairs):
"""
ImageD11.sinograms.geometry.dty_values_grain_in_beam_sincos gives:
dty - y0 = -sx sin(w) -sy cos(w)
Define:
s = [ sx ], R = [ -sin(w1) -cos(w1) ], d = [ dty1 ], 1 = [ 1 ]
[ sy ] [ -sin(w2) -cos(w2) ] [ dty2 ] [ 1 ]
Now we can write:
R . s = d - y0 * 1
which is equivalent to the original geometry equation.
Rearranging gives:
s = R^-1 . (d - y0 * 1)
expanding:
s = (R^-1 . d) - y0 * (R^-1 . 1)
which is possible because y0 is independent of R.
We define:
s0 = R^-1 . d
v = R^-1 . 1
Therefore:
s = s0 - y0 * v
This is a function of y0: s(y0) = s0 - y0 * v
Which can be evaluated for any value of y0.
Returns s0, v, each shape (2, N) == (sx-row, sy-row) over all pairs.
"""
i1, i2 = pairs
r = np.radians(cf.omega)
so, co = np.sin(r), np.cos(r)
# Per-pair 2x2 matrix R, stacked over N pairs -> (N,2,2)
R = np.transpose(((-so[i1], -co[i1]),
(-so[i2], -co[i2])), axes=(2, 0, 1)) # (N,2,2)
# Data vector d = [dty_i1; dty_i2] per pair (the RHS when y0 = 0)
d = np.transpose((cf.dty[i1],
cf.dty[i2])) # (N,2)
# Right-hand-side matrix
rhs = np.stack([d, np.ones_like(d)], axis=-1) # (N,2,2): [d | 1]
# Solve R . [s0 | v] = [d | 1]
sol = np.linalg.solve(R, rhs) # (N,2,2): [s0 | v]
s0 = sol[..., 0].T # (2,N) == R^-1 . d
v = sol[..., 1].T # (2,N) == R^-1 . 1
return s0, v
def locate_pairs(cf, pairs, y0=0.):
"""
Fit the centre of mass position of the pairs
cf = colfile
pairs = (ip, im) = indices of low, high pair in cf
Returns sx, sy == sample x and y co-ordinates of the peak-pair
"""
s0, v = locate_pairs_affine(cf, pairs)
sx, sy = s0 - y0 * v
return (sx, sy)
The next cell does the pairing. It needs about one second per million peaks.
The histogram shows the g-vector distance of each match: real pairs sit in the peak near zero,
and the flat tail is accidental coincidences. If the peak runs into the tail, reduce gvtol.
ip, im = find_pairs_minus_eta(cring, gvtol=gvtol, doplot=True)
print('Got', len(ip), 'pairs from', cring.nrows, 'peaks, fraction paired =', len(ip)*2/cring.nrows)
sx_all, sy_all = locate_pairs(cring, (ip, im), y0=ds.y0)
Whole-sample mask#
Our next task is to determine a reconstruction mask for the entire sample.
This should adequately differentiate between sample and air.
We use it twice: to throw away pair positions that fall outside the sample (which are nearly all
mis-paired peaks), and to pass on to tomo_2_map.ipynb, which reads the same mask from the same
place in ds.grainsfile.
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 = ImageD11.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,
central_mask_radius=halfmask_radius)
# The mask lives in ds.grainsfile at masks/<phase_str>, which is where tomo_2_map.ipynb
# looks for it. So a mask drawn here is re-used there, and vice versa.
# Unlike tomo_2_map.ipynb, we are usually the first notebook to touch ds.grainsfile,
# so it very often does not exist yet - check before trying to open it for reading.
mask_on_disk = False
if os.path.exists(ds.grainsfile):
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
print('Read existing mask from', ds.grainsfile)
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
# opening in 'a' mode creates ds.grainsfile for us if it isn't there yet
with h5py.File(ds.grainsfile, "a") as hout:
mask_group = hout.require_group("masks")
save_array(mask_group, phase_str, whole_sample_mask)
print('Wrote mask to', ds.grainsfile)
Locating grains in the sample#
Each Friedel pair gives us a position in the sample. Histogram those positions onto the reconstruction grid and the grains show up as dense blobs, because every pair from one grain lands in the same place.
We then segment that histogram with the same connected-pixels code we use on detector images, and treat each blob as one candidate grain position to index.
# bin edges for the padded and shifted reconstruction, in sample units, centred on the rotation axis
# this is the same grid as the iradon reconstruction (and therefore the mask) above
bin_edges, bin_centres = recon_bins(ds.ybincens, ds.ymin, ds.ystep, ds.y0)
hist_all = np.histogram2d(sx_all, sy_all, bins=bin_edges)[0]
print('Histogrammed', len(sx_all), 'pair positions onto a', hist_all.shape, 'grid')
# a robust upper limit for the plots below - the histogram is mostly empty space
vmax = np.percentile(hist_all[hist_all > 0], 99) if (hist_all > 0).any() else 1
fig, ax = plt.subplots(figsize=(8, 8), layout='constrained')
pcm = ax.pcolormesh(bin_edges, bin_edges, hist_all.T, vmax=vmax)
ax.set(aspect='equal', xlabel='Sample x (beam) ->', ylabel='Sample y (transverse) ->',
title='Friedel pair positions')
fig.colorbar(pcm, ax=ax, label='pairs per pixel')
plt.show()
Masking the pair positions#
The reconstruction (and so the mask) is indexed (i, j), where i increases with sample x and
j increases with minus sample y - see the reference frames documented at the top of
ImageD11.sinograms.geometry.
hist_all is indexed (i, j) with both axes increasing with sample x and sample y.
The two grids have the same size and the same origin, so the only difference is the sign of the
second axis: hist_all[i, j] is whole_sample_recon[i, N-1-j], where N is always odd because
sino_shift_and_pad makes it so. That makes the conversion a simple flip of the second axis.
mask_hist = whole_sample_mask[:, ::-1]
fig, axs = plt.subplots(1, 2, figsize=(10, 5), sharex=True, sharey=True, layout='constrained')
axs[0].imshow(hist_all.T, origin='lower', vmax=vmax)
axs[0].set(title='Pair positions', aspect='equal')
axs[1].imshow(np.where(mask_hist, hist_all, 0).T, origin='lower', vmax=vmax)
axs[1].set(title='Masked', aspect='equal')
fig.supxlabel('Sample x (beam) ->')
fig.supylabel('Sample y (transverse) ->')
plt.show()
Segmentation#
Now we pick a threshold in pairs-per-pixel and label the blobs above it.
A good threshold gives roughly the number of grains you expect and is stable - if the blob count changes wildly between neighbouring thresholds you are cutting through the middle of the distribution. Too low and neighbouring grains merge into one blob; too high and you lose the small or weakly-diffracting grains.
# NB: the first argument to frmtosparse is the MASK, not the frame.
# Internally it does `img * mask > cut`, so passing the histogram here would square it
# and the effective threshold would be sqrt(cut).
fun = frmtosparse(mask_hist, np.float32)
def segment_hist(frame, cut):
"""Label the blobs in frame above cut. Returns the blob properties array."""
opts = get_opts_seg(cut=cut, pixels_in_spot=1, mask=mask_hist)
npx, row, col, val = fun(frame, cut=cut)
if npx == 0:
return None
spf = clean_frms(npx, row, col, val, opts)
sparse_connected_pixels(spf, threshold=cut)
return sparse_moments(spf, intensity_name='intensity', labels_name='connectedpixels')
for thresh in [1, 2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 100, 200, 500, 1000]:
props = segment_hist(hist_all, thresh)
print(thresh, 0 if props is None else props.shape[0])
props = segment_hist(hist_all, hist_threshold)
if props is None:
raise ValueError('No pixels above hist_threshold - lower it and try again')
# intensity-weighted centroids of each blob, in histogram pixels
# 'fast' is the second axis of hist_all (sample y), 'slow' is the first axis (sample x)
fast = props[:, ImageD11.cImageD11.s2D_fI] / props[:, ImageD11.cImageD11.s2D_I]
slow = props[:, ImageD11.cImageD11.s2D_sI] / props[:, ImageD11.cImageD11.s2D_I]
print(f'Found {len(fast)} candidate grain positions at threshold {hist_threshold}')
fig, ax = plt.subplots(constrained_layout=True, figsize=(10, 10))
ax.imshow(hist_all.T, vmax=vmax, origin='lower')
ax.scatter(slow, fast, marker='+', color='r')
ax.set(aspect='equal', xlabel='Sample x (beam) ->', ylabel='Sample y (transverse) ->',
title='Segmented grain positions')
plt.show()
Indexing#
For each candidate position we:
collect the Friedel pairs that sit within
ytolof itrecompute their g-vectors with the diffraction origin moved to that position
run the normal ImageD11 indexer on that small subset of peaks
Step 2 matters. The g-vectors in the columnfile are computed as if the grain sat on the rotation
axis, so a grain some distance off-axis gets a systematic tilt in its g-vectors, which smears out
the orientation. The correction subtracts the lab-frame x position of the origin point at each
omega, and is the same one used by ImageD11.sinograms.point_by_point.get_local_gv.
Because each position only has one or a few grains in it, the indexer has a far easier job here
than it does in tomo_1_index.ipynb.
if ytol is None:
ytol = 2 * ds.ystep
print('Using ytol', ytol)
# the indexer is chatty - turn it down before we run it a few thousand times
ImageD11.indexing.loglevel = 3
# geometry parameters are shared by all peaks, the phase-specific cell is in ucell
parglobal = cf_4d.parameters
# two g-vectors must be at least one omega step apart to give a sensible orientation
cosine_tol = np.cos(np.radians(90 - ds.ostep))
allgrains = []
for fpx_float, spx_float in tqdm(zip(fast, slow), total=len(fast)):
# blob centroids, rounded to the nearest histogram pixel
fpx_int = np.round(fpx_float).astype(int)
spx_int = np.round(spx_float).astype(int)
# the position of that pixel in the sample frame
# these are bin CENTRES - using bin_edges here puts every grain half a pixel off
sx_point = bin_centres[spx_int]
sy_point = bin_centres[fpx_int]
# select the pairs that came from this position
m = ((abs(sx_all - sx_point) < ytol) & (abs(sy_all - sy_point) < ytol))
if m.sum() < index_minpks:
continue
# take both halves of each selected pair
# idxpt, and therefore the rows of cgrain, run (all eta+ peaks, then all eta- peaks)
# so the pair positions have to be duplicated in the same order to match
idxpt = np.concatenate((ip[m], im[m]))
cgrain = cring.copyrows(idxpt)
sx_all_point = np.concatenate([sx_all[m], sx_all[m]])
sy_all_point = np.concatenate([sy_all[m], sy_all[m]])
# move the diffraction origin to this point and recompute the g-vectors
x_offset = sx_point * np.cos(np.radians(cgrain.omega)) - sy_point * np.sin(np.radians(cgrain.omega))
xyz_local = np.column_stack((cgrain.xl - x_offset, cgrain.yl, cgrain.zl))
gv_adjust = np.empty((cgrain.nrows, 3))
ImageD11.cImageD11.compute_gv(xyz_local,
cgrain.omega,
parglobal.get('omegasign'),
parglobal.get('wavelength'),
parglobal.get('wedge'),
parglobal.get('chi'),
np.array((0., 0., 0.)),
gv_adjust)
indexer = ImageD11.indexing.indexer(unitcell=ucell,
gv=gv_adjust,
wavelength=parglobal.get('wavelength'),
ds_tol=index_ds_tol,
cosine_tol=cosine_tol,
hkl_tol=index_hkl_tol,
minpks=index_minpks,
max_grains=index_max_grains)
try:
# score_all_pairs calls assigntorings for us
indexer.score_all_pairs(index_npairs)
except (IndexError, ValueError):
# not enough peaks on enough rings at this position
continue
for ginc, ubi in enumerate(indexer.ubis):
g = ImageD11.grain.grain(ubi)
# indexer.ga holds a grain label per peak, filled in as each orientation was accepted
# the labels are 1-based (0 would collide with 'not assigned')
g.pks_mask = indexer.ga == ginc + 1
g.npks = int(g.pks_mask.sum())
if g.npks == 0:
continue
# the grain sits at the median of the pair positions it indexed, which is a better
# estimate than the centre of the histogram pixel we started from
g.translation = np.array([np.median(sx_all_point[g.pks_mask]),
np.median(sy_all_point[g.pks_mask]),
0.])
gve_grain = np.column_stack((cgrain.gx[g.pks_mask], cgrain.gy[g.pks_mask], cgrain.gz[g.pks_mask])).T
g.hkl_int = np.round((g.ubi @ gve_grain).T).astype(int)
g.nuniq = np.unique(g.hkl_int, axis=0).shape[0]
g.idxpt = idxpt
allgrains.append(g)
print(f'Found {len(allgrains)} candidate grains from {len(fast)} positions')
Twins#
A twin shares only some of its reflections with its parent, so at a position containing both, the parent can dominate and the twin never gets generated by the indexer.
We can optionally add the twins of every grain we found by hand, and let the peak assignment below decide which of them are real.
WARNING: only sigma-3 twins (60 degrees about <111>) are supported, which means cubic phases
only. The cell will refuse to run if uniq_symmetry is anything other than 'cubic'. If you
need other twin systems (or a non-cubic phase), leave generate_twins = False.
# copied from ImageD11/sandbox/sigma_3_matrices.py
def make_sigma3_mats():
""" Rotations of 60 degrees on 111 """
v = 60/np.sqrt( 3 )
S3_matrices = [ scipy.spatial.transform.Rotation.from_rotvec( (x,y,z), degrees=True ).as_matrix()
for x in (-v,v)
for y in (-v,v)
for z in (-v,) ] # only need 1 z as -60 == 60
return S3_matrices
def applytwinmat( g, mat ):
""" U.B -> U.M'.B """
ubinew = np.linalg.inv( g.U.dot( mat.T ).dot( g.B ) )
return ImageD11.grain.grain( ubinew, g.translation )
if generate_twins:
if uniq_symmetry != 'cubic':
raise ValueError("Only sigma-3 twins of cubic phases are supported, but uniq_symmetry is "
+ repr(uniq_symmetry) + ". Set generate_twins = False.")
matrices = make_sigma3_mats()
twin_grains = [applytwinmat(g, mat) for g in allgrains for mat in matrices]
allgrains.extend(twin_grains)
print(f'Added {len(twin_grains)} twin orientations, {len(allgrains)} candidates in total')
Unique grains#
We find the same grain from several neighbouring positions, and the twin generation above makes
more duplicates still. uniq_grain_list merges orientations that agree to within tolangle
(after applying the crystal symmetry) and toldist in space.
The default toldist is deliberately enormous: it merges purely on orientation and ignores
position. Reduce it if you have a sample where distinct grains genuinely share an orientation.
if uniq_toldist is None:
uniq_toldist = 2000 * ytol
print('Merging with toldist', uniq_toldist, 'and tolangle', uniq_tolangle)
grainmanager = ImageD11.grid_index_parallel.uniq_grain_list(uniq_symmetry, toldist=uniq_toldist, tolangle=uniq_tolangle)
grainmanager.add(allgrains)
grains = grainmanager.uniqgrains
print(f'{len(grains)} unique grains from {len(allgrains)} candidates')
Peak assignment#
Now we go back to the whole dataset and see how many peaks each surviving orientation can explain. This is what tells us which of the candidate orientations (and which of the generated twins) are real.
Note that we do a greedy per-grain assignment here rather than utils.assign_peaks_to_grains:
each grain is scored against all the peaks independently, so grains are allowed to share
reflections. That is deliberate - a twin and its parent share reflections by definition, and
forcing peaks to pick one grain would throw them away.
cf_strong = select_ring_peaks_by_intensity(cf_4d, frac=cf_strong_frac, dsmax=cf_4d.ds.max(), dstol=cf_strong_dstol, ucell=ucell, doplot=0.5)
gves = np.column_stack((cf_strong.gx, cf_strong.gy, cf_strong.gz))
for g in tqdm(grains):
g.labels = np.full(cf_strong.nrows, fill_value=-1, dtype='i')
g.drlv2 = np.full(cf_strong.nrows, fill_value=1, dtype='d')
g.npks = ImageD11.cImageD11.score_and_assign(ubi=g.ubi,
gv=gves,
tol=peak_assign_tol,
drlv2=g.drlv2,
labels=g.labels,
label=0)
g.pks_mask = g.labels == 0
g.gves = gves[g.pks_mask]
# nuniq counts distinct hkls rather than peaks
# a bad orientation can pick up a lot of peaks on a few rings, but it will not
# explain many different reflections, so nuniq separates real grains from junk
g.hkl_int = np.rint((g.ubi @ g.gves.T).T)
g.nuniq = np.unique(g.hkl_int, axis=0).shape[0]
Choosing the cutoffs#
Real grains normally show up as a well-separated cloud at high npks and high nuniq.
Pick min_npks and min_nuniq in the first cell to cut between the two populations.
fig, axs = plt.subplots(1, 3, figsize=(15, 5), layout='constrained')
axs[0].hist([g.npks for g in grains], bins=100)
axs[0].set(xlabel='npks', ylabel='frequency', title='Peaks per grain')
axs[1].hist([g.nuniq for g in grains], bins=100)
axs[1].set(xlabel='nuniq', ylabel='frequency', title='Unique hkls per grain')
hh = axs[2].hist2d([g.npks for g in grains], [g.nuniq for g in grains], bins=75, norm='log')
axs[2].axvline(min_npks, color='red')
axs[2].axhline(min_nuniq, color='red')
axs[2].set(xlabel='npks', ylabel='nuniq', title='Cutoffs (red)')
plt.show()
good_grains = [g for g in grains if ((g.nuniq > min_nuniq) & (g.npks > min_npks))]
print(f'{len(good_grains)} grains of {len(grains)} passed the cutoffs')
Results#
for g in good_grains:
g.ref_unitcell = ucell
utils.get_rgbs_for_grains(good_grains)
# plt.style.use('dark_background')
fig, ax = plt.subplots(2, 2, figsize=(12, 12), layout='constrained', sharex=True, sharey=True)
a = ax.ravel()
x = [g.translation[0] for g in good_grains]
y = [g.translation[1] for g in good_grains]
s = [g.npks/10 for g in good_grains]
a[0].scatter(y, x, c=[g.rgb_z for g in good_grains], s=s)
a[0].set(title='IPF color Z', aspect='equal')
a[1].scatter(y, x, c=[g.rgb_y for g in good_grains], s=s)
a[1].set(title='IPF color Y', aspect='equal')
a[2].scatter(y, x, c=[g.rgb_x for g in good_grains], s=s)
a[2].set(title='IPF color X', aspect='equal')
a[3].scatter(y, x, c=[g.nuniq for g in good_grains], s=s)
a[3].set(title='Number of unique hkls', aspect='equal')
fig.supxlabel("<- Sample y (transverse)")
fig.supylabel("Sample x (beam) ->")
fig.suptitle("Grain centre-of-mass positions from Friedel pairs")
# sample y increases to the left, to match the reconstructions
for a in ax.ravel():
a.invert_xaxis()
plt.show()
Export data#
The grains are written to ds.grainsfile under the phase name, which is exactly what
tomo_2_map.ipynb expects to read, alongside the whole-sample mask we saved earlier.
Note that writing will fail if a grains group for this phase is already in the file - delete it (or the file) before re-running.
# reset grain labels so they are contiguous
for ginc, g in enumerate(good_grains):
g.gid = ginc
ds.save_grains_to_disk(good_grains, phase_name=phase_str)
ds.save()