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