S3DXRD processing first step: Import P21.2 data, segment and lable#
based on S3DXRD processing first step: dataset creation, segmentation and peak labelling. Written by James Ball, Haixing Fang and Jon Wright. Modified for DESY P21.2 by Hans-Henrik König.
Before to start: download install_ImageD11_from_git.py
Read data from P21.2 to imageD11 DataSet
Segment on DESYs Maxwell HPC
Save Segmented data -> continue with the imageD11 notebooks
Source: ImageD11/nbGui/S3DXRD/0_segment_P21_data.ipynb. Shown as saved in git; the documentation build does not run it.
!pwd
File locations and names#
# input
detector = 'eiger'
omegamotor = 'hdrz1' # Rotation stage, needs to agree with fio-file
dtymotor = 'hdty1' # Rotation stage, needs to agree with fio-file
# Default segmentation options
options = {'cut': 1, 'pixels_in_spot': 3, 'howmany': 100_000}
normalise_intensities_to_monitor = True
monitor_name = 'eh3_entrance' # Intensitiy monitor, needs to agree with fio-file
fiofileroot= '/asap3/petra3/gpfs/p21.2/2026/data/11024595/raw/fio' # Path to fio files
dataroot = '/asap3/petra3/gpfs/p21.2/2026/data/11024595/raw/data/340/Eiger2' # Path to detector images
analysisroot = '/asap3/petra3/gpfs/p21.2/2026/data/11024595/processed/s3DXRD/imageD11' # Path to save dir
# Sample and layer
sample = 'Al13MgC2130s' # only requiered for result naming
dataset = 'Layer01' # only requiered for result naming
#Detector images
detectorh5 = dataroot + '/frames_master.h5'
# Mask file
maskfile = '/asap3/petra3/gpfs/p21.2/2026/data/11024595/processed/s3DXRD/imageD11/masks/hotpixels_and_BS_mask_v2.edf' # Detector mask
PYTHONPATH = None
# Maxwell account and partition
max_account="hasylab"
max_partition="pscpu"
Imports#
# Imports
import pprint
import numpy as np
from matplotlib import pyplot as plt
import h5py
import ast
import ImageD11.sinograms.dataset
import ImageD11.sinograms.lima_segmenter
import ImageD11.sinograms.assemble_label
import ImageD11.sinograms.properties
import ImageD11.nbGui.nb_utils as utils
from ImageD11.nbGui import segmenter_gui
import fabio
from pathlib import Path
#import sys
#sys.path.append(str(Path.home() / "myscripts"))
#import maxwell_helpers as mh
%matplotlib widget
Modified SegmenterGUI for P21.2 data#
# Modified segmenterGUI
import ImageD11.sparseframe
from ImageD11.nbGui.segmenter_gui import SegmenterGui
class P21SegmenterGui(SegmenterGui):
def __init__(self, dset, frame_counter_path=None, data_path="entry/data", **kwargs):
self.data_path = data_path
self.frame_counter_path = frame_counter_path
super().__init__(dset, **kwargs)
def chooseframe(self, counter):
# "scan" is a chunk name like "data_000002"
if self.scan is None:
self.scan = self.dset.scans[len(self.dset.scans) // 2]
with h5py.File(self.dset.masterfile, "r") as hin:
frames = hin[self.data_path][self.scan]
if self.idx is None:
if self.frame_counter_path is not None:
roi1 = hin[self.frame_counter_path][:]
if roi1.shape[0] != frames.shape[0]:
raise ValueError(
f"Counter length {roi1.shape[0]} does not match "
f"frame stack length {frames.shape[0]} for {self.scan}"
)
self.idx = int(np.argmax(roi1))
else:
# Fallback: just use the middle frame
self.idx = frames.shape[0] // 2
print("Using frame", self.idx, "from chunk", self.scan)
def segment_frame(self):
ds = self.dset
opts = ImageD11.sinograms.lima_segmenter.OPTIONS = (
ImageD11.sinograms.lima_segmenter.SegmenterOptions(**self.options)
)
opts.setup()
with h5py.File(ds.masterfile, "r") as hin:
frms = hin[self.data_path][self.scan]
spf = None
ref = None
for i, spf in enumerate(
ImageD11.sinograms.lima_segmenter.reader(
frms, opts.mask, opts.cut, start=self.idx
)
):
if spf is None:
print("Warning: no pixels found", self.scan, i, self.idx)
ref = frms[i + self.idx]
break
ref = frms[i + self.idx]
break
if ref is None:
ref = frms[self.idx]
if spf is None:
spi = np.zeros_like(ref)
npeaks = 0
else:
spi = spf.to_dense("intensity")
npeaks = ImageD11.sparseframe.sparse_localmax(spf)
if opts.mask is not None:
ref = ref * opts.mask
spi = spi * opts.mask
return ref, spi, npeaks
P21 helper functions#
import h5py, os
import numpy as np
from io import StringIO
def load_fio(path, use_pandas=True):
"""
Parse a timesweep-style file into:
- comments: list of strings (from %c section)
- parameters: dict (from %p section, values parsed when possible)
- data: pandas DataFrame or list-of-lists (from %d section)
Trailing lines starting with '!' after the data rows are ignored.
"""
with open(path, "r") as f:
lines = f.readlines()
comments = []
parameters = {}
# 1) Parse comments (%c) and parameters (%p)
current_section = None
for line in lines:
stripped = line.strip()
# Section switches
if stripped == "%c":
current_section = "comments"
continue
elif stripped == "%p":
current_section = "parameters"
continue
elif stripped == "%d":
current_section = None # we'll parse data separately
continue
# Skip separators / headings
if not stripped or stripped.startswith("!"):
continue
if current_section == "comments":
comments.append(line.rstrip("\n"))
elif current_section == "parameters":
if "=" in line:
key, val = line.split("=", 1)
key = key.strip()
val = val.strip()
# Try to interpret as Python literal (dict, number, etc.)
try:
parsed_val = ast.literal_eval(val)
except Exception:
parsed_val = val
parameters[key] = parsed_val
# 2) Parse data (%d section)
# Find the %d line
start = None
for i, line in enumerate(lines):
if line.strip() == "%d":
start = i
break
data = None
if start is not None:
# Column definitions like " Col 1 botjaw DOUBLE"
colnames = []
idx = start + 1
while idx < len(lines) and lines[idx].lstrip().startswith("Col"):
parts = lines[idx].strip().split()
# ["Col", "1", "botjaw", "DOUBLE"]
if len(parts) >= 3:
colnames.append(parts[2])
else:
colnames.append(f"col_{len(colnames) + 1}")
idx += 1
# The rest are data lines
data_lines = lines[idx:]
# Drop trailing lines that start with "!"
while data_lines and data_lines[-1].lstrip().startswith("!"):
data_lines.pop()
if use_pandas:
import pandas as pd
data_text = "".join(data_lines)
try:
df = pd.read_csv(
StringIO(data_text),
sep=r"\s+",
header=None
)
if colnames and len(colnames) == df.shape[1]:
df.columns = colnames
data = df
except pd.errors.EmptyDataError:
print('This file looks empty!:', path)
data = pd.DataFrame()
else:
# Pure Python: list of list of floats
parsed_rows = []
for line in data_lines:
s = line.strip()
print(s)
if not s or s.startswith("!"):
continue
row = [0.0 if x == "None" else float(x) for x in s.split()]
parsed_rows.append(row)
data = parsed_rows
return {
"comments": comments,
"parameters": parameters,
"data": data,
}
def trim_overlap(omega_raw, dty_raw, monitor_raw, keep_lo=-180.0, keep_hi=180.0):
"""Direction-aware removal of the 360.9deg overlap for snake/back-and-forth scans.
Keeps only frames with keep_lo < omega < keep_hi (one clean turn), which is the
last N frames of an up-sweep and the first N of a down-sweep.
Returns trimmed (omega, dty, monitor), the per-row start offset into the raw
stride (needed by the harvester), and nomega."""
ny, nraw = omega_raw.shape
keep = (omega_raw > keep_lo) & (omega_raw < keep_hi) # (ny, nraw) bool
counts = keep.sum(axis=1)
nomega = int(counts[0])
assert np.all(counts == nomega), \
f"rows drop unequal #frames {np.unique(counts)} -> non-rectangular; check keep_lo/keep_hi vs grid"
offs = np.argmax(keep, axis=1) # first kept frame per row
idx = offs[:, None] + np.arange(nomega)[None, :] # (ny, nomega)
assert np.all(np.take_along_axis(keep, idx, axis=1)), "kept frames are not contiguous"
omega = np.take_along_axis(omega_raw, idx, axis=1)
dty = np.take_along_axis(dty_raw, idx, axis=1)
monitor = np.take_along_axis(monitor_raw, idx, axis=1)
return omega, dty, monitor, offs, nomega
# Todo: Check the nnz handling here!
def getsparse_slice(dset, chunk_idx, frame_a, frame_b):
"""Read frames [frame_a, frame_b) from one sparse chunk file."""
path = os.path.join(dset.analysispath, dset.sparsefiles[chunk_idx])
with h5py.File(path, "r") as hin:
grp = hin[dset.limapath]
nnz_full = grp["nnz"][:]
nnz = nnz_full[frame_a:frame_b]
cum = np.concatenate([[0], np.cumsum(nnz_full)])
ps, pe = int(cum[frame_a]), int(cum[frame_b])
row = grp["row"][ps:pe]
col = grp["col"][ps:pe]
intensity = grp["intensity"][ps:pe]
return row, col, intensity, nnz
def harvest_p212(dset, monitor_name, row_offsets, outname=None):
"""
Reads p21.2 data with droping omega values larger then 360 deg.
"""
if outname is None:
outname = dset.sparsefile
ny, nomega = dset.shape # desired output: (101, 3600)
shape0, shape1 = dset.imageshape
itype = 'uint32'
# How many frames per dty step are actually in the chunk files
total_raw = int(dset.frames_per_file.sum()) # 101 × 3610 = 364610
nomega_raw = total_raw // ny # 3610 — the real chunk stride
assert len(row_offsets) == ny
assert int(np.max(row_offsets)) + nomega <= nomega_raw, "offset+nomega exceeds raw stride"
cum = np.concatenate([[0], np.cumsum(dset.frames_per_file)])
opts = {"chunks": (10000,), "maxshape": (None,),
"compression": "lzf", "shuffle": True}
with h5py.File(outname, "w") as hout:
hout.attrs["h5input"] = dset.masterfile
for i, scan in enumerate(dset.scans):
g = hout.require_group(scan)
gm = g.require_group("measurement")
if "rot" not in gm:
gm.create_dataset("rot", data=dset.omega[i, :]) # already trimmed to nomega
if "dty" not in gm:
gm.create_dataset("dty",
data=np.full(nomega, dset.dty[i, 0],
dtype=dset.dty.dtype))
if dset.monitor is not None and monitor_name not in gm:
gm.create_dataset(monitor_name, data=dset.monitor[i, :]) # already trimmed
g.attrs.update({"itype": itype, "nframes": nomega,
"shape0": shape0, "shape1": shape1})
# ── Index into chunk files using raw_offsets
f_start = i * nomega_raw + int(row_offsets[i])
f_end = f_start + nomega
chunk_idx = int(np.searchsorted(cum, f_start, side='right')) - 1
rows_l, cols_l, ints_l, nnzs_l = [], [], [], []
while chunk_idx < len(dset.frames_per_file):
c_start = int(cum[chunk_idx])
c_end = int(cum[chunk_idx + 1])
if c_start >= f_end:
break
a = max(f_start, c_start) - c_start
b = min(f_end, c_end) - c_start
row, col, intensity, nnz = getsparse_slice(dset, chunk_idx, a, b)
rows_l.append(row); cols_l.append(col)
ints_l.append(intensity); nnzs_l.append(nnz)
chunk_idx += 1
all_nnz = np.concatenate(nnzs_l)
all_row = np.concatenate(rows_l)
all_col = np.concatenate(cols_l)
all_int = np.concatenate(ints_l)
g.require_dataset("nnz", shape=(nomega,), dtype=np.uint32)
g["nnz"][:] = all_nnz
for nm, dat, dt in (("row", all_row, np.uint16),
("col", all_col, np.uint16),
("intensity", all_int, itype)):
if nm not in g:
g.create_dataset(nm, shape=(0,), dtype=dt, **opts)
g[nm].resize((len(dat),))
g[nm][:] = dat
print(scan, end=", ", flush=True)
print()
Read fio#
# read fio file
# Todo: use common fio reader
fio = load_fio(fiofileroot + '/eh3scan1_00340.fio')
print(fio['comments'])
fio['data'][:5]
# FIO data and data shapes
# We have to trim data that was recorded at more than 360°.
dty_flat = fio['data']['hdty1'].to_numpy().astype(float) # all y-positions
ny = len(np.unique(dty_flat)) # only unique y-positions
omega_flat = ((fio['data']['hdrz1(start)'] + fio['data']['hdrz1(end)']) / 2).to_numpy().astype(float) # omega positions in the middle of the frames
eh3 = fio['data']['eh3_entrance'].to_numpy() # Intensity monitor
mon_flat = np.where(eh3 == '<no-data>', np.nan, eh3).astype(float) # Intensity monitor: no-data -> nan
assert len(omega_flat) % ny == 0, "omega length not divisible by ny"
nraw = len(omega_flat) // ny # 3610, full sweep incl. overlap
omega_raw = omega_flat.reshape(ny, nraw)
dty_raw = dty_flat.reshape(ny, nraw)
monitor_raw = mon_flat.reshape(ny, nraw)
# fill invalid monitor frames (<no-data> -> NaN, or <=0) by interpolating along each dty row
bad = ~np.isfinite(monitor_raw) | (monitor_raw <= 0)
print(f"monitor: filling {bad.sum()} invalid frames of {monitor_raw.size}")
for i in range(ny):
b = bad[i]
if b.any():
assert not b.all(), f"row {i}: monitor entirely invalid"
x = np.arange(nraw)
monitor_raw[i, b] = np.interp(x[b], x[~b], monitor_raw[i, ~b])
assert np.isfinite(monitor_raw).all() and (monitor_raw > 0).all()
# Trim data
omega, dty, monitor, row_offsets, nomega = trim_overlap(omega_raw, dty_raw, monitor_raw)
assert omega.shape == dty.shape == monitor.shape == (ny, nomega)
assert omega.max() - omega.min() < 360, "span >= 360 -> guessbins would fold"
print(f"ny={ny} nraw={nraw} nomega={nomega} dropped {nraw - nomega}/row")
print(f"omega {omega.min():.2f}..{omega.max():.2f} | offsets present: {np.unique(row_offsets)}")
Read Eiger images#
# get shape of data in Eiger hdf
with h5py.File(detectorh5, "r") as f:
# create list of all image containing files belonging to this layer
scannames = sorted(f['entry/data'].keys()) # Here are the 365 scans lifing
print(f['entry/data'][scannames[0]]) # one stack of files of 1000 images
print(f'{scannames[:3]=}')
# length for each file. At least the last one will/could be diffrent
frames_per_file = [f['entry/data'][name].shape[0] for name in scannames]
# convert to np
frames_per_file = np.array(frames_per_file, dtype=int)
print(f'{frames_per_file[-3:]=}')
Create and populate ImageD11 DataSet#
# dataset file to import
dset_path = Path(analysisroot, sample, (sample + '_' + dataset), (sample + '_' + dataset + '_dataset.h5'))
if dset_path and os.path.exists(dset_path):
ds = ImageD11.sinograms.dataset.load(str(dset_path)) # This one doesn't like PosixPath
ds.imageshape = (2162, 2068)
ds.splinefile = None
print(f'Reloaded existing Dataset: {dset_path}')
else:
# make data set
ds = ImageD11.sinograms.dataset.DataSet(dataroot=dataroot,
analysisroot=analysisroot,
sample=sample,
dset=dataset,
detector=detector,
omegamotor=omegamotor, # This doesn't do anything currently.
dtymotor=dtymotor # This doesnt't do anything currently, either
)
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']
ds.shape = (ny, nomega)
print(f'{ds.shape=}')
ds.omega = omega
ds.dty = dty
# detector metadata / file references
ds.detector = "eiger" # or your detector label ## TODO: Make sure that this is not loading a hardcoded detector!
ds.masterfile = detectorh5 #"/path/to/master_or_index_file.h5"
ds.imagefiles = [f"{dataroot}/frames_{name}.h5" for name in scannames]
ds.imageshape = (2162, 2068) # Eiger 4M image size
ds.frames_per_file = frames_per_file
ds.limapath = "/entry/data/data" # whatever dataset path holds the frames in a single .h5 file
ds.maskfile = maskfile
ds.sparsefiles = [f"{name}_sparse.h5" for name in scannames] # needs to match image files
# compute sinogram bining
#ds.guessbins() # This is done below after peak harvesting.
# Intensity monitor
ds.monitor = monitor
ds.monitor_ref = float(np.nanmean(monitor[np.isfinite(monitor) & (monitor > 0)]))
# Geometry
#ds.parfile = "./geometry.par"
# Detector distortions (One of those can be choosen?)
#ds.detectorh5 = None # This is a pyFAI detector definition with per-pixel spatial-distortion map
ds.e2dxfile = None # Spatial distrotion file
ds.e2dyfile = None # Spatial distortion file
ds.splinefile = None # is not saved or loadeded
# Phases
# Number of non-zero pixels / number of peaks per frame
# This gets populated after segmentation
#ds.nnz = nnz.reshape(ny, nomega)
# peaks file
#ds.pksfile = "./analysis/peaks_table.h5"
# save (first write). Use an explicit path so we never rely on the
# save()-with-no-arg branch, which always overwrites dsfile_default.
ds.save() # later saves: always ds.save(ds.dsfile)
print(ds)
Example demo to see how a frame is segmented for one dataset:#
# Use SegmenterGui on P21.2 data
ui = P21SegmenterGui(
ds,
#scan=ds.scans[50], # e.g. "data_000002"
frame=15, # falls back to middle frame
data_path = "entry/data",
frame_counter_path = None, # set this only if you have a per-frame counter
**options
)
options = ui.getopts()
Sparse file creation#
# helper to make the slurm script work on maxwell
def patch_slurm_script(sbat, account=max_account, partition=max_partition:
"""Add missing SLURM directives to generated script."""
with open(sbat, 'r') as f:
content = f.read()
directives = f"#!/bin/bash\n#SBATCH --account={account}\n#SBATCH --partition={partition}"
content = content.replace("#!/bin/bash", directives)
with open(sbat, 'w') as f:
f.write(content)
print(f"Patched {sbat} with account={account}, partition={partition}")
return sbat
# create batch file to send to SLURM cluster
try:
sbat = ImageD11.sinograms.lima_segmenter.setup(ds.dsfile, **options, pythonpath=PYTHONPATH)
# Patch SLURM directives for Maxwell
sbat = patch_slurm_script(sbat, account="hasylab", partition="pscpu")
print(sbat)
except TypeError:
raise ValueError("This scan has already been segmented!")
utils.slurm_submit_and_wait(sbat, 60)
Peak labeling#
harvest_p212(ds, monitor_name, row_offsets)
# fresh bins from the trimmed (span < 360) omega -> guessbins takes the stable NO-FOLD path
for k in ("omega_for_bins","obincens","obinedges","ybincens","ybinedges"):
setattr(ds, k, None)
ds.guessbins()
# check peaks-frame == axis-frame
span = ds.omega.max() - ds.omega.min()
assert span < 360, f"omega span {span:.3f} >= 360 -> guessbins will fold; trim more frames"
assert abs(ds.omega_for_bins.min() - ds.obincens[0]) < ds.ostep
assert abs(ds.omega_for_bins.max() - ds.obincens[-1]) < ds.ostep
print(f"omega_for_bins {ds.omega_for_bins.min():.2f}..{ds.omega_for_bins.max():.2f} | "
f"obincens {ds.obincens[0]:.2f}..{ds.obincens[-1]:.2f} | ostep {ds.ostep:.4f} ✓")
ds.save(ds.dsfile)
# test allignment
import h5py, os
i = 1 # a down-row
with h5py.File(ds.sparsefile, "r") as h:
rot = h[ds.scans[i]]["measurement/rot"][:]
assert np.allclose(rot, ds.omega[i]), "written rot != trimmed omega -> offset mismatch"
print("row", i, "rot", rot[:2], "...", rot[-2:], " aligned OK")
# generate peaks table
ImageD11.sinograms.properties.main(ds.dsfile, options={'algorithm': 'lmlabel', 'wtmax': 70000, 'save_overlaps': False})
Intensity normalisation#
You can optionally normalise your observed intensities to a monitor column, such as a pico, if you had one in the beam path.
fig, ax = plt.subplots(layout='constrained', figsize=(10,7))
im, om_edges, dty_edges = ds.sinohist(np.log(ds.pk2d['sum_intensity']), ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)
pcm = ax.pcolormesh(om_edges, dty_edges, im.T, vmin=10)
ax.set(xlabel=r'$\omega~(\degree)$', ylabel='dty', title='Un-normalised sinogram of all 2D peaks')
cax = fig.colorbar(pcm, ax=ax, label='log(intensity)')
plt.show()
Let’s look at an image of the monitor signal across (dty, omega)
if normalise_intensities_to_monitor:
monitor_per_frame = ds.get_monitor(monitor_name)
print(monitor_per_frame.shape)
om_centers = ds.omega[0, :]
dty_centers = ds.dty[:, 0]
fig, ax = plt.subplots(layout='constrained')
pcm = ax.pcolormesh(om_centers, dty_centers, monitor_per_frame, shading='nearest')
ax.set(xlabel=r'$\omega~(\degree)$', ylabel='dty', title='Monitor column')
fig.colorbar(pcm, ax=ax, label='Monitor')
plt.show()
To normalise to a monitor signal, we need to choose a “reference” monitor value that we scale to.
A good choice may be np.mean(monitor_per_frame)
We then compute scale_factor_per_frame = np.mean(monitor_per_frame) / monitor_per_frame
We then multiply the observed intensities by scale_factor_per_frame
You can choose which function to use to generate the “reference” monitor value, for example:
ds.set_monitor(monitor_name='fpico6', ref_value_func=np.mean)
if normalise_intensities_to_monitor:
# ensure no monitor currently set
ds.monitor = None
ds.monitor_ref = None
ds.reset_peaks_cache()
fig, ax = plt.subplots(layout='constrained')
im, om_edges, dty_edges = ds.sinohist(ds.pk2d['sum_intensity'], ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)
ax.plot(dty_edges, im.sum(axis=0), label='before scaling')
# here we set the monitor
print(np.shape(monitor))
ds.monitor = monitor
ds.monitor_ref = float(np.nanmean(monitor[np.isfinite(monitor) & (monitor > 0)]))
# ds.set_monitor(monitor_name, ref_value_func=np.mean)
ds.reset_peaks_cache()
im, om_edges, dty_edges = ds.sinohist(ds.pk2d['sum_intensity'], ds.pk2d['omega'], ds.pk2d['dty'], return_edges=True)
ax.plot(dty_edges, im.sum(axis=0), label='after scaling')
ax.legend()
ax.set(xlabel='dty', ylabel='intensity', title='Before vs after setting monitor')
plt.show()
# save the choice of monitor to disk
ds.save(ds.dsfile)
Finished segmenting!#
You can now choose between two different indexing routes: tomographic (tomo) and point-by-point (pbp).
Tomo gives you better grain shapes, but can’t handle highly deformed samples.
Point-by-point can only give you convex grain shapes (less accurate) but can handle high levels of deformation.
Both techniques will join back together during the strain refinement stage (notebook 3).
Therefore notebooks 4 and onwards should work from either the tomo or pbp route.