{"cells": [{"cell_type": "markdown", "id": "8deabe5b", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# 3DXRD segmentation notebook for Frelon-ish detectors \n", "__Written by Haixing Fang, Jon Wright and James Ball__ \n", "__Date: 21/02/2025__"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/0_segment_frelon.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/0_segment_frelon.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "markdown", "id": "6835a47c-a552-4d1d-b605-1867dd631b2a", "metadata": {}, "source": ["This notebook will help you to extract the locations of diffraction peaks on your detector images. \n", "It will also merge together your 2D spots (on a stack of detector images with different omega angles). \n", "We merge across omega because we often see the same spot twice on multiple detector images. \n", "The results are saved to the PROCESSED_DATA folder of the experiment, inside the sample and dataset folders that you select within this notebook\n", "\n", "__NOTE: These notebooks are under active development\n", "They require the latest version of ImageD11 from Git to run.__ \n", "If you don't have this set up yet, you can run the below cell. \n", "It will automatically download and install ImageD11 to your home directory"]}, {"cell_type": "code", "execution_count": null, "id": "7a943975-9dc1-4b89-af44-4283350def66", "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", "\n", "# give dx/dy as tuple instead of spline\n", "# Since 2024: there is no good spline for a detector at ID11. You probably want to use an e2dx, e2dy file\n", "# You can provide this as a simple string:\n", "# splinefile = '/path/to/spline.spline'\n", "# or as a tuple of strings for e2dx/e2dy files\n", "splinefile = ('/data/id11/3dxrd/inhouse/Frelon36/frelon36_spline_20240604_dx.edf','/data/id11/3dxrd/inhouse/Frelon36/frelon36_spline_20240604_dy.edf')\n", "bgfile = None\n", "maskfile = '/data/id11/inhouse1/ewoks/detectors/files/Frelon2k_C36/mask.edf'\n", "darkfile = \"/data/id11/inhouse1/ewoks/detectors/files/Frelon2k_C36/dark_20240416.edf\"\n", "flatfile = \"/data/id11/inhouse1/ewoks/detectors/files/Frelon2k_C36/F36_Nov2023.edf\"\n", "\n", "detector = \"frelon3\" # fixme - guess this from masterfile + scan\n", "omegamotor = \"diffrz\"\n", "dtymotor = \"diffty\"\n", "\n", "# Default segmentation options\n", "options = {\n", " \"bgfile\":bgfile,\n", " \"maskfile\":maskfile,\n", " \"darkfile\":darkfile,\n", " \"flatfile\":flatfile,\n", " \"threshold\":70,\n", " \"smoothsigma\":1.0,\n", " \"bgc\":0.9,\n", " \"minpx\":3,\n", " \"m_offset_thresh\":100,\n", " \"m_ratio_thresh\":150,\n", "}\n", "normalise_intensities_to_monitor = True\n", "monitor_name = 'fpico4'\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\n", "scans = None"]}, {"cell_type": "code", "execution_count": null, "id": "2402147c-5513-4907-8ca9-76e3e252df0c", "metadata": {"tags": []}, "outputs": [], "source": ["if IMAGED11_PATH is not None:\n", " exec(open('/data/id11/nanoscope/install_ImageD11_from_git.py').read())\n", " setup_ImageD11_from_git(CHECKOUT_PATH, IMAGED11_PATH)"]}, {"cell_type": "code", "execution_count": null, "id": "9b5c1db6-5a32-4294-abef-cfc2150d24de", "metadata": {"tags": []}, "outputs": [], "source": ["import fabio\n", "import numpy as np\n", "import matplotlib.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", "from ImageD11.nbGui import nb_utils as utils\n", "from ImageD11.nbGui import segmenter_gui\n", "from ImageD11.frelon_peaksearch import worker, segment_dataset, guess_bg\n", "\n", "%matplotlib widget"]}, {"cell_type": "code", "execution_count": null, "id": "5560db3e-720d-440e-954d-6dc313f6c460", "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", "print('dataroot =',repr(dataroot))\n", "print('analysisroot =',repr(analysisroot))"]}, {"cell_type": "code", "execution_count": null, "id": "de77981e-c3bf-4a29-8944-95286831ac34", "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 = 'sample'"]}, {"cell_type": "code", "execution_count": null, "id": "2b2a72fa-ff6d-4e45-89b7-fa64adb62214", "metadata": {"tags": []}, "outputs": [], "source": ["# List the datasets for that sample:\n", "segmenter_gui.printdatasets( dataroot, sample )"]}, {"cell_type": "code", "execution_count": null, "id": "90e2aeb5-8893-4f0f-bf4f-de2c541a83df", "metadata": {"tags": []}, "outputs": [], "source": ["# USER: Decide which dataset\n", "if dataset is None:\n", " dataset = \"dataset\""]}, {"cell_type": "code", "execution_count": null, "id": "ad077c4b-39cc-4b90-9637-33c32f12e364", "metadata": {"tags": []}, "outputs": [], "source": ["# create ImageD11 dataset object\n", "\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", "ds.import_all(scans=scans)\n", "if isinstance(splinefile, (tuple, list)) and len(splinefile) == 1:\n", " # we have (\"splinefile\", )\n", " ds.splinefile = splinefile[0] # take the splinefile out of the tuple\n", "elif isinstance(splinefile, (tuple, list)):\n", " # we have (e2dx, e2dy)\n", " ds.e2dxfile, ds.e2dyfile = splinefile\n", "else:\n", " # we have \"splinefile\"\n", " ds.splinefile = splinefile\n", "ds.maskfile = maskfile\n", "ds.bgfile = bgfile\n", "ds.darkfile = darkfile\n", "ds.flatfile = flatfile\n", "ds.save()"]}, {"cell_type": "code", "execution_count": null, "id": "8822b96c-a33b-4bf2-9d95-e42d6d90e55b", "metadata": {"tags": []}, "outputs": [], "source": ["# normally not needed:\n", "\n", "# bg = guess_bg( ds )\n", "# plt.imshow(bg)\n", "# fabio.edfimage.edfimage(bg).save('bg.edf')\n", "# plt.colorbar()\n", "# ds.bgfile = 'bg.edf'"]}, {"cell_type": "code", "execution_count": null, "id": "68b22a6a-9325-40f4-af9d-945c0187ffae", "metadata": {"tags": []}, "outputs": [], "source": ["ui = segmenter_gui.FrelonSegmenterGui(ds, worker, segment_dataset, **options)"]}, {"cell_type": "code", "execution_count": null, "id": "eee00548-3a48-44d0-b4ad-e71b71de95ca", "metadata": {"tags": []}, "outputs": [], "source": ["options = ui.getopts()\n", "print(options)"]}, {"cell_type": "markdown", "id": "efafbf8b-97d0-4105-a35c-01096adaca0c", "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": "c0bded5b-b5bb-4c70-b4fd-d2815602c9d4", "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", " ax.plot(ds.omega[0], monitor_per_frame[0])\n", " ax.set(xlabel=r'$\\omega~(\\degree)$', ylabel='Intensity', title='Monitor column')\n", " plt.show()"]}, {"cell_type": "markdown", "id": "d41793ba-5be0-4e4f-8a7a-0e4bf13974f1", "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", "`segment_dataset(..., monitor_name='fpico6', monitor_ref_func=np.mean)`"]}, {"cell_type": "code", "execution_count": null, "id": "263c9bc4-0651-445b-9bc4-49718e1d13e7", "metadata": {}, "outputs": [], "source": ["# ensure that we don't normalise if you choose not to\n", "\n", "if not normalise_intensities_to_monitor:\n", " monitor_name = None\n", " # ensure no monitor currently set\n", " ds.monitor = None\n", " ds.monitor_ref = None\n", " ds.reset_peaks_cache()"]}, {"cell_type": "markdown", "id": "8cf32fdd-a76f-4c2c-af49-95faa9ac87ab", "metadata": {}, "source": ["# Segment"]}, {"cell_type": "code", "execution_count": null, "id": "87e56bf0-0cdd-4881-a975-a10d879d6054", "metadata": {"tags": []}, "outputs": [], "source": ["# now we run the segmenter on all our data\n", "\n", "cf_2d, cf_4d = segment_dataset(ds, options, scan_number=range(len(ds.scans)), monitor_name=monitor_name)"]}, {"cell_type": "code", "execution_count": null, "id": "0fa07e53-93f4-4ce9-b0e5-1da5e6a5d511", "metadata": {"tags": []}, "outputs": [], "source": ["# display some peaks\n", "f,a=plt.subplots(1,2,figsize=(12,6), layout='constrained')\n", "a[0].plot(cf_4d.f_raw,cf_4d.s_raw,'.',ms=1)\n", "a[0].set(xlabel='fast index', ylabel='slow index',aspect='equal', title='peaks on detector')\n", "a[1].plot(cf_4d.omega,cf_4d.sum_intensity,'.',ms=1)\n", "a[1].set(xlabel=r'$\\omega~(\\degree)$',ylabel='sum intensity',yscale='log',title='peaks vs omega')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "4f6fb626-a1bc-493c-b00b-d508311af0a4", "metadata": {"tags": []}, "outputs": [], "source": ["# display some peaks\n", "f,a=plt.subplots(1,2,figsize=(12,6), layout='constrained')\n", "a[0].plot(cf_4d.f_raw,cf_4d.s_raw,'.',ms=1)\n", "a[0].set(xlabel='fast index', ylabel='slow index',aspect='equal', title='peaks on detector')\n", "a[1].plot(cf_4d.dty,cf_4d.sum_intensity,'.',ms=1)\n", "a[1].set(xlabel=r'$dty$',ylabel='sum intensity',yscale='log',title='peaks vs dty')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "b9dafe51-b5a5-42d3-94d2-c0cdf4449bbd", "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained')\n", "im, om_edges, dty_edges = ds.sinohist(np.log(cf_4d.sum_intensity),cf_4d.omega, cf_4d.dty, return_edges=True)\n", "pcm = ax.pcolormesh(om_edges, dty_edges, im.T, norm='log')\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, "id": "197e8418-030b-4901-8e8f-9f8b1df7c017", "metadata": {"tags": []}, "outputs": [], "source": ["ImageD11.columnfile.colfile_to_hdf(cf_2d, ds.col2dfile)\n", "ImageD11.columnfile.colfile_to_hdf(cf_4d, ds.col4dfile)"]}, {"cell_type": "code", "execution_count": null, "id": "7085183c-1991-49b3-af09-abe119542166", "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": 5}