{"cells": [{"cell_type": "markdown", "id": "8deabe5b", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# S3DXRD processing first step: dataset creation, segmentation and peak labelling\n", "\n", "Written by James Ball, Haixing Fang and Jon Wright\n", "\n", "Last updated: 21/02/2025\n", "\n", "Outside ESRF: download [install_ImageD11_from_git.py](https://github.com/FABLE-3DXRD/ImageD11/tree/master/ImageD11/nbGui/install_ImageD11_from_git.py), and update the path in the next cell:"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/0_segment_and_label.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/0_segment_and_label.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "id": "c3bddb80-39f9-4cd7-9cc1-59fc8d240c24", "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", "# Experts : update these files for your detector if you need to\n", "maskfile = \"/data/id11/nanoscope/Eiger/eiger_mask_E-08-0144_20250819.edf\"\n", "# old papermill tests still use e2dx + e2dy\n", "# if you give e2dxfile, this is used. Otherwise it takes the detector h5 below.\n", "e2dxfile = None # \"/data/id11/nanoscope/Eiger/e2dx_E-08-0144_20240205.edf\"\n", "e2dyfile = None # \"/data/id11/nanoscope/Eiger/e2dy_E-08-0144_20240205.edf\"\n", "# For the future easier to have one detectorh5 (so you can't mix up x/y).\n", "detectorh5 = \"/data/id11/nanoscope/Eiger/spatial_20250826_LJ/newSpatial_20250819.h5\"\n", "detector = 'eiger'\n", "omegamotor = 'rot_center'\n", "dtymotor = 'dty'\n", "\n", "# do we segment on the local machine or on slurm?\n", "segment_local = False\n", "ncores_local = None\n", "\n", "# Default segmentation options\n", "options = { 'cut' : 1, 'pixels_in_spot' : 3, 'howmany' : 100000 }\n", "normalise_intensities_to_monitor = True\n", "monitor_name = 'fpico6'\n", "\n", "# EXPERTS: These can be provided as papermill parameters. Users, leave these as None for now...\n", "dataroot = None\n", "analysisroot = None\n", "sample = None\n", "dataset = None"]}, {"cell_type": "code", "execution_count": null, "id": "9c13f01e-86bd-4a8f-bb75-62fb803cc2d2", "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, "id": "5726795e-91cf-40cf-b3a9-b114de84e017", "metadata": {"tags": []}, "outputs": [], "source": ["# Import needed packages\n", "import pprint\n", "import numpy as np\n", "from matplotlib import pyplot as plt\n", "\n", "import ImageD11.sinograms.dataset\n", "import ImageD11.sinograms.lima_segmenter\n", "import ImageD11.sinograms.assemble_label\n", "import ImageD11.sinograms.properties\n", "import ImageD11.nbGui.nb_utils as utils\n", "from ImageD11.nbGui import segmenter_gui\n", "\n", "%matplotlib ipympl"]}, {"cell_type": "code", "execution_count": null, "id": "a2245f5b-b3ad-404c-b52b-9fc2fcba7fea", "metadata": {"tags": []}, "outputs": [], "source": ["# Set up the file paths. Edit this if you are not at ESRF or not using the latest data policy.\n", "if dataroot is None:\n", " dataroot, analysisroot = segmenter_gui.guess_ESRF_paths() \n", "\n", "if len(dataroot)==0:\n", " print(\"Please fix in the dataroot and analysisroot folder names above!!\")\n", " \n", "print('dataroot =',repr(dataroot))\n", "print('analysisroot =',repr(analysisroot))"]}, {"cell_type": "code", "execution_count": null, "id": "f92ff08b-5ff4-4a44-8f26-4286acf529a2", "metadata": {"tags": []}, "outputs": [], "source": ["# List the samples available:\n", "segmenter_gui.printsamples(dataroot)"]}, {"cell_type": "code", "execution_count": null, "id": "187950bd-18b5-4bd4-80da-2a0c7a984b11", "metadata": {"tags": []}, "outputs": [], "source": ["# USER: Decide which sample\n", "if sample is None:\n", " sample = 'FeAu_0p5_tR_nscope'"]}, {"cell_type": "code", "execution_count": null, "id": "400a9642-81d1-4a2c-bc20-9762fcad5d65", "metadata": {"tags": []}, "outputs": [], "source": ["# List the datasets for that sample:\n", "segmenter_gui.printdatasets( dataroot, sample )"]}, {"cell_type": "code", "execution_count": null, "id": "c9f1d713-0fe0-4f32-963f-969084b0a0d3", "metadata": {"tags": []}, "outputs": [], "source": ["# USER: Decide which dataset\n", "if dataset is None:\n", " dataset = \"top_100um\""]}, {"cell_type": "markdown", "id": "1a329268-ba97-4405-8573-45475144c437", "metadata": {}, "source": ["## Example demo to see how a frame is segmented for one dataset:"]}, {"cell_type": "code", "execution_count": null, "id": "ad077c4b-39cc-4b90-9637-33c32f12e364", "metadata": {"tags": []}, "outputs": [], "source": ["# create ImageD11 dataset object\n", "ds = ImageD11.sinograms.dataset.DataSet(dataroot=dataroot,\n", " analysisroot=analysisroot,\n", " sample=sample,\n", " dset=dataset,\n", " detector=detector,\n", " omegamotor=omegamotor,\n", " dtymotor=dtymotor\n", " )\n", "ds.import_all() # Can use scans = [f'{scan}.1' for scan in range(1,102)] )\n", "ds.maskfile = maskfile\n", "if e2dxfile is not None:\n", " ds.e2dxfile = e2dxfile\n", " ds.e2dyfile = e2dyfile\n", "else:\n", " ds.detectorh5 = detectorh5\n", "ds.save()"]}, {"cell_type": "code", "execution_count": null, "id": "106c6c7f-5e18-4cd7-b9a2-ca27ead7531f", "metadata": {"tags": []}, "outputs": [], "source": ["ui = segmenter_gui.SegmenterGui(ds, **options )"]}, {"cell_type": "markdown", "id": "601cb925-c1a5-469f-a1fa-7474eaba718e", "metadata": {}, "source": ["**IMPORTANT NOTE**\n", "\n", "If you changed the segmentation parameters from the defaults, you **MUST** manually update them to match in the first cell under `options = {'cut': ...`\n", "\n", "If you do not do this, **Papermill** (batch processing other layers) will **not** use your updated values!"]}, {"cell_type": "code", "execution_count": null, "id": "70aa24d9-2df8-4a04-8cb7-0ea394217abc", "metadata": {"tags": []}, "outputs": [], "source": ["options = ui.getopts()"]}, {"cell_type": "markdown", "id": "4d605405-5ff6-4fcf-a963-0a476b4c287e", "metadata": {}, "source": ["# Sparse file creation"]}, {"cell_type": "code", "execution_count": null, "id": "81929009-7445-434a-b19e-57bcd9e3e6a4", "metadata": {"tags": []}, "outputs": [], "source": ["# create batch file to send to SLURM cluster\n", "sbat = ImageD11.sinograms.lima_segmenter.setup(ds.dsfile, **ui.getopts(), pythonpath=PYTHONPATH)\n", "if sbat is None:\n", " raise ValueError(\"This scan has already been segmented!\")\n", "print(sbat)"]}, {"cell_type": "code", "execution_count": null, "id": "3827f616-bfae-45c1-969c-24da93886a4e", "metadata": {"tags": []}, "outputs": [], "source": ["if segment_local:\n", " ImageD11.sinograms.lima_segmenter.sbatchlocal(sbat, cores=ncores_local)\n", "else:\n", " utils.slurm_submit_and_wait(sbat, 60)"]}, {"cell_type": "markdown", "id": "03b30383-cd8a-4724-bb8c-6a6402bd65ba", "metadata": {}, "source": ["# Peak labeling"]}, {"cell_type": "code", "execution_count": null, "id": "5de23264-4c22-43fe-8be6-8cc54039ea2d", "metadata": {"tags": []}, "outputs": [], "source": ["# label sparse peaks\n", "\n", "ImageD11.sinograms.assemble_label.main(ds.dsfile)"]}, {"cell_type": "code", "execution_count": null, "id": "ddb029cd-7f66-4c91-abee-5f1723303360", "metadata": {"tags": []}, "outputs": [], "source": ["# generate peaks table\n", "\n", "ImageD11.sinograms.properties.main(ds.dsfile, options={'algorithm': 'lmlabel', 'wtmax': 70000, 'save_overlaps': False})"]}, {"cell_type": "markdown", "id": "39fefff8-5abe-4a47-8d7d-d2d38ce1d90f", "metadata": {}, "source": ["# Intensity normalisation\n", "You can optionally normalise your observed intensities to a monitor column, such as a pico, if you had one in the beam path."]}, {"cell_type": "code", "execution_count": null, "id": "a49354c5-78d3-487d-b6f5-633707368f0e", "metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained')\n", "im, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)\n", "pcm = ax.pcolormesh(om_edges, dty_edges, im.T)\n", "ax.set(xlabel=r'$\\omega~(\\degree)$', ylabel='dty', title='Un-normalised sinogram of all 2D peaks')\n", "cax = fig.colorbar(pcm, ax=ax, label='log(intensity)')\n", "plt.show()"]}, {"cell_type": "markdown", "id": "e79140ea-33a1-4951-8a7a-4682c818d3a3", "metadata": {}, "source": ["Let's look at an image of the monitor signal across (dty, omega)"]}, {"cell_type": "code", "execution_count": null, "id": "7f114ddc-a8ed-4709-9cf6-343ddcaf298d", "metadata": {}, "outputs": [], "source": ["if normalise_intensities_to_monitor:\n", " monitor_per_frame = ds.get_monitor(monitor_name)\n", "\n", " fig, ax = plt.subplots(layout='constrained')\n", " pcm = ax.pcolormesh(om_edges, dty_edges, monitor_per_frame)\n", " ax.set(xlabel=r'$\\omega~(\\degree)$', ylabel='dty', title='Monitor column')\n", " cax = fig.colorbar(pcm, ax=ax, label='Monitor')\n", " plt.show()"]}, {"cell_type": "markdown", "id": "420d4f5a-035c-4c92-b81f-dfdba03f1d9f", "metadata": {}, "source": ["To normalise to a monitor signal, we need to choose a \"reference\" monitor value that we scale to.\n", "A good choice may be `np.mean(monitor_per_frame)`\n", "\n", "We then compute `scale_factor_per_frame = np.mean(monitor_per_frame) / monitor_per_frame` \n", "We then multiply the observed intensities by `scale_factor_per_frame`\n", "\n", "You can choose which function to use to generate the \"reference\" monitor value, for example:\n", "\n", "`ds.set_monitor(monitor_name='fpico6', ref_value_func=np.mean)`"]}, {"cell_type": "code", "execution_count": null, "id": "2651fada-724f-4387-9976-181989bd59b7", "metadata": {}, "outputs": [], "source": ["if normalise_intensities_to_monitor:\n", " # ensure no monitor currently set\n", " ds.monitor = None\n", " ds.monitor_ref = None\n", " ds.reset_peaks_cache()\n", "\n", " fig, ax = plt.subplots(layout='constrained')\n", " im, om_edges, dty_edges = ds.sinohist(ds.pk2d['sum_intensity'], ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)\n", " ax.plot(dty_edges, im.sum(axis=0), label='before scaling')\n", " \n", " # here we set the monitor\n", " ds.set_monitor(monitor_name, ref_value_func=np.mean)\n", "\n", " im, om_edges, dty_edges = ds.sinohist(ds.pk2d['sum_intensity'], ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)\n", " ax.plot(dty_edges, im.sum(axis=0), label='after scaling')\n", " ax.legend()\n", " ax.set(xlabel='dty', ylabel='intensity', title='Before vs after setting monitor')\n", " plt.show()\n", " \n", " # save the choice of monitor to disk\n", " ds.save()"]}, {"cell_type": "markdown", "id": "3db1c3e1-e812-4098-a3ab-a7a10b7cab4c", "metadata": {}, "source": ["# Finished segmenting!\n", "\n", "You can now choose between two different indexing routes: tomographic (tomo) and point-by-point (pbp). \n", "Tomo gives you better grain shapes, but can't handle highly deformed samples. \n", "Point-by-point can only give you convex grain shapes (less accurate) but can handle high levels of deformation. \n", "Both techniques will join back together during the strain refinement stage (notebook 3). \n", "Therefore notebooks 4 and onwards should work from either the tomo or pbp route."]}], "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": 5}