{"cells": [{"cell_type": "markdown", "id": "8deabe5b", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# S3DXRD processing first step: Import P21.2 data, segment and lable\n", "\n", "based on S3DXRD processing first step: dataset creation, segmentation and peak labelling.\n", "Written by James Ball, Haixing Fang and Jon Wright. Modified for DESY P21.2 by Hans-Henrik K\u00f6nig.\n", "\n", "Before to start: download [install_ImageD11_from_git.py](https://github.com/FABLE-3DXRD/ImageD11/tree/master/ImageD11/nbGui/install_ImageD11_from_git.py)\n", "\n", "1. Read data from P21.2 to imageD11 DataSet\n", "2. Segment on DESYs Maxwell HPC\n", "3. Save Segmented data\n", "-> continue with the [imageD11 notebooks]([[https://github.com/FABLE-3DXRD/ImageD11/tree/master/ImageD11/nbGui/S3DXRD]])"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/0_segment_P21_data.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/0_segment_P21_data.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "id": "5f550bf4-f655-434d-a6ed-002b4a404124", "metadata": {}, "outputs": [], "source": ["!pwd"]}, {"cell_type": "markdown", "id": "72fdcef3-6b75-44d7-bb53-4d19b934166f", "metadata": {}, "source": ["## File locations and names"]}, {"cell_type": "code", "execution_count": null, "id": "688f0b73-ec7d-4c30-9522-2aa8c4ac2eed", "metadata": {}, "outputs": [], "source": ["# input\n", "detector = 'eiger'\n", "omegamotor = 'hdrz1' # Rotation stage, needs to agree with fio-file\n", "dtymotor = 'hdty1' # Rotation stage, needs to agree with fio-file\n", "\n", "# Default segmentation options\n", "options = {'cut': 1, 'pixels_in_spot': 3, 'howmany': 100_000}\n", "normalise_intensities_to_monitor = True\n", "monitor_name = 'eh3_entrance' # Intensitiy monitor, needs to agree with fio-file\n", "\n", "fiofileroot= '/asap3/petra3/gpfs/p21.2/2026/data/11024595/raw/fio' # Path to fio files \n", "dataroot = '/asap3/petra3/gpfs/p21.2/2026/data/11024595/raw/data/340/Eiger2' # Path to detector images\n", "analysisroot = '/asap3/petra3/gpfs/p21.2/2026/data/11024595/processed/s3DXRD/imageD11' # Path to save dir\n", " \n", "# Sample and layer\n", "sample = 'Al13MgC2130s' # only requiered for result naming\n", "dataset = 'Layer01' # only requiered for result naming\n", "#Detector images\n", "detectorh5 = dataroot + '/frames_master.h5'\n", "\n", "# Mask file\n", "maskfile = '/asap3/petra3/gpfs/p21.2/2026/data/11024595/processed/s3DXRD/imageD11/masks/hotpixels_and_BS_mask_v2.edf' # Detector mask\n", "PYTHONPATH = None\n", "\n", "# Maxwell account and partition\n", "max_account=\"hasylab\"\n", "max_partition=\"pscpu\""]}, {"cell_type": "markdown", "id": "3da84a7b-12d4-4b71-919f-bed681fc2a1b", "metadata": {}, "source": ["## Imports"]}, {"cell_type": "code", "execution_count": null, "id": "5726795e-91cf-40cf-b3a9-b114de84e017", "metadata": {"tags": []}, "outputs": [], "source": ["# Imports\n", "import pprint\n", "import numpy as np\n", "from matplotlib import pyplot as plt\n", "import h5py\n", "import ast\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", "import fabio\n", "from pathlib import Path\n", "#import sys\n", "#sys.path.append(str(Path.home() / \"myscripts\"))\n", "#import maxwell_helpers as mh\n", "\n", "%matplotlib widget"]}, {"cell_type": "markdown", "id": "b21b7cc0-2ae7-4254-ba93-998cfd7de4c8", "metadata": {}, "source": ["## Modified SegmenterGUI for P21.2 data"]}, {"cell_type": "code", "execution_count": null, "id": "e795e765-63b6-4dca-97e5-a7b0ad982840", "metadata": {"jupyter": {"source_hidden": true}}, "outputs": [], "source": ["# Modified segmenterGUI\n", "import ImageD11.sparseframe\n", "from ImageD11.nbGui.segmenter_gui import SegmenterGui\n", "\n", "\n", "class P21SegmenterGui(SegmenterGui):\n", " def __init__(self, dset, frame_counter_path=None, data_path=\"entry/data\", **kwargs):\n", " self.data_path = data_path\n", " self.frame_counter_path = frame_counter_path\n", " super().__init__(dset, **kwargs)\n", "\n", " def chooseframe(self, counter):\n", " # \"scan\" is a chunk name like \"data_000002\"\n", " if self.scan is None:\n", " self.scan = self.dset.scans[len(self.dset.scans) // 2]\n", "\n", " with h5py.File(self.dset.masterfile, \"r\") as hin:\n", " frames = hin[self.data_path][self.scan]\n", "\n", " if self.idx is None:\n", " if self.frame_counter_path is not None:\n", " roi1 = hin[self.frame_counter_path][:]\n", " if roi1.shape[0] != frames.shape[0]:\n", " raise ValueError(\n", " f\"Counter length {roi1.shape[0]} does not match \"\n", " f\"frame stack length {frames.shape[0]} for {self.scan}\"\n", " )\n", " self.idx = int(np.argmax(roi1))\n", " else:\n", " # Fallback: just use the middle frame\n", " self.idx = frames.shape[0] // 2\n", "\n", " print(\"Using frame\", self.idx, \"from chunk\", self.scan)\n", "\n", " def segment_frame(self):\n", " ds = self.dset\n", " opts = ImageD11.sinograms.lima_segmenter.OPTIONS = (\n", " ImageD11.sinograms.lima_segmenter.SegmenterOptions(**self.options)\n", " )\n", " opts.setup()\n", "\n", " with h5py.File(ds.masterfile, \"r\") as hin:\n", " frms = hin[self.data_path][self.scan]\n", "\n", " spf = None\n", " ref = None\n", " for i, spf in enumerate(\n", " ImageD11.sinograms.lima_segmenter.reader(\n", " frms, opts.mask, opts.cut, start=self.idx\n", " )\n", " ):\n", " if spf is None:\n", " print(\"Warning: no pixels found\", self.scan, i, self.idx)\n", " ref = frms[i + self.idx]\n", " break\n", " ref = frms[i + self.idx]\n", " break\n", "\n", " if ref is None:\n", " ref = frms[self.idx]\n", "\n", " if spf is None:\n", " spi = np.zeros_like(ref)\n", " npeaks = 0\n", " else:\n", " spi = spf.to_dense(\"intensity\")\n", " npeaks = ImageD11.sparseframe.sparse_localmax(spf)\n", "\n", " if opts.mask is not None:\n", " ref = ref * opts.mask\n", " spi = spi * opts.mask\n", "\n", " return ref, spi, npeaks"]}, {"cell_type": "markdown", "id": "16c5c947-f268-4d9d-b571-695c437947c4", "metadata": {}, "source": ["## P21 helper functions"]}, {"cell_type": "code", "execution_count": null, "id": "06d262af-4e43-4f31-84c2-44170deb6a8b", "metadata": {"jupyter": {"source_hidden": true}}, "outputs": [], "source": ["import h5py, os\n", "import numpy as np\n", "from io import StringIO\n", "\n", "def load_fio(path, use_pandas=True):\n", " \"\"\"\n", " Parse a timesweep-style file into:\n", " - comments: list of strings (from %c section)\n", " - parameters: dict (from %p section, values parsed when possible)\n", " - data: pandas DataFrame or list-of-lists (from %d section)\n", " Trailing lines starting with '!' after the data rows are ignored.\n", " \"\"\"\n", " with open(path, \"r\") as f:\n", " lines = f.readlines()\n", "\n", " comments = []\n", " parameters = {}\n", "\n", " # 1) Parse comments (%c) and parameters (%p)\n", " current_section = None\n", "\n", " for line in lines:\n", " stripped = line.strip()\n", "\n", " # Section switches\n", " if stripped == \"%c\":\n", " current_section = \"comments\"\n", " continue\n", " elif stripped == \"%p\":\n", " current_section = \"parameters\"\n", " continue\n", " elif stripped == \"%d\":\n", " current_section = None # we'll parse data separately\n", " continue\n", "\n", " # Skip separators / headings\n", " if not stripped or stripped.startswith(\"!\"):\n", " continue\n", "\n", " if current_section == \"comments\":\n", " comments.append(line.rstrip(\"\\n\"))\n", "\n", " elif current_section == \"parameters\":\n", " if \"=\" in line:\n", " key, val = line.split(\"=\", 1)\n", " key = key.strip()\n", " val = val.strip()\n", " # Try to interpret as Python literal (dict, number, etc.)\n", " try:\n", " parsed_val = ast.literal_eval(val)\n", " except Exception:\n", " parsed_val = val\n", " parameters[key] = parsed_val\n", "\n", " # 2) Parse data (%d section)\n", " # Find the %d line\n", " start = None\n", " for i, line in enumerate(lines):\n", " if line.strip() == \"%d\":\n", " start = i\n", " break\n", "\n", " data = None\n", "\n", " if start is not None:\n", " # Column definitions like \" Col 1 botjaw DOUBLE\"\n", " colnames = []\n", " idx = start + 1\n", " while idx < len(lines) and lines[idx].lstrip().startswith(\"Col\"):\n", " parts = lines[idx].strip().split()\n", " # [\"Col\", \"1\", \"botjaw\", \"DOUBLE\"]\n", " if len(parts) >= 3:\n", " colnames.append(parts[2])\n", " else:\n", " colnames.append(f\"col_{len(colnames) + 1}\")\n", " idx += 1\n", "\n", " # The rest are data lines\n", " data_lines = lines[idx:]\n", "\n", " # Drop trailing lines that start with \"!\"\n", " while data_lines and data_lines[-1].lstrip().startswith(\"!\"):\n", " data_lines.pop()\n", "\n", " if use_pandas:\n", " import pandas as pd\n", "\n", " data_text = \"\".join(data_lines)\n", " try:\n", " df = pd.read_csv(\n", " StringIO(data_text),\n", " sep=r\"\\s+\",\n", " header=None\n", " )\n", " if colnames and len(colnames) == df.shape[1]:\n", " df.columns = colnames\n", " data = df\n", " except pd.errors.EmptyDataError:\n", " print('This file looks empty!:', path)\n", " data = pd.DataFrame()\n", " else:\n", " # Pure Python: list of list of floats\n", " parsed_rows = []\n", " for line in data_lines:\n", " s = line.strip()\n", " print(s)\n", " if not s or s.startswith(\"!\"):\n", " continue\n", " row = [0.0 if x == \"None\" else float(x) for x in s.split()]\n", " parsed_rows.append(row)\n", " data = parsed_rows\n", "\n", " return {\n", " \"comments\": comments,\n", " \"parameters\": parameters,\n", " \"data\": data,\n", " }\n", "\n", "\n", "def trim_overlap(omega_raw, dty_raw, monitor_raw, keep_lo=-180.0, keep_hi=180.0):\n", " \"\"\"Direction-aware removal of the 360.9deg overlap for snake/back-and-forth scans.\n", " Keeps only frames with keep_lo < omega < keep_hi (one clean turn), which is the\n", " last N frames of an up-sweep and the first N of a down-sweep.\n", " Returns trimmed (omega, dty, monitor), the per-row start offset into the raw\n", " stride (needed by the harvester), and nomega.\"\"\"\n", " ny, nraw = omega_raw.shape\n", " keep = (omega_raw > keep_lo) & (omega_raw < keep_hi) # (ny, nraw) bool\n", " counts = keep.sum(axis=1)\n", " nomega = int(counts[0])\n", " assert np.all(counts == nomega), \\\n", " f\"rows drop unequal #frames {np.unique(counts)} -> non-rectangular; check keep_lo/keep_hi vs grid\"\n", " offs = np.argmax(keep, axis=1) # first kept frame per row\n", " idx = offs[:, None] + np.arange(nomega)[None, :] # (ny, nomega)\n", " assert np.all(np.take_along_axis(keep, idx, axis=1)), \"kept frames are not contiguous\"\n", " omega = np.take_along_axis(omega_raw, idx, axis=1)\n", " dty = np.take_along_axis(dty_raw, idx, axis=1)\n", " monitor = np.take_along_axis(monitor_raw, idx, axis=1)\n", " return omega, dty, monitor, offs, nomega\n", "\n", "# Todo: Check the nnz handling here!\n", "def getsparse_slice(dset, chunk_idx, frame_a, frame_b):\n", " \"\"\"Read frames [frame_a, frame_b) from one sparse chunk file.\"\"\"\n", " path = os.path.join(dset.analysispath, dset.sparsefiles[chunk_idx])\n", " with h5py.File(path, \"r\") as hin:\n", " grp = hin[dset.limapath]\n", " nnz_full = grp[\"nnz\"][:]\n", " nnz = nnz_full[frame_a:frame_b]\n", " cum = np.concatenate([[0], np.cumsum(nnz_full)])\n", " ps, pe = int(cum[frame_a]), int(cum[frame_b])\n", " row = grp[\"row\"][ps:pe]\n", " col = grp[\"col\"][ps:pe]\n", " intensity = grp[\"intensity\"][ps:pe]\n", " return row, col, intensity, nnz\n", "\n", "\n", "def harvest_p212(dset, monitor_name, row_offsets, outname=None):\n", " \"\"\"\n", " Reads p21.2 data with droping omega values larger then 360 deg.\n", " \"\"\"\n", " if outname is None:\n", " outname = dset.sparsefile\n", "\n", " ny, nomega = dset.shape # desired output: (101, 3600)\n", " shape0, shape1 = dset.imageshape\n", " itype = 'uint32'\n", "\n", " # How many frames per dty step are actually in the chunk files\n", " total_raw = int(dset.frames_per_file.sum()) # 101 \u00d7 3610 = 364610\n", " nomega_raw = total_raw // ny # 3610 \u2014 the real chunk stride\n", " assert len(row_offsets) == ny\n", " assert int(np.max(row_offsets)) + nomega <= nomega_raw, \"offset+nomega exceeds raw stride\"\n", "\n", " cum = np.concatenate([[0], np.cumsum(dset.frames_per_file)])\n", " opts = {\"chunks\": (10000,), \"maxshape\": (None,),\n", " \"compression\": \"lzf\", \"shuffle\": True}\n", "\n", " with h5py.File(outname, \"w\") as hout:\n", " hout.attrs[\"h5input\"] = dset.masterfile\n", "\n", " for i, scan in enumerate(dset.scans):\n", " g = hout.require_group(scan)\n", " gm = g.require_group(\"measurement\")\n", "\n", " if \"rot\" not in gm:\n", " gm.create_dataset(\"rot\", data=dset.omega[i, :]) # already trimmed to nomega\n", " if \"dty\" not in gm:\n", " gm.create_dataset(\"dty\",\n", " data=np.full(nomega, dset.dty[i, 0],\n", " dtype=dset.dty.dtype))\n", " if dset.monitor is not None and monitor_name not in gm:\n", " gm.create_dataset(monitor_name, data=dset.monitor[i, :]) # already trimmed\n", "\n", " g.attrs.update({\"itype\": itype, \"nframes\": nomega,\n", " \"shape0\": shape0, \"shape1\": shape1})\n", "\n", " # \u2500\u2500 Index into chunk files using raw_offsets\n", " f_start = i * nomega_raw + int(row_offsets[i])\n", " f_end = f_start + nomega\n", "\n", " chunk_idx = int(np.searchsorted(cum, f_start, side='right')) - 1\n", "\n", " rows_l, cols_l, ints_l, nnzs_l = [], [], [], []\n", " while chunk_idx < len(dset.frames_per_file):\n", " c_start = int(cum[chunk_idx])\n", " c_end = int(cum[chunk_idx + 1])\n", " if c_start >= f_end:\n", " break\n", " a = max(f_start, c_start) - c_start\n", " b = min(f_end, c_end) - c_start\n", " row, col, intensity, nnz = getsparse_slice(dset, chunk_idx, a, b)\n", " rows_l.append(row); cols_l.append(col)\n", " ints_l.append(intensity); nnzs_l.append(nnz)\n", " chunk_idx += 1\n", "\n", " all_nnz = np.concatenate(nnzs_l)\n", " all_row = np.concatenate(rows_l)\n", " all_col = np.concatenate(cols_l)\n", " all_int = np.concatenate(ints_l)\n", "\n", " g.require_dataset(\"nnz\", shape=(nomega,), dtype=np.uint32)\n", " g[\"nnz\"][:] = all_nnz\n", "\n", " for nm, dat, dt in ((\"row\", all_row, np.uint16),\n", " (\"col\", all_col, np.uint16),\n", " (\"intensity\", all_int, itype)):\n", " if nm not in g:\n", " g.create_dataset(nm, shape=(0,), dtype=dt, **opts)\n", " g[nm].resize((len(dat),))\n", " g[nm][:] = dat\n", "\n", " print(scan, end=\", \", flush=True)\n", " print()"]}, {"cell_type": "markdown", "id": "a4ee8a09-66e1-4732-84b1-b8aa02f9a0f5", "metadata": {}, "source": ["## Read fio"]}, {"cell_type": "code", "execution_count": null, "id": "964ac4fb-c3e6-4b4d-921e-085f3f9f01bc", "metadata": {}, "outputs": [], "source": ["# read fio file\n", "# Todo: use common fio reader\n", "fio = load_fio(fiofileroot + '/eh3scan1_00340.fio')\n", "print(fio['comments'])\n", "fio['data'][:5]"]}, {"cell_type": "code", "execution_count": null, "id": "1d932700-a27e-4a65-a1e2-b1a9ad5422df", "metadata": {}, "outputs": [], "source": ["# FIO data and data shapes\n", "# We have to trim data that was recorded at more than 360\u00b0.\n", "\n", "dty_flat = fio['data']['hdty1'].to_numpy().astype(float) # all y-positions\n", "ny = len(np.unique(dty_flat)) # only unique y-positions\n", "omega_flat = ((fio['data']['hdrz1(start)'] + fio['data']['hdrz1(end)']) / 2).to_numpy().astype(float) # omega positions in the middle of the frames\n", "eh3 = fio['data']['eh3_entrance'].to_numpy() # Intensity monitor\n", "mon_flat = np.where(eh3 == '', np.nan, eh3).astype(float) # Intensity monitor: no-data -> nan\n", "\n", "assert len(omega_flat) % ny == 0, \"omega length not divisible by ny\"\n", "nraw = len(omega_flat) // ny # 3610, full sweep incl. overlap\n", "omega_raw = omega_flat.reshape(ny, nraw)\n", "dty_raw = dty_flat.reshape(ny, nraw)\n", "monitor_raw = mon_flat.reshape(ny, nraw)\n", "\n", "# fill invalid monitor frames ( -> NaN, or <=0) by interpolating along each dty row\n", "bad = ~np.isfinite(monitor_raw) | (monitor_raw <= 0)\n", "print(f\"monitor: filling {bad.sum()} invalid frames of {monitor_raw.size}\")\n", "for i in range(ny):\n", " b = bad[i]\n", " if b.any():\n", " assert not b.all(), f\"row {i}: monitor entirely invalid\"\n", " x = np.arange(nraw)\n", " monitor_raw[i, b] = np.interp(x[b], x[~b], monitor_raw[i, ~b])\n", "assert np.isfinite(monitor_raw).all() and (monitor_raw > 0).all()\n", "\n", "# Trim data\n", "omega, dty, monitor, row_offsets, nomega = trim_overlap(omega_raw, dty_raw, monitor_raw)\n", "\n", "assert omega.shape == dty.shape == monitor.shape == (ny, nomega)\n", "assert omega.max() - omega.min() < 360, \"span >= 360 -> guessbins would fold\"\n", "print(f\"ny={ny} nraw={nraw} nomega={nomega} dropped {nraw - nomega}/row\")\n", "print(f\"omega {omega.min():.2f}..{omega.max():.2f} | offsets present: {np.unique(row_offsets)}\")"]}, {"cell_type": "markdown", "id": "9fc074df-0469-4d9d-bb10-0030daf2d425", "metadata": {}, "source": ["## Read Eiger images"]}, {"cell_type": "code", "execution_count": null, "id": "af241159-e9c4-4135-a907-b631c00c234b", "metadata": {}, "outputs": [], "source": ["# get shape of data in Eiger hdf\n", "with h5py.File(detectorh5, \"r\") as f:\n", " # create list of all image containing files belonging to this layer\n", " scannames = sorted(f['entry/data'].keys()) # Here are the 365 scans lifing\n", " print(f['entry/data'][scannames[0]]) # one stack of files of 1000 images\n", " print(f'{scannames[:3]=}')\n", " \n", " # length for each file. At least the last one will/could be diffrent\n", " frames_per_file = [f['entry/data'][name].shape[0] for name in scannames]\n", " \n", " # convert to np\n", " frames_per_file = np.array(frames_per_file, dtype=int)\n", " print(f'{frames_per_file[-3:]=}')"]}, {"cell_type": "markdown", "id": "9e166102-9212-43fc-ae4a-ff8ab93b64f4", "metadata": {}, "source": ["## Create and populate ImageD11 DataSet"]}, {"cell_type": "code", "execution_count": null, "id": "0fd1a69f-3df4-4cd4-a98b-94eb206d5200", "metadata": {}, "outputs": [], "source": ["# dataset file to import\n", "dset_path = Path(analysisroot, sample, (sample + '_' + dataset), (sample + '_' + dataset + '_dataset.h5'))\n", " \n", "if dset_path and os.path.exists(dset_path):\n", " ds = ImageD11.sinograms.dataset.load(str(dset_path)) # This one doesn't like PosixPath\n", " ds.imageshape = (2162, 2068)\n", " ds.splinefile = None\n", " print(f'Reloaded existing Dataset: {dset_path}')\n", "else:\n", " # make data set\n", " ds = ImageD11.sinograms.dataset.DataSet(dataroot=dataroot,\n", " analysisroot=analysisroot,\n", " sample=sample,\n", " dset=dataset,\n", " detector=detector,\n", " omegamotor=omegamotor, # This doesn't do anything currently.\n", " dtymotor=dtymotor # This doesnt't do anything currently, either \n", " )\n", " \n", " ds.scans = [f\"data_{i:06d}\" for i in range(1, ny+1)] # list of scan identifiers, length ny. exp: ['data_000001', 'data_000002', 'data_000003']\n", " ds.shape = (ny, nomega)\n", " print(f'{ds.shape=}')\n", " ds.omega = omega\n", " ds.dty = dty\n", " \n", " # detector metadata / file references\n", " ds.detector = \"eiger\" # or your detector label ## TODO: Make sure that this is not loading a hardcoded detector!\n", " ds.masterfile = detectorh5 #\"/path/to/master_or_index_file.h5\"\n", " ds.imagefiles = [f\"{dataroot}/frames_{name}.h5\" for name in scannames]\n", " ds.imageshape = (2162, 2068) # Eiger 4M image size\n", " ds.frames_per_file = frames_per_file\n", " ds.limapath = \"/entry/data/data\" # whatever dataset path holds the frames in a single .h5 file\n", " ds.maskfile = maskfile\n", " ds.sparsefiles = [f\"{name}_sparse.h5\" for name in scannames] # needs to match image files\n", " \n", " # compute sinogram bining \n", " #ds.guessbins() # This is done below after peak harvesting.\n", " \n", " # Intensity monitor\n", " ds.monitor = monitor\n", " ds.monitor_ref = float(np.nanmean(monitor[np.isfinite(monitor) & (monitor > 0)]))\n", " \n", " # Geometry\n", " #ds.parfile = \"./geometry.par\"\n", " # Detector distortions (One of those can be choosen?)\n", " #ds.detectorh5 = None # This is a pyFAI detector definition with per-pixel spatial-distortion map\n", " ds.e2dxfile = None # Spatial distrotion file\n", " ds.e2dyfile = None # Spatial distortion file\n", " ds.splinefile = None # is not saved or loadeded\n", " \n", " # Phases\n", " \n", " # Number of non-zero pixels / number of peaks per frame \n", " # This gets populated after segmentation\n", " #ds.nnz = nnz.reshape(ny, nomega)\n", " \n", " # peaks file\n", " #ds.pksfile = \"./analysis/peaks_table.h5\"\n", " \n", " # save (first write). Use an explicit path so we never rely on the\n", " # save()-with-no-arg branch, which always overwrites dsfile_default.\n", " ds.save() # later saves: always ds.save(ds.dsfile)\n", " print(ds)"]}, {"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": "33cb2d35-5d0f-4c41-bc09-54a5ff00366a", "metadata": {}, "outputs": [], "source": ["# Use SegmenterGui on P21.2 data\n", "ui = P21SegmenterGui(\n", " ds,\n", " #scan=ds.scans[50], # e.g. \"data_000002\"\n", " frame=15, # falls back to middle frame\n", " data_path = \"entry/data\",\n", " frame_counter_path = None, # set this only if you have a per-frame counter\n", " **options\n", ")"]}, {"cell_type": "code", "execution_count": null, "id": "ddc92c1d-f38d-404c-8a64-e9a70e8970a1", "metadata": {}, "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": "74cc73a9-c6bf-415a-8fcc-7c71ae46c763", "metadata": {}, "outputs": [], "source": ["# helper to make the slurm script work on maxwell\n", "def patch_slurm_script(sbat, account=max_account, partition=max_partition:\n", " \"\"\"Add missing SLURM directives to generated script.\"\"\"\n", " with open(sbat, 'r') as f:\n", " content = f.read()\n", " \n", " directives = f\"#!/bin/bash\\n#SBATCH --account={account}\\n#SBATCH --partition={partition}\"\n", " content = content.replace(\"#!/bin/bash\", directives)\n", " \n", " with open(sbat, 'w') as f:\n", " f.write(content)\n", " \n", " print(f\"Patched {sbat} with account={account}, partition={partition}\")\n", " return sbat"]}, {"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", "try:\n", " sbat = ImageD11.sinograms.lima_segmenter.setup(ds.dsfile, **options, pythonpath=PYTHONPATH)\n", " # Patch SLURM directives for Maxwell\n", " sbat = patch_slurm_script(sbat, account=\"hasylab\", partition=\"pscpu\")\n", " print(sbat)\n", "except TypeError:\n", " raise ValueError(\"This scan has already been segmented!\")"]}, {"cell_type": "code", "execution_count": null, "id": "3827f616-bfae-45c1-969c-24da93886a4e", "metadata": {"tags": []}, "outputs": [], "source": ["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": "53fd5380-d025-4139-b45b-19ea48316421", "metadata": {}, "outputs": [], "source": ["harvest_p212(ds, monitor_name, row_offsets)\n", "\n", "# fresh bins from the trimmed (span < 360) omega -> guessbins takes the stable NO-FOLD path\n", "for k in (\"omega_for_bins\",\"obincens\",\"obinedges\",\"ybincens\",\"ybinedges\"):\n", " setattr(ds, k, None)\n", "ds.guessbins()\n", "\n", "# check peaks-frame == axis-frame\n", "span = ds.omega.max() - ds.omega.min()\n", "assert span < 360, f\"omega span {span:.3f} >= 360 -> guessbins will fold; trim more frames\"\n", "assert abs(ds.omega_for_bins.min() - ds.obincens[0]) < ds.ostep\n", "assert abs(ds.omega_for_bins.max() - ds.obincens[-1]) < ds.ostep\n", "print(f\"omega_for_bins {ds.omega_for_bins.min():.2f}..{ds.omega_for_bins.max():.2f} | \"\n", " f\"obincens {ds.obincens[0]:.2f}..{ds.obincens[-1]:.2f} | ostep {ds.ostep:.4f} \u2713\")\n", "\n", "ds.save(ds.dsfile)"]}, {"cell_type": "code", "execution_count": null, "id": "55002987-8862-45b5-901b-8c8e7acdfd66", "metadata": {}, "outputs": [], "source": ["# test allignment\n", "import h5py, os\n", "i = 1 # a down-row\n", "with h5py.File(ds.sparsefile, \"r\") as h:\n", " rot = h[ds.scans[i]][\"measurement/rot\"][:]\n", "assert np.allclose(rot, ds.omega[i]), \"written rot != trimmed omega -> offset mismatch\"\n", "print(\"row\", i, \"rot\", rot[:2], \"...\", rot[-2:], \" aligned OK\")"]}, {"cell_type": "code", "execution_count": null, "id": "ddb029cd-7f66-4c91-abee-5f1723303360", "metadata": {"tags": []}, "outputs": [], "source": ["# generate peaks table\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', figsize=(10,7))\n", "im, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)\n", "\n", "pcm = ax.pcolormesh(om_edges, dty_edges, im.T, vmin=10)\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", " print(monitor_per_frame.shape)\n", " om_centers = ds.omega[0, :]\n", " dty_centers = ds.dty[:, 0]\n", " \n", " fig, ax = plt.subplots(layout='constrained')\n", " pcm = ax.pcolormesh(om_centers, dty_centers, monitor_per_frame, shading='nearest')\n", " ax.set(xlabel=r'$\\omega~(\\degree)$', ylabel='dty', title='Monitor column')\n", " 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", " print(np.shape(monitor))\n", " ds.monitor = monitor \n", " ds.monitor_ref = float(np.nanmean(monitor[np.isfinite(monitor) & (monitor > 0)]))\n", " # ds.set_monitor(monitor_name, ref_value_func=np.mean)\n", " ds.reset_peaks_cache() \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(ds.dsfile)"]}, {"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."]}, {"cell_type": "code", "execution_count": null, "id": "1406d98d-3423-406c-aea4-6d39135b997f", "metadata": {}, "outputs": [], "source": []}], "metadata": {"kernelspec": {"display_name": "imageD11-env2", "language": "python", "name": "imaged11-env2"}, "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.11.15"}, "widgets": {"application/vnd.jupyter.widget-state+json": {"state": {}, "version_major": 2, "version_minor": 0}}}, "nbformat": 4, "nbformat_minor": 5}