{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Tomographic mapping 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/tomo_2_map.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/tomo_2_map.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 (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": {}, "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", "# peak filtration parameters\n", "cf_strong_frac = 0.993\n", "cf_strong_dstol = 0.005\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", "# 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", "# tolerance for building sinograms from assigned peaks\n", "hkltol = 0.25\n", "\n", "# manual override of y0 (ignores any value saved in dataset)\n", "y0_manual = None\n", "# or y0_manual = 0.0 (typical NSCOPE) or 13.5 (typical TDXRD)\n", "\n", "# set to True if you want to update ds.y0 with the value from the sinograms\n", "update_y0 = True\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. Not needed if you had a monitor column\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", "first_tmap_cutoff_level = 0.4\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", "second_tmap_cutoff_level = 0.05"]}, {"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": {"editable": true, "slideshow": {"slide_type": ""}, "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\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.sinograms.sinogram import GrainSinogram, read_h5, write_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": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ucell = ds.phases.unitcells[phase_str]\n", "print(ucell)"]}, {"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)\n", "ucell.makerings(cf_4d.ds.max())\n", "print(f\"Read {cf_4d.nrows} 4D peaks\")"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Grains"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["grains = ds.get_grains_from_disk(phase_str)\n", "grainsinos = [GrainSinogram(g, ds) for g in grains]\n", "utils.get_rgbs_for_grains(grains)\n", "for grain_label, g in enumerate(grains):\n", " g.gid = grain_label\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": ["# Filtration\n", "Here 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=cf_strong_frac, dstol=cf_strong_dstol, dsmax=cf_4d.ds.max(), ucell=ucell, doplot=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["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')\n", "ax.plot(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='cf_strong')\n", "ax.vlines(ucell.ringds, 1e3, 1e4, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='Intensity', yscale='log', title='Peak filtration')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "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": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "outputs": [], "source": ["# Priority order (decreasing)\n", "# manual override in first cell\n", "# ds attribute\n", "\n", "# fails if no y0 provided at all\n", "\n", "if y0_manual is not None:\n", " print('Using manually supplied y0')\n", " y0_guess = y0_manual\n", "else:\n", " if hasattr(ds, 'y0') and ds.y0 is not None:\n", " print('Using ds.y0')\n", " y0_guess = ds.y0\n", " else:\n", " # not using manual y0, and couldn't find one. guess it from ymax/ymin\n", " if not is_half_scan:\n", " y0_guess = (ds.ymax + ds.ymin)/2\n", " else:\n", " # half scan, not sure\n", " raise ValueError('You must manually supply a y0 value in the first cell to continue.')\n", "print('Using y0:', y0_guess)"]}, {"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], y0_guess)\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", "for a in ax.ravel():\n", " a.invert_xaxis()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# $y_0$ refinement\n", "We need to determine what the value of `dtymotor` is where the rotation axis intercepts the beam. \n", "This should be close to zero for the NSCOPE station, and somewhere around `14 mm` for the TDXRD station."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["sample_y0s = [gs.recon_y0 for gs in grainsinos]\n", "y0_fit = np.median(sample_y0s)\n", "fig, ax = plt.subplots(constrained_layout=True)\n", "ax.plot(sample_y0s)\n", "ax.hlines(y0_fit, 0, len(grainsinos), color='red', label='y0 fit from sinograms')\n", "ax.hlines(y0_guess, 0, len(grainsinos), color='green', label='y0 guess')\n", "ax.set(xlabel='Grain ID', ylabel=r'$y_0$')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["print('y0_guess is', y0_guess)\n", "print('fitted y0 from sinograms is', y0_fit)\n", "\n", "if update_y0:\n", " print('Updating y0 to', y0_fit)\n", " ds.y0 = y0_fit\n", "else:\n", " ds.y0 = y0_guess\n", "\n", "ds.save()\n", "\n", "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", "print('shift is', shift)\n", "print('pad is', pad)\n", "# update the grainsinogram parameters accordingly:\n", "for gs in grainsinos:\n", " gs.update_recon_parameters(y0=ds.y0, shift=shift, pad=pad)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Whole-sample mask"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Our next task is to determine a reconstruction mask for the entire sample.\n", "\n", "This should adequately differentiate between sample and air."]}, {"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/{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, 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, hkl_tol, 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": {"tags": []}, "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": {"tags": []}, "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": {"tags": []}, "source": ["### Reconstruct all grains"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["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": ["utils.plot_grain_recons(grainsinos)"]}, {"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=99,\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": {"tags": []}, "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. \n", "The ASTRA EM_CUDA method will be used."]}, {"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=phase_str)\n", " bash_script_path = utils.prepare_astra_bash(ds, ds.grainsfile, PYTHONPATH, group_name=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=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": ["# Export\n", "## Grains"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["write_h5(ds.grainsfile, grainsinos, overwrite_grains=True, group_name=phase_str)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## TensorMap"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tensor_map_astra.to_h5(ds.grainsfile, h5group='TensorMap_' + phase_str)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## XDMF"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["tensor_map_astra.to_paraview(ds.grainsfile, h5group='TensorMap_' + phase_str)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "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}