{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Point-by-point refinement 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_3_refinement.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/pbp_3_refinement.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["This notebook will try to perform a point-by-point strain refinement of your pbp index results. \n", "As with the pbp index, the results of this process are multi-valued. \n", "You can run 4_visualise to convert the refinement results to an accurate single-valued map. \n", "\n", "### NOTE: It is highly recommended to run this notebook on a Jupyter server with many cores and a lot of RAM. \n", "The compute_origins() function in particular runs locally and can be compute-intensive for large datasets. \n", "If this is a big scan (e.g 100 million + 2D peaks), you should definitely refine on the cluster rather than locally."]}, {"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 refine\n", "phase_str = 'Si'\n", "\n", "# the minimum number of peaks you want a pixel to have to be counted\n", "min_unique = 20\n", "\n", "# threshold for whole-sample mask binarisation\n", "manual_threshold = None\n", "\n", "# refinement parameters\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", "# refinement tolerances\n", "hkl_tol_origins = 0.05\n", "# ^ we forgot to square this before!\n", "hkl_tol_refine = 0.1\n", "hkl_tol_refine_merged = 0.05\n", "ds_tol = 0.006\n", "ifrac = 1e-4\n", "rings_to_refine = None \n", "# ^ can be a list of rings\n", "drop_input_peaks = False\n", "# ^ for large datasets, delete cf_2d from memory after choosing peaks to refine with\n", "use_origin_found_only=True\n", "set_mask_from_input = False # do we mask just from the min_unique value?\n", "use_cluster = False"]}, {"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", "from ImageD11.grain import grain\n", "from ImageD11 import unitcell\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.sinograms.point_by_point import PBPMap\n", "from ImageD11.sinograms.pbp_refine import PBPRefine\n", "from ImageD11.sinograms.tensor_map import TensorMap\n", "from ImageD11.nbGui import nb_utils as utils\n", "\n", "%matplotlib ipympl"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Load data\n", "## Dataset"]}, {"cell_type": "code", "execution_count": null, "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "outputs": [], "source": ["ds = ImageD11.sinograms.dataset.load(dset_path)\n", "print(ds)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["y0 = ds.y0\n", "print(y0)"]}, {"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": ["# load phases from parameter file\n", "\n", "ds.phases = ds.get_phases_from_disk()\n", "ds.phases.unitcells"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ref_ucell = ds.phases.unitcells[phase_str]\n", "print(ref_ucell)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Point-by-point map"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["pmap = PBPMap(ds.pbpfile.replace('.txt', f'_{phase_str}.txt'))\n", "pmap.plot_nuniq_hist()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# choose the minimum number of peaks you want a pixel to have to be counted\n", "pmap.choose_best(min_unique)\n", "pmap.plot_best(min_unique)"]}, {"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)\n", "print(f\"Read {cf_2d.nrows} 2D peaks\")"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "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", " 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": ["# Refinement"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# set up a refinement manager object\n", "refine = PBPRefine(dset=ds,\n", " y0=y0, hkl_tol_origins=hkl_tol_origins, hkl_tol_refine=hkl_tol_refine, hkl_tol_refine_merged=hkl_tol_refine_merged,\n", " ds_tol=ds_tol, ifrac=ifrac, phase_name=phase_str, forref=rings_to_refine,\n", " beam_size=None) # use step size as beam size - important for regularisation\n", "# change the default paths of the refinement manager to append the phase name\n", "refine.own_filename = os.path.splitext(refine.own_filename)[0] + f'_{phase_str}.h5'\n", "refine.icolf_filename = os.path.splitext(refine.icolf_filename)[0] + f'_{phase_str}.h5'\n", "refine.pbpmap_filename = os.path.splitext(refine.pbpmap_filename)[0] + f'_{phase_str}.h5'\n", "refine.refinedmap_filename = os.path.splitext(refine.refinedmap_filename)[0] + f'_{phase_str}.h5'"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# tell it which point-by-point map we are refining\n", "refine.setmap(pmap)\n", "\n", "# or load from disk:\n", "# refine.loadmap()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# choose 2D peaks to refine with\n", "refine.setpeaks(cf_2d, keep_colf=not drop_input_peaks)\n", "\n", "# or load from disk:\n", "# refine.loadpeaks()"]}, {"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": ["# plot the peaks you selected\n", "refine.iplot()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# generate a single-valued map to refine on\n", "refine.setsingle(refine.pbpmap, minpeaks=min_unique)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# set whole-sample mask to choose where to refine\n", "# if use_singlemap is true, we will generate a mask simply based on where self.singlemap > min_unique\n", "refine.setmask(manual_threshold=manual_threshold, doplot=True, use_singlemap=set_mask_from_input)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Compute peak diffraction origins"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# compute diffraction origins - these will be added as a column to refine.icolf\n", "# will then save the new column to disk to avoid re-computation\n", "refine.get_origins()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# after refine.get_origins()\n", "if use_origin_found_only:\n", " n0 = refine.icolf.nrows\n", " refine.icolf = refine.icolf.copyrows(refine.icolf.origin_found == 1)\n", " print(f\"origin_found filter: kept {refine.icolf.nrows} / {n0} peaks\")"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Run refinement"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# run the refinement\n", "# if compute_origins took more than a couple of minutes to run, I suggest setting use_cluster=True below\n", "# otherwise if you asked for lots of cores and RAM on this Jupyter instance, you can run it locally (use_cluster=False)\n", "refine.run_refine(use_cluster=use_cluster, pythonpath=PYTHONPATH)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Export"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# make sure refinement is saved to disk\n", "\n", "if not use_cluster:\n", " refine.to_h5(save_peaks=False)\n", "\n", "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}