Friedel Pair Mapping notebook#
The idea behind this is similar to the idea in DCT and here https://doi.org/10.1107/S1600576724009634, where Friedel pairs are used to locate where diffraction spots come from in space. In those cases we use peaks that are 180 degrees apart. This notebook is looking for peaks that are separated by twotheta. These are the peaks we use in the friedel_rois macro at ID11 that aligns grains on the centre of rotation.
The pairs we use will have:
eta -> -eta
tth -> tth
gve -> -gve
Jon Wright. March 2025.
Source: ImageD11/nbGui/S3DXRD/friedel_pair_map.ipynb. Shown as saved in git; the documentation build does not run it.
# 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
dset_path = '/path/to/dataset.h5'
phase_str = None # or 'Fe' for example
y0 = 0.0
gvtol = 0.002 # value is often OK
# xpos, ypos and ytol erance for a position in space.
# update these after you see your plot
ytol = 1.0 # For selecting peaks in space - same units as y0!
px = 0.0
py = 0.0
# peak filtration parameters
min_frames_per_peak = 0
filter_by_phase = False # or True
cf_strong_ifrac = 5e-5
cf_strong_dstol = 0.003
par_file = None
# test dataset:
if False:
dset_path = "/data/id11/inhouse2/test_data_3DXRD/S3DXRD/FeAu/PROCESSED_DATA/20250303_JW/tomo_route/FeAu_0p5_tR_nscope/FeAu_0p5_tR_nscope_top_200um/FeAu_0p5_tR_nscope_top_200um_dataset.h5"
y0 = -15.9 # matches your dataset, if known.
phase_str = 'Fe'
# xpos, ypos and tolerance for a position in space.
# update these after you see your plot
px = -108.
py = -164.
ytol = 2.
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, sys, time
start = time.time()
%matplotlib ipympl
import numpy as np
import matplotlib.pyplot as plt
import ImageD11.sinograms.dataset
import ImageD11.sinograms.geometry
import ImageD11.transformer
import ImageD11.indexing
import ImageD11.sinograms.roi_iradon
from ImageD11.peakselect import select_rings_by_ifrac
import scipy.spatial
ds = ImageD11.sinograms.dataset.load(dset_path)
print(ds)
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()
if hasattr(ds, 'y0') and ds.y0 is not None:
y0 = ds.y0
else:
print('You must manually supply a y0 value to continue:')
y0 = 0.0 # manual supply - recommend running fit_y0.ipynb if you don't know it!
cf_4d = ds.get_cf_4d()
ds.update_colfile_pars(cf_4d, phase_str)
print(cf_4d.nrows/1e6, "million peaks read in")
# Optionally remove some noisy peaks
if min_frames_per_peak > 0:
cf_4d.filter(cf_4d['npk2d'] > min_frames_per_peak)
if filter_by_phase:
ds.phases = ds.get_phases_from_disk()
ucell = ds.phases.unitcells[phase_str]
print(ucell)
ucell.makerings(cf_4d.ds.max())
ds.update_colfile_pars(cf_4d, phase_str)
cring = select_rings_by_ifrac(cf_4d, dstol=cf_strong_dstol, dsmax=cf_4d.ds.max(), ifrac=cf_strong_ifrac, uc=ucell)
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()
else:
cring = cf_4d
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) # was np.mgrid[0:cf.nrows][cf_4d.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()
ax.hist(coo.data.flat, bins=500)
ax.set(xlabel='gvtol', ylabel='count')
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.
Now we need to solve for s0 and v.
We can form matrices:
[ s0 | v ] and [ d | 1 ]
such that:
R . [ s0 | v ] = [ d | 1 ]
We can solve this once and determine s0 and v given R and d.
This whole thing happens over N pairs.
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], # (N,2)
cf.dty[i2]))
# 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
Uses the affine form s(y0) = s0 - y0*v (see locate_pairs_affine), so the
linear solve is done once and evaluating at a given y0 is just a
multiply-and-subtract.
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 is locating the Friedel pairs. It seems to need about 1 second per million peaks.
ip, im = find_pairs_minus_eta( cring, gvtol=gvtol )
print('Got',len(ip),'pairs from',cring.nrows,'peaks, fraction paired =',len(ip)*2/cring.nrows )
Now fit the positions. Should be faster than finding the pairs.
sx, sy = locate_pairs( cring, (ip,im), y0 = y0 )
For the plots, we have selected a position in space to extract a grain:
# accounts for y0 padding
bin_edges, bin_centres = ImageD11.sinograms.geometry.recon_bins(ds.ybincens, ds.ymin, ds.ystep, y0)
# Mask for this position in space
m = ((abs(sx-px) < ytol) & (abs(sy-py) < ytol))
idxpt = np.concatenate( (ip[m], im[m]))
cgrain = cring.copyrows( idxpt )
# gvectors from the point px,py in the sample
gvp = (cgrain.gx,cgrain.gy,cgrain.gz)
# verify whether we got the geometry right
xfit,yfit,y0fit = ImageD11.sinograms.geometry.fit_sine_wave(cgrain.omega, cgrain.dty, [0.1,0.1,y0])
calcy = ImageD11.sinograms.geometry.dtycalc(ds.obincens, xfit, yfit, y0fit )
f = plt.figure(figsize=(10,4),constrained_layout=True)
a = [f.add_subplot(131),f.add_subplot(132),f.add_subplot(133, projection='3d', proj_type='ortho') ]
f.colorbar( a[0].hist2d( sx, sy, bins=bin_edges, norm='log', zorder=1)[-1] )
a[0].scatter(px,py,s=10,color='k',fc='none',ec='k')
a[0].set(aspect='equal', xlabel='x sample' , ylabel='ysample',title='Pair locations')
a[1].plot( cgrain.omega, cgrain.dty, '.')
a[1].plot( ds.obincens, calcy, '-', label='fitted' )
a[1].set(title='Fit: x %.3f, y %.3f y0 %.3f'%( xfit, yfit, y0fit ), xlabel='omega', ylabel='dty');
# Select peaks from some position in space
a[2].scatter( *gvp,',',s=1)
a[2].set_box_aspect((1,1,1))
a[2].set_aspect('equal')
a[2].set(title=f"Selected gve",
xlabel='gx', ylabel='gy', zlabel='gz');
Check: run some indexing#
def run_index_unknown(gid, cf, frac=0.2, tol=0.05, sigma=10):
"""
gid = string to name files
cf = colfile to index
frac = fraction of peaks you want to index
tol = hkl tolerance
"""
tr = ImageD11.transformer.transformer()
tr.colfile = cf
tr.parameterobj = cf.parameters
# need to have cell params to save gves
try:
cell_a = cgrain.parameters.get('cell__a')
except KeyError:
# no lattice parameters found
tr.parameterobj.set('cell__a', 3.0)
tr.parameterobj.set('cell__b', 3.0)
tr.parameterobj.set('cell__c', 3.0)
tr.parameterobj.set('cell_alpha', 90.0)
tr.parameterobj.set('cell_beta', 90.0)
tr.parameterobj.set('cell_gamma', 90.0)
tr.parameterobj.set('cell_lattice_[P,A,B,C,I,F,R]','P') # integer not backwards compatible
tr.savegv( f'gr{gid}.gve' )
!index_unknown.py -g gr{gid}.gve -m 40 --fft -t {tol} -f {frac} -o {gid}.ubi -k 1 -s {sigma}
if os.path.exists(f'{gid}.ubi'):
fixhandedness( f'{gid}.ubi' ) # the script on path might not be the one in git
def do_index_with_cctbx(gid, cf_point):
from rstbx.indexing.do_index import do_index
gve = np.vstack((cf_point.gx, cf_point.gy, cf_point.gz)).T
D, L = do_index(gve, verbose=False)
UBI_cctbx = np.array(D.getOrientation().direct_matrix()).reshape(3,3)
# fix handedness
if np.linalg.det( UBI_cctbx ) < 0:
UBI_cctbx[-1] = -UBI_cctbx[-1]
assert np.linalg.det( UBI_cctbx ) > 0
best_cell = L.result_groups[0]['best_subsym']
g = ImageD11.grain.grain(UBI_cctbx, symmetry=best_cell.space_group_number())
print('Found a grain with this UBI, writing to', f'{gid}.ubi')
print(g.ubi)
print(g.unitcell)
print('The best choice of unitcell seems to be:')
print(best_cell)
print("Here's the output of the symmetriser:")
ImageD11.grain.write_grain_file(f'{gid}.ubi', [g])
L.show()
def fixhandedness( ubifile ):
ubis = ImageD11.indexing.readubis( ubifile )
for i in range(len(ubis)):
if np.linalg.det( ubis[i] ) < 0:
ubis[i][-1] = -ubis[i][-1]
assert np.linalg.det( ubis[i] ) > 0
ImageD11.indexing.write_ubi_file( ubifile, ubis )
def choose_peaks(cf, g, tol=1e-4):
"""
get the peaks a grain indexes using g error tol
Belongs somewhere else (grain method?)
"""
gve = (cf.gx, cf.gy, cf.gz)
hkl = g.ubi.dot( gve )
gcalc = g.ub.dot( np.round( hkl ) )
gerr = ((gcalc - gve )**2).sum(axis=0)
return gerr < tol
def plot_indexing( cf, ubifiles, tol=1e-4 ):
gl = []
for f in ubifiles:
gl += ImageD11.grain.read_grain_file( f )
fig = plt.figure()
ax = fig.add_subplot( 1, 2, 1, projection='3d', proj_type='ortho')
ax2 = fig.add_subplot(1, 2, 2)
ax.plot( cf.gx, cf.gy, cf.gz, '.', ms = 1)
ax2.plot( cf.omega, cf.dty, ".", ms=1 )
for i,g in enumerate(gl):
indexed = choose_peaks( cf, g, tol=tol )
ax.scatter( cf.gx[indexed], cf.gy[indexed], cf.gz[indexed], s=3, c='rgbmyk'[i] )
for j in range(3):
ax.plot( [0,g.ub[0,j]],
[0,g.ub[1,j]],
[0,g.ub[2,j]],
'-'+'rgb'[j] )
ax2.plot( cf.omega[ indexed ], cf.dty[indexed], "+"+'rgbmyk'[i] )
ax.set_box_aspect((1,1,1))
ax.set_aspect('equal')
def equiv_symm(latpars):
from cctbx.uctbx import unit_cell
from rstbx.dps_core.lepage import iotbx_converter
L = iotbx_converter(unit_cell(parameters=tuple(latpars)).minimum_cell(),5.0)
best_cell = L.result_groups[0]['best_subsym']
print([(res['best_subsym'], res['best_subsym'].space_group_number()) for res in L.result_groups])
print(L.result_groups[0])
run_index_unknown( '0', cgrain, frac=0.2, tol=0.05, sigma=10)
indexed = choose_peaks( cgrain, ImageD11.grain.read_grain_file( '0.ubi')[0], tol=1e-4 )
print(indexed.sum())
# re-index using the peaks indexed
run_index_unknown( 1, cgrain.copyrows( indexed ) , frac=0.2, tol=0.05, sigma=10)
plot_indexing(cgrain, ['1.ubi'], tol=1e-4)
# or index with cctbx
do_index_with_cctbx(2, cgrain)
You can check for higher symmetry at https://www.cryst.ehu.es/cryst/lattice.html
# or do this:
grains = ImageD11.grain.read_grain_file('1.ubi')
equiv_symm(grains[0].unitcell)
print('Total runtime', time.time()-start)