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