{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Point-by-point 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/pbp_1_indexing.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/pbp_1_indexing.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {}, "source": ["This notebook will try to perform a point-by-point index of the 2D peaks you segmented.\n", "The point-by-point results (usually saved to a .txt file in the sample PROCESSED_DATA folder) are multi-valued (we can find multiple UBIs at each map voxel). \n", "You can view the results of the point-by-point process 'live' by running the next notebook (pbp_2_visualise). \n", "That notebook will also allow you to save a single-valued version of the pbp map to H5, ParaView XDMF and MTEX CTF.\n", "The UBIs we find from the PBP index should have reasonably accurate orientations, but the strains are likely to be poor. \n", "To get much better strains, slightly better orientations and possibly better grain shapes, you should run pbp_3_refinement\n", "Then run 4_visualise to convert the refinement results to an accurate single-valued map with good strains."]}, {"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", "# which phase to index\n", "phase_str = 'Si'\n", "\n", "# filter the columnfile to discard weak peaks\n", "minpkint = 5\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", "is_half_scan = False\n", "# need to know for automatic y0 guessing from scan ranges.\n", "\n", "# point-by-point parameters\n", "hkl_tol = 0.025\n", "fpks = 0.9\n", "ds_tol = 0.004\n", "etacut = 0.1\n", "ifrac = 5e-3\n", "drop_input_peaks = False\n", "# ^ for large datasets, delete cf_2d from memory after choosing peaks to refine with\n", "\n", "symmetry = \"cubic\"\n", "foridx = [0, 1, 3, 5, 7]\n", "forgen = [1, 5, 7]\n", "uniqcut = 0.85\n", "uniqueness = 0.5\n", "# ^ an orientation is kept at a point only if more than this fraction of its peaks are unclaimed.\n", "# 0.5 rejects duplicates but can also reject one member of a twin pair (they share ~1/3 of reflections)\n", "# should we mask based on whole-sample sinogram before indexing? helps get clean sample edges\n", "mask_before_indexing = True\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", "# cluster indexing\n", "use_cluster = False\n", "n_chunks = 4\n", "cpus_per_chunk = 24\n", "time_h = 8\n", "partition = 'nice'\n", "# ^ can be nice-long\n", "mem_G = 32\n", "\n", "# EXPERTS: Can specify par_file as a parameter if you want\n", "par_file = None"]}, {"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 numpy as np\n", "from matplotlib import pyplot as plt\n", "\n", "try:\n", " from ImageD11.nbGui.S3DXRD.run_pbp_recon_chunk import merge_chunk_outputs\n", "except:\n", " merge_chunk_outputs = None # Old version\n", "import ImageD11.sinograms.point_by_point\n", "import ImageD11.sinograms.tensor_map # trigger tensor_map computation so chunked version doesn't crash (try to fix #571)\n", "import ImageD11.sinograms.dataset\n", "import ImageD11.columnfile\n", "\n", "import ImageD11.nbGui.nb_utils as utils\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": ["## Parameters\n", "Specify the path to your parameter file.\n", "\n", "You can optionally set up some default parameters for either an Eiger or Frelon detector like so:\n", "```python\n", "from ImageD11.parameters import AnalysisSchema\n", "asc = AnalysisSchema.from_default(detector='eiger') # or detector='frelon'\n", "asc.save('./pars.json')\n", "```\n", "Please note in this case that you will still have to update the `geometry.par` values accordingly for your experiment. \n", "If you haven't already, you should run one of the calibration notebooks to determine these."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["if par_file is not None:\n", " # only change if ds has no parfile\n", " if not hasattr(ds, 'parfile') or ds.parfile is None:\n", " ds.parfile = par_file\n", " ds.save()"]}, {"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 = y0_manual\n", "else:\n", " if hasattr(ds, 'y0') and ds.y0 is not None:\n", " print('Using ds.y0')\n", " y0 = 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", " print('Guessing y0 from ymax/ymin')\n", " y0 = (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)\n", "# if we got here, save to ds.y0 - future refinements should use the same one\n", "ds.y0 = y0\n", "ds.save()"]}, {"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_2d = ds.get_cf_2d()\n", "ds.update_colfile_pars(cf_2d, phase_name=phase_str)\n", "if not os.path.exists(ds.col2dfile):\n", " # save the 2D peaks to file so we don't have to spatially correct them again\n", " ImageD11.columnfile.colfile_to_hdf(cf_2d, ds.col2dfile)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# filter the columnfile to discard weak peaks\n", "\n", "cf_2d.filter(cf_2d.Number_of_pixels > minpkint)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cosine_tol=np.cos(np.radians(90 - ds.ostep))\n", "\n", "pbp_object = ImageD11.sinograms.point_by_point.PBP(ds.parfile,\n", " ds,\n", " hkl_tol=hkl_tol,\n", " fpks=fpks,\n", " ds_tol=ds_tol,\n", " etacut=etacut,\n", " ifrac=ifrac,\n", " cosine_tol=cosine_tol,\n", " y0=y0,\n", " symmetry=symmetry,\n", " foridx=foridx,\n", " forgen=forgen,\n", " uniqcut=uniqcut,\n", " uniqueness=uniqueness,\n", " phase_name=phase_str)\n", "\n", "# make icolf filename phase-aware\n", "icolf_filename = ds.icolfile.replace('.h5', f'_{phase_str}.h5')\n", "grains_filename = ds.pbpfile.replace('.txt', f'_{phase_str}.txt')\n", "\n", "pbp_object.setpeaks(cf_2d, icolf_filename=icolf_filename, keep_colf=not drop_input_peaks)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if drop_input_peaks:\n", " del cf_2d\n", " import gc; gc.collect()\n", " print(\"released input peaks\")"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = pbp_object.iplot(skip=1) # increase skip to make plot faster"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if mask_before_indexing:\n", " 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": {}, "outputs": [], "source": ["if mask_before_indexing:\n", "\n", " from ImageD11 import cImageD11\n", " from ImageD11.sinograms.roi_iradon import run_iradon\n", " from ImageD11.sinograms.geometry import sino_shift_and_pad, recon_to_step, step_grid_from_ybincens\n", " from ImageD11.nbGui.draw_mask import InteractiveMask, threshold_mask\n", " is_half_scan = False # change to True for half-acquisition\n", " \n", " shift, pad = sino_shift_and_pad(y0, len(ds.ybincens), min(ds.ybincens), ds.ystep)\n", " 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": {}, "outputs": [], "source": ["# Now we generate a whole-sample mask for the image\n", "if mask_before_indexing:\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_before_indexing:\n", " if draw_mask_interactive:\n", " whole_sample_mask = masker.get_mask(doplot=True)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if mask_before_indexing:\n", " # determine points to index\n", " # add the corners back into the mask to keep a consistent shape\n", " whole_sample_mask[0, 0] = 1\n", " whole_sample_mask[0, -1] = 1\n", " whole_sample_mask[-1, 0] = 1\n", " whole_sample_mask[-1, -1] = 1\n", " ri, rj = np.where(whole_sample_mask)\n", " si, sj = recon_to_step(ri, rj, whole_sample_mask.shape)\n", " debugpoints = np.array((si, sj)).T\n", " debugpoints = [tuple(row) for row in debugpoints]\n", " print(debugpoints[:2], debugpoints[-2:]) # limits\n", "else:\n", " debugpoints = None"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Indexing"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["if merge_chunk_outputs is not None and use_cluster:\n", " grains_prefix = ds.pbpfile.replace(ds.analysispath, os.path.join(ds.analysispath, 'slurm_pbp')).replace('.txt', f'_{phase_str}_')\n", " bash_script_path, grains_files = pbp_object.submit_slurm_chunks(grains_prefix,\n", " PYTHONPATH,\n", " n_chunks=n_chunks,\n", " cpus_per_chunk=cpus_per_chunk,\n", " time_h=time_h,\n", " partition=partition,\n", " mem_G=mem_G,\n", " debugpoints=debugpoints) # (N, 2) array. these can be supplied then chunked if you want\n", " \n", " utils.slurm_submit_and_wait(bash_script_path, 15)\n", " \n", " merge_chunk_outputs(grains_files, grains_filename)\n", "else:\n", " pbp_object.point_by_point(grains_filename, loglevel=3, debugpoints=debugpoints)"]}, {"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}