NXmx reader: derive missing beam centre, distance and pixel size from the module geometry; accept micron units

NXmx makes beam_center_x/y, distance and x_pixel_size optional - the detector
module's geometry places the detector. A file that states none of them (as
DIALS dxtbx.any2nexus writes it) was refused. Now, when absent, they are taken
from the first NXdetector_module (found by its fast_pixel_direction, whatever
the group is called): pixel (0, 0) is the pixel direction's offset plus the
translations along its depends_on chain, the beam centre is where +z meets the
module plane (in image pixels, data_origin added), the distance is the
perpendicular distance to that plane, the pixel size the fast step. Rotations
are left to the existing chain reader, so a tilted file round-trips exactly.

Length units are parsed in one place (NXmxLengthUnit_m), used by the master
reader and the module reader alike, and now accept m/mm/um, the micro sign and
Greek mu, micron(s) and spelled-out forms; sensor_thickness in "microns" was
refused before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3
(cherry picked from commit a1926aea754adb6ce6c3455f54ccaddd61fbb0de)
This commit is contained in:
leonarski_f committed 2026-11-21 13:54:05 +01:00
1 parent 441f020a2b
commit 9049ad66ec
5 files changed
+252 -26

No files matched your search

+6
View File
@@ -682,6 +682,12 @@ into the master file:
* **Units** are written as the HDF5 `units` attribute on the dataset (e.g. `m`, `eV`, `deg`,
`Angstrom`, `Angstrom^-1`, `Angstrom^2`, `pixel`, `s`).
* **Reading NXmx written elsewhere.** A length may be in any of `m`, `mm`, `um`/`µm`/`micron(s)`
(and their spelled-out forms); no unit means metres. `beam_center_x`/`_y`, `distance` and
`x_pixel_size` are optional in NXmx: when a file leaves them out (DIALS `dxtbx.any2nexus` does),
they are derived from the first NXdetector_module's geometry - its `fast_pixel_direction`,
`slow_pixel_direction`, their `offset` and the `depends_on` chain - as the point where the beam
meets the module plane, the distance to that plane and the fast pixel step.
* **Sentinels.** Missing per-image values are `NaN` (floats) or `-1`/`0` (integer indices); image
pixels use `INTx_MIN` / `UINTx_MAX`.
* **Master vs data file.** In legacy/VDS formats the analysis arrays physically live in the data
+32 -18
View File
@@ -203,15 +203,7 @@ std::string ResolveRelativeToMaster(const std::string &directory,
float LengthUnitFactor(HDF5DataSet &dataset, const std::string &name) {
if (!dataset.AttrExists("units"))
return 1.0f;
const std::string units = dataset.ReadAttrStr("units");
if (units == "m")
return 1.0f;
if (units == "mm")
return 1e-3f;
if (units == "um")
return 1e-6f;
throw JFJochException(JFJochExceptionCategory::HDF5, name + ": unknown length unit " + units);
return static_cast<float>(NXmxLengthUnit_m(dataset.ReadAttrStr("units"), name));
}
// The sample temperature, in K. NXmx states its unit; an undeclared one means K, as every DECTRIS master
@@ -245,11 +237,11 @@ float ReadLength_m(HDF5Object &file, const std::string &name) {
// firmware release-2020.2.1 through release-2024.1.1 - all of them write detector_distance and
// countrate_correction_count_cutoff beside the NXmx names). So this can never change what a
// modern file reads. ReadIntWithLegacyFallback below is the same arrangement for saturation_value.
float ReadLengthWithFallback_m(HDF5Object &file, const std::vector<std::string> &names) {
std::optional<float> ReadLengthWithFallback_m(HDF5Object &file, const std::vector<std::string> &names) {
for (const auto &name: names)
if (file.Exists(name))
return ReadLength_m(file, name);
throw JFJochException(JFJochExceptionCategory::HDF5, "Cannot find " + names.front());
return std::nullopt;
}
int64_t ReadIntWithLegacyFallback(HDF5Object &file, const std::string &nxmx, const std::string &legacy) {
@@ -885,13 +877,32 @@ HDF5MetadataSource::OpenResult HDF5MetadataSource::Open(const std::string &filen
}
dataset->experiment.SampleTemperature_K(ReadSampleTemperature_K(*master_file));
dataset->experiment.BeamX_pxl(master_file->GetFloat("/entry/instrument/detector/beam_center_x"));
dataset->experiment.BeamY_pxl(master_file->GetFloat("/entry/instrument/detector/beam_center_y"));
// NXmx makes beam_center_x/y, distance and x_pixel_size optional: the detector module's geometry is
// what places the detector. A file that states none of them (DIALS dxtbx.any2nexus writes none) is
// read from that geometry instead.
std::optional<NXmxModuleGeometry> module_geometry;
auto from_module = [&]() -> const NXmxModuleGeometry & {
if (!module_geometry) {
module_geometry = ReadNXmxModuleGeometry(*master_file);
Logger("HDF5Reader").Info("Geometry from the NXmx detector module: beam {:.2f} {:.2f} px, "
"distance {:.2f} mm, pixel {:.4f} mm",
module_geometry->beam_x_pxl, module_geometry->beam_y_pxl,
module_geometry->distance_m * 1e3f, module_geometry->pixel_size_m * 1e3f);
}
return *module_geometry;
};
float det_distance = ReadLengthWithFallback_m(*master_file,
{"/entry/instrument/detector/distance",
"/entry/instrument/detector/detector_distance",
"/entry/instrument/detector_distance"});
if (master_file->Exists("/entry/instrument/detector/beam_center_x")) {
dataset->experiment.BeamX_pxl(master_file->GetFloat("/entry/instrument/detector/beam_center_x"));
dataset->experiment.BeamY_pxl(master_file->GetFloat("/entry/instrument/detector/beam_center_y"));
} else
dataset->experiment.BeamX_pxl(from_module().beam_x_pxl).BeamY_pxl(from_module().beam_y_pxl);
const auto file_distance = ReadLengthWithFallback_m(*master_file,
{"/entry/instrument/detector/distance",
"/entry/instrument/detector/detector_distance",
"/entry/instrument/detector_distance"});
float det_distance = file_distance ? file_distance.value() : from_module().distance_m;
if (det_distance < 0.001)
det_distance = 0.1; // Set to 100 mm, if det distance is less than 1 mm
dataset->experiment.DetectorDistance_mm(det_distance * 1000.0);
@@ -1089,7 +1100,10 @@ HDF5MetadataSource::OpenResult HDF5MetadataSource::Open(const std::string &filen
auto detector_name = master_file->GetString("/entry/instrument/detector/description");
DetectorSetup detector = DetDECTRIS(image_size_x, image_size_y, detector_name, {});
detector.PixelSize_um(ReadLength_m(*master_file, "/entry/instrument/detector/x_pixel_size") * 1e6);
if (master_file->Exists("/entry/instrument/detector/x_pixel_size"))
detector.PixelSize_um(ReadLength_m(*master_file, "/entry/instrument/detector/x_pixel_size") * 1e6);
else
detector.PixelSize_um(from_module().pixel_size_m * 1e6);
// Whether the stored image is mirrored in Y. A file written before this was recorded is
// mirrored - that is the only thing Jungfraujoch has ever produced - so absence means true.
detector.MirrorY(master_file
+84 -8
View File
@@ -4,6 +4,8 @@
#include "NXmxModules.h"
#include <cmath>
#include <map>
#include <set>
#include "../common/JFJochException.h"
@@ -17,22 +19,96 @@ Coord ReadTranslation_px(HDF5Object &file, const std::string &path, double pixel
const auto vec = ds.ReadAttrVec("vector");
if (value.empty() || vec.size() != 3)
throw JFJochException(JFJochExceptionCategory::HDF5, path + ": not a translation");
double scale = 1.0;
if (ds.AttrExists("units")) {
const std::string units = ds.ReadAttrStr("units");
if (units == "mm")
scale = 1e-3;
else if (units == "um" || units == "microns")
scale = 1e-6;
}
const double scale = ds.AttrExists("units") ? NXmxLengthUnit_m(ds.ReadAttrStr("units"), path) : 1.0;
const double len_px = value[0] * scale / pixel_size_m;
// McStas -> internal is a half turn about z; the discrete image orientation is undone after it.
const Coord mcstas(static_cast<float>(-vec[0]), static_cast<float>(-vec[1]), static_cast<float>(vec[2]));
return delta.transpose() * (static_cast<float>(len_px) * mcstas);
}
Coord ReadCoord(const std::vector<double> &v) {
return {static_cast<float>(v[0]), static_cast<float>(v[1]), static_cast<float>(v[2])};
}
double LengthUnit_m(HDF5DataSet &ds, const std::string &attr, const std::string &path) {
return ds.AttrExists(attr) ? NXmxLengthUnit_m(ds.ReadAttrStr(attr), path) : 1.0;
}
// Where a transformation moves what depends on it, in metres (McStas): its offset, and for a translation
// its value along its vector too. A rotation's turn is not taken.
Coord TranslationPart_m(HDF5DataSet &ds, const std::string &path, bool with_value) {
Coord t(0, 0, 0);
if (ds.AttrExists("offset"))
t += ReadCoord(ds.ReadAttrVec("offset")) * static_cast<float>(LengthUnit_m(ds, "offset_units", path));
if (with_value && ds.AttrExists("transformation_type") && ds.ReadAttrStr("transformation_type") == "translation") {
std::vector<double> value;
ds.ReadVector(value);
t += ReadCoord(ds.ReadAttrVec("vector")) * static_cast<float>(value[0] * LengthUnit_m(ds, "units", path));
}
return t;
}
} // namespace
double NXmxLengthUnit_m(const std::string &units, const std::string &name) {
static const std::map<std::string, double> factors = {
{"", 1.0}, {"m", 1.0}, {"metre", 1.0}, {"meter", 1.0},
{"mm", 1e-3}, {"millimetre", 1e-3}, {"millimeter", 1e-3},
// Micro sign and Greek mu, as UTF-8 bytes (a literal would be in the compiler's code page on MSVC)
{"um", 1e-6}, {"\xc2\xb5m", 1e-6}, {"\xce\xbcm", 1e-6}, {"micron", 1e-6}, {"microns", 1e-6},
{"micrometre", 1e-6}, {"micrometer", 1e-6}};
const auto it = factors.find(units);
if (it == factors.end())
throw JFJochException(JFJochExceptionCategory::HDF5, name + ": unknown length unit " + units);
return it->second;
}
NXmxModuleGeometry ReadNXmxModuleGeometry(HDF5Object &file) {
// The module is found by what it holds, not by its name: this system calls it "module", dxtbx names it
// after its panel.
const std::string detector = "/entry/instrument/detector/";
std::string base;
for (const auto &name: file.FindLeafs(detector)) {
if (file.IsDataSet(detector + name + "/fast_pixel_direction")) {
base = detector + name + "/";
break;
}
}
if (base.empty())
throw JFJochException(JFJochExceptionCategory::HDF5,
"No beam_center_x/y, distance or x_pixel_size, and no detector module to derive them from");
HDF5DataSet fast(file, base + "fast_pixel_direction");
HDF5DataSet slow(file, base + "slow_pixel_direction");
const Coord f = ReadCoord(fast.ReadAttrVec("vector")).Normalize();
const Coord s = ReadCoord(slow.ReadAttrVec("vector")).Normalize();
std::vector<double> pixel;
fast.ReadVector(pixel);
const auto pixel_size_m = static_cast<float>(pixel[0] * LengthUnit_m(fast, "units", base));
// Pixel (0, 0) of the module: the pixel direction's own offset, then the chain it depends on.
Coord p = TranslationPart_m(fast, base, false);
std::string node = fast.AttrExists("depends_on") ? fast.ReadAttrStr("depends_on") : ".";
std::set<std::string> seen;
while ((node != ".") && !node.empty() && file.IsDataSet(node) && seen.insert(node).second) {
HDF5DataSet t(file, node);
p += TranslationPart_m(t, node, true);
node = t.AttrExists("depends_on") ? t.ReadAttrStr("depends_on") : ".";
}
// The beam runs along +z from the sample at the origin and meets the module plane at b.
const Coord n = (f % s).Normalize();
const float d = p * n;
const Coord b(0, 0, d / n.z);
const auto origin = file.ReadVector<int64_t>(base + "data_origin");
return {
.beam_x_pxl = static_cast<float>(origin[1]) + ((b - p) * f) / pixel_size_m,
.beam_y_pxl = static_cast<float>(origin[0]) + ((b - p) * s) / pixel_size_m,
.distance_m = std::fabs(d),
.pixel_size_m = pixel_size_m
};
}
std::string NXmxModuleGroup(HDF5Object &file, size_t n) {
// The index is written zero-padded to the width of the last one (module_00 ... module_15); the width is
// the one module 0 has.
+19
View File
@@ -7,6 +7,25 @@
#include "../common/DetectorOrientation.h"
#include "../writer/HDF5Objects.h"
// Metres per one `units`, a length unit as NXmx states it ("m", "mm", "um", "microns", ...). No unit means
// metres - what every DECTRIS master and everything this system writes means by one. A unit not recognised is
// refused rather than guessed at: read as metres, a length in millimetres is a silent factor of a thousand.
double NXmxLengthUnit_m(const std::string &units, const std::string &name);
// The geometry the file's first NXdetector_module states, square to the beam: where the beam (+z from the
// sample) meets the module plane, in pixels of the image (the module's data_origin added), the distance from
// the sample to that plane, and the pixel size along the fast direction. NXmx makes beam_center_x/y, distance
// and x_pixel_size optional, the module geometry being what places the detector; a file that leaves them out
// is read from here. Rotations in the chain are not taken, as ReadDetectorRotationChain in
// HDF5MetadataSource.cpp reads them separately. Throws when the file has no module.
struct NXmxModuleGeometry {
float beam_x_pxl;
float beam_y_pxl;
float distance_m;
float pixel_size_m;
};
NXmxModuleGeometry ReadNXmxModuleGeometry(HDF5Object &file);
// The group of module n, "/entry/instrument/detector/module_<n>/" with n padded as the file pads it
// (module_3 or module_03), or empty when the file has no such module.
std::string NXmxModuleGroup(HDF5Object &file, size_t n);
+111
View File
@@ -13,6 +13,7 @@
#include "../reader/JFJochSMVReader.h"
#include "../reader/JFJochXTCReader.h"
#include "../reader/MiniCBF.h"
#include "../reader/NXmxModules.h"
#include "../reader/FileNamePatterns.h"
#include "../rugnux/RugnuxDefaults.h"
#include "../compression/JFJochCompressor.h"
@@ -4193,6 +4194,116 @@ TEST_CASE("JFJochReader_DetectorTwoThetaZeroIsSquareOn", "[HDF5][Full]") {
REQUIRE(H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL) == 0);
}
TEST_CASE("JFJochReader_NXmxLengthUnits", "[HDF5]") {
CHECK(NXmxLengthUnit_m("", "x") == 1.0);
CHECK(NXmxLengthUnit_m("m", "x") == 1.0);
CHECK(NXmxLengthUnit_m("mm", "x") == 1e-3);
CHECK(NXmxLengthUnit_m("um", "x") == 1e-6);
CHECK(NXmxLengthUnit_m("\xc2\xb5m", "x") == 1e-6);
CHECK(NXmxLengthUnit_m("micron", "x") == 1e-6);
CHECK(NXmxLengthUnit_m("microns", "x") == 1e-6);
CHECK_THROWS(NXmxLengthUnit_m("furlong", "x"));
}
// NXmx makes beam_center_x/y, distance and x_pixel_size optional, the detector module being what places
// the detector. A file as DIALS dxtbx.any2nexus writes it states none of the four: the module, under a
// name of its own, has pixel directions in mm whose offset puts pixel (0, 0), and they depend on a chain
// of a zero rotation and the distance translation. Its sensor thickness is in "microns".
TEST_CASE("JFJochReader_NXmxGeometryFromModule", "[HDF5][Full]") {
const hsize_t nx = 8, ny = 6;
std::vector<uint16_t> image(nx * ny, 5);
WriteThirdPartyDataFile("module_geom_000001.h5", image, 2, ny, nx);
{
HDF5File master("module_geom_master.h5");
HDF5Group entry(master, "entry");
entry.SaveScalar("definition", "NXmx");
HDF5Group instrument(entry, "instrument");
HDF5Group beam(instrument, "beam");
beam.SaveScalar("incident_wavelength", 1.0)->Units("angstrom");
HDF5Group detector(instrument, "detector");
detector.SaveScalar("description", "synthetic");
detector.SaveScalar("sensor_material", "Si");
detector.SaveScalar("sensor_thickness", 450.0)->Units("microns");
detector.SaveScalar("count_time", 0.1);
detector.SaveScalar("saturation_value", static_cast<int64_t>(65535));
HDF5Group transformations(detector, "transformations");
transformations.SaveVector("det_z", std::vector<double>{120.0})
->Transformation("mm", ".", "detector", "", "translation", {0, 0, 1});
transformations.SaveVector("axis", std::vector<double>{0.0})
->Transformation("deg", "/entry/instrument/detector/transformations/det_z",
"detector", "", "rotation", {0, 0, -1});
HDF5Group module(detector, "panel_a");
module.SaveVector("data_origin", std::vector<int32_t>{0, 0});
module.SaveVector("data_size", std::vector<int32_t>{static_cast<int32_t>(ny), static_cast<int32_t>(nx)});
// McStas: fast -x and slow -y are the identity orientation; pixel (0, 0) at (+0.35, +0.25) mm puts
// the beam 3.5 pixels along fast and 2.5 along slow from it.
module.SaveVector("fast_pixel_direction", std::vector<double>{0.1})
->Transformation("mm", "/entry/instrument/detector/transformations/axis",
"", "", "translation", {-1, 0, 0}, {0.35, 0.25, 0.0}, "mm");
module.SaveVector("slow_pixel_direction", std::vector<double>{0.1})
->Transformation("mm", "/entry/instrument/detector/transformations/axis",
"", "", "translation", {0, -1, 0}, {0.35, 0.25, 0.0}, "mm");
HDF5Group data(entry, "data");
data.ExternalLink("module_geom_000001.h5", "/data", "data_000001");
}
{
JFJochHDF5Reader reader;
REQUIRE_NOTHROW(reader.ReadFile("module_geom_master.h5"));
const auto &x = reader.GetDataset()->experiment;
CHECK(x.GetBeamX_pxl() == Catch::Approx(3.5));
CHECK(x.GetBeamY_pxl() == Catch::Approx(2.5));
CHECK(x.GetDetectorDistance_mm() == Catch::Approx(120.0));
CHECK(x.GetDetectorSetup().GetPixelSize_mm() == Catch::Approx(0.1));
CHECK(x.GetDetectorSetup().GetSensorThickness_um() == Catch::Approx(450.0));
}
remove("module_geom_000001.h5");
remove("module_geom_master.h5");
REQUIRE(H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL) == 0);
}
// The same derivation on a master this system wrote, with the four fields taken out: the module geometry
// the writer puts in must give back the beam centre, distance and pixel size it was written from - also
// with the detector tilted, whose rotations are read separately.
TEST_CASE("JFJochReader_NXmxGeometryFromModule_RoundTrip", "[HDF5][Full]") {
DiffractionExperiment x(DetJF(1));
x.FilePrefix("module_geom_rt").ImagesPerTrigger(1).OverwriteExistingFiles(true);
x.BeamX_pxl(100.25).BeamY_pxl(200.75).DetectorDistance_mm(150)
.IncidentEnergy_keV(WVL_1A_IN_KEV)
.PoniRot1_rad(0.05).PoniRot2_rad(-0.02);
RegisterHDF5Filter();
{
StartMessage start_message;
x.FillMessage(start_message);
EndMessage end_message;
end_message.max_image_number = 0;
std::unique_ptr<NXmx> master = std::make_unique<NXmx>(start_message);
master->Finalize(end_message);
master.reset();
}
{
hid_t file = H5Fopen("module_geom_rt_master.h5", H5F_ACC_RDWR, H5P_DEFAULT);
REQUIRE(file >= 0);
for (const char *name: {"beam_center_x", "beam_center_y", "distance", "x_pixel_size"})
REQUIRE(H5Ldelete(file, (std::string("/entry/instrument/detector/") + name).c_str(), H5P_DEFAULT) >= 0);
H5Fclose(file);
}
{
JFJochHDF5Reader reader;
REQUIRE_NOTHROW(reader.ReadFile("module_geom_rt_master.h5"));
const auto &y = reader.GetDataset()->experiment;
CHECK(y.GetBeamX_pxl() == Catch::Approx(x.GetBeamX_pxl()).margin(1e-3));
CHECK(y.GetBeamY_pxl() == Catch::Approx(x.GetBeamY_pxl()).margin(1e-3));
CHECK(y.GetDetectorDistance_mm() == Catch::Approx(x.GetDetectorDistance_mm()));
CHECK(y.GetDetectorSetup().GetPixelSize_mm() == Catch::Approx(x.GetDetectorSetup().GetPixelSize_mm()));
CHECK(y.GetPoniRot1_rad() == Catch::Approx(0.05).margin(1e-6));
}
remove("module_geom_rt_master.h5");
REQUIRE(H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL) == 0);
}
// A file this system wrote states its own PONI angles twice: as the three scalars the reader takes
// them from, and as three rotations in the detector's depends_on chain. Following the chain must
// therefore skip them - applied on top of the scalars they would tilt the detector twice, which is