{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# 3DXRD 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/TDXRD/1_index_default.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/TDXRD/1_index_default.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "metadata": {"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", "# desination of H5 files\n", "# replace below with e.g.:\n", "# dset_path = '/data/visitor/expt1234/20240101/PROCESSED_DATA/sample/dataset/sample_dataset.h5'\n", "\n", "dset_path = ''\n", "\n", "phase_str = 'Fe'\n", "\n", "# path to parameters .json/.par\n", "parfile = ''\n", "\n", "# peak filtration options\n", "cf_strong_frac = 0.9837\n", "cf_strong_dsmax = 1.01\n", "cf_strong_dstol = 0.01\n", "\n", "# indexing options\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]\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, 1, 2, 3]\n", "\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.75]\n", "# the max number of UBIs we can find per pair of rings\n", "max_grains = 1000\n", "\n", "# makemap parameters\n", "makemap_hkl_tol_seq = [0.05, 0.025, 0.01]\n", "symmetry = \"cubic\"\n", "\n", "absolute_minpks = 120"]}, {"cell_type": "code", "execution_count": null, "metadata": {"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.sinograms import dataset\n", "from ImageD11.peakselect import select_ring_peaks_by_intensity\n", "from ImageD11.nbGui import nb_utils as utils\n", "\n", "%matplotlib widget"]}, {"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": {}, "outputs": [], "source": ["ds.parfile = parfile\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": {"tags": []}, "outputs": [], "source": ["ucell = ds.phases.unitcells[phase_str]\n", "print(ucell)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_3d = ds.get_cf_3d_from_disk()\n", "ds.update_colfile_pars(cf_3d, phase_name=phase_str) \n", "cf_3d_path = 'cf_3d.flt'\n", "cf_3d.writefile(cf_3d_path)"]}, {"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_3d.ds.max())\n", "fig, ax = plt.subplots(figsize=(10,5), layout='constrained')\n", "ax.plot(cf_3d.ds[::skip], cf_3d.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": ["# Filtration\n", "Here we are filtering our peaks (`cf_3d`) 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_3d, frac=cf_strong_frac, dsmax=cf_strong_dsmax, dstol=cf_strong_dstol, ucell=ucell, doplot=0.5)\n", "cf_strong_path = 'cf_strong.flt'\n", "cf_strong.writefile(cf_strong_path)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# we will also export some additional strong peaks across all rings\n", "# this will be useful for grain refinement later (using makemap)\n", "cf_strong_allrings = select_ring_peaks_by_intensity(cf_3d, frac=cf_strong_frac, dsmax=cf_3d.ds.max(), dstol=cf_strong_dstol, ucell=ucell, doplot=0.5)\n", "cf_strong_allrings_path = 'cf_strong_allrings.flt'\n", "cf_strong_allrings.writefile(cf_strong_allrings_path)"]}, {"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_3d.ds[::skip], cf_3d.sum_intensity[::skip],',', label='cf_3d')\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": {}, "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": {}, "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=ucell,\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", " g.translation = np.array([0., 0., 0.])\n", "print(f'Found {len(grains)} grains!')"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_all_ipfs(grains)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Grain refinement"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tmp_ubi_path = 'grains.ubi'\n", "tmp_map_path = 'grains.map'\n", "new_flt_path = 'cf_strong_allrings.flt.new' # flt file containing assignments from makemap\n", "unindexed_flt_path = 'cf_strong_allrings.flt.unindexed' # remaining unassigned peaks from makemap\n", "ImageD11.grain.write_grain_file(tmp_ubi_path, grains)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# now we write a classic parameter file for makemap.py\n", "oldparfile = phase_str + '.par'\n", "ds.phases.to_old_pars_file(oldparfile, phase_str)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# now run makemap in a loop\n", "omega_slop = ds.ostep/2\n", "for inc, makemap_tol in enumerate(makemap_hkl_tol_seq):\n", " print(f\"Running makemap {inc+1}/{len(makemap_hkl_tol_seq)}\")\n", " if inc == 0: # ubi into map\n", " makemap_output = !makemap.py -p {oldparfile} -u {tmp_ubi_path} -U {tmp_map_path} -f {cf_strong_allrings_path} -F {unindexed_flt_path} -s {symmetry} -t {makemap_hkl_tol_seq[inc]} --omega_slop={omega_slop} --no_sort\n", " else: # map into map\n", " makemap_output = !makemap.py -p {oldparfile} -u {tmp_map_path} -U {tmp_map_path} -f {cf_strong_allrings_path} -F {unindexed_flt_path} -s {symmetry} -t {makemap_hkl_tol_seq[inc]} --omega_slop={omega_slop} --no_sort"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_grain_histograms(new_flt_path, tmp_map_path, oldparfile, omega_slop, tol=makemap_hkl_tol_seq[-1])"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# re-import our refined grains from the makemap procedure\n", "grains2 = ImageD11.grain.read_grain_file(tmp_map_path)\n", "grains2 = [grain for grain in grains2 if \"no peaks\" not in grain.intensity_info]\n", "for g in grains2:\n", " g.ref_unitcell = ucell\n", "utils.get_rgbs_for_grains(grains2)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_grain_positions(grains2, colour='npks', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = plt.subplots(figsize=(10, 7), layout='constrained')\n", "ax.hist([float(grain.npks) for grain in grains2], bins=30)\n", "ax.set(xlabel='Number of peaks per grain', ylabel='Count', title='Histogram of peaks per grain')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# filter out grains with fewer than absolute_minpks peaks\n", "# most grains should have a high number of peaks\n", "# choose absolute_minpks such that the low-peak grains are removed\n", "grains_filtered = [grain for grain in grains2 if float(grain.npks) > absolute_minpks]"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_grain_positions(grains_filtered, colour='npks', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# we now have our trustworthy grains\n", "# we should run makemap again to regenerate our peak <-> grain assigments\n", "\n", "map_path = 'grains_filtered.map'\n", "final_unindexed_flt_path = 'cf_3d.flt.unindexed'\n", "final_new_flt_path = 'cf_3d.flt.new'\n", "\n", "# write filtered grains to disk\n", "ImageD11.grain.write_grain_file(map_path, grains_filtered)\n", "\n", "# run makemap on filtered grains with all 3D peaks\n", "makemap_output = !makemap.py -p {oldparfile} -u {map_path} -U {map_path} -f {cf_3d_path} -F {final_unindexed_flt_path} -s {symmetry} -t {makemap_hkl_tol_seq[-1]} --omega_slop={omega_slop} --no_sort\n", "\n", "# import makemap output columnfile with peak assignments\n", "cf_3d = ImageD11.columnfile.columnfile(final_new_flt_path)\n", "\n", "# write 3D columnfile to disk\n", "ImageD11.columnfile.colfile_to_hdf(cf_3d, ds.col3dfile, name='peaks')\n", "\n", "# re-import filtered grains with new peak statistics\n", "grains_filtered = ImageD11.grain.read_grain_file(map_path)\n", "for g in grains_filtered:\n", " g.ref_unitcell = ucell\n", " \n", "utils.get_rgbs_for_grains(grains_filtered)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_grain_histograms(final_new_flt_path, map_path, oldparfile, omega_slop, tol=makemap_hkl_tol_seq[-1])"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_all_ipfs(grains_filtered)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_grain_positions(grains_filtered, colour='npks', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_grain_positions(grains_filtered, colour='z', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["unit_cell_lengths = np.array([np.sort(g.unitcell.copy()) for g in grains_filtered])\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": "markdown", "metadata": {}, "source": ["# Export data"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ds.save_grains_to_disk(grains_filtered, phase_name=phase_str)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["ds.save()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Deleting temporary files"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["for path in [\n", " cf_3d_path,\n", " cf_strong_path,\n", " cf_strong_allrings_path,\n", " tmp_ubi_path,\n", " tmp_map_path,\n", " new_flt_path,\n", " unindexed_flt_path,\n", " map_path,\n", " final_unindexed_flt_path,\n", " final_new_flt_path,\n", "]:\n", " if os.path.exists(path):\n", " os.remove(path)"]}], "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}