def integrate_powder_parallel(
master_file: Path,
output_file: Path,
poni_file: Path,
mask_file: Path,
rot: np.ndarray,
n_points: int = 1000,
n_workers: int = 16,
unit: str = "2th_deg",
remove_spots: bool = False,
percentile: tuple = (10, 90),
camera_name: str = "eiger",
monitor_name: str = "fpico6",
translation_motor: str = "dty",
rotation_motor: str = "rot",
):
"""
Perform parallel 1D azimuthal integration reading image stacks directly
from each entry in the HDF5 master file, with normalisation by a monitor
counter.
Args:
master_file (Path): Path to the master HDF5 file containing all scan entries.
output_file (Path): Path to the output HDF5 file.
poni_file (Path): Path to the PONI calibration file.
mask_file (Path): Path to the mask file (fabio-readable).
rot (np.ndarray): Array of rotation angles.
n_points (int): Number of radial bins in the integrated pattern.
n_workers (int): Number of parallel integration threads.
unit (str): Radial unit for integration (e.g. ``"2th_deg"``, ``"q_A^-1"``).
remove_spots (bool, optional): If ``True``, use percentile-filtered integration
(:func:`azimuthal_integration_1d_filter`) to reject single-crystal Bragg
spots from each frame; otherwise plain integration is used (default ``False``).
percentile (tuple, optional): ``(low, high)`` percentile bounds passed to
:func:`azimuthal_integration_1d_filter` when *remove_spots* is ``True``
(default ``(10, 90)``).
camera_name (str, optional): Name of the detector dataset inside each HDF5
entry under ``measurement/`` (default ``"eiger"``). Change this to match
the detector name used at your beamline or facility.
monitor_name (str, optional): Name of the monitor/ion-chamber dataset inside
each HDF5 entry under ``measurement/`` used for normalisation
(default ``"fpico6"``). Change this to match the monitor channel available
at your beamline or facility.
translation_motor (str, optional): Name of the translation motor (sample
y-position) read from ``instrument/positioners/`` in each HDF5 entry
(default ``"dty"``). Change this to match the motor name at your beamline.
rotation_motor (str, optional): Name of the rotation motor dataset inside
each HDF5 entry under ``measurement/`` (default ``"rot"``). Change this
to match the rotation axis name at your beamline.
"""
t0 = time.time()
mask = fabio.open(mask_file).data
# ── Read and validate entries from master file ────────────────────────────
print("Reading entries from master file...")
valid_entries, bad_entries, dty_values = [], [], []
with h5py.File(master_file, "r") as hin:
all_entries = list(hin.keys())
for entry in tqdm(all_entries, desc="Validating entries"):
try:
_ = hin[f"{entry}/measurement/{camera_name}"].shape
_ = hin[f"{entry}/measurement/{monitor_name}"].shape
dty = float(hin[f"{entry}/instrument/positioners/{translation_motor}"][()])
valid_entries.append(entry)
dty_values.append(dty)
except KeyError as e:
print(f" ⚠ Entry {entry} missing expected dataset ({e}) — skipping")
bad_entries.append(entry)
print(f"\n✓ {len(valid_entries)}/{len(all_entries)} entries OK")
if bad_entries:
print(f"⚠ Skipping {len(bad_entries)} incomplete entries: {bad_entries}\n")
# ── Initialise output file ────────────────────────────────────────────────
with h5py.File(master_file, "r") as hin, h5py.File(output_file, "a") as hout:
if "integrated/radial" not in hout:
first_image = hin[f"{valid_entries[0]}/measurement/{camera_name}"][0].astype(
np.float32
)
tt, _, _ = azimuthal_integration_1d(
image=first_image,
poni_file=poni_file,
npt=n_points,
mask=mask,
unit=unit,
)
mascake = (
cake_integration(
np.ones_like(first_image) * 10,
poni_file,
npt_rad=n_points,
mask=mask,
)[0]
> 0
)
hout["integrated/cake_mask"] = mascake
hout["integrated/radial"] = tt
hout["integrated/radial"].attrs["unit"] = unit
if f"motors/{translation_motor}" not in hout:
hout[f"motors/{translation_motor}"] = dty_values
if f"motors/{rotation_motor}" not in hout:
hout[f"motors/{rotation_motor}"] = rot
if bad_entries and "bad_entries" not in hout:
hout["bad_entries"] = bad_entries
# ── Helper: integrate and normalise one frame ─────────────────────────────
def integrate_frame(args: tuple) -> tuple:
jj, image, monitor = args
if remove_spots:
_, itt, _ = azimuthal_integration_1d_filter(
image=image,
poni_file=poni_file,
npt=n_points,
mask=mask,
unit=unit,
percentile=percentile,
)
else:
_, itt, _ = azimuthal_integration_1d(
image=image, poni_file=poni_file, npt=n_points, mask=mask, unit=unit
)
if monitor <= 0:
print(
f" ⚠ Frame {jj}: {monitor_name} monitor value is {monitor:.4g}, skipping normalisation"
)
return jj, itt
return jj, itt / monitor
# ── Main loop over master file entries ────────────────────────────────────
for ii, entry in enumerate(valid_entries):
scan_name = f"scan_{ii:04d}"
group_path = f"integrated/{scan_name}"
with h5py.File(output_file, "r") as hout:
if group_path in hout:
print(f"Skipping {scan_name} (already done)")
continue
print(
f"\n{'='*60}\nProcessing {scan_name} — entry {entry} [{ii+1}/{len(valid_entries)}]\n{'='*60}"
)
try:
with h5py.File(master_file, "r") as hin:
images = hin[f"{entry}/measurement/{camera_name}"][:].astype(np.float32)
fpico6 = hin[f"{entry}/measurement/{monitor_name}"][:].astype(np.float64)
rot = hin[f"{entry}/measurement/{rotation_motor}"][:]
except OSError as e:
print(f" ✗ Failed to read entry {entry}: {e} — skipping")
continue
if rot[-1] < rot[0]:
images = images[::-1]
fpico6 = fpico6[::-1]
rot = rot[::-1]
# Sanity check lengths match
if len(fpico6) != len(images):
print(
f" ✗ Entry {entry}: fpico6 length {len(fpico6)} != images length {len(images)} — skipping"
)
continue
n_frames = len(images)
sinogram = np.empty((n_frames, n_points), dtype=np.float32)
with ThreadPoolExecutor(max_workers=n_workers) as pool:
futures = {
pool.submit(integrate_frame, (jj, images[jj], fpico6[jj])): jj
for jj in range(n_frames)
}
for future in tqdm(as_completed(futures), total=n_frames, desc=scan_name):
try:
jj, itt = future.result()
sinogram[jj] = itt
except Exception as e:
print(f" ✗ Frame {futures[future]} failed: {e}")
sinogram[futures[future]] = np.nan
with h5py.File(output_file, "a") as hout:
ds = hout.create_dataset(
group_path,
data=sinogram,
compression="gzip",
compression_opts=4,
chunks=(1, n_points),
)
ds.attrs["entry"] = entry
ds.attrs[translation_motor] = dty_values[ii]
ds.attrs["source"] = str(master_file)
ds.attrs[f"{monitor_name}_mean"] = float(np.mean(fpico6))
ds.attrs[f"{monitor_name}_min"] = float(np.min(fpico6))
ds.attrs[f"{monitor_name}_max"] = float(np.max(fpico6))
ds.attrs["normalised_by"] = monitor_name
ds.attrs["valid"] = True
elapsed = time.time() - t0
print(f"\nDone in {elapsed:.1f} s ({elapsed/len(valid_entries):.1f} s/scan).")