{"cells": [{"cell_type": "markdown", "id": "d7a0cf0a", "metadata": {"papermill": {"duration": 0.006454, "end_time": "2025-02-17T13:42:50.829319", "exception": false, "start_time": "2025-02-17T13:42:50.822865", "status": "completed"}, "tags": []}, "source": ["# (experimental) notebook to stack multiple box-beam 3DXRD layer scans together \n", "__Written by Haixing Fang, Jon Wright and James Ball__ \n", "__Date: 21/02/2025__"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/TDXRD/3_merge_slices.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/TDXRD/3_merge_slices.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "id": "f372b7a7", "metadata": {"papermill": {"duration": 0.344849, "end_time": "2025-02-17T13:42:51.201659", "exception": false, "start_time": "2025-02-17T13:42:50.856810", "status": "completed"}, "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", "dset_path = ''\n", "\n", "phase_str = 'Fe'\n", "\n", "z_translation_motor = \"samtz\"\n", "\n", "dset_prefix = \"ff\""]}, {"cell_type": "code", "execution_count": null, "id": "ee3ddc28", "metadata": {"papermill": {"duration": 0.017851, "end_time": "2025-02-17T13:42:50.853074", "exception": false, "start_time": "2025-02-17T13:42:50.835223", "status": "completed"}, "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": "6d835bf9", "metadata": {"papermill": {"duration": 1.245379, "end_time": "2025-02-17T13:42:52.469521", "exception": false, "start_time": "2025-02-17T13:42:51.224142", "status": "completed"}, "tags": []}, "outputs": [], "source": ["import os\n", "from collections import OrderedDict\n", "\n", "import h5py\n", "import numpy as np\n", "import networkx as nx\n", "from tqdm.notebook import tqdm\n", "from scipy.spatial.transform import Rotation as R\n", "import matplotlib.cm as cm\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 properties, dataset\n", "from ImageD11.nbGui import nb_utils as utils\n", "from ImageD11.sym_u import find_uniq_u, getgroup, cubic\n", "from xfab.symmetry import Umis, ROTATIONS\n", "\n", "%matplotlib widget"]}, {"cell_type": "markdown", "id": "8d54fa62-db66-402c-9a10-d5a6ce999e4f", "metadata": {"tags": []}, "source": ["# Load data\n", "## Single example dataset"]}, {"cell_type": "code", "execution_count": null, "id": "ee0bca2c", "metadata": {"papermill": {"duration": 0.029215, "end_time": "2025-02-17T13:42:52.509173", "exception": false, "start_time": "2025-02-17T13:42:52.479958", "status": "completed"}, "tags": []}, "outputs": [], "source": ["ds = ImageD11.sinograms.dataset.load(dset_path)\n", "print(ds)"]}, {"cell_type": "markdown", "id": "c6c344f2-0750-485b-a1f7-671f2c0f10fc", "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": "613cc3a3", "metadata": {"papermill": {"duration": 0.012703, "end_time": "2025-02-17T13:42:52.527052", "exception": false, "start_time": "2025-02-17T13:42:52.514349", "status": "completed"}, "tags": []}, "outputs": [], "source": ["ds.phases = ds.get_phases_from_disk()\n", "ds.phases.unitcells"]}, {"cell_type": "code", "execution_count": null, "id": "9169d34d", "metadata": {"papermill": {"duration": 0.011312, "end_time": "2025-02-17T13:42:52.541569", "exception": false, "start_time": "2025-02-17T13:42:52.530257", "status": "completed"}, "tags": []}, "outputs": [], "source": ["ucell = ds.phases.unitcells[phase_str]\n", "print(ucell.lattice_parameters, ucell.spacegroup)"]}, {"cell_type": "markdown", "id": "be36a423-325d-4c71-a1f1-e1376fde53c1", "metadata": {}, "source": ["## All datasets"]}, {"cell_type": "code", "execution_count": null, "id": "e3b5d68d", "metadata": {"papermill": {"duration": 0.012904, "end_time": "2025-02-17T13:42:52.558725", "exception": false, "start_time": "2025-02-17T13:42:52.545821", "status": "completed"}, "tags": []}, "outputs": [], "source": ["# you can optionally skip samples\n", "# skips_dict = {\n", "# \"FeAu_0p5_tR\": [\"ff6\",]\n", "# }\n", "# otherwise by default skip nothing:\n", "skips_dict = {\n", " ds.sample: []\n", "}\n", "\n", "sample_list = [ds.sample, ]\n", "\n", "samples_dict = utils.find_datasets_to_process(ds.dataroot, skips_dict, dset_prefix, sample_list)\n", "\n", "print(samples_dict)\n", " \n", "# manual override:\n", "# samples_dict = {\"FeAu_0p5_tR_nscope\": [\"top_100um\", \"top_150um\"]}"]}, {"cell_type": "code", "execution_count": null, "id": "87b45496", "metadata": {"papermill": {"duration": 0.070269, "end_time": "2025-02-17T13:42:52.632738", "exception": false, "start_time": "2025-02-17T13:42:52.562469", "status": "completed"}, "tags": []}, "outputs": [], "source": ["# just take first sample for now\n", "\n", "sample = sample_list[0]\n", "datasets = samples_dict[sample]\n", "ds_dict = OrderedDict()\n", "\n", "# try to sort datasets alphabetically\n", "\n", "datasets_sorted = sorted(datasets)\n", "\n", "for dataset in datasets_sorted:\n", " dset_path = os.path.join(ds.analysisroot, sample, f\"{sample}_{dataset}\", f\"{sample}_{dataset}_dataset.h5\")\n", " ds = ImageD11.sinograms.dataset.load(dset_path)\n", " print(f\"I have a DataSet {ds.dset} in sample {ds.sample}\")\n", " ds_dict[dataset] = ds"]}, {"cell_type": "code", "execution_count": null, "id": "4edac262", "metadata": {"papermill": {"duration": 0.020151, "end_time": "2025-02-17T13:42:52.658280", "exception": false, "start_time": "2025-02-17T13:42:52.638129", "status": "completed"}, "tags": []}, "outputs": [], "source": ["# populate z translations\n", "\n", "for ds in ds_dict.values():\n", " with h5py.File(ds.masterfile, 'r' ) as hin:\n", " this_z_trans_value = hin[\"1.1/instrument/positioners\"][z_translation_motor][()]\n", " ds.zpos = this_z_trans_value # this is in microns for samtz"]}, {"cell_type": "code", "execution_count": null, "id": "5b028319", "metadata": {"papermill": {"duration": 0.614724, "end_time": "2025-02-17T13:42:53.276467", "exception": false, "start_time": "2025-02-17T13:42:52.661743", "status": "completed"}, "tags": []}, "outputs": [], "source": ["# load grains for each dataset and tie them to the dataset objects\n", "for ds in ds_dict.values():\n", " ds.grains = ds.get_grains_from_disk(phase_str)"]}, {"cell_type": "code", "execution_count": null, "id": "113c2fb3", "metadata": {"papermill": {"duration": 0.013082, "end_time": "2025-02-17T13:42:53.298262", "exception": false, "start_time": "2025-02-17T13:42:53.285180", "status": "completed"}, "tags": []}, "outputs": [], "source": ["# get positions within the sample (set middle slice as zero position)\n", "\n", "middle_ds = list(ds_dict.values())[len(ds_dict.values())//2]\n", "middle_pos = middle_ds.zpos\n", "\n", "for ds in ds_dict.values():\n", " # adjust so that the first letterbox (lowest z so highest on the sample) has the highest value of zpos\n", " ds.zpos_sample = middle_pos - ds.zpos\n", " print(ds.zpos, ds.zpos_sample)"]}, {"cell_type": "code", "execution_count": null, "id": "9b40b2c8", "metadata": {"papermill": {"duration": 0.013815, "end_time": "2025-02-17T13:42:53.315512", "exception": false, "start_time": "2025-02-17T13:42:53.301697", "status": "completed"}, "tags": []}, "outputs": [], "source": ["for inc, ds in enumerate(ds_dict.values()):\n", " for gid, grain in enumerate(ds.grains):\n", " grain.pos_sample = grain.translation + np.array([0., 0., ds.zpos_sample * 1000])\n", " grain.dataset = ds.dsname\n", " grain.z_slice = inc\n", " grain.gid = gid\n", " grain.ref_unitcell = ucell\n", " grain.mean_int = float(grain.intensity_info.split('mean = ')[1].split(' ,')[0])\n", " \n", " utils.get_rgbs_for_grains(ds.grains)"]}, {"cell_type": "code", "execution_count": null, "id": "9186c7c9", "metadata": {"papermill": {"duration": 0.010577, "end_time": "2025-02-17T13:42:53.330899", "exception": false, "start_time": "2025-02-17T13:42:53.320322", "status": "completed"}, "tags": []}, "outputs": [], "source": ["all_grains = []\n", "for ds in ds_dict.values():\n", " all_grains.extend(ds.grains)"]}, {"cell_type": "code", "execution_count": null, "id": "db6232c1", "metadata": {"papermill": {"duration": 0.011207, "end_time": "2025-02-17T13:42:53.345624", "exception": false, "start_time": "2025-02-17T13:42:53.334417", "status": "completed"}, "tags": []}, "outputs": [], "source": ["print(all_grains[0].pos_sample, all_grains[0].translation)"]}, {"cell_type": "code", "execution_count": null, "id": "b26bb116", "metadata": {"papermill": {"duration": 0.231902, "end_time": "2025-02-17T13:42:53.581600", "exception": false, "start_time": "2025-02-17T13:42:53.349698", "status": "completed"}, "tags": []}, "outputs": [], "source": ["centre_plot = False\n", "fig = plt.figure(figsize=(12, 12))\n", "ax = fig.add_subplot(projection='3d', proj_type='ortho')\n", "colors = cm.rainbow(np.linspace(0, 1, len(list(ds_dict.values()))))\n", "for ds in ds_dict.values():\n", " xx = [grain.pos_sample[0] for grain in ds.grains]\n", " yy = [grain.pos_sample[1] for grain in ds.grains]\n", " zz = [grain.pos_sample[2] for grain in ds.grains]\n", " scatterplot = ax.scatter(xx, yy, zz, c=[grain.rgb_z for grain in ds.grains], s=[0.1*np.power(g.mean_int, 2/3) for g in ds.grains], label=ds.grains[0].z_slice)\n", "ax.set(title=\"Grains coloured by ipf-z\", xlabel='x', ylabel='y', zlabel='z', aspect='equal')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "9c36a4bc-2442-4416-a749-db4503f89161", "metadata": {"tags": []}, "outputs": [], "source": ["centre_plot = False\n", "fig = plt.figure(figsize=(12, 12))\n", "ax = fig.add_subplot(projection='3d', proj_type='ortho')\n", "colors = cm.rainbow(np.linspace(0, 1, len(list(ds_dict.values()))))\n", "for ds in ds_dict.values():\n", " xx = [grain.pos_sample[0] for grain in ds.grains]\n", " yy = [grain.pos_sample[1] for grain in ds.grains]\n", " zz = [grain.pos_sample[2] for grain in ds.grains]\n", " scatterplot = ax.scatter(xx, yy, zz, c=colors[ds.grains[0].z_slice], label=ds.grains[0].z_slice)\n", "ax.set(title=\"Grains coloured by z slice\", xlabel='x', ylabel='y', zlabel='z', aspect='equal')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "3a5c12d1-7838-4973-91a4-37df07ba877f", "metadata": {"tags": []}, "outputs": [], "source": ["# grain deduplication philosophy\n", "# create a Graph with networkx - each grain is a node on the graph\n", "# build an adjacency matrix - every grain vs every other grain\n", "# vectors on the graph are drawn based on whether two grains are considered to match\n", "# then extract the connected components of the graph"]}, {"cell_type": "code", "execution_count": null, "id": "ee69756c-06f1-4e76-b843-520d80b96256", "metadata": {"tags": []}, "outputs": [], "source": ["len(all_grains)"]}, {"cell_type": "code", "execution_count": null, "id": "bdc2814a-0459-4868-bd45-6f0309a8e6e0", "metadata": {"tags": []}, "outputs": [], "source": ["crystal_system_number = 7 # cubic\n", "\n", "def misorien_deg(U1, U2, crystal_system_number=7):\n", " return Umis(U1, U2, crystal_system_number)[:, 1].min() # 7 == cubic\n", "\n", "# euclidean distance function\n", "def eudis(v1, v2):\n", " return np.linalg.norm(v1-v2)\n", "\n", "def are_grains_duplicate(grain_a, grain_b, distance_tolerance=25, angle_tolerance=2):\n", " # are they the same grain?\n", " if grain_a is grain_b:\n", " return False\n", " # # are they from the same slice?\n", " # if grain_a.z_slice == grain_b.z_slice:\n", " # return False\n", " # now check their euclidean distance\n", " translation = eudis(grain_a.pos_sample, grain_b.pos_sample)\n", " if translation > distance_tolerance:\n", " return False\n", " misorien = misorien_deg(grain_a.U, grain_b.U)\n", " if misorien > angle_tolerance:\n", " return False\n", " # if we got here, we have a misorientation match\n", " return True"]}, {"cell_type": "code", "execution_count": null, "id": "192d9d3d-d40a-46f1-b290-eac40af208ef", "metadata": {"tags": []}, "outputs": [], "source": ["adjacency_matrix = np.zeros((len(all_grains), len(all_grains))).astype(bool)\n", "inds = np.array(np.triu_indices(adjacency_matrix.shape[0])).T # upper triangular indices to the adjacency matrix\n", "\n", "distance_tolerance_for_merging_grains = 150\n", "angular_tolerance_for_merging_grains = 0.5\n", "\n", "for ind in tqdm(inds):\n", " i_a, i_b = ind\n", " grain_a = all_grains[i_a]\n", " grain_b = all_grains[i_b]\n", " if are_grains_duplicate(grain_a, grain_b, distance_tolerance_for_merging_grains, angular_tolerance_for_merging_grains):\n", " adjacency_matrix[*ind] = 1\n", "\n", "print(np.sum(adjacency_matrix))"]}, {"cell_type": "code", "execution_count": null, "id": "2b51f4bf-a6db-46c8-b358-ffa3185ee051", "metadata": {"tags": []}, "outputs": [], "source": ["# build networkx graph\n", "\n", "G = nx.from_numpy_array(adjacency_matrix)\n", "components = list(nx.connected_components(G))"]}, {"cell_type": "code", "execution_count": null, "id": "4c21b848-f4c0-419b-9969-084f026a6e92", "metadata": {"tags": []}, "outputs": [], "source": ["def merge_grains(grains_to_merge, distance_tolerance=25, angle_tolerance=2):\n", " grain_positions = np.array([g.pos_sample for g in grains_to_merge])\n", " \n", " # take first grain in grains_to_merge\n", " # take the fundamental zone of that grain\n", " # move all other grains into the same fundamental zone\n", " first_grain = grains_to_merge[0]\n", " umats_fz = []\n", " umats_fz.append(first_grain.U)\n", " for g in grains_to_merge[1:]:\n", " umis_out = Umis(g.U, first_grain.U, 7)\n", " rot_operator_idx = np.argmin(umis_out[:, 1])\n", " rot_operator = ROTATIONS[7][rot_operator_idx]\n", " second_grain_in_fz = g.U @ rot_operator.T\n", " umats_fz.append(second_grain_in_fz)\n", " \n", " grain_umats = np.array(umats_fz)\n", " # find_uniq_u has corner cases!\n", " grain_as = np.array([np.linalg.inv(g.B) for g in grains_to_merge])\n", " grain_volumes = np.array([g.mean_int for g in grains_to_merge])\n", " vol_weighted_umat = R.from_matrix(grain_umats).mean(weights=grain_volumes).as_matrix()\n", " vol_weighted_position = np.average(grain_positions, weights=grain_volumes, axis=0)\n", " vol_weighted_amat = np.average(grain_as, weights=grain_volumes, axis=0)\n", " vol_weighted_bmat = np.linalg.inv(vol_weighted_amat)\n", " vol_weighted_ubi = np.linalg.inv(vol_weighted_umat.dot(vol_weighted_bmat))\n", " new_grain = ImageD11.grain.grain(vol_weighted_ubi)\n", " new_grain.pos_sample = vol_weighted_position\n", " new_grain.names = [g.name for g in grains_to_merge]\n", " new_grain.mean_int = np.sum(grain_volumes)\n", " \n", " # new grain should be close to first grain\n", " assert eudis(new_grain.pos_sample, grains_to_merge[0].pos_sample) < distance_tolerance, eudis(new_grain.pos_sample, grains_to_merge[0].pos_sample)\n", " assert misorien_deg(new_grain.U, grains_to_merge[0].U) < angle_tolerance, misorien_deg(new_grain.U, grains_to_merge[0].U)\n", " \n", " return new_grain"]}, {"cell_type": "code", "execution_count": null, "id": "e5a0dc60-ea9c-4f92-b43d-e4231512cfff", "metadata": {"tags": []}, "outputs": [], "source": ["# build list of merged grains\n", "merged_grains = []\n", "# comp is a list of dictionaries\n", "for comp in tqdm(list(nx.connected_components(G))):\n", " # list of grain IDs\n", " cl = list(comp)\n", " # list of grains\n", " grains_here = [all_grains[inc] for inc in cl]\n", " if len(grains_here) == 1:\n", " merged_grains.append(grains_here[0])\n", " else:\n", " gnew = merge_grains(grains_here, distance_tolerance_for_merging_grains, angular_tolerance_for_merging_grains)\n", " merged_grains.append(gnew)"]}, {"cell_type": "code", "execution_count": null, "id": "d2952c83-dac9-4dd9-ae25-8e05e533cea8", "metadata": {"tags": []}, "outputs": [], "source": ["for g in merged_grains:\n", " g.ref_unitcell = ucell\n", "\n", "utils.get_rgbs_for_grains(merged_grains)"]}, {"cell_type": "code", "execution_count": null, "id": "a6da4af2-ba72-413a-af8e-a8c3ebfcffbc", "metadata": {"tags": []}, "outputs": [], "source": ["centre_plot = False\n", "fig = plt.figure(figsize=(12, 12))\n", "ax = fig.add_subplot(projection='3d', proj_type='ortho')\n", "xx = [grain.pos_sample[0] for grain in merged_grains]\n", "yy = [grain.pos_sample[1] for grain in merged_grains]\n", "zz = [grain.pos_sample[2] for grain in merged_grains]\n", "c = [grain.rgb_z for grain in merged_grains]\n", "scatterplot = ax.scatter(xx, yy, zz, c=c, s=[0.1*np.power(g.mean_int, 2/3) for g in merged_grains])\n", "ax.set(title=\"Merged grains\", xlabel='x', ylabel='y', zlabel='z', aspect='equal')\n", "ax.legend()\n", "plt.show()"]}], "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"}, "papermill": {"default_parameters": {}, "duration": 23.994739, "end_time": "2025-02-17T13:43:13.919619", "environment_variables": {}, "exception": null, "input_path": "../ImageD11/nbGui/TDXRD/2_merge_slices.ipynb", "output_path": "/data/id11/inhouse2/test_data_3DXRD/TDXRD/FeAu/PROCESSED_DATA/20250127_JADB/friedel/nb_out/2_merge_slices_out.ipynb", "parameters": {"PYTHONPATH": "../", "dset_path": "/data/id11/inhouse2/test_data_3DXRD/TDXRD/FeAu/PROCESSED_DATA/20250127_JADB/friedel/FeAu_0p5_tR/FeAu_0p5_tR_ff1/FeAu_0p5_tR_ff1_dataset.h5", "dset_prefix": "ff", "phase_str": "Fe", "z_translation_motor": "samtz"}, "start_time": "2025-02-17T13:42:49.924880", "version": "2.6.0"}, "widgets": {"application/vnd.jupyter.widget-state+json": {"state": {}, "version_major": 2, "version_minor": 0}}}, "nbformat": 4, "nbformat_minor": 5}