{"cells": [{"cell_type": "code", "execution_count": null, "id": "9a64a463-d18c-4314-9fe0-cfc2899f139b", "metadata": {}, "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\n", "\n", "tmap_path = '/path/to/tmap.h5'"]}, {"cell_type": "code", "execution_count": null, "id": "e1fdc441-dfc4-4268-93fa-ece915236900", "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, "id": "7defe95a-70e6-40d1-bf7b-3186638847b6", "metadata": {}, "outputs": [], "source": ["import numba\n", "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.sinograms.tensor_map import TensorMap, fast_invert, ubi_and_b_to_u, ubi_and_unitcell_to_eps_crystal\n", "\n", "%matplotlib inline"]}, {"cell_type": "code", "execution_count": null, "id": "28dd81fe-7385-4599-bd6a-85e380ae4b0d", "metadata": {}, "outputs": [], "source": ["tmap = TensorMap.from_h5(tmap_path)"]}, {"cell_type": "code", "execution_count": null, "id": "51b7fa41-5994-49b1-8f8c-08445eb0bfe2", "metadata": {}, "outputs": [], "source": ["tmap.plot('ipf_x')\n", "tmap.plot('ipf_y')\n", "tmap.plot('ipf_z')"]}, {"cell_type": "markdown", "id": "75ab60c0-a38a-4feb-8f69-f5f04b878649", "metadata": {}, "source": ["# B matrix recomputation"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/incorporate_strains.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/incorporate_strains.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "id": "9217125f-d022-49e3-b423-0322a9cf7631", "metadata": {}, "source": ["When we perform a point-by-point refinement of each voxel, we refine in two separate steps:\n", "- The $\\matrix{UB}^{-1}$ matrix of the lattice\n", "- The strain tensor in the lab frame $\\varepsilon_{\\text{lab}}$\n", "\n", "Those familiar with some crystallography will know that the $\\matrix{B}$ matrix is supposed to encode the full strain tensor:\n", "\n", "$\\varepsilon_{\\text{crystal}} = \\frac{1}{2}\\left(\\matrix{B_0}\\matrix{B}^{-1}+\\left(\\matrix{B_0}\\matrix{B}^{-1}\\right)^{\\dagger}\\right) - \\matrix{I}$\n", "\n", "where $\\matrix{B_0}$ is the reference \"strain-free\" $\\matrix{B}$ matrix for the lattice.\n", "\n", "However, since we performed a separate refinement of the strain tensor, we want to update the $\\matrix{B}$ matrix to account for the new strains.\n", "\n", "This brings the strain from the $\\matrix{UB}^{-1}$ field (via $\\matrix{B}$) in line with the strain from the refinement."]}, {"cell_type": "markdown", "id": "b9ddccb9-7421-4b26-8ca6-6a69bd0a7fac", "metadata": {}, "source": ["# Current strain discrepancy"]}, {"cell_type": "code", "execution_count": null, "id": "96fc7657-9877-4b2f-8d38-87dae4a8e9f5", "metadata": {}, "outputs": [], "source": ["eps_crystal_from_B_before = ubi_and_unitcell_to_eps_crystal(tmap.UBI, tmap.dzero_unitcell)"]}, {"cell_type": "code", "execution_count": null, "id": "111461ae-bd4a-4323-b6c9-c47a5b0afd88", "metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots()\n", "ax.hist(tmap.eps_crystal.ravel(), bins=500, label='From eps_crystal', alpha=0.5)\n", "ax.hist(eps_crystal_from_B_before.ravel(), bins=500, label='From UBI', alpha=0.5)\n", "ax.set(xlabel='strain', ylabel='frequency', title='Histogram of strains')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "c6f505e3-dcb1-4d49-97b0-11f3c6be9ed6", "metadata": {}, "outputs": [], "source": ["strain_diff_before = (tmap.eps_crystal - eps_crystal_from_B_before).ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(strain_diff_before, bins=500)\n", "ax.set(xlabel='strain diff', ylabel='frequency', title='Histogram of strain differences before')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "8a9a5f9f-2280-43ae-a177-89e7a6b85850", "metadata": {}, "outputs": [], "source": ["np.nanmin(strain_diff_before), np.nanmedian(strain_diff_before), np.nanmax(strain_diff_before)"]}, {"cell_type": "markdown", "id": "6c5b05f9-8654-47eb-909a-2a1ac768ce69", "metadata": {}, "source": ["# Current unitcell distribution"]}, {"cell_type": "code", "execution_count": null, "id": "ae93616b-f5ad-4324-aab6-8e54e5000909", "metadata": {}, "outputs": [], "source": ["avals_before = tmap.unitcell[0, ..., 0].ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(avals_before, bins=500)\n", "ax.set(xlabel='a axis', ylabel='frequency', title='Histogram of a axis before recomputing B')\n", "plt.show()\n", "\n", "bvals_before = tmap.unitcell[0, ..., 1].ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(bvals_before, bins=500)\n", "ax.set(xlabel='b axis', ylabel='frequency', title='Histogram of b axis before recomputing B')\n", "plt.show()\n", "\n", "cvals_before = tmap.unitcell[0, ..., 2].ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(cvals_before, bins=500)\n", "ax.set(xlabel='c axis', ylabel='frequency', title='Histogram of c axis before recomputing B')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "f94df552-c392-4383-886a-831978cb6a9e", "metadata": {}, "outputs": [], "source": ["print(np.nanmean(tmap.unitcell[0, ...]))"]}, {"cell_type": "markdown", "id": "88cd9332-2963-485c-94f4-134aeda43545", "metadata": {}, "source": ["# Compute new B matrices from the strain tensors"]}, {"cell_type": "code", "execution_count": null, "id": "99d2a12a-c3df-40b6-b7d1-b3ed3db0367a", "metadata": {}, "outputs": [], "source": ["B0 = tmap.phases[0].B # strain free B matrix from reference phase\n", "B0"]}, {"cell_type": "markdown", "id": "990a909c-a820-4daf-b762-70acf9208d8e", "metadata": {}, "source": ["There is a neat trick for this:\n", "\n", "$\\varepsilon_{\\text{crystal}} = \\frac{1}{2}\\left(\\matrix{B_0}\\matrix{B}^{-1}+\\left(\\matrix{B_0}\\matrix{B}^{-1}\\right)^{\\dagger}\\right) - \\matrix{I}$\n", "\n", "$\\varepsilon_{\\text{crystal}} + \\matrix{I} = \\frac{1}{2}\\left(\\matrix{B_0}\\matrix{B}^{-1}+\\left(\\matrix{B_0}\\matrix{B}^{-1}\\right)^{\\dagger}\\right) $\n", "\n", "$2\\left(\\varepsilon_{\\text{crystal}} + \\matrix{I}\\right) = \\matrix{B_0}\\matrix{B}^{-1}+\\left(\\matrix{B_0}\\matrix{B}^{-1}\\right)^{\\dagger} $\n", "\n", "$\\matrix{S} = \\varepsilon_{\\text{crystal}} + \\matrix{I}$\n", "\n", "$\\matrix{M} = \\matrix{B_0}\\matrix{B}^{-1}$\n", "\n", "$2\\matrix{S} = \\matrix{M}+\\matrix{M}^{\\dagger}$\n", "\n", "$\\matrix{B_0}$ is upper-triangular, and so is $\\matrix{B}^{-1}$\n", "\n", "Therefore $\\matrix{M} = \\matrix{B_0}\\matrix{B}^{-1}$ is also upper-triangular:\n", "\n", "$M = \\begin{pmatrix} \n", "a & b & c \\\\\n", "0 & d & e \\\\\n", "0 & 0 & f \n", "\\end{pmatrix}$\n", "\n", "therefore:\n", "\n", "$\\matrix{M}+\\matrix{M}^{\\dagger} = \\begin{pmatrix} \n", "2a & b & c \\\\\n", "b & 2d & e \\\\\n", "c & e & 2f \n", "\\end{pmatrix}$\n", "\n", "$\\matrix{S} = \\varepsilon_{\\text{crystal}} + \\matrix{I}$ which is symmetric:\n", "\n", "$\\matrix{S} = \\begin{pmatrix} \n", "S_{11} & S_{12} & S_{13} \\\\\n", "S_{12} & S_{22} & S_{23} \\\\\n", "S_{13} & S_{23} & S_{33} \n", "\\end{pmatrix}$\n", "\n", "therefore:\n", "\n", "$\\matrix{S} = \\begin{pmatrix} \n", "S_{11} & S_{12} & S_{13} \\\\\n", "S_{12} & S_{22} & S_{23} \\\\\n", "S_{13} & S_{23} & S_{33} \n", "\\end{pmatrix} = \\frac{1}{2}\\begin{pmatrix} \n", "2a & b & c \\\\\n", "b & 2d & e \\\\\n", "c & e & 2f \n", "\\end{pmatrix}= \\begin{pmatrix} \n", "a & \\frac{b}{2} & \\frac{c}{2} \\\\\n", "\\frac{b}{2} & d & \\frac{e}{2} \\\\\n", "\\frac{c}{2} & \\frac{e}{2} & f \n", "\\end{pmatrix}$\n", "\n", "therefore:\n", "\n", "$\\matrix{M} = \\begin{pmatrix} \n", "S_{11} & 0 & 0 \\\\\n", "0 & S_{22} & 0 \\\\\n", "0 & 0 & S_{33} \n", "\\end{pmatrix} + 2\\begin{pmatrix} \n", "0 & 2S_{12} & 2S_{13} \\\\\n", "0 & 0 & 2S_{23} \\\\\n", "0 & 0 & 0 \n", "\\end{pmatrix}$\n", "\n", "which in code is:\n", "\n", "```\n", "M = np.diag(np.diag(S)) + 2 * np.triu(S, k=1)\n", "```"]}, {"cell_type": "code", "execution_count": null, "id": "c7a49fde-3d74-4b52-9eb2-5f077ed4af3c", "metadata": {}, "outputs": [], "source": ["@numba.guvectorize([(numba.float64[:, :], numba.float64[:,:], numba.float64[:,:])], '(n,n),(n,n)->(n,n)', nopython=True, cache = True, target='parallel')\n", "def epsilon_to_b(eps_crystal, B0, res):\n", " \"\"\"\n", " xfab.laue.epsilon_to_b - made to go fast\n", " \"\"\"\n", "\n", " if np.isnan(eps_crystal[0,0]):\n", " res[...] = np.nan\n", " else:\n", " S = eps_crystal + np.eye(3)\n", " M = np.diag(np.diag(S)) + 2 * np.triu(S, k=1)\n", " M_inv = np.linalg.inv(M)\n", " B = np.dot(M_inv, B0)\n", " res[...] = B"]}, {"cell_type": "code", "execution_count": null, "id": "7d8cf911-e7fd-491d-b12a-9eceaa49c50f", "metadata": {}, "outputs": [], "source": ["B_new = epsilon_to_b(tmap.eps_crystal, B0)"]}, {"cell_type": "code", "execution_count": null, "id": "3d5cb60b-15ef-4ee4-8378-c1fb4d705fb3", "metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained')\n", "im = ax.imshow(B_new[0, ..., 0, 0] - tmap.B[0, ..., 0, 0], origin='lower')\n", "ax.set_xlabel('Lab X axis --->')\n", "ax.set_ylabel('Lab Y axis --->')\n", "ax.set_title('B[0,0] new - B[0,0] old')\n", "plt.colorbar(im)\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "06a86b0d-369e-4b69-9c20-dd137285a0e3", "metadata": {}, "outputs": [], "source": ["# now we have a new B matrix, we can recompute UBI, then update the tensormap"]}, {"cell_type": "code", "execution_count": null, "id": "f468b3a5-d509-4497-a141-ceded6ca694c", "metadata": {}, "outputs": [], "source": ["UB_new = tmap.U @ B_new"]}, {"cell_type": "code", "execution_count": null, "id": "4073732c-6288-4714-9a82-a42b8c3361ba", "metadata": {}, "outputs": [], "source": ["UBI_new = fast_invert(UB_new)"]}, {"cell_type": "code", "execution_count": null, "id": "ea406443-e388-48d4-bfd3-5dd1d62b5ec9", "metadata": {}, "outputs": [], "source": ["# check that the U matrix doesn't change\n", "U_old = tmap.U.copy()"]}, {"cell_type": "code", "execution_count": null, "id": "78f73411-398b-4b25-8148-4d7375346f89", "metadata": {}, "outputs": [], "source": ["# now update the UBI in the tensormap\n", "tmap.UBI = UBI_new"]}, {"cell_type": "code", "execution_count": null, "id": "5f23edcf-f9da-494d-be08-bbf5e37ae9cb", "metadata": {}, "outputs": [], "source": ["eps_crystal_from_B_after = ubi_and_unitcell_to_eps_crystal(tmap.UBI, tmap.dzero_unitcell)"]}, {"cell_type": "code", "execution_count": null, "id": "378f50ba-66b5-4e02-badf-e0e3e5faef12", "metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots()\n", "ax.hist(tmap.eps_crystal.ravel(), bins=500, label='From eps_crystal', alpha=0.5)\n", "ax.hist(eps_crystal_from_B_after.ravel(), bins=500, label='From UBI', alpha=0.5)\n", "ax.set(xlabel='strain', ylabel='frequency', title='Histogram of strains after correction')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "ec52fe16-1a18-41c6-9952-4ddc7c3f1fc7", "metadata": {}, "outputs": [], "source": ["strain_diff_after = (tmap.eps_crystal - eps_crystal_from_B_after).ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(strain_diff_before, bins=500, label='before')\n", "ax.hist(strain_diff_after, bins=500, label='after')\n", "ax.set_xlim(-3e-4, 3e-4)\n", "ax.set(xlabel='strain diff', ylabel='frequency', title='Histogram of strain differences')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "3e022521-f966-4566-bdd8-9a7ac46e72bb", "metadata": {}, "outputs": [], "source": ["np.nanmin(strain_diff_after), np.nanmedian(strain_diff_after), np.nanmax(strain_diff_after)"]}, {"cell_type": "code", "execution_count": null, "id": "c106ccea-dfd4-4d65-9194-5d6ae9bbcf71", "metadata": {}, "outputs": [], "source": ["assert np.allclose(tmap.U, U_old, equal_nan=True)"]}, {"cell_type": "code", "execution_count": null, "id": "60069a59-f87b-4eba-974c-ae0a8a908fda", "metadata": {}, "outputs": [], "source": ["assert np.allclose(tmap.B, B_new, equal_nan=True)"]}, {"cell_type": "code", "execution_count": null, "id": "e273031a-6593-4404-9531-8657f3da5ddd", "metadata": {}, "outputs": [], "source": ["avals_after = tmap.unitcell[0, ..., 0].ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(avals_before, bins=500, alpha=0.5, label='before')\n", "ax.hist(avals_after, bins=500, alpha=0.5, label='after')\n", "ax.set(xlabel='a axis', ylabel='frequency', title='Histogram of a axis')\n", "ax.legend()\n", "plt.show()\n", "\n", "bvals_after = tmap.unitcell[0, ..., 1].ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(bvals_before, bins=500, alpha=0.5, label='before')\n", "ax.hist(bvals_after, bins=500, alpha=0.5, label='after')\n", "ax.set(xlabel='b axis', ylabel='frequency', title='Histogram of b axis')\n", "ax.legend()\n", "plt.show()\n", "\n", "cvals_after = tmap.unitcell[0, ..., 2].ravel()\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(cvals_before, bins=500, alpha=0.5, label='before')\n", "ax.hist(cvals_after, bins=500, alpha=0.5, label='after')\n", "ax.set(xlabel='c axis', ylabel='frequency', title='Histogram of c axis')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "d7e69485-9e5d-4fb7-a886-974b90b35f35", "metadata": {}, "outputs": [], "source": ["tmap.to_h5('new_tmap.h5')\n", "tmap.to_paraview('new_tmap.h5')"]}, {"cell_type": "code", "execution_count": null, "id": "e2e492a9-d5ab-4802-9231-8238eada7784", "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": 5}