{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Tomographic indexing notebook with minor phase adjustments \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_minor_phase.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/tomo_1_index_minor_phase.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 notebook is optimised for a weaker minor phase in a larger major phase sample. \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", "# phase names\n", "major_phase_strs = ['Fe']\n", "minor_phase_str = 'Au'\n", "\n", "# peak filtration parameters\n", "min_frames_per_peak = 0\n", "# whether to filter out major phase peaks before trying to index\n", "remove_major_phase_peaks = True\n", "major_phase_cf_dstol = 0.005\n", "minor_phase_cf_frac = 0.9975\n", "minor_phase_cf_dsmax = 1.594\n", "minor_phase_cf_dstol = 0.005\n", "\n", "# indexing\n", "rings_for_gen = [0, 4, 5]\n", "\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, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13]\n", "\n", "# the sequence of hkl tolerances the indexer will iterate through\n", "hkl_tols_seq = [0.01, 0.02, 0.03, 0.04, 0.05]\n", "# the sequence of minpks fractions the indexer will iterate through\n", "fracs = [0.9]\n", "# the max number of UBIs we can find per pair of rings\n", "max_grains = 1000\n", "\n", "peak_assign_tol = 0.025"]}, {"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 numpy as np\n", "from matplotlib import pyplot as plt\n", "\n", "import ImageD11.grain\n", "import ImageD11.indexing\n", "import ImageD11.nbGui.nb_utils as utils\n", "from ImageD11.peakselect import select_ring_peaks_by_intensity, remove_peaks_from_phases\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": ["## 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": "markdown", "metadata": {}, "source": ["Now we need to decide which are our 'major' phases, which we will remove from our peaks before indexing."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["major_phase_unitcells = [ds.phases.unitcells[mps] for mps in major_phase_strs]\n", "print(*major_phase_unitcells)\n", "minor_phase_unitcell = ds.phases.unitcells[minor_phase_str]\n", "print(minor_phase_unitcell)"]}, {"cell_type": "markdown", "metadata": {}, "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) # computes geometry, needed for filtration\n", "for major_phase_unitcell in major_phase_unitcells:\n", " major_phase_unitcell.makerings(cf_4d.ds.max())\n", "minor_phase_unitcell.makerings(cf_4d.ds.max())"]}, {"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": ["# Filtration\n", "## (optional) remove major phase peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if remove_major_phase_peaks:\n", " cf_4d = remove_peaks_from_phases(cf_4d, major_phase_cf_dstol, major_phase_unitcells)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Filter by intensity\n", "Now 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=minor_phase_cf_frac, dsmax=minor_phase_cf_dsmax, dstol=minor_phase_cf_dstol, ucell=minor_phase_unitcell, doplot=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["minor_phase_unitcell.makerings(cf_strong.ds.max())\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',c='blue')\n", "ax.plot(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='minor phase',c='orange')\n", "ax.vlines(minor_phase_unitcell.ringds, 1e3, 3e3, color='red', label=minor_phase_unitcell.name)\n", "for inc, major_phase_unitcell in enumerate(major_phase_unitcells):\n", " ax.vlines(major_phase_unitcell.ringds, 3e3*(3**inc), 3e3*(2**inc)*3, color=plt.color_sequences['tab20'][inc], label=major_phase_unitcell.name)\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": ["# Indexing\n", "## Ring assignment"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["indexer = ImageD11.indexing.indexer_from_colfile_and_ucell(cf_strong, minor_phase_unitcell)\n", "indexer.ds_tol = minor_phase_cf_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": {}, "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(minor_phase_unitcell.ringds, -25, 25, color='red', label=minor_phase_unitcell.name)\n", "for inc, major_phase_unitcell in enumerate(major_phase_unitcells):\n", " ax.vlines(major_phase_unitcell.ringds, -25+(50*(inc+1)), 25+(50*(inc+1)), color=plt.color_sequences['tab20'][inc], label=major_phase_unitcell.name)\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel=r'$\\eta~(\\degree)$', xlim=(min(minor_phase_unitcell.ringds[0], cf_strong.ds.min()) - 0.02, cf_strong.ds.max() + 0.02), title='Ring assignments')\n", "ax.legend(loc='upper right')\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=minor_phase_unitcell,\n", " dstol=minor_phase_cf_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": {}, "outputs": [], "source": ["utils.plot_index_results(indexer, cf_strong, 'Indexing attempt')"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "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=minor_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}