Files
leonarski_f a63676247e 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)
(cherry picked from commit 9049ad66ec)
2026-11-24 08:43:11 +01:00

166 lines
7.7 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "NXmxModules.h"
#include <cmath>
#include <map>
#include <set>
#include "../common/JFJochException.h"
namespace {
// A translation dataset as a vector in pixels of the internal frame (x = column, y = row, z = beam).
Coord ReadTranslation_px(HDF5Object &file, const std::string &path, double pixel_size_m, const RotMatrix &delta) {
HDF5DataSet ds(file, path);
std::vector<double> value;
ds.ReadVector(value);
const auto vec = ds.ReadAttrVec("vector");
if (value.empty() || vec.size() != 3)
throw JFJochException(JFJochExceptionCategory::HDF5, path + ": not a translation");
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.
for (size_t digits = 1; digits <= 3; digits++) {
const std::string first = "/entry/instrument/detector/module_" + std::string(digits - 1, '0') + "0/";
if (file.Exists(first + "data_origin")) {
std::string index = std::to_string(n);
if (index.size() < digits)
index.insert(0, digits - index.size(), '0');
const std::string base = "/entry/instrument/detector/module_" + index + "/";
return file.Exists(base + "data_origin") ? base : "";
}
}
return "";
}
DetectorModules ReadNXmxModules(HDF5Object &file, double pixel_size_m, const DetectorOrientation &orientation) {
const RotMatrix delta = orientation.Matrix();
std::vector<DetectorModule> out;
for (size_t n = 0;; n++) {
const std::string base = NXmxModuleGroup(file, n);
if (base.empty())
break;
const auto origin = file.ReadVector<int64_t>(base + "data_origin");
const auto size = file.ReadVector<int64_t>(base + "data_size");
if (origin.size() != 2 || size.size() != 2)
throw JFJochException(JFJochExceptionCategory::HDF5, base + ": only two-dimensional modules are read");
const Coord o = ReadTranslation_px(file, base + "module_offset", pixel_size_m, delta);
const Coord f = ReadTranslation_px(file, base + "fast_pixel_direction", pixel_size_m, delta);
const Coord s = ReadTranslation_px(file, base + "slow_pixel_direction", pixel_size_m, delta);
if (std::fabs(o.z) > 1e-3 || std::fabs(f.z) > 1e-6 || std::fabs(s.z) > 1e-6)
throw JFJochException(JFJochExceptionCategory::HDF5, base + ": a module out of the detector plane is not read");
DetectorModule m;
m.y0 = origin[0];
m.x0 = origin[1];
m.height = size[0];
m.width = size[1];
m.ox = o.x;
m.oy = o.y;
m.fx = f.x;
m.fy = f.y;
m.sx = s.x;
m.sy = s.y;
// The readout axes, where the writer says (writer/NXmxModules.cpp); else the module's own array.
if (file.Exists(base + "readout_fast_axis") && file.Exists(base + "readout_slow_axis")) {
m.fast = DirectionFromName(file.GetString(base + "readout_fast_axis"));
m.slow = DirectionFromName(file.GetString(base + "readout_slow_axis"));
}
out.push_back(m);
}
if (out.size() < 2)
return {};
return DetectorModules(out);
}