{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# Jupyter notebook based on ImageD11 to process 3DXRD data\n", "# Written by Haixing Fang, Jon Wright and James Ball\n", "## Date: 10/09/2024"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/TDXRD/use_only_if_needed/1_3DXRD_refine_parameters.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/TDXRD/use_only_if_needed/1_3DXRD_refine_parameters.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["This notebook will help you to refine the experimental parameters (such as sample to detector distance etc).\n", "\n", "We do this by indexing a Z slice of a sample, refining the positions of the grains we find, then refining the parameters using the grain diffraction data"]}, {"cell_type": "code", "execution_count": null, "metadata": {"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"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "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 functions we need\n", "\n", "import os, glob, pprint\n", "import numpy as np\n", "import h5py\n", "from tqdm.notebook import tqdm\n", "\n", "import matplotlib\n", "%matplotlib widget\n", "from matplotlib import pyplot as plt\n", "\n", "# import utils\n", "from ImageD11.nbGui import nb_utils as utils\n", "\n", "import ImageD11.grain\n", "import ImageD11.indexing\n", "import ImageD11.columnfile\n", "from ImageD11.sinograms import properties, dataset\n", "\n", "from ImageD11.blobcorrector import eiger_spatial\n", "from ImageD11.peakselect import select_ring_peaks_by_intensity"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# 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 = ''"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# load the dataset from file\n", "\n", "ds = ImageD11.sinograms.dataset.load(dset_path)\n", "sample = ds.sample\n", "dataset = ds.dset\n", "\n", "print(ds)\n", "print(ds.shape)"]}, {"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": ["# now let's select a phase to index from our parameters json\n", "phase_str = 'Fe'\n", "\n", "ucell = ds.phases.unitcells[phase_str]\n", "\n", "print(ucell.lattice_parameters, ucell.spacegroup)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# load 3d columnfile from disk\n", "\n", "cf_3d = ds.get_cf_3d_from_disk()\n", "ds.update_colfile_pars(cf_3d, phase_name=phase_str) \n", "\n", "if \"index\" not in cf_3d.titles:\n", " cf_3d.addcolumn(np.arange(cf_3d.nrows), \"index\")"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# plot the 3D peaks (fewer of them) as a cake (two-theta vs eta)\n", "# if the parameters in the par file are good, these should look like straight lines\n", "\n", "ucell.makerings(cf_3d.ds.max())\n", "\n", "fig, ax = plt.subplots(figsize=(16,9), layout='constrained')\n", "\n", "ax.scatter(cf_3d.ds, cf_3d.eta, s=1)\n", "ax.plot( ucell.ringds, [0,]*len(ucell.ringds), '|', ms=90, c=\"red\")\n", "\n", "ax.set_xlabel(\"D-star\")\n", "ax.set_ylabel(\"eta\")\n", "\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# here we are filtering our peaks (cf_3d) to select only the strongest ones for indexing purposes only!\n", "# dsmax is being set to limit rings given to the indexer - 6-8 rings is normally good\n", "\n", "# USER: modify the \"frac\" parameter below and re-run the cell until the orange dot sits nicely on the \"elbow\" of the blue line\n", "# this indicates the fractional intensity cutoff we will select\n", "# if the blue line does not look elbow-shaped in the logscale plot, try changing the \"doplot\" parameter (the y scale of the logscale plot) until it does\n", "\n", "cf_strong = select_ring_peaks_by_intensity(cf_3d, frac=0.9850, dsmax=1.01, doplot=0.8, dstol=0.01)\n", "print(f\"Got {cf_strong.nrows} strong peaks for indexing\")\n", "cf_strong.writefile(f'{sample}_{dataset}_3d_peaks_strong.flt')"]}, {"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", "\n", "cf_strong_allrings = select_ring_peaks_by_intensity(cf_3d, frac=0.9855, dsmax=cf_3d.ds.max(), doplot=0.05, dstol=0.01)\n", "print(f\"Got {cf_strong_allrings.nrows} strong peaks for makemap\")\n", "cf_strong_allrings_path = f'{sample}_{dataset}_3d_peaks_strong_all_rings.flt'\n", "cf_strong_allrings.writefile(cf_strong_allrings_path)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# now we can take a look at the intensities of the remaining peaks\n", "\n", "fig, ax = plt.subplots(figsize=(16, 9), constrained_layout=True)\n", "\n", "\n", "\n", "ax.plot(cf_3d.ds, cf_3d.sum_intensity,',', label='cf_3d')\n", "ax.plot(cf_strong.ds, cf_strong.sum_intensity,',', label='cf_strong')\n", "ax.plot( ucell.ringds, [1e4,]*len(ucell.ringds), '|', ms=90, c=\"red\")\n", "ax.semilogy()\n", "\n", "ax.set_xlabel(\"Dstar\")\n", "ax.set_ylabel(\"Intensity\")\n", "ax.legend()\n", "\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# specify our ImageD11 indexer with these peaks\n", "\n", "indexer = ImageD11.indexing.indexer_from_colfile(cf_strong)\n", "\n", "print(f\"Indexing {cf_strong.nrows} peaks\")\n", "\n", "# USER: set a tolerance in d-space (for assigning peaks to powder rings)\n", "\n", "indexer.ds_tol = 0.05\n", "\n", "# change the log level so we can see what the ring assigments look like\n", "\n", "ImageD11.indexing.loglevel = 1\n", "\n", "# assign peaks to powder rings\n", "\n", "indexer.assigntorings()\n", "\n", "# change log level back again\n", "\n", "ImageD11.indexing.loglevel = 3"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# let's plot the assigned peaks\n", "\n", "fig, ax = plt.subplots(figsize=(16, 9), layout='constrained')\n", "\n", "# indexer.ra is the ring assignments\n", "\n", "ax.scatter(cf_strong.ds, cf_strong.eta, c=indexer.ra, cmap='tab20', s=1)\n", "ax.plot( ucell.ringds, [0,]*len(ucell.ringds), '|', ms=90, c=\"red\")\n", "ax.set_xlabel(\"d-star\")\n", "ax.set_ylabel(\"eta\")\n", "ax.set_xlim(cf_strong.ds.min()-0.05, cf_strong.ds.max()+0.05)\n", "\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# now we are indexing!\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 tolerance in g-vector angle\n", "cosine_tol = np.cos(np.radians(90 - 0.25))\n", "# the max number of UBIs we can find per pair of rings\n", "max_grains = 1000\n", "\n", "grains, indexer = utils.do_index(cf=cf_strong,\n", " dstol=indexer.ds_tol,\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", ")"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# create grain objects\n", "grains = [ImageD11.grain.grain(ubi, translation=np.array([0., 0., 0.])) for ubi in indexer.ubis]\n", "\n", "# set grain GIDs (useful if we ever delete a grain)\n", "for i, g in enumerate(grains):\n", " g.gid = i"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tmp_ubi_path = f'{sample}_{dataset}_grains.ubi'\n", "tmp_map_path = f'{sample}_{dataset}_grains.map'\n", "\n", "new_flt_path = f'{sample}_{dataset}_3d_peaks_strong_all_rings.flt.new' # flt file containing assignments from makemap\n", "unindexed_flt_path = f'{sample}_{dataset}_3d_peaks_strong_all_rings.flt.unindexed' # remaining unassigned peaks from makemap"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ImageD11.grain.write_grain_file(tmp_ubi_path, grains)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["omegas_sorted = np.sort(ds.omega)[0]\n", "omega_step = np.round(np.diff(omegas_sorted).mean(), 3)\n", "omega_slop = omega_step/2\n", "\n", "makemap_hkl_tol_seq = [0.05, 0.025, 0.01]"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# write a classic parameter file for makemap.py\n", "\n", "from ImageD11 import parameters\n", "\n", "oldpars = parameters.parameters()\n", "oldpars.parameters.update(ds.phases.get_xfab_pars_dict(phase_str))\n", "\n", "oldparfile = phase_str + '_old.par'\n", "\n", "oldpars.saveparameters(oldparfile)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["symmetry = \"cubic\"\n", "\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": {"tags": []}, "outputs": [], "source": ["grains_refined_positions = ImageD11.grain.read_grain_file(tmp_map_path)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = plt.subplots()\n", "ax.hist([np.mean(g.unitcell[0:3]) for g in grains_refined_positions], bins=50)\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["np.array([np.mean(g.unitcell[0:3]) for g in grains_refined_positions]).mean()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["refine_output = !refine_em.py {new_flt_path} {tmp_map_path} {oldparfile} --omega_slop={omega_slop} -x wedge"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# work out how many parameter files are missing\n", "# check the missing .par files, and copy to cover the missing files\n", "import shutil\n", "print(f'Total number of files expected = {len(grains_refined_positions)}')\n", "\n", "for i in range(len(grains_refined_positions)):\n", " filename = f\"{i}.par\"\n", " if not (os.path.isfile(filename)):\n", " print(f'Missing {filename}')\n", " if i == 0:\n", " i = 2\n", " print(f'Copying {i-1}.par to {filename}')\n", " shutil.copy(str(i-1) + '.par', filename)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["refined_parfile = phase_str + '_new.par'"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["avg_par_output = !avg_par.py {refined_parfile} {len(grains_refined_positions)}"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# clean up temporary files\n", "for i in range(len(grains_refined_positions)):\n", " pfile = str(i) + '.par'\n", " ffile = str(i) + '.flt'\n", " ufile = str(i) + '.ubi'\n", " for filename in [pfile, ffile, ufile]:\n", " if os.path.isfile(filename):\n", " os.remove(filename)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# refined parameter file has now been created!"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["!cat {refined_parfile}"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# load new pars into memory\n", "newpars = parameters.read_par_file(refined_parfile)\n", "\n", "# strip out anything unit-cell related\n", "parnames = list(newpars.parameters.keys())\n", "for parname in parnames:\n", " if parname.startswith('cell') or parname.startswith('phase'):\n", " newpars.parameters.pop(parname)\n", "\n", "# update ds.phases object\n", "ds.phases.geometry_pars_obj = newpars\n", "\n", "# update geometry file on disk\n", "ds.phases.update_geometryfile()\n", "\n", "# check geometry file is updated\n", "!cat {ds.phases.geometry_pars_obj.get('filename')}"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": []}], "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}