{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# Jupyter notebook based on ImageD11 to process scanning 3DXRD data\n", "# Written by Haixing Fang, Jon Wright and James Ball\n", "## Date: 16/01/2024"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/TDXRD/use_only_if_needed/3_look_at_peaks.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/TDXRD/use_only_if_needed/3_look_at_peaks.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "metadata": {"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": {}, "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", "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"]}, {"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", "\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": {}, "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) "]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# load 2d columnfile from disk\n", "\n", "cf_2d = ds.get_cf_2d_from_disk()\n", "ds.update_colfile_pars(cf_2d, phase_name=phase_str) "]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# load grains from disk\n", "\n", "grains = ds.get_grains_from_disk(phase_str)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# Work out what 2D and 3D peaks we have for each grain\n", "# These will be \"masks\" on cf_2d and cf_3d\n", "# Will save a lot of speed\n", "\n", "for inc, grain in enumerate(tqdm(grains)):\n", " grain.mask_3d = cf_3d.labels == inc\n", " grain.mask_2d = np.isin(cf_2d.spot3d_id, cf_3d.spot3d_id[grain.mask_3d])"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# let's say we want all the omega values for the 3D peaks of a grain\n", "# all we have to do for this is get the omega values from cf_3d (all 3d peaks)\n", "# you do this with cf_3d.omega\n", "# then mask it by the mask_3d of that grain\n", "# so you get cf_3d.omega[some_grain.mask_3d]"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# pick the grain with the most 3D peaks\n", "selected_grain = sorted(grains, key=lambda g: sum(g.mask_3d), reverse=True)[0]\n", "\n", "# and look at its 2D and 3D peaks\n", "\n", "fig, ax = plt.subplots()\n", "ax.scatter(cf_3d.fc[selected_grain.mask_3d], cf_3d.sc[selected_grain.mask_3d], marker=\"X\", c=cf_3d.omega[selected_grain.mask_3d], label='Merged 3D peak')\n", "cols = ax.scatter(cf_2d.fc[selected_grain.mask_2d], cf_2d.sc[selected_grain.mask_2d], c=cf_2d.omega[selected_grain.mask_2d], s=cf_2d.s_I[selected_grain.mask_2d] / 5000, label='Contibutory 2D peaks')\n", "fig.colorbar(cols)\n", "ax.set_xlim(0, 2048)\n", "ax.set_ylim(0, 2048)\n", "ax.invert_yaxis()\n", "ax.legend()\n", "ax.set_title(\"Color is omega of peak. Scaled by sum intensity\")\n", "ax.set_xlabel(\"f_raw\")\n", "ax.set_ylabel(\"s_raw\")\n", "ax.set_aspect(1)\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# take the selected grain\n", "# get the omega value (corresponding to some image frame) with the most associated 2D peaks\n", "\n", "unique, counts = np.unique(cf_2d.omega[selected_grain.mask_2d], return_counts=True)\n", "hits_dict = dict(zip(unique, counts))\n", "hits_dict_max = sorted(hits_dict.items(), key=lambda x: x[1], reverse=True)[0]\n", "max_omega, peaks_on_frame = hits_dict_max\n", "\n", "# mask all the omega values for the 2D peaks of the selected grain\n", "# so we are only selecting those of max_omega\n", "\n", "omega_mask = cf_2d.omega[selected_grain.mask_2d] == max_omega\n", "\n", "# now extract the fast, slow and omega values of the peaks\n", "# we are chaining masks together\n", "# we are first selecting 2D peaks for the selected grain with [selected_grain.mask_2d]\n", "# then we are selecting those with the correct omega value with [omega_mask]\n", "\n", "fast, slow, omega = cf_2d.f_raw[selected_grain.mask_2d][omega_mask], cf_2d.s_raw[selected_grain.mask_2d][omega_mask], cf_2d.omega[selected_grain.mask_2d][omega_mask]\n", "\n", "# print(fast, slow, omega)\n", "\n", "# get the corresponding frame number\n", "\n", "omegas_sorted = np.sort(ds.omega)[0]\n", "omega_slop = np.round(np.diff(omegas_sorted).mean(), 3)\n", "\n", "frame_number = np.where(np.isclose(ds.omega[0, :], max_omega, atol=omega_slop/10))[0][0]\n", "\n", "# get the corresponding 2D frame\n", "with h5py.File(ds.masterfile, 'r') as h5In:\n", " frame_2d = h5In['1.1/measurement/frelon3'][frame_number].astype('uint16')"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# plot it\n", "\n", "from matplotlib.colors import LogNorm\n", "\n", "fig, ax = plt.subplots()\n", "ax.imshow(frame_2d, norm=LogNorm(vmax=1000), interpolation=\"nearest\")\n", "ax.scatter(fast, slow, marker='+', c=\"r\")\n", "ax.set_title(f\"Frame {frame_number} at w = {max_omega:.2f}\")\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# unfortunately due to the segmenter used, we have very little information about the 3D peaks\n", "# we have the following columns in the columnfile:\n", "# \"s_raw\": centre-of-mass of peak in slow direction\n", "# \"f_raw\": centre-of-mass of peak in fast direction\n", "# \"omega\": centre-of-mass of peak in omega\n", "# \"sum_intensity\": sum of intensity of peak\n", "# \"Number_of_pixels\": number of pixels in peak\n", "\n", "# if you want 3D peak shape information, you need to calculate it!\n", "# below is an example of a function (using Numba for speed) to do this\n", "# it calculates the extent in slow, fast and omega for each 3D peak\n", "# it uses the 2D peak information to do this\n", "\n", "from numba import njit, prange\n", "\n", "@njit(parallel=True)\n", "def calculate_3d_peak_extents(index_3d, spot3d_id_2d, fc_2d, sc_2d, omega_2d):\n", " # make arrays to store the results in\n", " # same length as index_3d\n", " \n", " fast_extent = np.full(index_3d.shape, -1, dtype=fc_2d.dtype) # extent in fast direction\n", " slow_extent = np.full(index_3d.shape, -1, dtype=fc_2d.dtype) # extent in slow direction\n", " omega_extent = np.full(index_3d.shape, -1, dtype=fc_2d.dtype) # extent in omega direction\n", " \n", " # iterate through each of the 3D peaks\n", " for inc in prange(index_3d.shape[0]):\n", " # select 2D peaks that merged to form this 3D peak\n", " mask_2d = spot3d_id_2d == index_3d[inc]\n", " \n", " # get the fast, slow and omega for the 2D peaks\n", " peak_2d_fast = fc_2d[mask_2d]\n", " peak_2d_slow = sc_2d[mask_2d]\n", " peak_2d_omega = omega_2d[mask_2d]\n", " \n", " # use ptp (basically max-min) to determine extent\n", " fast_extent[inc] = np.ptp(peak_2d_fast)\n", " slow_extent[inc] = np.ptp(peak_2d_slow)\n", " omega_extent[inc] = np.ptp(peak_2d_omega)\n", " \n", " return fast_extent, slow_extent, omega_extent"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["fast_extent, slow_extent, omega_extent = calculate_3d_peak_extents(cf_3d.spot3d_id, cf_2d.spot3d_id, cf_2d.fc, cf_2d.sc, cf_2d.omega)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# store the results in the 3D peaks columnfile\n", "\n", "cf_3d.addcolumn(fast_extent, \"f_extent\") # extent in fast direction\n", "cf_3d.addcolumn(slow_extent, \"s_extent\") # extent in slow direction\n", "cf_3d.addcolumn(omega_extent, \"o_extent\") # extent in omega direction"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# validate that this function is working\n", "\n", "# pick the first 3d peak with over 30 2d peaks\n", "n_2d_peaks = -1\n", "peak_index_3d = -1\n", "while n_2d_peaks < 30:\n", " peak_index_3d += 1\n", " # get its 2D peaks\n", " peak_2d_mask = cf_2d.spot3d_id == cf_3d.spot3d_id[peak_index_3d]\n", "\n", " # make sure we have more than 1 2d peak\n", " n_2d_peaks = np.sum(peak_2d_mask)\n", " \n", "print(f\"3D peak {peak_index_3d} has {n_2d_peaks} 2D peaks\")\n", "\n", "# and get its extents\n", "first_3d_peak_f_extent = cf_3d.f_extent[peak_index_3d]\n", "first_3d_peak_s_extent = cf_3d.s_extent[peak_index_3d]\n", "first_3d_peak_o_extent = cf_3d.o_extent[peak_index_3d]\n", "\n", "# get the fast, slow and omega values\n", "peak_2d_fast = cf_2d.fc[peak_2d_mask]\n", "peak_2d_slow = cf_2d.sc[peak_2d_mask]\n", "peak_2d_omega = cf_2d.omega[peak_2d_mask]\n", "\n", "# work out extents and assert equality\n", "assert np.max(peak_2d_fast) - np.min(peak_2d_fast) == first_3d_peak_f_extent\n", "assert np.max(peak_2d_slow) - np.min(peak_2d_slow) == first_3d_peak_s_extent\n", "assert np.max(peak_2d_omega) - np.min(peak_2d_omega) == first_3d_peak_o_extent"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# we could plot these results for a single grain\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist(cf_3d.o_extent[selected_grain.mask_3d], bins=30)\n", "ax.set_xlabel(\"Omega extent of 3D peaks\")\n", "ax.set_ylabel(\"Count\")\n", "ax.semilogy()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# or we could compute the mean omega extent for each grain, and plot a scatter plot:\n", "\n", "for grain in grains:\n", " grain.mean_omega_extent = np.mean(cf_3d.o_extent[grain.mask_3d])\n", "\n", "centre_plot = False\n", "\n", "fig = plt.figure(figsize=(12, 12))\n", "ax = fig.add_subplot(projection='3d')\n", "xx = [grain.translation[0] for grain in grains]\n", "yy = [grain.translation[1] for grain in grains]\n", "zz = [grain.translation[2] for grain in grains]\n", "col = [grain.mean_omega_extent for grain in grains]\n", "sizes = [0.01*(cf_3d.nrows) for grain in grains]\n", "if centre_plot:\n", " scatterplot = ax.scatter(xx-np.mean(xx), yy-np.mean(yy), zz, c=col, s=sizes)\n", "else:\n", " scatterplot = ax.scatter(xx, yy, zz, c=col, s=sizes)\n", "ax.set_xlim(-200,200)\n", "ax.set_ylim(-200,200)\n", "ax.set_zlim(-200,200)\n", "plt.colorbar(scatterplot)\n", "ax.set_title(\"Grains coloured by omega extent\")\n", "ax.set_xlabel(\"x\")\n", "ax.set_ylabel(\"y\")\n", "ax.set_zlabel(\"z\")\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# could plot a histogram too:\n", "\n", "fig, ax = plt.subplots()\n", "ax.hist([grain.mean_omega_extent for grain in grains], bins=30)\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# Guide to what the 2D peaks columns mean, from ImageD11/src/blobs.h:\n", "\n", "# s_1 = 0, /* 1 Npix */\n", "# s_I, /* 2 Sum intensity */\n", "# s_I2, /* 3 Sum intensity^2 */\n", "# s_fI, /* 4 Sum f * intensity */\n", "# s_ffI, /* 5 Sum f * f* intensity */\n", "# s_sI, /* 6 Sum s * intensity */\n", "# s_ssI, /* 7 Sum s * s * intensity */\n", "# s_sfI, /* 8 Sum f * s * intensity */\n", "# s_oI, /* 9 sum omega * intensity */\n", "# s_ooI, /* 10 sum omega2 * intensity */\n", "# s_soI, /* 11 sum omega * s * intensity */\n", "# s_foI, /* 12 sum omega * f * intensity */\n", "\n", "# mx_I, /* 13 Max intensity */\n", "# mx_I_f, /* 14 fast at Max intensity */\n", "# mx_I_s, /* 15 slow at Max intensity */\n", "# mx_I_o, /* 16 omega at max I */\n", "\n", "# bb_mx_f, /* 17 max of f */\n", "# bb_mx_s, /* 18 max of s */\n", "# bb_mx_o, /* 19 max of omega */\n", "# bb_mn_f, /* 20 min of f */\n", "# bb_mn_s, /* 21 min of s */\n", "# bb_mn_o, /* 22 min of o */\n", "\n", "# avg_i, /* Average intensity */\n", "# f_raw, /* fast centre of mass */\n", "# s_raw, /* slow centre of mass */\n", "# omega, /* omega centre of mass */\n", "# m_ss, /* moments */\n", "# m_ff,\n", "# m_oo,\n", "# m_sf,\n", "# m_so,\n", "# m_fo,"]}], "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}