{"cells": [{"cell_type": "markdown", "id": "bbc4bc96-cbc7-436a-a174-c99388869cbb", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Tomographic mapping 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_3_refinement.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/tomo_3_refinement.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "id": "831932fc-8a7f-4509-8042-47a8b542a68c", "metadata": {}, "source": ["This notebook will try to perform a point-by-point strain refinement from your tomographic-derived grain shapes. \n", "\n", "### NOTE: It is highly recommended to run this notebook on a Jupyter server with many cores and a lot of RAM. \n", "The compute_origins() function in particular runs locally and can be compute-intensive for large datasets. \n", "If this is a big scan (e.g 100 million+ 2D peaks), you should definitely refine on the cluster rather than locally."]}, {"cell_type": "code", "execution_count": null, "id": "94b89030-fdb2-47d2-bc26-3e5cfb0d6509", "metadata": {}, "outputs": [], "source": ["import os\n", "\n", "os.environ['OMP_NUM_THREADS'] = '1'\n", "os.environ['OPENBLAS_NUM_THREADS'] = '1'\n", "os.environ['MKL_NUM_THREADS'] = '1'"]}, {"cell_type": "code", "execution_count": null, "id": "80809290-53e9-48a0-bb4a-6a5ed3ef5b1f", "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 refine\n", "phase_str = 'Si'\n", "\n", "# manual override of y0 (ignores any value saved in dataset)\n", "y0_manual = None\n", "# or y0_manual = 0.0 (typical NSCOPE) or 13.5 (typical TDXRD)\n", "\n", "# default options for the single-valued map (shouldn't need to modify this)\n", "default_npks = 20\n", "default_nuniq = 20\n", "\n", "# refinement tolerances\n", "hkl_tol_origins = 0.05\n", "# ^ we forgot to square this before!\n", "hkl_tol_refine = 0.1\n", "hkl_tol_refine_merged = 0.05\n", "ds_tol = 0.004\n", "ifrac = 1e-4\n", "rings_to_refine = None # can be a list of rings\n", "drop_input_peaks = False\n", "\n", "# ^ for large datasets, delete cf_2d from memory after choosing peaks to refine with\n", "use_origin_found_only=True\n", "# use cluster for refinement or run locally?\n", "use_cluster = False"]}, {"cell_type": "code", "execution_count": null, "id": "3c4d7e65-9b41-47d2-860a-81a03054554f", "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, "id": "8f4b91e0-7a83-462b-85cb-27f65721ff93", "metadata": {}, "outputs": [], "source": ["import os\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.sinograms.sinogram import read_h5\n", "from ImageD11.sinograms.tensor_map import TensorMap\n", "from ImageD11.sinograms.pbp_refine import PBPRefine\n", "\n", "import ImageD11.nbGui.nb_utils as utils\n", "\n", "%matplotlib ipympl"]}, {"cell_type": "markdown", "id": "c04c8ebe-c7e2-4d50-a856-f26078b6c924", "metadata": {}, "source": ["# Load data\n", "## Dataset"]}, {"cell_type": "code", "execution_count": null, "id": "20ff052b-cca8-4310-8b29-4c82e0e513c8", "metadata": {"tags": []}, "outputs": [], "source": ["ds = ImageD11.sinograms.dataset.load(dset_path)\n", "print(ds)"]}, {"cell_type": "markdown", "id": "3d7063c4-cca6-474e-add9-7d66a72c63c0", "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, "id": "2d1b9af4-89a7-4dff-b258-cc2f77db5ee3", "metadata": {"tags": []}, "outputs": [], "source": ["ds.phases = ds.get_phases_from_disk()\n", "ds.phases.unitcells"]}, {"cell_type": "code", "execution_count": null, "id": "8722e04a-a23f-4af3-8530-a90874e27e64", "metadata": {"tags": []}, "outputs": [], "source": ["ucell = ds.phases.unitcells[phase_str]\n", "print(ucell)"]}, {"cell_type": "markdown", "id": "95826252-761c-48b3-8fdd-b54117202bd9", "metadata": {}, "source": ["## Peaks"]}, {"cell_type": "code", "execution_count": null, "id": "01a2b143-ed90-4817-92ac-bd78dea2c73c", "metadata": {"tags": []}, "outputs": [], "source": ["cf_2d = ds.get_cf_2d()\n", "ds.update_colfile_pars(cf_2d) # computes geometry, needed for filtration\n", "print(f\"Read {cf_2d.nrows} 2D peaks\")"]}, {"cell_type": "markdown", "id": "f9c632b6-1999-4868-ae21-2176cc5e41fc", "metadata": {}, "source": ["## Grains"]}, {"cell_type": "code", "execution_count": null, "id": "2fe3dc2d-b294-4159-a53b-960b0913a714", "metadata": {}, "outputs": [], "source": ["grainsinos = read_h5(ds.grainsfile, ds, phase_str)\n", "grains = [gs.grain for gs in grainsinos]"]}, {"cell_type": "markdown", "id": "66e23f14-0d4e-4aa6-9974-b7e6402304fd", "metadata": {}, "source": ["## TensorMap"]}, {"cell_type": "code", "execution_count": null, "id": "ec5ff57a-0a7f-44cd-b437-eb4cc4e2ea25", "metadata": {"tags": []}, "outputs": [], "source": ["tensor_map = TensorMap.from_h5(ds.grainsfile, h5group='TensorMap_' + phase_str)\n", "tensor_map.plot('phase_ids')"]}, {"cell_type": "code", "execution_count": null, "id": "08715524-4a8e-41bb-9d67-165523980f6b", "metadata": {"tags": []}, "outputs": [], "source": ["# make a PBPMap from our TensorMap\n", "# fills voxels that have grains with npks = 20 and nuniq = 20\n", "pmap = tensor_map.to_pbpmap(z_layer=0, default_npks=default_npks, default_nuniq=default_nuniq)"]}, {"cell_type": "code", "execution_count": null, "id": "33282e98-4e2c-4805-a2b2-468d6949e554", "metadata": {"tags": []}, "outputs": [], "source": ["pmap.choose_best(1)\n", "pmap.plot_best(1)"]}, {"cell_type": "code", "execution_count": null, "id": "26c54dcc-9e74-4623-862f-3922e49bdb9d", "metadata": {}, "outputs": [], "source": ["# Priority order (decreasing)\n", "# manual override in first cell\n", "# ds attribute\n", "\n", "# fails if no y0 provided at all\n", "\n", "if y0_manual is not None:\n", " print('Using manually supplied y0')\n", " y0 = y0_manual\n", "else:\n", " if hasattr(ds, 'y0') and ds.y0 is not None:\n", " print('Using ds.y0')\n", " y0 = ds.y0\n", " else:\n", " raise ValueError('You must manually supply a y0 value in the first cell to continue.')\n", "print('Using y0:', y0)\n", "# if we got here, save to ds.y0 - future refinements should use the same one\n", "ds.y0 = y0\n", "ds.save()"]}, {"cell_type": "markdown", "id": "c4e11f7d-0854-48a4-a999-eb898981176a", "metadata": {}, "source": ["# Refinement"]}, {"cell_type": "code", "execution_count": null, "id": "f8feef60-367b-478a-9ce4-8a94e3cedd60", "metadata": {"tags": []}, "outputs": [], "source": ["# set up a refinement manager object\n", "\n", "refine = PBPRefine(dset=ds,\n", " y0=y0, hkl_tol_origins=hkl_tol_origins, hkl_tol_refine=hkl_tol_refine, hkl_tol_refine_merged=hkl_tol_refine_merged,\n", " ds_tol=ds_tol, ifrac=ifrac, phase_name=phase_str, forref=rings_to_refine,\n", " beam_size=None) # use step size as beam size - important for regularisation\n", "# change the default paths of the refinement manager to append the phase name\n", "refine.own_filename = os.path.splitext(refine.own_filename)[0] + f'_{phase_str}.h5'\n", "refine.icolf_filename = os.path.splitext(refine.icolf_filename)[0] + f'_{phase_str}.h5'\n", "refine.pbpmap_filename = os.path.splitext(refine.pbpmap_filename)[0] + f'_{phase_str}.h5'\n", "refine.refinedmap_filename = os.path.splitext(refine.refinedmap_filename)[0] + f'_{phase_str}.h5'"]}, {"cell_type": "code", "execution_count": null, "id": "9b4fe817-5794-459b-9974-9d70624af3a8", "metadata": {"tags": []}, "outputs": [], "source": ["# tell it which point-by-point map we are refining\n", "refine.setmap(pmap)\n", "\n", "# or load from disk:\n", "# refine.loadmap()"]}, {"cell_type": "code", "execution_count": null, "id": "9372bfa0-4dfc-4727-a927-0d3b55c46875", "metadata": {"tags": []}, "outputs": [], "source": ["# set the mask from minimum peak values\n", "# anything greater than 0 should be accepted\n", "refine.mask = pmap.best_npks > 0"]}, {"cell_type": "code", "execution_count": null, "id": "839ddf32-a6eb-46c5-8725-d1b400acc44c", "metadata": {"tags": []}, "outputs": [], "source": ["# generate a single-valued map to refine on\n", "refine.setsingle(refine.pbpmap, minpeaks=1)"]}, {"cell_type": "code", "execution_count": null, "id": "006c33da-97be-434a-b68a-05477814f42f", "metadata": {"tags": []}, "outputs": [], "source": ["# choose 2D peaks to refine with\n", "refine.setpeaks(cf_2d, keep_colf=not drop_input_peaks)\n", "\n", "# or load from disk:\n", "# refine.loadpeaks()"]}, {"cell_type": "code", "execution_count": null, "id": "939ea631-c1d1-472b-8b8a-3ecc4797be5c", "metadata": {}, "outputs": [], "source": ["if drop_input_peaks:\n", " del cf_2d\n", " import gc; gc.collect()\n", " print(\"released input peaks\")"]}, {"cell_type": "markdown", "id": "e0ea9b12-67d5-4cf4-ab4c-1d6ca09528b8", "metadata": {}, "source": ["## Setting up peaks"]}, {"cell_type": "code", "execution_count": null, "id": "0166325e-2716-492c-a39d-a0ea3b8680b0", "metadata": {"tags": []}, "outputs": [], "source": ["# plot the peaks you selected\n", "refine.iplot()"]}, {"cell_type": "markdown", "id": "66569e9c-2413-4042-ae8e-fb7d03d23a66", "metadata": {}, "source": ["## Compute peak diffraction origins"]}, {"cell_type": "code", "execution_count": null, "id": "22f5c297-a8b9-4d89-9f86-366cb7144adb", "metadata": {"tags": []}, "outputs": [], "source": ["# compute diffraction origins - these will be added as a column to refine.icolf\n", "# will then save the new column to disk to avoid re-computation\n", "refine.get_origins()"]}, {"cell_type": "code", "execution_count": null, "id": "145fc201-95ef-4264-9538-36ef1bf89d1d", "metadata": {}, "outputs": [], "source": ["# after refine.get_origins()\n", "if use_origin_found_only:\n", " n0 = refine.icolf.nrows\n", " refine.icolf = refine.icolf.copyrows(refine.icolf.origin_found == 1)\n", " print(f\"origin_found filter: kept {refine.icolf.nrows} / {n0} peaks\")"]}, {"cell_type": "markdown", "id": "efce75c5-3bad-4379-8d01-da098ae11660", "metadata": {}, "source": ["## Run refinement"]}, {"cell_type": "code", "execution_count": null, "id": "7cde5eb5-ce0f-49b5-a6cb-4761f16cee32", "metadata": {"tags": []}, "outputs": [], "source": ["# run the refinement\n", "# if compute_origins took more than a couple of minutes to run, I suggest setting use_cluster=True below\n", "# otherwise if you asked for lots of cores and RAM on this Jupyter instance, you can run it locally (use_cluster=False)\n", "refine.run_refine(use_cluster=use_cluster, pythonpath=PYTHONPATH)"]}, {"cell_type": "markdown", "id": "3a6e9fca-eac8-43ac-af74-4638943bd8c5", "metadata": {"tags": []}, "source": ["# Export"]}, {"cell_type": "code", "execution_count": null, "id": "acbd5197-268c-48ab-b676-ac0c186b4533", "metadata": {"tags": []}, "outputs": [], "source": ["# make sure refinement is saved to disk\n", "\n", "if not use_cluster:\n", " refine.to_h5(save_peaks=False)\n", "\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": 5}