Friedel Pair Matching — Demo Notebook#
Written by Jean-Baptiste Jacob, May 2026
This notebook demonstrates how to find and validate Friedel pairs in an ImageD11 columnfile using the friedel_pairs module.
Friedel relationships — geometry on the detector#
A Friedel pair is a couple of diffraction peaks related by the centrosymmetry of the diffraction pattern: reflection \((h,k,l)\) and its Friedel mate \((-h,-k,-l)\) produce peaks at predictable mirror positions in detector/reciprocal space. A maximum of four Friedel reflections (“entry” and “exit” reflections of \((h,k,l)\) and \((-h,-k,-l)\)) occurs during a full 360° rotation of the sample. Finding these pairs is useful for refining diffraction geometry, estimating grain positions, and improving indexing.
η = 0°
|
(ω_0,η_0) p0 | p2 (ω_3,η_3)
o | *
|
|
η=-90° -------+------- η = 90°
|
|
o | *
(ω_1,η_1) p1 | p2 (ω_2,η_2)
|
η = ±180°
Two types of Friedel pairs can be exploited, depending on the acquisition (half or ful-360° rotation in omega):
Omega pairs — the two twins \(p_0\), \(p_1\) that appear at omega angles 180° apart:
\(\mathbf{g}_1 = -\mathbf{g}_0 \qquad \eta_1 = 180° - \eta_0\)
Eta pairs — “entry” and “exit” twins \(p_0\), \(p_2\) at \(\omega \pm \theta\):
\(\mathbf{g}_2 = -\mathbf{g}_0 \qquad \eta_2 = 180° + \eta_0\)
Both types share the same g-vector antisymmetry (\(\mathbf{g}_{twin} = -\mathbf{g}_{ref}\)) and are matched using a KDTree search in the 5D space \((g_x, g_y, g_z, \eta, \log I)\).
Symmetrically, \(p_2\) and \(p_3\) form a mirror set of omega-pairs, and \(p_1\) and \(p_2\) a mirror set of eta-pairs. The set \((p_0,p_1,p_2,p_3)\) forms a full Friedel quadruplet.
Source: ImageD11/nbGui/match_friedel_pairs.ipynb. Shown as saved in git; the documentation build does not run it.
Load data#
import os, sys, time
start = time.time()
# python environment stuff
IMAGED11_PATH = None # None means do not use git, otherwise enter the name of the folder to use for the git checkout "ImageD11" or "ImageD11_version_xx", etc
CHECKOUT_PATH = 'ImageD11' # the name of the git checkout folder within path. None means guess
if IMAGED11_PATH is not None:
if '/data/id11/nanoscope' not in sys.path:
sys.path.append('/data/id11/nanoscope')
import install_ImageD11_from_git
install_ImageD11_from_git.setup_ImageD11_from_git(IMAGED11_PATH,CHECKOUT_PATH)
# Setting path via:
sys.path.insert(0, /home/esrf/jean1994b/ImageD11_jbjacob/ImageD11 )
# Running from: /home/esrf/jean1994b/ImageD11_jbjacob/ImageD11/ImageD11/__init__.py
import numpy as np
import matplotlib.pyplot as plt
import ImageD11.sinograms.dataset
import ImageD11.sinograms.geometry
import ImageD11.friedel_pairs as fp
import logging
logging.basicConfig(level=logging.INFO)
%load_ext autoreload
%autoreload 2
%matplotlib ipympl
# Datasets examples
# WG: Westerly Granite | ~5mmx2.5mm chunk, 50µm voxels, 360° acq. | quartz, feldspars, biotite, Fe-oxides. peaks_2D only
#dset_path = '/data/id11/inhouse2/test_data_3DXRD/S3DXRD/full_360_deg_scans/WG/WG_DT360Z5480/WG_DT360Z5480_dataset.h5'
# C18A_01: metamorphic rock (quartz + garnet) | 1x2mm chunk, 360° acq on central ROI on central ROI (800µm diam.), 7.5 µm voxels.
#dset_path = '/data/id11/inhouse2/test_data_3DXRD/S3DXRD/full_360_deg_scans/C18A_01/C18A_01_z180/C18A_01_z180_dataset.h5'
# FeAu: Iron-gold sample. 180° acquisition
#dset_path = '/data/id11/inhouse2/test_data_3DXRD/S3DXRD/FeAu/PROCESSED_DATA/20250320/tomo_route/FeAu_0p5_tR_nscope/FeAu_0p5_tR_nscope_top_200um/FeAu_0p5_tR_nscope_top_200um_dataset.h5'
# FeAu f2scan: Iron-Gold sample, 360° acquisition with f2scan
dset_path = '/data/id11/inhouse2/test_data_3DXRD/S3DXRD/FeAu_f2scan/PROCESSED_DATA/20250312_JADB/FeAu_No1_190um/FeAu_No1_190um_2um_redo_z_0/FeAu_No1_190um_2um_redo_z_0_dataset.h5'
ds = ImageD11.sinograms.dataset.load(dset_path)
print(ds)
dataroot = "/data/id11/inhouse2/test_data_3DXRD/S3DXRD/FeAu_f2scan/RAW_DATA"
analysisroot = "/data/id11/inhouse2/test_data_3DXRD/S3DXRD/FeAu_f2scan/PROCESSED_DATA/20250312_JADB"
sample = "FeAu_No1_190um"
dset = "2um_redo_z_0"
shape = ( 140, 900)
# scans 140 from 1.1::[0:900] to 14.1::[8100:9000]
#ds.shape = (70,900)
#ds.ybincens = None
#ds.guessbins()
#ds.ybincens.shape
cf_2d = ds.get_cf_2d()
cf_2d.parameters.loadparameters(ds.parfile)
cf_2d.updateGeometry()
print(cf_2d.nrows)
Loading existing colfile from /data/id11/inhouse2/test_data_3DXRD/S3DXRD/FeAu_f2scan/PROCESSED_DATA/20250312_JADB/FeAu_No1_190um/FeAu_No1_190um_2um_redo_z_0/FeAu_No1_190um_2um_redo_z_0_peaks_2d.h5
Reading your columnfile in hdf format
20432767
cf_4d = ds.get_cf_4d()
cf_4d.parameters.loadparameters(ds.parfile)
cf_4d.updateGeometry()
cf_4d.nrows
3508161
sino = ds.sinohist(cf_2d.sum_intensity, cf_2d.omega, cf_2d.dty)
plt.figure()
plt.pcolormesh(ds.obinedges, ds.ybinedges, sino.T, vmax = np.percentile(sino.flatten(),99))
<matplotlib.collections.QuadMesh at 0x116ee0883c80>
1 — Global pairing (small peakfiles)#
Suitable for box-beam datasets or any columnfile small enough (~up to a few million peaks). The full columnfile is split into two mirror halves, the partner half is flipped into the reference frame, and an iterative nearest-neighbour search finds the pairs.
1.1 — Set up FriedelPairIndexer#
Create an indexer object by passing a columnfile and a dataset object. The key tolerance parameters control the maximum allowed mismatch between a candidate pair:
tol_gv— g-vector distance tolerancetol_eta— eta angle tolerance (degrees)tol_logI— log_10 intensity tolerance; set tonp.infto ignore intensity
An optional weights dict lets you emphasise or suppress individual dimensions of the search space. n_steps controls how many distance increments are used in the iterative search: more steps = finer resolution. For large peakfiles, increasing n_steps to a large number (>50) can make pairing faster.
weights keys: gx, gy, gz, eta, I. Default to 1
# Initiate FriedelPairsIndexer instance with 4d peaks
FPIndexer = fp.FriedelPairIndexer(cf_4d, ds,
tol_gv=0.05,
tol_eta=0.1,
tol_logI=1.,
n_steps=30,
weights = {})
1.2 — Match omega pairs#
Call match_friedel_pairs(pair_type='omega') to find omega pairs across the full columnfile. Internally this:
Sorts the columnfile by omega and splits it into the two 180°-apart halves
Runs a pilot pairing on a small subset to auto-calibrate the search-space weights
Performs the iterative KDTree search, applying physical tolerance filters at each step (in
strictmode) or once at the end (relaxedmode)Writes an
omega_pair_idcolumn to the columnfile (-1for unpaired peaks)
Once omega-pairs have been matched, repeat with pair_type='eta' to find eta pairs and add an eta_pair_id column.
NOTE: omega-pairs can only be found in complete rotation scans with a full 360-deg acquisition in omega. For half-scans (180° acquisition), setting pair_type = 'omega' will raise an error.
FPIndexer
FriedelPairIndexer(cf: 3508161 peaks, tol_gv=0.05, tol_eta=0.1, tol_logI=1.0, n_steps=30, outputs=0 chunk(s))
# try omega pairs. should raise error with the default FeAu dataset (180° acquisition)
cf_paired = FPIndexer.match_friedel_pairs(pair_type='omega',
drop_unpaired=False,
filter_mode='relaxed',
doplot=True,
timeout = 120)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MATCH FRIEDEL PAIRS [omega pairs] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- SEARCH SPACE CALIBRATION [pilot pairing] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: pilot search: cutoff=0.0202 pairs found: 142092
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:Typical (median) pair distances in non-weighted search space:
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: gvecs: 0.0082
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: eta: 0.0065 deg
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: logI: 0.0045
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Euclidean dist: 0.0163
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Effective weights : {'gx': '0.552', 'gy': '0.552', 'gz': '0.552', 'eta': '0.692', 'I': '1.000'}
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Rescaled dist_max : 1.0035
--------------------------------------------------
FRIEDEL PAIR SEARCH [omega]
--------------------------------------------------
Subsets : 1742582 + 1765579 peaks
Tolerances : gv=0.05 eta=0.1 deg logI=1.0
dist_max : 1.0035 (30 steps)
--------------------------------------------------
ITERATIVE PAIR MATCHING [30 steps]
--------------------------------------------------
step 1/30 cutoff=0.0335 -> +477353 pairs
[########......................] 27.4% (477353/1742582)
step 2/30 cutoff=0.0669 -> +462037 pairs
[################..............] 53.9% (939390/1742582)
step 3/30 cutoff=0.1004 -> +298670 pairs
[#####################.........] 71.0% (1238060/1742582)
step 4/30 cutoff=0.1338 -> +162717 pairs
[########################......] 80.4% (1400777/1742582)
step 5/30 cutoff=0.1673 -> +83770 pairs
[#########################.....] 85.2% (1484547/1742582)
step 6/30 cutoff=0.2007 -> +43739 pairs
[##########################....] 87.7% (1528286/1742582)
step 7/30 cutoff=0.2342 -> +25250 pairs
[##########################....] 89.2% (1553536/1742582)
step 8/30 cutoff=0.2676 -> +15078 pairs
[###########################...] 90.0% (1568614/1742582)
step 9/30 cutoff=0.3011 -> +9576 pairs
[###########################...] 90.6% (1578190/1742582)
step 10/30 cutoff=0.3345 -> +6292 pairs
[###########################...] 90.9% (1584482/1742582)
step 11/30 cutoff=0.3680 -> +4604 pairs
[###########################...] 91.2% (1589086/1742582)
step 12/30 cutoff=0.4014 -> +3404 pairs
[###########################...] 91.4% (1592490/1742582)
step 13/30 cutoff=0.4349 -> +2589 pairs
[###########################...] 91.5% (1595079/1742582)
step 14/30 cutoff=0.4683 -> +2127 pairs
[###########################...] 91.7% (1597206/1742582)
step 15/30 cutoff=0.5018 -> +1766 pairs
[###########################...] 91.8% (1598972/1742582)
step 16/30 cutoff=0.5352 -> +1450 pairs
[###########################...] 91.8% (1600422/1742582)
step 17/30 cutoff=0.5687 -> +1265 pairs
[###########################...] 91.9% (1601687/1742582)
step 18/30 cutoff=0.6021 -> +1066 pairs
[###########################...] 92.0% (1602753/1742582)
step 19/30 cutoff=0.6356 -> +889 pairs
[###########################...] 92.0% (1603642/1742582)
step 20/30 cutoff=0.6690 -> +853 pairs
[###########################...] 92.1% (1604495/1742582)
step 21/30 cutoff=0.7025 -> +739 pairs
[###########################...] 92.1% (1605234/1742582)
step 22/30 cutoff=0.7359 -> +687 pairs
[###########################...] 92.2% (1605921/1742582)
step 23/30 cutoff=0.7694 -> +628 pairs
[###########################...] 92.2% (1606549/1742582)
step 24/30 cutoff=0.8028 -> +600 pairs
[###########################...] 92.2% (1607149/1742582)
step 25/30 cutoff=0.8363 -> +500 pairs
[###########################...] 92.3% (1607649/1742582)
step 26/30 cutoff=0.8697 -> +448 pairs
[###########################...] 92.3% (1608097/1742582)
step 27/30 cutoff=0.9032 -> +400 pairs
[###########################...] 92.3% (1608497/1742582)
step 28/30 cutoff=0.9366 -> +377 pairs
[###########################...] 92.3% (1608874/1742582)
step 29/30 cutoff=0.9701 -> +326 pairs
[###########################...] 92.3% (1609200/1742582)
step 30/30 cutoff=1.0035 -> +334 pairs
[###########################...] 92.4% (1609534/1742582)
--------------------------------------------------
OUTPUT
--------------------------------------------------
Total pairs found : 1609534 / 1742582
[###########################...] 92.4% (1609534/1742582)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MERGING OUTPUTS [omega-pair] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 1 chunk(s) to merge (3508161 peaks total)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 807805 candidate pairs from 1 chunks
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: OK: all pair_ids appear exactly twice
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 807805 pairs, 1615610 peaks paired (46.1%)
Applying final tolerance filters
Total pairs after filtering : 807805 / 1742582
[#############.................] 46.4% (807805/1742582)
--------------------------------------------------
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 27.8% of total intensity matched
# match eta pairs
cf_paired = FPIndexer.match_friedel_pairs(pair_type='eta',
drop_unpaired=False,
filter_mode='relaxed',
doplot=True,
timeout= 120)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MATCH FRIEDEL PAIRS [eta pairs] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- SEARCH SPACE CALIBRATION [pilot pairing] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: pilot search: cutoff=0.0202 pairs found: 141100
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:Typical (median) pair distances in non-weighted search space:
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: gvecs: 0.0082
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: eta: 0.0066 deg
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: logI: 0.0045
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Euclidean dist: 0.0163
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Effective weights : {'gx': '0.549', 'gy': '0.549', 'gz': '0.549', 'eta': '0.687', 'I': '1.000'}
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Rescaled dist_max : 1.0035
--------------------------------------------------
FRIEDEL PAIR SEARCH [eta]
--------------------------------------------------
Subsets : 1836593 + 1671568 peaks
Tolerances : gv=0.05 eta=0.1 deg logI=1.0
dist_max : 1.0035 (30 steps)
--------------------------------------------------
ITERATIVE PAIR MATCHING [30 steps]
--------------------------------------------------
step 1/30 cutoff=0.0334 -> +478682 pairs
[########......................] 28.6% (478682/1671568)
step 2/30 cutoff=0.0669 -> +461077 pairs
[################..............] 56.2% (939759/1671568)
step 3/30 cutoff=0.1003 -> +294786 pairs
[######################........] 73.9% (1234545/1671568)
step 4/30 cutoff=0.1338 -> +155274 pairs
[########################......] 83.1% (1389819/1671568)
step 5/30 cutoff=0.1672 -> +76707 pairs
[##########################....] 87.7% (1466526/1671568)
step 6/30 cutoff=0.2007 -> +37388 pairs
[##########################....] 90.0% (1503914/1671568)
step 7/30 cutoff=0.2341 -> +20830 pairs
[###########################...] 91.2% (1524744/1671568)
step 8/30 cutoff=0.2676 -> +12324 pairs
[###########################...] 92.0% (1537068/1671568)
step 9/30 cutoff=0.3010 -> +8271 pairs
[###########################...] 92.4% (1545339/1671568)
step 10/30 cutoff=0.3345 -> +5168 pairs
[###########################...] 92.8% (1550507/1671568)
step 11/30 cutoff=0.3679 -> +3523 pairs
[###########################...] 93.0% (1554030/1671568)
step 12/30 cutoff=0.4014 -> +2418 pairs
[###########################...] 93.1% (1556448/1671568)
step 13/30 cutoff=0.4348 -> +1723 pairs
[###########################...] 93.2% (1558171/1671568)
step 14/30 cutoff=0.4683 -> +1452 pairs
[###########################...] 93.3% (1559623/1671568)
step 15/30 cutoff=0.5017 -> +1146 pairs
[############################..] 93.4% (1560769/1671568)
step 16/30 cutoff=0.5352 -> +830 pairs
[############################..] 93.4% (1561599/1671568)
step 17/30 cutoff=0.5686 -> +693 pairs
[############################..] 93.5% (1562292/1671568)
step 18/30 cutoff=0.6021 -> +581 pairs
[############################..] 93.5% (1562873/1671568)
step 19/30 cutoff=0.6355 -> +505 pairs
[############################..] 93.5% (1563378/1671568)
step 20/30 cutoff=0.6690 -> +430 pairs
[############################..] 93.6% (1563808/1671568)
step 21/30 cutoff=0.7024 -> +410 pairs
[############################..] 93.6% (1564218/1671568)
step 22/30 cutoff=0.7359 -> +368 pairs
[############################..] 93.6% (1564586/1671568)
step 23/30 cutoff=0.7693 -> +339 pairs
[############################..] 93.6% (1564925/1671568)
step 24/30 cutoff=0.8028 -> +294 pairs
[############################..] 93.6% (1565219/1671568)
step 25/30 cutoff=0.8362 -> +286 pairs
[############################..] 93.7% (1565505/1671568)
step 26/30 cutoff=0.8697 -> +278 pairs
[############################..] 93.7% (1565783/1671568)
step 27/30 cutoff=0.9031 -> +248 pairs
[############################..] 93.7% (1566031/1671568)
step 28/30 cutoff=0.9366 -> +253 pairs
[############################..] 93.7% (1566284/1671568)
step 29/30 cutoff=0.9700 -> +254 pairs
[############################..] 93.7% (1566538/1671568)
step 30/30 cutoff=1.0035 -> +249 pairs
[############################..] 93.7% (1566787/1671568)
--------------------------------------------------
OUTPUT
--------------------------------------------------
Total pairs found : 1566787 / 1671568
[############################..] 93.7% (1566787/1671568)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MERGING OUTPUTS [eta-pair] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 1 chunk(s) to merge (3508161 peaks total)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 796125 candidate pairs from 1 chunks
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: OK: all pair_ids appear exactly twice
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 796125 pairs, 1592250 peaks paired (45.4%)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 18.0% of total intensity matched
Applying final tolerance filters
Total pairs after filtering : 796125 / 1671568
[##############................] 47.6% (796125/1671568)
--------------------------------------------------
1.3 — Evaluate pair distances#
Setting doplot = True plots the distributions of physical distances between matched pairs along each search dimension: g-vector norm, Δη, and Δlog_10(I). Well-matched pairs should cluster tightly near zero. Broad or skewed distributions suggest the tolerances may need adjusting or the geometry calibration could be improved.
These plots can also can be displayed a posteriori with plot_pair_distances(cf, pair_type)
fp.plot_pair_distances(cf_paired, pair_type='eta')
(<Figure size 1200x400 with 3 Axes>,
array([<Axes: xlabel='gvec distance', ylabel='counts'>,
<Axes: xlabel='$\\Delta\\eta$ ($^\\circ$)', ylabel='counts'>,
<Axes: xlabel='$\\Delta \\log_{10}(\\rm{Ints})$', ylabel='counts'>],
dtype=object))
get_pair_distances(cf, pair_type='omega') returns the raw distances (dict) and corresponding tuple of indices (idx1,idx2) for the two paired subsets.
get_pairs(cf, pair_type) returns the indices tuple only.
# get pair distances and indices
dist, (idx1, idx2) = fp.get_pair_distances(cf_paired, 'eta')
dist
{'d_gv': array([0.03146551, 0.00373502, 0.02502991, ..., 0.00353307, 0.00418272,
0.04628525]),
'd_eta': array([4.99039677e-02, 1.76361965e-02, 2.99076922e-03, ...,
5.03423414e-04, 2.66744899e-04, 4.84770339e-07]),
'd_logI': array([0.00713625, 0.05313615, 0.00089305, ..., 0.00233941, 0.02047534,
0.00440197])}
#plot d_tth = |tth2 - tth1|
idx1, idx2 = fp.get_pairs(cf_paired, 'eta')
dtth = np.abs(cf_paired.tth[idx2] - cf_paired.tth[idx1])
plt.figure()
plt.hist(dtth, 50);
plt.xlabel('$\\Delta 2\\theta$ ($^\\circ$)')
plt.ylabel('counts')
Text(0, 0.5, 'counts')
1.4 — Relocate pairs in the sample#
Once omega and eta-pairs have been identified, both can be used to relocate the diffraction source \((x_s,y_s)\) in the sample with locate_omega_pairs and locate_eta_pairs.
Eta-pairs: paired reflections arising from the same spot are observed at different omega angles and dty positions. The dty–omega relationship:
\(\text{dty} - y_0 = -x_s \sin(\omega) - y_s \cos(\omega)\)
yields a 2×2 linear system per pair:
\(\begin{pmatrix} -\sin(\omega_1) & -\cos(\omega_1) \\ -\sin(\omega_2) & -\cos(\omega_2) \end{pmatrix} \begin{pmatrix} x_s \\ y_s \end{pmatrix} = \begin{pmatrix} \text{dty}_1 - y_0 \\ \text{dty}_2 - y_0 \end{pmatrix}\)
which is solved directly.
Omega-pairs: the two reflections are observed ~180° apart in omega, making the matrix above near-singular. Instead, the offset \(d_x\) along the beam axis is derived from the two-theta asymmetry:
Then, the lab-frame coordinates \((d_x, \text{dty} - y_0)\) are rotated back into the sample frame.
np.nanpercentile(ys, (5,95))
array([-2.91790324, 3.07774229])
# get pairs
i1, i2 = fp.get_pairs(cf_paired, 'omega')
i1_, i2_ = fp.get_pairs(cf_paired, 'eta')
# sample coordinates. y0_guess from fit_y0 notebook
y0_guess = 14.31
xs, ys = fp.locate_omega_pairs(cf_paired, (i1,i2), ds, y0=y0_guess)
xs_, ys_ = fp.locate_eta_pairs(cf_paired, (i1_,i2_), ds, y0=y0_guess)
locate_omega_pairs and locate_eta_pairs add sample coordinates to cf as new columns. The last function call overwrites the previous one.
Now we can get a diffraction image of the sample, by plotting a 2D histogram of peaks in (xs,ys) space.
# histogram values
hist_guess = np.histogram2d(xs+y0_guess, ys+y0_guess, bins=ds.ybinedges)[0]
hist_guess_ = np.histogram2d(xs_+y0_guess, ys_+y0_guess, bins=ds.ybinedges)[0]
# plot for omega and eta hist
fig, ax = plt.subplots(1,2,layout='constrained', figsize=(12,6))
im0 = ax[0].pcolormesh(ds.ybinedges, ds.ybinedges, hist_guess, vmax=np.percentile(hist_guess.flatten(),99))
ax[0].set_aspect(1)
ax[0].set(title=f'omega_pairs', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.colorbar(im0, ax=ax[0], orientation='vertical', pad=0.04, shrink=0.7)
im1 = ax[1].pcolormesh(ds.ybinedges, ds.ybinedges, hist_guess_, vmax=np.percentile(hist_guess_.flatten(),99))
ax[1].set_aspect(1)
ax[1].set(title=f'eta_pairs', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.colorbar(im1, ax=ax[1], orientation='vertical', pad=0.04, shrink=0.7)
<matplotlib.colorbar.Colorbar at 0x116ee0513080>
1.5 — Match quadruplets#
Once both omega_pair_id and eta_pair_id columns exist, match_quadruplets() finds the 2×2 blocks of peaks that satisfy both pairing relations simultaneously:
eta pair A eta pair B
omega pair 0: peak p00 —— peak p01
| |
omega pair 1: peak p10 —— peak p11
Each such quadruplet is a complete Friedel group for one reflection family. The method writes a quadruplet_id column to the columnfile (-1 for peaks not belonging to any quadruplet, otherwise a shared integer repeated exactly 4 times).
# quads is a (N,4) array of indices positions in cf containing the complete Friedel groups
quads = FPIndexer.match_quadruplets()
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[43], line 2
1 # quads is a (N,4) array of indices positions in cf containing the complete Friedel groups
----> 2 quads = FPIndexer.match_quadruplets()
File ~/ImageD11_jbjacob/ImageD11/ImageD11/friedel_pairs.py:1020, in FriedelPairIndexer.match_quadruplets(self)
1018 for col in ('omega_pair_id', 'eta_pair_id'):
1019 if col not in cf.titles:
-> 1020 raise RuntimeError(
1021 "'{}' column not found. "
1022 "Run match_{}_pairs() first.".format(col, col.split('_')[0]))
1024 om_col = cf.getcolumn('omega_pair_id') # (nrows,)
1025 eta_col = cf.getcolumn('eta_pair_id') # (nrows,)
RuntimeError: 'omega_pair_id' column not found. Run match_omega_pairs() first.
cf_4d.omega_pair_id[quads], cf_4d.eta_pair_id[quads], cf_4d.quadruplet_id[quads]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[44], line 1
----> 1 cf_4d.omega_pair_id[quads], cf_4d.eta_pair_id[quads], cf_4d.quadruplet_id[quads]
AttributeError: 'columnfile' object has no attribute 'omega_pair_id'
2 — Chunk-based pairing (scanning-3DXRD only)#
For large scanning-3DXRD datasets (>10M peaks), searching within very large KDTrees over the full columnfile quickly becomes inefficient. Instead, the columnfile is divided into small mirror chunks — pairs of mirror subsets that potentially contain the Friedel mates of one another — and matching is done independently within each chunk, then merged. This approch is much more memory efficient as global pairing for large datasets and can be easily paralellized, as each pair of chunks can be treated independently.
2.1 — Chunking strategy and the PeakSubsets object#
Omega pairs#
The PeakSubsets object handles all bookkeeping: it sorts the columnfile in sinogram order (dty primary, omega secondary) and builds lookup tables (LUTs) for fast peak selection by bin index.
Two chunking granularities are available:
Scan-wise chunking (chunk_type='scans'): each chunk is a full dty scan (all omegas) paired with its mirror scan on the opposite side of y₀. This is the default option
dty
^──────────────────────────────────────────────────────
| |
| |
|██████████████████████████████████████████████████████| -> scan hi (y0 + Δy)
| |
| |
y0 +------------------------------------------------------+
| |
| |
|██████████████████████████████████████████████████████| -> scan lo (y0 - Δy)
| |
| |
| |
───────────────────────────+────────────────────────── > ω
ω=180°
Frame-wise chunking (chunk_type='frames'): each chunk is a single (dty, ω) frame paired with its mirror frame at (y0 − Δy, ω + 180°). Finer granularity, but slower to compute.
dty
^──────────────────────────────────────────────────────
| ' |
| ' |
| · · · · · [A] · · · · · · · · · · · · · · · · · · · | y0 + Δy
| ' |
| ' |
y0 +---------------------------'--------------------------+
| ' |
| ' |
| · · · · · · · · · · · · · · · · · · · [B] · · · · · | y0 - Δy
| ' |
| ' |
| ' |
────────────+──────────────+────────────+───────────── > ω
ω₀ ω=180° ω₀+180°
frame A : (y0+Δy, ω₀) ↔ frame B : (y0−Δy, ω₀+180°)
This chunking strategy works only for omega-pairs. eta-pairs are more tricky because there is no direct way of splitting the sinogram into mirror chunks that contain eta-pairs. An alternative strategy to match eta pairs by chunks is presented in section 2.3
PeakSubsets is instantiated and populated automatically when you first call match_omega_pairs_by_chunks(), or you can set it up manually via FPIndexer.set_peak_subsets() and FPIndexer.sort_peak_subsets() to inspect the LUTs and valid-subset masks beforehand.
What it does internally:
Take omega and dty bins in ds and find mirror scans / frames pairs -> populate lists
scans_subsetsandframes_subsetsSort cf in sinogram order (
dtyfirst,omegasecond) and build lookup tables returning the (start,end) index pos for each dty block (single scan) and dty-omega block (single frame) -> stored inscans_LUTandframes_LUTGet the list of valid pairs in
scans_subsetsandframes_subsets: pairs for which both twins have some peaks in the corresponding LUT.
# Initiate a new FriedelPairsIndexer instance with 4d peaks
FPIndexer = fp.FriedelPairIndexer(cf_2d, ds,
tol_gv=0.1,
tol_eta=0.8,
tol_logI=0.8,
n_steps=5,
weights = {'I':1})
# set PeakSubsets instance
FPIndexer.set_peak_subsets(n_eta_bins=360)
FPIndexer.sort_peak_subsets(pair_type='omega')
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- SET PEAKSUBSETS ---
INFO:ImageD11.friedel_pairs:[get_scans_subsets] 71 pairs of dty scans (y0=14.309899999999999)
INFO:ImageD11.friedel_pairs:[get_frames_subsets] 63450 pairs of 2D frames (y0=14.309899999999999): 450 at y0 (omega-only), 63000 off-y0.
INFO:ImageD11.friedel_pairs:[get_eta_bins_subsets] 180 pairs of eta bins
[correct_bins_for_half_scan] y0 = 14.3099, central bin value = 14.3089, central bin id: 69, halfrange=0.1419, n_bins=141 (140 real + 1 padded).
INFO:ImageD11.friedel_pairs:[sort_by_sinogram] already sorted, 20432767 peaks
INFO:ImageD11.friedel_pairs:73243 non-empty frames (53657 empty).
INFO:ImageD11.friedel_pairs:140 non-empty scans (1 empty).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 71 pairs checked in scans_LUT
found 70 subset pairs where both members have peaks (98.59% valid).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 63450 pairs checked in frames_LUT
found 25975 subset pairs where both members have peaks (40.94% valid).
# scans_subsets and pairs_subset: lists of namedtuples that contain the indices positions and values of paired scans / frames in ds.ybincens / ds.obincens
Psub = FPIndexer.PeakSubsets
Psub.scans_subsets[30], Psub.frames_subsets[30]
(Pair(yi_hi=100, yi_lo=40, dty_hi=14.369706474820143, dty_lo=14.24806618705036),
Pair(yi_A=71, yi_B=69, omi_A=30, omi_B=480, dty_A=14.310913669064748, dty_B=14.306858992805756, omega_A=12.079187672395848, omega_B=192.13637599173038))
# scans_LUT and frames_LUT : dict of index position in, cf for a given dty / omega-dty block
# {idx:(slice, len(slice), sum_intensity[slice]) } idx keys match the yi / omi indices in Pair namedtuples
Psub.scans_LUT[84]
BinEntry(slice=slice(13881296, 13935046, None), npeaks=53750, sumI=45277302.16789634)
Mirror subsets of scans / frames should contain roughly the same number of peaks and display the same total intensity. This can be checked for paired scans using check_symmetry()
Mismatch in dty is diagnostic for wrong dty alignment (incorrect y0), or some issue during scan acquisiton (beam issue or sample drift)
TO DO: implement some check at the frame level
some ideas:
correlation coefficient between frames A and frames B
compute sinogram heatmaps for the two halves of the data flipping the ω > 180° side to match the lower side, then do the cross-correlation -> should allow fitting optimal y0 by maximizing the cross-correlation value.
fig = Psub.check_symmetry()
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 71 pairs checked in scans_LUT
found 70 subset pairs where both members have peaks (98.59% valid).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 63450 pairs checked in frames_LUT
found 25975 subset pairs where both members have peaks (40.94% valid).
2.2 — Match omega pairs by chunks#
match_friedel_pairs_by_chunks() orchestrates the full pipeline:
Initialisation — builds
PeakSubsets, computes valid chunk pairs (both members must contain at least one peak)Pilot pairing — picks a representative chunk near the centre of the sinogram and runs a quick search to auto-calibrate the search-space weights
Parallel matching — dispatches all valid chunk pairs to a pool of worker processes; each worker calls
_run_pairingsilently and returns a local result dictMerging — local pair IDs from each chunk are offset to be globally unique and written into the
omega_pair_idcolumn of the master columnfile
options
chunk_typeis eitherscansorframesfor omega-pairs.extended_bin_search=Trueconsiders also direct bin neighbours for Friedel pair matching. Works only forscans(andeta_binsfor eta-pairs, see below). Slowerdrop_unpaired=Truefilters unpaired peaks out of the columnfile after merging.reset_psub=Truere-initializesPeakSubsetsin the indexer. UseFalseif you want to use pre-defined subsets.n_workers=-1use all available cores.
%%time
cf_paired = FPIndexer.match_friedel_pairs_by_chunks(chunk_type='scans',
extended_bin_search=False,
filter_mode='relaxed',
drop_unpaired=False,
reset_psub=False,
doplot=True,
n_workers=-1)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MATCH FRIEDEL PAIRS [omega pairs] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- INITIALIZATION ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:Chunk type for pairing: scans
INFO:ImageD11.friedel_pairs:[sort_by_sinogram] already sorted, 20432767 peaks
INFO:ImageD11.friedel_pairs:73243 non-empty frames (53657 empty).
INFO:ImageD11.friedel_pairs:140 non-empty scans (1 empty).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 71 pairs checked in scans_LUT
found 70 subset pairs where both members have peaks (98.59% valid).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 63450 pairs checked in frames_LUT
found 25975 subset pairs where both members have peaks (40.94% valid).
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 71 pairs of subsets, 70 valid
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- SEARCH SPACE CALIBRATION [pilot pairing] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: pilot search: cutoff=0.0572 pairs found: 8101
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:Typical (median) pair distances in non-weighted search space:
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: gvecs: 0.0182
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: eta: 0.0186 deg
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: logI: 0.0111
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Euclidean dist: 0.0383
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Effective weights : {'gx': '0.610', 'gy': '0.610', 'gz': '0.610', 'eta': '0.598', 'I': '1.000'}
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Rescaled dist_max : 0.9379
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- FRIEDEL PAIR MATCHING ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 70 chunks | 19 worker(s) | 19 cores available
100%|██████████| 70/70 [00:07<00:00, 9.31it/s]
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MERGING OUTPUTS ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MERGING OUTPUTS [omega-pair] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 70 chunk(s) to merge (20432767 peaks total)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 2226003 candidate pairs from 69 chunks
WARNING:ImageD11.friedel_pairs.FriedelPairIndexer: 134107 pair_id(s) appear only once — broken pairs
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 134107 peaks reassigned to -1
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 2091896 pairs, 4183792 peaks paired (20.5%)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 13.4% of total intensity matched
CPU times: user 2.98 s, sys: 1.64 s, total: 4.62 s
Wall time: 11.6 s
# get indices positions for omega and eta pairs
io1, io2 = fp.get_pairs(cf_paired, 'omega')
# sample coordinates
xs, ys = fp.locate_omega_pairs(cf_paired, (io1,io2), ds=ds, y0=0)
hist_guess = np.histogram2d(xs+ds.y0, ys+ds.y0, bins=ds.ybinedges)[0]
# plot omega hist
fig, ax = plt.subplots(1,1,layout='constrained', figsize=(6,6))
im0 = ax.pcolormesh(ds.ybinedges, ds.ybinedges, hist_guess, vmax=np.percentile(hist_guess.flatten(),99))
ax.set_aspect(1)
ax.set(title=f'omega_pairs', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.colorbar(im0, ax=ax, orientation='vertical', pad=0.04, shrink=0.7)
<matplotlib.colorbar.Colorbar at 0x116f7be32390>
Eta pairs#
For eta pairs, the peakfile is split into \(N\) bins of equal width \(\Delta\eta\) covering \([-180°, 180°)\). Mirror bins at \(\eta\) and \(\eta + 180°\) are paired together for the Friedel search.
This binning is arbitrary and does not correspond to physical scans or frames, which creates a boundary problem: a peak near the edge of bin \(k\) may have its Friedel mate in the neighbouring bin \(k\pm1\) rather than in the exact mirror bin.
To avoid this issue, use extended_bin_search=True:
This widens the search window to include the direct neighbours of the mirror bin, so the two subsets compared are:
Consecutive windows overlap by one bin, so every peak appears in at least two searches:
bins : | k-1 | k | k+1 | k+2 | k+3 | k+4 | k+5 ...
┌────────────┐
window 1: │k-1, k, k+1│ vs mirror(k)
└────────────┘
┌─────────────┐
window 2: │k+1, k+2, k+3│ vs mirror(k+2)
└─────────────┘
┌─────────────┐
window 3: │k+3, k+4, k+5│ vs mirror(k+3)
└─────────────┘
Peaks near bin boundaries therefore have two chances to be matched. Conflicts arising from the overlap (same peak assigned to a pair in more than one window) are resolved at merging time by keeping the assignment with the smallest g-vector distance.
# re-initiate Peaksubset; chose the thickness of eta binning
FPIndexer.set_peak_subsets(n_eta_bins=360)
FPIndexer.sort_peak_subsets(pair_type='eta')
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- SET PEAKSUBSETS ---
INFO:ImageD11.friedel_pairs:[get_scans_subsets] 71 pairs of dty scans (y0=14.309899999999999)
INFO:ImageD11.friedel_pairs:[get_frames_subsets] 63450 pairs of 2D frames (y0=14.309899999999999): 450 at y0 (omega-only), 63000 off-y0.
INFO:ImageD11.friedel_pairs:[get_eta_bins_subsets] 180 pairs of eta bins
INFO:ImageD11.friedel_pairs:[sort_by_sinogram] sorting columnfile in eta order – 20432767 peaks to sort, may take some time...
[correct_bins_for_half_scan] y0 = 14.3099, central bin value = 14.3089, central bin id: 69, halfrange=0.1419, n_bins=141 (140 real + 1 padded).
INFO:ImageD11.friedel_pairs:360 non-empty bins indexed (0 bins have no peaks).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 180 pairs checked in eta_bins_LUT
found 180 subset pairs where both members have peaks (100.00% valid).
check_symmetry can also be used to compare the number of peaks in mirror eta bins. The function detects automatically the type of pairing based on LUTs present in the Peaksubsets
fig = FPIndexer.PeakSubsets.check_symmetry()
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 180 pairs checked in eta_bins_LUT
found 180 subset pairs where both members have peaks (100.00% valid).
# match eta-pairs: use eta_bins subsets and set extended_bin_search=True to have overlap between bins
cf_paired = FPIndexer.match_friedel_pairs_by_chunks(chunk_type='eta_bins',
drop_unpaired=False,
extended_bin_search=True,
filter_mode='relaxed',
n_workers=-1,
reset_psub=False,
doplot=True)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MATCH FRIEDEL PAIRS [eta pairs] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- INITIALIZATION ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:Chunk type for pairing: eta_bins
INFO:ImageD11.friedel_pairs:[sort_by_sinogram] peakfile already sorted – 20432767 peaks
INFO:ImageD11.friedel_pairs:360 non-empty bins indexed (0 bins have no peaks).
INFO:ImageD11.friedel_pairs:[find_valid_subsets] 180 pairs checked in eta_bins_LUT
found 180 subset pairs where both members have peaks (100.00% valid).
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 180 pairs of subsets, 180 valid
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- SEARCH SPACE CALIBRATION [pilot pairing] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: pilot search: cutoff=0.0572 pairs found: 21916
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:Typical (median) pair distances in non-weighted search space:
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: gvecs: 0.0123
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: eta: 0.0139 deg
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: logI: 0.0094
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Euclidean dist: 0.0271
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Effective weights : {'gx': '0.770', 'gy': '0.770', 'gz': '0.770', 'eta': '0.677', 'I': '1.000'}
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: Rescaled dist_max : 0.9754
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- FRIEDEL PAIR MATCHING ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 90 chunks | 19 worker(s) | 19 cores available
100%|██████████| 90/90 [00:14<00:00, 6.00it/s]
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MERGING OUTPUTS ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer:--- MERGING OUTPUTS [eta-pair] ---
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 90 chunk(s) to merge (20432767 peaks total)
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 11775135 candidate pairs from 90 chunks
INFO:ImageD11.friedel_pairs.FriedelPairIndexer: 8050657 unique candidate pairs after deduplication
# get indices positions for omega and eta pairs
ie1, ie2 = fp.get_pairs(cf_paired, 'eta')
# sample coordinates
xs_, ys_ = fp.locate_eta_pairs(cf_paired, (ie1,ie2), ds=ds, y0=ds.y0)
hist_guess_ = np.histogram2d(xs_+ds.y0, ys_+ds.y0, bins=ds.ybinedges)[0]
# plot eta hist
fig, ax = plt.subplots(1,1,layout='constrained', figsize=(6,6))
im = ax.pcolormesh(ds.ybinedges, ds.ybinedges, hist_guess_, vmax=np.percentile(hist_guess_.flatten(),99))
ax.set_aspect(1)
ax.set(title=f'eta_pairs', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.colorbar(im, ax=ax, orientation='vertical', pad=0.04, shrink=0.7)
<matplotlib.colorbar.Colorbar at 0x116f101af620>
# plot for omega and eta hist side by side
fig, ax = plt.subplots(1,2,layout='constrained', figsize=(12,6))
im0 = ax[0].pcolormesh(ds.ybinedges, ds.ybinedges, hist_guess, vmax=np.percentile(hist_guess.flatten(),99))
ax[0].set_aspect(1)
ax[0].set(title=f'omega_pairs', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.colorbar(im0, ax=ax[0], orientation='vertical', pad=0.04, shrink=0.7)
im1 = ax[1].pcolormesh(ds.ybinedges, ds.ybinedges, hist_guess_, vmax=np.percentile(hist_guess_.flatten(),99))
ax[1].set_aspect(1)
ax[1].set(title=f'eta_pairs', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')
plt.colorbar(im1, ax=ax[1], orientation='vertical', pad=0.04, shrink=0.7)
<matplotlib.colorbar.Colorbar at 0x116f4972f500>
Don’t forget to save the peakfiles once they have been paired
ImageD11.columnfile.colfile_to_hdf(cf_paired, '~/cf_2d_paired.h5')