{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Tomographic mapping notebook, with optimizations for minor phases \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_2_map_minor_phase.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/tomo_2_map_minor_phase.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {}, "source": ["This notebook will try to reconstruct grain shapes and positions from the grain orientations you found in the first notebook. \n", "This notebook is optimised for weak and noisy minor phase data. \n", "This notebook (and the tomo route in general) works best for low levels of deformation. \n", "If it doesn't seem to work well, try the point-by-point route instead!"]}, {"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": {"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", "# phase names to look at\n", "major_phase_strs = ['Fe']\n", "minor_phase_str = 'Au'\n", "\n", "# peak filtration parameters\n", "# whether to filter out major phase peaks before trying to build sinograms\n", "remove_major_phase_peaks = True\n", "major_phase_cf_dstol = 0.005\n", "minor_phase_cf_frac = 0.9975\n", "minor_phase_cf_dstol = 0.005\n", "\n", "# We can interactively draw a mask\n", "draw_mask_interactive = True\n", "# or we can threshold with Otsu, or a manual threshold value:\n", "# e.g. manual_threshold = 0.006\n", "manual_threshold = None\n", "\n", "# If the sinograms are only half-sinograms (we scanned dty across half the sample rather than the full sample), set the below to true:\n", "is_half_scan = False\n", "# If we did halfmask, choose the radius to mask in the centre of the reconstruction (normally hot pixels)\n", "halfmask_radius = 25\n", "\n", "# assign peaks to the grains with hkl tolerance peak_assign_tol\n", "peak_assign_tol = 0.05\n", "\n", "# tolerance for building sinograms from assigned peaks\n", "hkltol = 0.25\n", "\n", "# We can optionally correct each row of the sinogram by the ring current of that rotation\n", "# This helps remove artifacts in the reconstruction\n", "correct_sinos_with_ring_current = False\n", "\n", "# optional twin-friendly assignment\n", "# allows grains to share reflections\n", "twin_assign = False\n", "\n", "# optional structure factor correction\n", "# needs CIF!\n", "struc_factor_correction = False\n", "cif_for_sf_path = '/path/to/cif.cif'\n", "\n", "# use astra to run a second cycle of sinogram reconstructions?\n", "run_astra = True\n", "# run astra locally or on the cluster?\n", "run_astra_on_cluster = True\n", "# which ASTRA method?\n", "astra_method = 'EM_CUDA'\n", "# or 'FBP' if you run locally without CUDA\n", "# how many iterations for Astra reconstruction?\n", "niter = 500\n", "\n", "if struc_factor_correction:\n", " first_tmap_cutoff_level = 0.01\n", " second_tmap_cutoff_level = 0.01\n", "else:\n", " first_tmap_cutoff_level = 0.4\n", " second_tmap_cutoff_level = 0.5\n", "\n", "# filter out grains with more than grain_too_many_px pixels in the label map\n", "# this normally indicates a dodgy reconstruction for this grain\n", "# only really applies if the grains are very small!\n", "grain_too_many_px = 10"]}, {"cell_type": "code", "execution_count": null, "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, "metadata": {"tags": []}, "outputs": [], "source": ["import concurrent.futures\n", "\n", "import h5py\n", "import hdf5plugin\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import ipywidgets as widgets\n", "from tqdm.notebook import tqdm\n", "\n", "from ImageD11 import cImageD11\n", "from ImageD11.peakselect import select_ring_peaks_by_intensity, remove_peaks_from_phases\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.sinograms.sinogram import GrainSinogram, write_h5, read_h5, get_2d_peaks_from_4d_peaks, counting_sort, save_array\n", "from ImageD11.sinograms.roi_iradon import run_iradon\n", "from ImageD11.sinograms.tensor_map import TensorMap\n", "from ImageD11.sinograms.geometry import sino_shift_and_pad\n", "import ImageD11.nbGui.nb_utils as utils\n", "from ImageD11.nbGui.draw_mask import plot_mask_result, InteractiveMask, threshold_mask\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": "markdown", "metadata": {}, "source": ["Now we need to decide which are our 'major' phases, which we will remove from our peaks before indexing."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["major_phase_unitcells = [ds.phases.unitcells[mps] for mps in major_phase_strs]\n", "print(*major_phase_unitcells)\n", "minor_phase_unitcell = ds.phases.unitcells[minor_phase_str]\n", "print(minor_phase_unitcell)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_4d = ds.get_cf_4d()\n", "ds.update_colfile_pars(cf_4d) # computes geometry, needed for filtration\n", "for major_phase_unitcell in major_phase_unitcells:\n", " major_phase_unitcell.makerings(cf_4d.ds.max())\n", "minor_phase_unitcell.makerings(cf_4d.ds.max())"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Grains"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["grains = ds.get_grains_from_disk(minor_phase_str)\n", "grainsinos = [GrainSinogram(g, ds) for g in grains]\n", "utils.get_rgbs_for_grains(grains)\n", "print(f\"{len(grains)} grains imported\")"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_all_ipfs(grains)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Inherit the reconstruction parameters"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if is_half_scan:\n", " ds.correct_bins_for_half_scan(y0=ds.y0)\n", "\n", "# try to automatically determine the sinogram shift and the padding from the y0 values\n", "shift, pad = sino_shift_and_pad(ds.y0, len(ds.ybincens), min(ds.ybincens), ds.ystep)\n", "\n", "print(shift, ds.y0, pad)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Filtration\n", "## (optional) remove major phase peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if remove_major_phase_peaks:\n", " cf_4d = remove_peaks_from_phases(cf_4d, major_phase_cf_dstol, major_phase_unitcells)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Filter by intensity\n", "Now we are filtering our peaks (`cf_4d`) to select only the strongest ones .\n", "This time, we don't clip via `dsmax`, because we need the higher-angle projections for complete sinograms. \n", "We first filter the peaks in $d^{*}$ to keep only those close to the predicted peaks from the unit cell. \n", "We then sort our peaks by intensity, and take a certain intensity-weighted fraction of them. \n", "`dstol`: The tolerance in $d^{*}$ between a peak and a predicted reflection. \n", "`frac`: The intensity fraction: `frac=0.9` keeps 90% of the peak intensity. We recommend that you choose a value close to the 'elbow' of the plot."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_strong = select_ring_peaks_by_intensity(cf_4d, frac=minor_phase_cf_frac, dstol=minor_phase_cf_dstol, dsmax=cf_4d.ds.max(), ucell=minor_phase_unitcell, doplot=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["minor_phase_unitcell.makerings(cf_strong.ds.max())\n", "skip = 1 # we can skip peaks to speed up plotting if needed\n", "fig, ax = plt.subplots(figsize=(10, 5), constrained_layout=True)\n", "ax.plot(cf_4d.ds[::skip], cf_4d.sum_intensity[::skip],',', label='cf_4d',c='blue')\n", "ax.plot(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='minor phase',c='orange')\n", "ax.vlines(minor_phase_unitcell.ringds, 1e3, 3e3, color='red', label=minor_phase_unitcell.name)\n", "for inc, major_phase_unitcell in enumerate(major_phase_unitcells):\n", " ax.vlines(major_phase_unitcell.ringds, 3e3*(3**inc), 3e3*(2**inc)*3, color=plt.color_sequences['tab20'][inc], label=major_phase_unitcell.name)\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='Intensity', yscale='log', title='Peak filtration')\n", "ax.legend(loc='upper right')\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["# Peak assignment"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.assign_peaks_to_grains(grains, cf_strong, peak_assign_tol)\n", "gid = cf_strong.grain_id.astype(int)\n", "npks_4d = np.bincount(gid[gid >= 0], minlength=len(grains))\n", "for grain_label, g in enumerate(grains):\n", " g.gid = grain_label\n", " g.npks_4d = npks_4d[grain_label]"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_grain_sinograms(grains, cf_strong, min(len(grains), 25))"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Grain position refinement"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# sort peaks by grain once, then slice per grain (stable: same peak order as a mask)\n", "gid = cf_strong.grain_id.astype(int)\n", "order = np.argsort(gid, kind='stable')\n", "bounds = np.searchsorted(gid[order], np.arange(len(grainsinos) + 1))\n", "for grain_label, gs in enumerate(grainsinos):\n", " sel = order[bounds[grain_label]:bounds[grain_label + 1]]\n", " sx, sy, y0 = ImageD11.sinograms.geometry.sx_sy_y0_from_dty_omega(\n", " cf_strong.dty[sel], cf_strong.omega[sel], ds.y0)\n", " gs.grain.translation = np.array([sx, sy, 0])\n", " gs.recon_y0 = y0"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# plt.style.use('dark_background')\n", "fig, ax = plt.subplots(2,2, figsize=(12,12), layout='constrained')\n", "a = ax.ravel()\n", "x = [g.translation[0] for g in grains]\n", "y = [g.translation[1] for g in grains]\n", "s = [g.npks_4d/10 for g in grains]\n", "a[0].scatter(y, x, c=[g.rgb_z for g in grains], s=s)\n", "a[0].set(title='IPF color Z', aspect='equal')\n", "a[1].scatter(y, x, c=[g.rgb_y for g in grains], s=s)\n", "a[1].set(title='IPF color Y', aspect='equal')\n", "a[2].scatter(y, x, c=[g.rgb_x for g in grains], s=s)\n", "a[2].set(title='IPF color X', aspect='equal')\n", "a[3].scatter(y, x, c=s)\n", "a[3].set(title='Number of 4D peaks', aspect='equal')\n", "fig.supxlabel(\"<- Sample y (transverse)\")\n", "fig.supylabel(\"Sample x (beam) ->\")\n", "fig.suptitle(\"Grain centre-of-mass positions from 4D peaks\")\n", "\n", "a[0].invert_xaxis()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Masking"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained')\n", "whole_sample_sino, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)\n", "whole_sample_sino = whole_sample_sino.T\n", "pcm = ax.pcolormesh(om_edges, dty_edges, whole_sample_sino)\n", "ax.set(xlabel=r'$\\omega~(\\degree)$', ylabel='dty', title='Sinogram of all peaks')\n", "cax = fig.colorbar(pcm, ax=ax, label='log(intensity)')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["nthreads = cImageD11.cores_available()\n", "whole_sample_recon = run_iradon(whole_sample_sino, ds.obincens, pad, shift, workers=nthreads, apply_halfmask=is_half_scan, mask_central_zingers=is_half_scan)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["mask_on_disk = False\n", "\n", "with h5py.File(ds.grainsfile, \"r\") as hin:\n", " mask_path = f'masks/{minor_phase_str}' \n", " if mask_path in hin:\n", " whole_sample_mask = hin[mask_path][:]\n", " mask_on_disk = True\n", "\n", "if not mask_on_disk:\n", " if draw_mask_interactive:\n", " masker = InteractiveMask(whole_sample_recon)\n", " else:\n", " whole_sample_mask = threshold_mask(whole_sample_recon, manual_threshold=manual_threshold, doplot=True)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if mask_on_disk:\n", " plot_mask_result(whole_sample_recon, whole_sample_mask)\n", "else:\n", " if draw_mask_interactive:\n", " whole_sample_mask = masker.get_mask(doplot=True)\n", "\n", " # write mask to disk\n", " with h5py.File(ds.grainsfile, \"a\") as hout:\n", " mask_group = hout.require_group(\"masks\")\n", " save_array(mask_group, minor_phase_str, whole_sample_mask)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Grain sinogram generation"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["corrector = ds.get_spatial_corrector()\n", "\n", "if twin_assign:\n", " # assign from 4D peaks\n", " # allow grains to share reflections\n", " p2d = ds.pk2d\n", " # sort the 2D peaks by spot3d_id once; per grain we then look up only that grain's spots\n", " numba_order, numba_histo = counting_sort(p2d['spot3d_id'])\n", " sid2d_sorted = p2d['spot3d_id'][numba_order]\n", " gves = np.column_stack((cf_strong.gx, cf_strong.gy, cf_strong.gz))\n", "\n", " for grain_label, gs in enumerate(tqdm(grainsinos[:])):\n", " labels = np.full(cf_strong.nrows, fill_value=-1, dtype='i')\n", " drlv2 = np.full(cf_strong.nrows, fill_value=1, dtype='d')\n", " npks = ImageD11.cImageD11.score_and_assign(\n", " ubi=gs.grain.ubi,\n", " gv=gves,\n", " tol=peak_assign_tol,\n", " drlv2=drlv2,\n", " labels=labels,\n", " label=0\n", " )\n", "\n", " # 3D spot ids of this grain's 4D peaks -> runs of 2D peaks in the sorted order\n", " sel = np.unique(cf_strong.spot3d_id[labels == 0]).astype(sid2d_sorted.dtype)\n", " lo = np.searchsorted(sid2d_sorted, sel, side='left')\n", " hi = np.searchsorted(sid2d_sorted, sel, side='right')\n", " n = hi - lo\n", " pos = np.arange(n.sum()) + np.repeat(lo - (np.cumsum(n) - n), n)\n", " idx = np.sort(numba_order[pos]) # ascending 2D peak index, as before\n", "\n", " gs.prepare_peaks_from_4d(cf_strong, idx, np.array([0, 0, len(idx)]), 0, corrector, hkltol)\n", "\n", "else:\n", " gord, inds = get_2d_peaks_from_4d_peaks(ds.pk2d, cf_strong)\n", " \n", " for grain_label, gs in enumerate(tqdm(grainsinos)):\n", " gs.prepare_peaks_from_4d(cf_strong, gord, inds, grain_label, corrector, hkltol)\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# ^ if you segmented frelon data for scanning, the above cell won't work, because we don't have a 2d peaks table\n", "# you can instead try the below to prepare the peaks from the 2D peaks:\n", "\n", "# cf_2d = ds.get_cf_2d()\n", "# ds.update_colfile_pars(cf_2d, phase_str)\n", "\n", "# gv = np.ascontiguousarray(np.array((cf_2d.gx, cf_2d.gy, cf_2d.gz), dtype=float).T)\n", "\n", "# for grain_label, gs in enumerate(tqdm(grainsinos)):\n", "# gs.prepare_peaks_from_2d(cf_2d, grain_label, 0.02, gv=gv)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if struc_factor_correction:\n", " # |F|^2 of every reflection from the CIF (needs Dans_Diffraction)\n", " sfc = ImageD11.sinograms.sinogram.StructureFactorCorrection.from_cif(\n", " cif_for_sf_path,\n", " wavelength=cf_4d.parameters.get('wavelength'),\n", " tth_max=cf_4d.tth.max(),\n", " )\n", "\n", " # correct intensity\n", " for gs in tqdm(grainsinos):\n", " gs.filter_valid_hkls(sfc)\n", " intensity_column = gs.compute_corrected_intensity(sf_correction=sfc, apply_lf_pol=True)\n", "\n", "else:\n", " intensity_column = \"sum_intensity\""]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["for gs in tqdm(grainsinos):\n", " gs.build_sinogram(intensity_column=intensity_column, normalise=not struc_factor_correction) # normalises if no structure factors"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# optionally correct the halfmask:\n", "if is_half_scan:\n", " for gs in grainsinos:\n", " gs.correct_halfmask()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["gs = grainsinos[0]\n", "fig, ax = plt.subplots(figsize=(7, 7), layout='constrained')\n", "ax.pcolormesh(gs.sinoangles, ds.ybincens, gs.ssino)\n", "ax.set(xlabel=r'Projection angle ($\\degree$)', ylabel='dty', title='Grain sinogram')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# We can optionally correct each row of the sinogram by the ring current of that rotation\n", "# This helps remove artifacts in the reconstruction\n", "if correct_sinos_with_ring_current:\n", " ds.get_ring_current_per_scan()\n", " for gs in grainsinos:\n", " gs.correct_ring_current(is_half_scan=is_half_scan)\n", "\n", " gs = grainsinos[0]\n", " fig, ax = plt.subplots(figsize=(7, 7), layout='constrained')\n", " ax.pcolormesh(gs.sinoangles, ds.ybincens, gs.ssino)\n", " ax.set(xlabel=r'Projection angle ($\\degree$)', ylabel='dty', title='Grain sinogram')\n", " plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Grain shape reconstruction\n", "## iradon\n", "### First grain as example"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["gs.update_recon_parameters(pad=pad, shift=shift, mask=whole_sample_mask, y0=ds.y0)\n", "gs.recon()\n", "if is_half_scan:\n", " gs.mask_central_zingers(\"iradon\", radius=halfmask_radius)\n", "fig, axs = plt.subplots(1,2, figsize=(10,5), layout=\"constrained\")\n", "axs[0].pcolormesh(gs.sinoangles, ds.ybincens, gs.ssino)\n", "axs[0].set(xlabel=r'Projection angle ($\\degree$)', ylabel='dty', title='Grain sinogram')\n", "axs[1].imshow(gs.recons[\"iradon\"], vmin=0, origin=\"lower\")\n", "axs[1].set(title=\"ID11 iradon\", xlabel=\"<-- Sample Y\", ylabel=\"Sample X\")\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["for gs in grainsinos:\n", " gs.update_recon_parameters(pad=pad, shift=shift, mask=whole_sample_mask, y0=ds.y0)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### Reconstruct all grains"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["nthreads = cImageD11.cores_available()\n", "with concurrent.futures.ThreadPoolExecutor(max_workers= max(1,nthreads-1)) as pool:\n", " for i in tqdm(pool.map(GrainSinogram.recon, grainsinos), total=len(grainsinos)):\n", " pass\n", "if is_half_scan:\n", " for gs in grainsinos:\n", " gs.mask_central_zingers(\"iradon\", radius=halfmask_radius)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### View outputs"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["def update_frame(i):\n", " rec.set_array(grainsinos[i].recons[\"iradon\"])\n", " sin = a[1].pcolormesh(grainsinos[i].sinoangles, ds.ybincens, grainsinos[i].ssino)\n", " fig.suptitle(\"Grain \" + str(i))\n", " fig.canvas.draw()\n", "frame_slider = widgets.IntSlider(\n", " value=0,\n", " min=0,\n", " max=len(grains) - 1,\n", " step=1,\n", " description='Grain:'\n", ")\n", "fig, a = plt.subplots(1,2,figsize=(10,5), constrained_layout=True)\n", "rec = a[0].imshow(grainsinos[0].recons[\"iradon\"], vmin=0, origin=\"lower\")\n", "sin = a[1].pcolormesh(grainsinos[0].sinoangles, ds.ybincens, grainsinos[0].ssino)\n", "a[0].set(xlabel=\"<-- Sample Y\", ylabel=\"Sample X\", title=\"iradon Reconstruction\")\n", "a[1].set(xlabel=r'Projection angle ($\\degree$)', ylabel='dty', title='Grain sinogram')\n", "widgets.interact(update_frame, i=frame_slider)\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### Assemble TensorMap"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tensor_map = TensorMap.from_grainsinos(grainsinos, cutoff_level=first_tmap_cutoff_level,\n", " sf_normalisation=struc_factor_correction, sf_norm_percentile=50,\n", " smooth_labels=False, smooth_size=5)\n", "tensor_map.plot(\"ipf_z\")\n", "tensor_map.plot(\"labels\")\n", "tensor_map.plot(\"intensity\")"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## ASTRA\n", "We can clean up these reconstructions using an MLEM iterative recon. \n", "We will carry this out using ASTRA on the GPU on the SLURM cluster."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["if run_astra:\n", " for gs in grainsinos:\n", " gs.update_recon_parameters(pad=pad, shift=shift, mask=whole_sample_mask, niter=niter, y0=ds.y0)\n", "\n", " if run_astra_on_cluster:\n", " # save to disk and send slurm job\n", " write_h5(ds.grainsfile, grainsinos, overwrite_grains=True, group_name=minor_phase_str)\n", " bash_script_path = utils.prepare_astra_bash(ds, ds.grainsfile, PYTHONPATH, group_name=minor_phase_str, method=astra_method)\n", " utils.slurm_submit_and_wait(bash_script_path, 10)\n", "\n", " grainsinos = read_h5(ds.grainsfile, ds, group_name=minor_phase_str)\n", " for gs, g in zip(grainsinos, grains):\n", " gs.grain = g\n", " gs.ds = ds\n", "\n", " else:\n", " # run astra locally\n", " # first check if we have CUDA\n", " import astra\n", " if astra.use_cuda():\n", " # we have a local CUDA-enabled GPU\n", " print('ASTRA will run with GPU!')\n", " else:\n", " # we don't have a CUDA-enabled GPU\n", " if 'CUDA' in astra_method:\n", " print('ASTRA method requested:', astra_method)\n", " raise ValueError(\"You want to run ASTRA locally with a CUDA method, but you don't have a CUDA GPU available!\")\n", "\n", " # go ahead and run it\n", " for gs in tqdm(grainsinos):\n", " gs.recon(method='astra', astra_method=astra_method, niter=niter)\n", "\n", " utils.plot_grain_recons(grainsinos, method='astra')\n", "\n", " tensor_map_astra = TensorMap.from_grainsinos(grainsinos, cutoff_level=second_tmap_cutoff_level, method='astra',\n", " sf_normalisation=struc_factor_correction, sf_norm_percentile=99,\n", " smooth_labels=False, smooth_size=5)\n", " tensor_map_astra.plot(\"ipf_z\")\n", " tensor_map_astra.plot(\"labels\")\n", " tensor_map_astra.plot(\"intensity\")\n", "\n", "else:\n", " tensor_map_astra = tensor_map"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Filter by reconstruction quality \n", "For weak grains, there will likely be many streaks, indicating a few grains have dodgy reconstructions and are probably not to be trusted. \n", "To fix this, we can count how many pixels in the grain labels array each grain has. \n", "It can be helpful to run this filtration more than once. "]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["labels, counts = np.unique(tensor_map_astra[\"labels\"], return_counts=True)\n", "fig, ax = plt.subplots(constrained_layout=True, figsize=(6, 6))\n", "ax.plot(labels[labels > 0], counts[labels > 0])\n", "ax.set(xlabel='Grain ID', ylabel='Pixels in TensorMap')\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Filter out grains with more than grain_too_many_px pixels in the label map. \n", "This normally indicates a dodgy reconstruction for this grain. \n", "Only really applies if the grains are very small!"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["bad_gids = [int(label) for (label, count) in zip(labels, counts) if count > grain_too_many_px and label > 0]\n", "print(f\"{len(grainsinos)} grains before filtration\")\n", "grainsinos_clean = [gs for (inc, gs) in enumerate(grainsinos) if inc not in bad_gids]\n", "grain_labels_clean = [inc for (inc, gs) in enumerate(grainsinos) if inc not in bad_gids]\n", "print(f\"{len(grainsinos_clean)} grains after filtration\")\n", "for gs, label in zip(grainsinos_clean, grain_labels_clean):\n", " gs.grain.gid = label"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### Assemble cleaned TensorMap"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tensor_map_astra_clean = TensorMap.from_grainsinos(grainsinos_clean, cutoff_level=second_tmap_cutoff_level, method='astra',\n", " sf_normalisation=struc_factor_correction, sf_norm_percentile=50,\n", " smooth_labels=False, smooth_size=5)\n", "tensor_map_astra_clean.plot(\"ipf_z\")\n", "tensor_map_astra_clean.plot(\"labels\")\n", "tensor_map_astra_clean.plot(\"intensity\")"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["### Re-fit grain positions from reconstructions"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["for gs in tqdm(grainsinos):\n", " gs.update_lab_position_from_recon()\n", "for gs in grainsinos:\n", " gs.update_recon_parameters(y0=ds.y0)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# plt.style.use('dark_background')\n", "fig, ax = plt.subplots(2,2, figsize=(12,12), layout='constrained')\n", "a = ax.ravel()\n", "x = [gs.grain.translation[0] for gs in grainsinos_clean]\n", "y = [gs.grain.translation[1] for gs in grainsinos_clean]\n", "s = [gs.grain.npks_4d/10 for gs in grainsinos_clean]\n", "a[0].scatter(y, x, c=[gs.grain.rgb_z for gs in grainsinos_clean], s=s)\n", "a[0].set(title='IPF color Z', aspect='equal')\n", "a[1].scatter(y, x, c=[gs.grain.rgb_y for gs in grainsinos_clean], s=s)\n", "a[1].set(title='IPF color Y', aspect='equal')\n", "a[2].scatter(y, x, c=[gs.grain.rgb_x for gs in grainsinos_clean], s=s)\n", "a[2].set(title='IPF color X', aspect='equal')\n", "a[3].scatter(y, x, c=s)\n", "a[3].set(title='Number of 4D peaks', aspect='equal')\n", "fig.supxlabel(\"<- Sample y (transverse)\")\n", "fig.supylabel(\"Sample x (beam) ->\")\n", "fig.suptitle(\"Grain centre-of-mass positions from 4D peaks\")\n", "\n", "a[0].invert_xaxis()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Export\n", "## Grains"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["write_h5(ds.grainsfile, grainsinos, overwrite_grains=True, group_name=minor_phase_str)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## TensorMap"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["tensor_map_astra.to_h5(ds.grainsfile, h5group='TensorMap_' + minor_phase_str)"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["## XDMF"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tensor_map_astra.to_paraview(ds.grainsfile, h5group='TensorMap_' + minor_phase_str)"]}, {"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}