{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Point-by-point refined map visualisation 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/4_visualise.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/4_visualise.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {}, "source": ["This notebook will convert the (potentially) multi-valued results of a point-by-point strain refinement process to a single-valued 'TensorMap' with many useful export formats, like H5, Paraview XDMF, and MTEX CTF."]}, {"cell_type": "code", "execution_count": null, "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "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, "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", "# the minimum number of peaks you want a pixel to have to be counted\n", "min_unique = 400"]}, {"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 numpy as np\n", "from matplotlib import pyplot as plt\n", "import matplotlib.cm as cm\n", "from matplotlib.colors import Normalize\n", "\n", "from ImageD11.grain import grain\n", "from ImageD11 import unitcell\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.sinograms.point_by_point import PBPMap\n", "from ImageD11.sinograms.pbp_refine import PBPRefine\n", "from ImageD11.sinograms.tensor_map import TensorMap\n", "from ImageD11.nbGui import 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": ["## 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": ["ref_ucell = ds.phases.unitcells[phase_str]\n", "print(ref_ucell)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Point-by-point refined map"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["refmanpath = os.path.splitext(ds.refmanfile)[0] + f'_{phase_str}.h5'\n", "refine = PBPRefine.from_h5(refmanpath, load_peaks=False, load_input=False)\n", "refine.refinedmap.plot_nuniq_hist()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# choose the minimum number of peaks you want a pixel to have to be counted\n", "refine.refinedmap.choose_best(min_unique)\n", "refine.refinedmap.plot_best(min_unique)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Make TensorMap"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# now make a TensorMap from our refined map so we can plot and export\n", "# let's make a phase id map from our pbpmap\n", "phase_ids = TensorMap.recon_order_to_map_order(np.where(refine.refinedmap.best_nuniq > min_unique, 0, -1))\n", "eps_sample = TensorMap.recon_order_to_map_order(refine.refinedmap.best_eps)\n", "tmap = TensorMap.from_pbpmap(refine.refinedmap, steps=(1, ds.ystep, ds.ystep), phases={0: ref_ucell})\n", "tmap['phase_ids'] = phase_ids\n", "tmap['eps_sample'] = eps_sample\n", "tmap.get_ipf_maps()\n", "tmap.plot('nuniq')\n", "tmap.plot('ipf_x')\n", "tmap.plot('ipf_y')\n", "tmap.plot('ipf_z')\n", "eul = tmap.euler # trigger calculation of all the maps"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# plot some (hopefully cleaner) strains\n", "\n", "fig, axs = plt.subplots(3,3, sharex=True, sharey=True, layout='constrained', figsize=(10,10))\n", "cmap = plt.get_cmap('RdBu_r')\n", "normalizer = Normalize(-1e-3, 1e-3)\n", "im = cm.ScalarMappable(norm=normalizer, cmap=cmap)\n", "for i in range(3):\n", " for j in range(3):\n", " axs[i,j].imshow(tmap.eps_sample[0, ..., i, j], origin=\"lower\", cmap=cmap, norm=normalizer, interpolation='nearest')\n", " axs[i,j].set_title(f'eps_{i+1}{j+1}')\n", "fig.supxlabel('Lab X axis --->')\n", "fig.supylabel('Lab Y axis --->')\n", "fig.colorbar(im, ax=axs.ravel().tolist())\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# mean unitcell?\n", "print(np.nanmean(tmap.unitcell[0, ...]))"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# if we have a previous tomographic TensorMap, we can try to get the labels map too:\n", "try:\n", " tmap_tomo = TensorMap.from_h5(ds.grainsfile, h5group='TensorMap_' + phase_str)\n", " tmap.add_map('labels', tmap_tomo.labels)\n", "except (FileNotFoundError, OSError, KeyError):\n", " # couldn't find one, continue anyway\n", " pass"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Export\n", "## TensorMap"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# save the refined TensorMap to disk\n", "\n", "refined_tmap_path = os.path.join(ds.analysispath, f'{ds.sample}_{ds.dset}_refined_tmap_{phase_str}.h5')\n", "tmap.to_h5(refined_tmap_path)\n", "tmap.to_paraview(refined_tmap_path)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# MTEX"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# you can also do an MTEX export if you like:\n", "\n", "refined_ctf_path = os.path.join(ds.analysispath, f'{ds.sample}_{ds.dset}_refined_tmap_{phase_str}.ctf')\n", "tmap.to_ctf_mtex(refined_ctf_path, z_index=0)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["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}