ImageD11.sinograms.pbp_refine module#
Point-by-point refinement of orientation and strain.
Originally written by Axel Henningsson, with adaptations by James Ball.
https://www.nature.com/articles/s41598-024-71006-0
The method follows Henningsson et al., and the equation numbers below refer to the supplementary material of that paper. This module refines what the point-by-point indexer produced: for every voxel and every candidate orientation it selects the peaks that saw that voxel, refines the unit cell matrix, and then fits an elastic strain tensor.
Notation, and where each symbol lives in the code#
- G measured diffraction vector, in sample coordinates
G = U B G_hkl eq (5)
(eq (4) is the same in the lab frame, with the turntable rotation Omega applied; everything here works in sample coordinates, so Omega does not appear)
G_hkl integer Miller indices -> fit_hkl (UB)^-1 unit cell matrix inverse, “the UBI” -> ubi_out U, B0 orientation, and the undeformed reference B -> Umat, B0 y + dy distance from the beam to the voxel centroid -> g_yd
Peak selection#
A peak is assigned to a voxel when the beam was illuminating that voxel as the peak was recorded, i.e. when
y0 - sx sin(w) - sy cos(w) - dty | <= ystep
for the peak’s own omega and dty. sx, sy is the voxel centroid in sample coordinates and y0 the rotation axis offset. ystep is the scan step, which is set to the measured beam FWHM.
Peaks recorded at different omega that share (h, k, l), the sign of eta and the scan line are merged into one intensity-weighted peak before fitting.
Orientation refinement, eq (6) to (11)#
Each merged peak carries a weight that falls off with how far the beam passed from the voxel centre:
w = r / (y + dy + r) eq (6)
r is a regularisation length, so that w = 1 for a peak straight through the centroid. The paper writes r as 1 um for a 3 um beam; it is beam_size / 3, and lives in the code as weight_reg. This is the only absolute length in the module – everything else is a ratio of lengths and is therefore free of any assumption about the dty motor units.
A peak counts towards the fit when its Miller indices come out close enough to integers:
|| (UB)^-1 G - round((UB)^-1 G) ||_2 < e_hkl eq (8)
with e_hkl = hkl_tol_refine before merging and hkl_tol_refine_merged after.
The unit cell matrix is then the weighted least squares solution over all such peaks, eq (11). The code solves the equivalent normal equations directly, accumulating
GtWWG = sum_n w^2 G G^T GtWWH = sum_n w^2 G G_hkl^T
and getting (UB)^-1 from a 3x3 Cholesky rather than forming the full system of eq (7) and (10).
Strain refinement, eq (12) to (20)#
Each merged peak is reduced to one scalar strain along its own scattering direction, by comparing the measured G with the one the refined orientation and an undeformed reference cell predict, G0 = U B0 G_hkl:
eps = (G^T G0) / (G^T G) - 1 eq (12)
The elastic strain tensor is the unknown that reproduces those numbers,
eps = (G^T eps_tensor G) / (G^T G) eq (13)
which is linear in the six independent components, so many measurements form
y = M s eq (14) s = [eps_xx, eps_yy, eps_zz, eps_xy, eps_xz, eps_yz] eq (15) M_j = [k1^2, k2^2, k3^2, 2 k1 k2, 2 k1 k3, 2 k2 k3] eq (16) kappa = G / ||G||_2 eq (17)
Weights combine the beam-proximity factor of eq (6) with the g-vector noise sigma_g propagated through eq (12):
- w = ( r / (y + dy + r) ) * ( sigma_g^2 G0^T G0 / (G^T G)^2 )^(-1/2)
eq (18)
Measurements more than 3.5 standard deviations from the mean directional strain are dropped, eq (19), and the tensor is the weighted least squares solution, eq (20). As with the orientation fit the code accumulates the normal equations (MtWWM, MtWWy) and solves a 6x6 Cholesky rather than building M and W.
The whole procedure runs independently for every voxel and every candidate orientation.
Where this code differs from the paper#
Four differences, none of them large, all deliberate:
eq (10) and (11) fit the flattened UB by minimising the residual in G space. This code minimises in hkl space and obtains (UB)^-1 directly, which is what ImageD11’s own indexing.refine does (Paciorek et al., Acta A55 543, 1999). Least squares is not invariant under inverting the model, so the two differ – by about 1e-8 in strain, four orders below the strain precision.
eq (18) as printed has (G^T G) where the code has (G^T G)^2. Propagating sigma_g through eq (12) gives sigma_eps = sigma_g / ||G||, which is what the code computes; the printed form reduces to a constant and would not weight anything. Confirmed typo with Axel.
eq (8) as printed omits the subtraction of the rounded indices. The code tests the residual, which is what the surrounding text describes.
the origin calculation in the original implementation compared the SQUARED hkl residual against an unsquared hkl_tol, so a nominal 0.05 was really a tolerance of sqrt(0.05) = 0.224. Axel has confirmed this was a typo. Here hkl_tol_origins is squared before comparison, matching hkl_tol_refine, so 0.05 now means 0.05. Origins computed with earlier versions of this code, and with the original, used the looser value.
Two apparent typos in the supplement, for anyone reading along: eq (9) lists UB23 twice and omits UB22, and eq (15) is labelled y where eq (14) and (20) call it s.
- class ImageD11.sinograms.pbp_refine.PBPRefine(dset, phase_name, hkl_tol_origins=0.05, hkl_tol_refine=0.1, hkl_tol_refine_merged=0.05, ds_tol=0.005, etacut=0.1, ifrac=None, forref=None, y0=0.0, min_grain_npks=6, beam_size=None)#
Bases:
objectClass to manage point-by-point refinement. The maps in this class are set up on a grid that matches the PBPMap reference frame This is in step space in geometry.py
- classmethod from_h5(filename, h5group='PBPRefine', load_peaks=True, load_input=True, load_output=True)#
- get_origins(nthreads=None, nchunks=None, omega_binsize='auto', omega_step=None, verbose=True)#
Fill the xpos_refined column.
- iplot(skip=1)#
Same as PBP.iplot for now
- loadmap(filename=None, refined=False)#
Load an existing input/refined PBPMap from h5. If you only have a .txt file, you want self.setmap()
- loadpeaks(icolf_filename=None)#
Load icolf from disk
- run_refine(points_step_space=None, npoints=None, output_filename=None, use_cluster=False, pythonpath=None, nthreads=None, nchunks=None, omega_binsize='auto', omega_step=None, save=True, verbose=True, cpus_per_task=16, time_h=1, partition='nice', mem_G=32)#
Refine every UBI candidate in self.pbpmap.
Computes the diffraction origins first if they are not already there, so on the cluster the worker does that too – get_origins is the expensive part and there is no reason to run it on a submission node. Call get_origins() yourself first if you want to inspect them.
- savemap(filename=None, refined=False)#
Save self.pbpmap/self.refinedmap to an H5 file
- savepeaks(icolf_filename=None)#
- setmap(pbpmap)#
Set an input PBPMap Python object to use
- setmask(manual_threshold=None, doplot=False, use_icolf=True, use_singlemap=False)#
Set a mask for choosing what to refine or not.
- setpeaks(colf, keep_colf=True)#
Set icolf to refine against.
keep_colf: keep a reference to colf as self.colf (prevents del colf calls from notebook from working)
- setsingle(pbpmap, method='best', **method_args)#
Function to go from a multi-valued PBPMap to a single-valued PBPMap
- to_h5(filename=None, h5group='PBPRefine', save_peaks=True)#
- ImageD11.sinograms.pbp_refine.build_csr(cells, ncell)#
Counting sort of item indices into ncell buckets. O(N).
- ImageD11.sinograms.pbp_refine.build_partition(refine, omega_binsize='auto', omega_step=None, verbose=True)#
Partition the peaks into (omega bin, dty bin) cells.
See voxel_mask.VoxelSinoMasker.partition for how the partitioning works.
Path 1: already built this session, held as refine._partition Path 2: build it
This is not saved to disk, because we don’t need to memmap like for indexing.
- ImageD11.sinograms.pbp_refine.build_refine_inputs(refine, omega_binsize='auto', omega_step=None, verbose=True)#
Everything refine_map needs, on top of the partition.
- Returns {“partition”: …, “peaks”: …, “pstart”: …, “porder”: …,
“pbpmap_ubis”: …, “nrj”: …, “gvec_pars”: …}
- ImageD11.sinograms.pbp_refine.compute_origins(singlemap, sample_mask, gve, sinomega, cosomega, dty, sx_ax, sy_ax, dsx, dsy, y0, ystep, hkl_tol, weight_reg, omega_partitions, dty_partitions, nom, ndty, usin, ucos, ymin, ray_margin, max_cell, nchunks)#
Compute the origin of diffraction for each peak.
For each (omega frame, dtyi) cell we cast a ray through singlemap; where a voxel’s orientation indexes the peak we accumulate its position, weighted by 1/(ydist+1). All arrays are in CSR (permuted) order, so cells are contiguous runs; the caller un-permutes the result.
Three changes from the version that grouped with lexsort + np.split:
cells come from the CSR index instead of unique_with_counts and np.split, which built reflected Python lists per omega group
the ray is a line, so instead of building full-map ydist / ray_mask / final_mask / weights arrays per cell (~1.5 MB of allocation each, and above the mmap threshold) we solve the strip analytically: for fixed i the set of j with |dty - ygrid| <= ystep is a contiguous interval. Drive along whichever axis keeps the strip narrow.
the inner test is fused. orien.dot(g), np.round and the sum of squares allocated three small arrays for every (peak, voxel) pair.
The CSR cell is only a pre-filter: the exact predicate |dty_p - (y0 - sx sin(w_p) - sy cos(w_p))| <= ystep is still applied per peak, with that peak’s own sinomega/cosomega.
- ImageD11.sinograms.pbp_refine.count_ray_voxels(sample_mask, sx_ax, sy_ax, dsx, dsy, y0, ystep, dty_partitions, nom, ndty, usin, ucos, ymin, ray_margin)#
Diagnostic: mean voxels visited per non-empty cell, and cell occupancy.
- ImageD11.sinograms.pbp_refine.detector_rotation_matrix(tilt_x, tilt_y, tilt_z)#
- ImageD11.sinograms.pbp_refine.grid_axes(sx_grid, sy_grid)#
sx_grid/sy_grid come from np.meshgrid(sx, sy, indexing=’ij’), so they are separable: sx_grid[i, j] == sx[i] and sy_grid[i, j] == sy[j]. The strip walk in compute_origins relies on that, so check it rather than assume.
- ImageD11.sinograms.pbp_refine.gvec_one(xl, yl, zl, xpos, so, co, A, oc, invw, a_is_eye)#
One g-vector, no allocation and no trig.
xl, yl, zl peak position in the lab frame, at the nominal distance xpos diffraction origin along lab x (the refined origin) so, co sin, cos of that peak’s omega
- ImageD11.sinograms.pbp_refine.gvec_pars(pars)#
Pack the sample<->lab part of the pars for the fast kernels.
Returns (A, oc, invwvln, a_is_eye):
- A (3, 3) W(wedge) @ C(chi). origin_lab = A @ R(omega) @ t and
g = R(omega)^T @ A^T @ k, matching ImageD11’s compute_grain_origins and compute_g_from_k.
- oc (3, 3) origin_lab[i] = cos(om) oc[i,0] + sin(om) oc[i,1]
oc[i,2]
invwvln 1 / wavelength a_is_eye True when wedge == chi == 0, so A^T can be skipped
- ImageD11.sinograms.pbp_refine.gvectors_from_lab(xl, yl, zl, xpos, sinomega, cosomega, A, oc, invw, a_is_eye, nblocks)#
(N, 3) g-vectors, C-contiguous, in one parallel pass.
Blocked rather than a bare prange over N, because refine_map sets numba.set_parallel_chunksize(1) and that would otherwise make every single peak its own task.
- ImageD11.sinograms.pbp_refine.main(argv=None)#
- ImageD11.sinograms.pbp_refine.prepare_refine_bash(pbp_object, id11_code_path, output_filename=None, cpus_per_task=16, time_h=1, partition='nice', mem_G=32)#
- ImageD11.sinograms.pbp_refine.refine_map(points_ri, points_rj, pstart, porder, pbpmap_ubis, nrj, sx_grid, sy_grid, mask, omega_partitions, dty_partitions, usin, ucos, ymin, xl, yl, zl, eta, sum_intensity, sinomega, cosomega, omega, dty, dtyi, xpos, gve_all, ystep, y0, B0, A, oc, invwvln, a_is_eye, tol, merge_tol, min_grain_npks, sigma_g, weight_reg, maxlocal, nchunks)#