{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Tomographic indexing notebook \n", "__Written by Haixing Fang, Jon Wright and James Ball__ \n", "__Date: 21/02/2025__"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/tomo_1_index.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/tomo_1_index.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {}, "source": ["This notebook will try to find good grain orientations from a 4D merge of your peak data. \n", "This means your peaks have been merged across omega and dty. \n", "This notebook (and the tomo route in general) works best for low levels of deformation. \n", "If it doesn't seem to work well, try the point-by-point route instead!"]}, {"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", "min_frames_per_peak = 0\n", "cf_strong_frac = 0.9939\n", "cf_strong_dsmax = 1.594\n", "cf_strong_dstol = 0.005\n", "\n", "# indexing parameters\n", "# we have to choose which rings we want to generate orientations on\n", "# generally we want two or three low-multiplicity rings that are isolated from other phases\n", "# take a look at the ring assignment output from a few cells above, and choose two or three\n", "rings_for_gen = [0, 1, 3]\n", "# now we want to decide which rings to score our found orientations against\n", "# generally we can just exclude dodgy rings (close to other phases, only a few peaks in etc)\n", "rings_for_scoring = [0, 1, 2, 3, 4]\n", "# the sequence of hkl tolerances the indexer will iterate through\n", "hkl_tols_seq = [0.01, 0.02, 0.03, 0.04]\n", "# the sequence of minpks fractions the indexer will iterate through\n", "fracs = [0.9, 0.7]\n", "# the max number of UBIs we can find per pair of rings\n", "max_grains = 1000\n", "\n", "peak_assign_tol = 0.05\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": ""}, "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": {"tags": []}, "outputs": [], "source": ["import os\n", "import numpy as np\n", "from matplotlib import pyplot as plt\n", "\n", "import ImageD11.grain\n", "import ImageD11.indexing\n", "import ImageD11.columnfile\n", "from ImageD11.peakselect import select_ring_peaks_by_intensity\n", "import ImageD11.nbGui.nb_utils as utils\n", "\n", "%matplotlib ipympl"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Load data\n", "## Dataset"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "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": ""}, "tags": []}, "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": {"tags": []}, "outputs": [], "source": ["ds.phases = ds.get_phases_from_disk()\n", "ds.phases.unitcells"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ucell = ds.phases.unitcells[phase_str]\n", "print(ucell)"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["## Peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_4d = ds.get_cf_4d()\n", "ds.update_colfile_pars(cf_4d)\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)"]}, {"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": "markdown", "metadata": {}, "source": ["# Visualise data\n", "### $d^{*}$ vs $\\eta$"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["skip = 1 # we can skip peaks to speed up plotting if needed\n", "ucell.makerings(cf_4d.ds.max())\n", "fig, ax = plt.subplots(figsize=(10,5), layout='constrained')\n", "ax.plot(cf_4d.ds[::skip], cf_4d.eta[::skip], ',')\n", "ax.vlines(ucell.ringds, -50, 50, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel=r'$\\eta~(\\degree)$', title='2D azimuthal transform')\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### Sinogram"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained')\n", "im, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)\n", "pcm = ax.pcolormesh(om_edges, dty_edges, im.T)\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": "markdown", "metadata": {}, "source": ["# Filtration\n", "Here we are filtering our peaks (`cf_4d`) to select only the strongest ones for indexing purposes only! \n", "We first filter the peaks in $d^{*}$ to keep only those close to the predicted peaks from the unit cell. \n", "We then sort our peaks by intensity, and take a certain intensity-weighted fraction of them. \n", "`dstol`: The tolerance in $d^{*}$ between a peak and a predicted reflection. \n", "`dsmax`: The maximum allowed peak $d^{*}$ value. Used to limit the number of rings given to the indexer - 6-8 rings max are normally sufficient. \n", "`frac`: The intensity fraction: `frac=0.9` keeps 90% of the peak intensity. We recommend that you choose a value close to the 'elbow' of the plot."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_strong = select_ring_peaks_by_intensity(cf_4d, frac=cf_strong_frac, dsmax=cf_strong_dsmax, dstol=cf_strong_dstol, ucell=ucell, doplot=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "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(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='cf_strong')\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": {"tags": []}, "source": ["# Indexing\n", "## Ring assignment"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["indexer = ImageD11.indexing.indexer_from_colfile_and_ucell(cf_strong, ucell)\n", "indexer.ds_tol = cf_strong_dstol\n", "ImageD11.indexing.loglevel = 1\n", "indexer.assigntorings()\n", "ImageD11.indexing.loglevel = 3\n", "print(f\"Indexing {cf_strong.nrows} peaks\")"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["skip = 1 # we can skip peaks to speed up plotting if needed\n", "fig, ax = plt.subplots(layout='constrained', figsize=(10,5))\n", "ax.scatter(indexer.colfile.ds[::skip], indexer.colfile.eta[::skip], c=indexer.ra[::skip]%20, cmap='tab20', s=1)\n", "ax.vlines(ucell.ringds, -50, 50, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel=r'$\\eta~(\\degree)$', xlim=(min(ucell.ringds[0], cf_strong.ds.min()) - 0.02, cf_strong.ds.max() + 0.02), title='Ring assignments')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cosine_tol = np.cos(np.radians(90 - ds.ostep))\n", "grains, indexer = utils.do_index(cf=cf_strong,\n", " unitcell=ds.phases.unitcells[phase_str],\n", " dstol=cf_strong_dstol,\n", " forgen=rings_for_gen,\n", " foridx=rings_for_scoring,\n", " hkl_tols=hkl_tols_seq,\n", " fracs=fracs,\n", " cosine_tol=cosine_tol,\n", " max_grains=max_grains,\n", ")\n", "for ginc, g in enumerate(grains):\n", " g.gid = ginc\n", "print(f'Found {len(grains)} grains!')"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Results"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["unit_cell_lengths = np.array([np.sort(g.unitcell.copy()) for g in grains])\n", "median_unit_cell = np.median(unit_cell_lengths, axis=0)\n", "print(\"Median unit cell:\", median_unit_cell)\n", "fig, ax = plt.subplots(constrained_layout=True)\n", "ax.plot(unit_cell_lengths[:,:3])\n", "ax.hlines(median_unit_cell[:3], 0, len(unit_cell_lengths))\n", "ax.set(xlabel='Grain ID', ylabel='Unit cell length')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.assign_peaks_to_grains(grains, cf_strong, tol=peak_assign_tol)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_index_results(indexer, cf_strong, 'Indexing attempt')"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_grain_sinograms(grains, cf_strong, min(len(grains), 25))"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Export data"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ds.save_grains_to_disk(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"}, "toc-autonumbering": false, "toc-showmarkdowntxt": false, "widgets": {"application/vnd.jupyter.widget-state+json": {"state": {}, "version_major": 2, "version_minor": 0}}}, "nbformat": 4, "nbformat_minor": 4}