Source code for coseda.nexus.detector
"""Helpers for detector geometry metadata in NeXus."""
from __future__ import annotations
import h5py
import numpy as np
from coseda.nexus.groups import ensure_nexus_parents
from coseda.nexus.paths import SAMPLE_TRANSFORM_PATH
def _safe_dataset(group: h5py.Group, name: str, value, units: str, long_name: str) -> None:
if name in group:
del group[name]
ds = group.create_dataset(name, data=value)
ds.attrs["units"] = units
ds.attrs["long_name"] = long_name
[docs]
def write_detector_geometry(
h5file: h5py.File,
camera_length_m: float,
correction_factor: float = 1.0,
) -> None:
"""
Store camera length metadata and NXtransformations for detector placement.
- camera_length: given value from microscope (m)
- camera_length_correction: dimensionless multiplier
- camera_length_effective: corrected length (m)
- transformations/det_z: translation along +Z by corrected length
"""
if camera_length_m is None or camera_length_m <= 0:
return
if correction_factor is None or correction_factor <= 0:
correction_factor = 1.0
ensure_nexus_parents(h5file)
det_group = h5file.require_group("entry/instrument/detector")
det_group.attrs["NX_class"] = "NXdetector"
corrected = float(camera_length_m) * float(correction_factor)
_safe_dataset(det_group, "camera_length", float(camera_length_m), "m", "Given camera length")
_safe_dataset(
det_group,
"camera_length_correction",
float(correction_factor),
"1",
"Camera length correction factor",
)
_safe_dataset(det_group, "camera_length_effective", corrected, "m", "Corrected camera length")
trans_group = det_group.require_group("transformations")
trans_group.attrs["NX_class"] = "NXtransformations"
if "det_z" in trans_group:
del trans_group["det_z"]
det_z = trans_group.create_dataset("det_z", data=corrected)
det_z.attrs["transformation_type"] = "translation"
det_z.attrs["vector"] = np.array([0.0, 0.0, 1.0], dtype=np.float32)
det_z.attrs["units"] = "m"
det_z.attrs["depends_on"] = SAMPLE_TRANSFORM_PATH
det_group.attrs["depends_on"] = "/entry/instrument/detector/transformations/det_z"