{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Indexing unknown secondary phases"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/select_for_index_unknown.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/select_for_index_unknown.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {}, "source": ["This notebook gives a demo for a couple of methods for selecting a grain and indexing it.\n", "\n", "1: select a peak, find the Friedel pair, use the pair to locate a position\n", "\n", "2: just select a position in space.\n", "\n", "Then filter spots by position, and/or, by using a selected peak to generate lattice translations and checking for translational symmetry.\n", "\n", "Subsets of selected peaks are then indexing using index_unknown.py from ImageD11\n", "\n", "Last modified 15/11/2024"]}, {"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", "if IMAGED11_PATH is not None:\n", " exec(open('/data/id11/nanoscope/install_ImageD11_from_git.py').read())\n", " setup_ImageD11_from_git(CHECKOUT_PATH, IMAGED11_PATH)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["%matplotlib ipympl\n", "import os, sys\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.nbGui.interactive_peakselect import FriedelPairSelector\n", "import ImageD11.nbGui.nb_utils as utils\n", "import ImageD11.peakselect\n", "import scipy.spatial\n", "import ImageD11.transformer\n", "import ImageD11.indexing\n", "import ImageD11.sinograms.geometry"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["def find_overlaps_3d( cf, pkids, gtol = 5e-3 ):\n", " \"\"\"\n", " cf = columnfile with g-vectors\n", " pkids = peaks to use for offsetting your data and overlapping\n", " \n", " This shifts the g-vectors by the gvector of pkid and checks for overlaps\n", " \n", " returns (peaks_having_overlaps, distances used)\n", " \"\"\"\n", " g3 = np.transpose( (cf.gx, cf.gy, cf.gz) )\n", " kd0 = scipy.spatial.cKDTree( g3 )\n", " pks = []\n", " distances = []\n", " for pkid in pkids:\n", " pk1 = np.argmin( abs( cf.spot3d_id - pkid ) )\n", " for o in (-1, 1):\n", " kd1 = scipy.spatial.cKDTree( g3 + o * g3[pk1] ) # plus or minus\n", " sd1 = kd0.sparse_distance_matrix( kd1, max_distance=gtol ).tocoo()\n", " #print(pkid, pk1, o, g3.shape, sd1.nnz)\n", " pks.append( sd1.row )\n", " pks.append( sd1.col )\n", " distances.append( sd1.data )\n", " return np.unique( np.concatenate( pks ) ), np.concatenate( distances )\n", "\n", "\n", "\n", "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 ):\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 )\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": ["dset_file = '/path/to/dataset.h5'\n", "ds = ImageD11.sinograms.dataset.load(dset_file)\n", "print(ds)"]}, {"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": {}, "outputs": [], "source": ["ds.phases = ds.get_phases_from_disk()\n", "ds.phases.unitcells"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["major_phase_strs = ['Fe']\n", "major_phase_unitcells = [ds.phases.unitcells[mps] for mps in major_phase_strs]\n", "print(major_phase_unitcells)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_4d = ds.get_cf_4d()\n", "ds.update_colfile_pars(cf_4d, major_phase_strs[0] )"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# remove the peaks that are not found on more than one frame\n", "cf_4d.filter( cf_4d.npk2d > 2 )"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# powder patterns\n", "pbins = 5000\n", "hsI, dsbinedges = np.histogram( cf_4d.ds, weights=cf_4d.sum_intensity, bins=np.linspace(0, cf_4d.ds.max(), pbins))\n", "hs1, dsbinedges = np.histogram( cf_4d.ds, bins=np.linspace(0, cf_4d.ds.max(), pbins))\n", "dsbincens = 0.5*(dsbinedges[1:]+dsbinedges[:-1])"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# filter out peaks from major phases\n", "major_phase_dstol = 0.004\n", "cf_4d = ImageD11.peakselect.remove_peaks_from_phases(cf_4d, major_phase_dstol, major_phase_unitcells)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# cring = columnfile of things not indexed by the main rings\n", "dsmax = 1.0\n", "cring = cf_4d.copyrows(cf_4d.ds < dsmax)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["f, ax = plt.subplots(constrained_layout=True, figsize=(10,7))\n", "ax.plot( dsbincens, hsI/hsI.max() , '-', label='Pre-filtration histogram')\n", "for inc, major_phase_unitcell in enumerate(major_phase_unitcells):\n", " ax.vlines(major_phase_unitcell.ringds, 1e-3*(2**inc), 1e-3*(2**inc)*2, color=plt.color_sequences['tab20'][inc+2], label=major_phase_unitcell.name)\n", "ax.plot( cring.ds, cring.sum_intensity/cring.sum_intensity.max(), \".\", ms=1, label='Surviving peaks' )\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='Fractional intensity', yscale='log', xlim=(0.1,1), ylim=(1e-5,1))\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## impurity phase method 1 : pick a peak\n", "\n", "Select a not-indexed ring in two theta that appears on more than one frame (npk2d > 1)\n", "\n", "This is plotted on the left as a sinogram.\n", "\n", "On the right you have all the non-indexed peaks.\n", "\n", "When the peak is selected, the code looks for the Friedel pair and tries to fit a grain position.\n", "\n", "We assume the y0 is 0 (otherwise you need to input this)."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# from the plot above, choose a ring_dstar that represents a ring of an unknown phase\n", "\n", "ring_dstar = 0.301\n", "ring_dstol = 0.003\n", "\n", "m = abs(cring.ds - ring_dstar) < ring_dstol\n", "\n", "cpk = cring.copyrows( m )\n", "cpk.sortby( 'sum_intensity' )\n", "cring.sortby( 'sum_intensity' )"]}, {"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": ["selector_gui = FriedelPairSelector(cring, cpk, y0)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["p1, p2, xy, peak_ycalc = selector_gui.get_selection()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["dtyrange = ds.ystep * 5\n", "f,ax = plt.subplots(constrained_layout=True, figsize=(7,4))\n", "ax.hist(cring.dty - peak_ycalc, bins = np.arange(-dtyrange,dtyrange,ds.ystep))\n", "ax.set(title='dty error histogram', xlabel='dty', ylabel='frequency')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# now we select the peaks from the sinogram based on that position in space\n", "dty_cut = 2.5 # from the last plot\n", "\n", "ymask = abs(peak_ycalc - cring.dty)