Notebook to fit y0#
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/fit_y0.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 = 'si_cube_test/processed/Si_cube/Si_cube_S3DXRD_nt_moves_dty/Si_cube_S3DXRD_nt_moves_dty_dataset.h5'
par_file = None
# 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.
gvtol = 0.002 # value is often OK
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
import matplotlib.pyplot as plt
import scipy.spatial
import ImageD11.sinograms.dataset
from ImageD11.sinograms.geometry import recon_bins
from tqdm.autonotebook import tqdm
from scipy.optimize import curve_fit
%matplotlib ipympl
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()
cf_4d = ds.get_cf_4d()
ds.update_colfile_pars(cf_4d)
print(cf_4d.nrows/1e6, "million peaks read in")
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)
def fit_y0(cf, pairs, y0s, npks=100_000, nbx=256, nby=256,
fit_window=15, seed=0, doplot=False):
"""
Find the beam-centre offset y0 that best focuses the pair reconstruction,
i.e. maximises the standard deviation of the 2D histogram of (sx, sy).
Sweeps y0s on a subsample using the affine relation s(y0) = s0 - y0*v
(no per-y0 solve), scores every y0 on one fixed grid via a single
bincount, then fits a parabola to the peak for sub-grid-step resolution.
Parameters
----------
cf : ImageD11 columnfile
pairs : (ip, im) arrays of cf indices for each pair
y0s : array of y0 values to scan
npks : max pairs to subsample (peak location scales like 1/sqrt(n))
nbx, nby : fixed grid size used for scoring
fit_window : points either side of the argmax for the parabola fit
seed : rng seed for the subsample
doplot : draw the stdev curve, fit, and vertex
Returns
-------
best_y0 : float, the fitted optimum
y0s : the scan grid (unchanged)
stdevs : stdev of the fixed-grid histogram at each y0
"""
s0, v = locate_pairs_affine(cf, pairs)
y0s = np.asarray(y0s)
n_y0 = len(y0s)
# subsample the pairs
rng = np.random.default_rng(seed)
N = s0.shape[1]
n_sub = min(N, npks)
sub = rng.choice(N, n_sub, replace=False) if N > n_sub else slice(None)
s0x, s0y = s0[0, sub], s0[1, sub]
vx, vy = v[0, sub], v[1, sub]
# point positions over the whole sweep: (n_sub, n_y0)
sx = s0x[:, None] - y0s[None, :] * vx[:, None]
sy = s0y[:, None] - y0s[None, :] * vy[:, None]
# one fixed grid for every y0 (robust extent so outliers don't blow it up)
xlo, xhi = np.percentile(sx, [0.05, 99.95])
ylo, yhi = np.percentile(sy, [0.05, 99.95])
xedges = np.linspace(xlo, xhi, nbx + 1)
yedges = np.linspace(ylo, yhi, nby + 1)
ix = np.searchsorted(xedges, sx, 'right') - 1
iy = np.searchsorted(yedges, sy, 'right') - 1
ok = (ix >= 0) & (ix < nbx) & (iy >= 0) & (iy < nby) # drops out-of-grid, like histogram2d
col = np.broadcast_to(np.arange(n_y0), sx.shape)
flat = col[ok] * (nbx * nby) + ix[ok] * nby + iy[ok] # (y0, bin) -> one index
counts = np.bincount(flat, minlength=n_y0 * nbx * nby).reshape(n_y0, nbx * nby)
B = nbx * nby
sumsq = np.einsum('ij,ij->i', counts, counts).astype(float) # Σc² per y0
Ncol = counts.sum(1) # in-grid points per y0
stdevs = np.sqrt(sumsq / B - (Ncol / B) ** 2) # == std of the 2D hist
# parabola fit to the peak -> sub-grid-step vertex
k = np.argmax(stdevs)
lo, hi = max(0, k - fit_window), min(n_y0, k + fit_window + 1)
a, b, c = np.polyfit(y0s[lo:hi], stdevs[lo:hi], 2)
best_y0 = -b / (2 * a)
if doplot:
best_std = np.polyval((a, b, c), best_y0)
y0_fit = np.linspace(y0s[lo], y0s[hi - 1], 200)
fig, ax = plt.subplots()
ax.plot(y0s, stdevs, label='stdev')
ax.plot(y0_fit, np.polyval((a, b, c), y0_fit),
color='red', ls='--', label='parabola fit')
ax.axvspan(y0s[lo], y0s[hi - 1], color='red', alpha=0.08)
ax.axvline(best_y0, color='red', label=f'best_y0 = {best_y0:.3f}')
ax.plot(best_y0, best_std, 'ro')
ax.set(xlabel='y0', ylabel='stdev')
ax.legend()
plt.show()
return best_y0, y0s, stdevs
The next cell is locating the Friedel pairs. It seems to need about 1 second per million peaks.
ip, im = find_pairs_minus_eta( cf_4d, gvtol=gvtol, doplot=True )
print('Got',len(ip),'pairs from',cf_4d.nrows,'peaks, fraction paired =',len(ip)*2/cf_4d.nrows )
# 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_guess = y0_manual
else:
if hasattr(ds, 'y0') and ds.y0 is not None:
print('Using ds.y0')
y0_guess = ds.y0
else:
# not using manual y0, and couldn't find one. guess it from ymax/ymin
if not is_half_scan:
y0_guess = (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_guess)
Now fit the positions with the y0 guess. Should be faster than finding the pairs.
sx, sy = locate_pairs( cf_4d, (ip,im), y0 = y0_guess )
bin_edges_guess, bin_centres_guess = recon_bins(ds.ybincens, ds.ymin, ds.ystep, y0_guess)
hist_guess = np.histogram2d(sx, sy, bins=bin_edges_guess)[0]
fig, ax = plt.subplots(layout='constrained', figsize=(8,8))
ax.pcolormesh(bin_edges_guess, bin_edges_guess, hist_guess)
ax.set_aspect(1)
ax.set(title=f'y0 guess: {y0_guess}', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.show()
# now we try this with a range of y0 guesses, and look for peaks in the standard deviation
# guess += 5 from y0_guess, you can change this as needed
y0_min = y0_guess - 5
y0_max = y0_guess + 5
n_y0 = 200
y0s = np.linspace(y0_min, y0_max, n_y0)
# choose how many peaks to use to fit - this is faster than using the full array
npks = 500_000
%%time
best_y0, y0s, stdevs = fit_y0(cf_4d, (ip, im), y0s, npks=npks, doplot=True, fit_window=30)
# take the results of the Laplace fit:
y0_final = best_y0
# or manually override from your interpretation of the plot:
# y0_final = 0
print(y0_final)
sx, sy = locate_pairs( cf_4d, (ip,im), y0 = y0_final )
bin_edges_final, bin_centres_final = recon_bins(ds.ybincens, ds.ymin, ds.ystep, y0_final)
hist_final = np.histogram2d(sx, sy, bins=bin_edges_final)[0]
fig, ax = plt.subplots(layout='constrained', figsize=(8,8))
ax.pcolormesh(bin_edges_final, bin_edges_final, hist_final)
ax.set_aspect(1)
ax.set(title=f'y0 final: {y0_final}', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.show()
fig, axs = plt.subplots(1, 2, layout='constrained', figsize=(12,6), sharex=True, sharey=True)
axs[0].pcolormesh(bin_edges_guess, bin_edges_guess, hist_guess)
axs[0].set_aspect(1)
axs[0].set(title=f'y0 guess: {y0_guess}')
axs[1].pcolormesh(bin_edges_final, bin_edges_final, hist_final)
axs[1].set_aspect(1)
axs[1].set(title=f'y0 final: {y0_final}')
fig.supxlabel('Sample Y axis -->')
fig.supylabel('Sample X axis -->')
plt.show()
# save final result to disk
ds.y0 = y0_final
ds.save()