From 59a2f46d150b00ff752746b4725acb3b8ea089af Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Fri, 20 Nov 2026 22:33:04 +0100 Subject: [PATCH 01/24] Merged MTZ: multiplicity columns N, N(+) and N(-) The merged MTZ carries the number of observations merged into each value: N (type I) after SIGIMEAN, N(+)/N(-) after SIGI(-) where the anomalous columns are written - the labels and the integer type dials.merge gives them. The merged reflection carries the counts from the half-set accumulators (rotation and on-the-fly merges) and per hand from the anomalous table; the two places that swap the Bijvoet hands on a reindexing swap the counts with them. Centrics, which have no anomalous split, carry N(+) = N(-) = 0. Every existing column keeps its label, type and value. The synthetic merged generator carries the multiplicity it simulates and the writer tests check the new columns; the MTZ column lists in the docs are updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3 (cherry picked from commit 01a24d7b7b37f6263a950cc56af069448922df48) (cherry picked from commit 441f020a2b8896f957b87bd6b70e1ad1663db64b) --- common/Reflection.h | 4 ++++ docs/CPU_DATA_ANALYSIS_DECISIONS.md | 2 +- docs/RUGNUX_INTEGRATION.md | 7 +++--- docs/RUGNUX_TUTORIAL.md | 4 ++-- image_analysis/WriteReflections.cpp | 24 ++++++++++++------- image_analysis/scale_merge/Merge.cpp | 3 ++- .../scale_merge/ReindexAmbiguity.cpp | 1 + .../scale_merge/RotationScaleMerge.cpp | 6 ++++- .../structure_refinement/Refinement.cpp | 1 + tests/RugnuxResultFilesTest.cpp | 10 ++++---- tests/SyntheticMergedReflections.h | 1 + tests/WriteReflectionsTest.cpp | 9 ++++++- 12 files changed, 49 insertions(+), 23 deletions(-) diff --git a/common/Reflection.h b/common/Reflection.h index 6f2d45b37..7946f2aac 100644 --- a/common/Reflection.h +++ b/common/Reflection.h @@ -112,6 +112,10 @@ struct MergedReflection { // written - the ring contaminates it, it does not make it absent - and this only marks it so // a consumer that must not read the ring as crystal signal can leave it out. bool on_ice_ring = false; + // Observations merged into I, and into each Bijvoet hand of it (the MTZ N, N(+), N(-) columns). + int32_t n_obs = 0; + int32_t n_plus = 0; + int32_t n_minus = 0; bool rfree_flag = false; float F = NAN; // French-Wilson amplitude |F| (filled by ApplyFrenchWilson at end of merge) float sigmaF = NAN; // its sigma diff --git a/docs/CPU_DATA_ANALYSIS_DECISIONS.md b/docs/CPU_DATA_ANALYSIS_DECISIONS.md index 6e72d2f07..cceac4d7b 100644 --- a/docs/CPU_DATA_ANALYSIS_DECISIONS.md +++ b/docs/CPU_DATA_ANALYSIS_DECISIONS.md @@ -124,7 +124,7 @@ Everything lands in `_report.txt` section 4 (`ANISOTROPY_*` keys), in th - **Space-group symmetry** beyond centering absences is not enforced during prediction/integration unless the space group is supplied and used downstream. - **Resolution masking** is controllable, and so is every stage of ice-ring handling (§3.3, §10.10). None of it runs unless the crystal is measured to have ice, because the fixed bands are a fixed cost in unique reflections whether it does or not. - **Rotation vs still modes** differ substantially in prediction and scaling: partiality is angle-driven in rotation data, while stills are predicted within an excitation-error window that follows the run's rocking curve (§8.2) and get their partiality from the default-on per-crystal tilt post-refinement (§10.2) — or unit partiality with `--simple-stills`. -- **Amplitudes and intensities.** The merged output carries both intensities (mmCIF `intensity_meas`, MTZ `IMEAN`/`SIGIMEAN`) and French–Wilson amplitudes (mmCIF `F_meas_au`, MTZ `F`/`SIGF`; §10.8), so a downstream program can refine against either. +- **Amplitudes and intensities.** The merged output carries both intensities (mmCIF `intensity_meas`, MTZ `IMEAN`/`SIGIMEAN`, with the multiplicity in `N`) and French–Wilson amplitudes (mmCIF `F_meas_au`, MTZ `F`/`SIGF`; §10.8), so a downstream program can refine against either. --- diff --git a/docs/RUGNUX_INTEGRATION.md b/docs/RUGNUX_INTEGRATION.md index d07ece54f..11cc30212 100644 --- a/docs/RUGNUX_INTEGRATION.md +++ b/docs/RUGNUX_INTEGRATION.md @@ -65,11 +65,12 @@ the `.hkl` worth knowing before using it: column types CCP4 programs dispatch on: ``` -H K L IMEAN SIGIMEAN I(+) SIGI(+) I(-) SIGI(-) F SIGF F(+) SIGF(+) F(-) SIGF(-) FreeR_flag -H H H J Q K M K M F Q G L G L I +H K L IMEAN SIGIMEAN N I(+) SIGI(+) I(-) SIGI(-) N(+) N(-) F SIGF F(+) SIGF(+) F(-) SIGF(-) FreeR_flag +H H H J Q I K M K M I I F Q G L G L I ``` -`F` is the French–Wilson amplitude. The header carries the determined space group, the refined cell +`F` is the French–Wilson amplitude; `N` is the number of observations merged into `IMEAN`, and +`N(+)`/`N(-)` into each Bijvoet hand (the multiplicity columns `dials.merge` writes). The header carries the determined space group, the refined cell and the wavelength, on a dataset of its own behind the reserved `HKL_base`, which is where the MTZ format puts them. `_unmerged.mtz` reads 1.54187 Å (CCP4's Cu Kα default) under `mtzinfo` and is not wrong: its columns sit on `HKL_base` deliberately, as POINTLESS expects, and the diff --git a/docs/RUGNUX_TUTORIAL.md b/docs/RUGNUX_TUTORIAL.md index ddc052d34..dcda19a53 100644 --- a/docs/RUGNUX_TUTORIAL.md +++ b/docs/RUGNUX_TUTORIAL.md @@ -304,8 +304,8 @@ Absorption is corrected only by the empirical surface a rotation run fits and ke - Merging is **on by default** (`--no-merge` disables it). The merged reflections are written in **three** formats — each has its uses downstream: - `.mtz` — CCP4 MTZ for the CCP4 / phenix reflection tools. The columns are - `H K L IMEAN SIGIMEAN I(+) SIGI(+) I(-) SIGI(-) F SIGF F(+) SIGF(+) F(-) SIGF(-) FreeR_flag` - (`F` is the French–Wilson amplitude); the anomalous columns are present whenever any reflection + `H K L IMEAN SIGIMEAN N I(+) SIGI(+) I(-) SIGI(-) N(+) N(-) F SIGF F(+) SIGF(+) F(-) SIGF(-) FreeR_flag` + (`F` is the French–Wilson amplitude, `N` the number of observations merged into each value); the anomalous columns are present whenever any reflection carries a Bijvoet split — a rotation run always does, a stills run only with `-A`. - `.cif` — mmCIF, for deposition and as the self-describing native format (also carries the merging statistics, ISa, twinning and radiation-damage indicators). diff --git a/image_analysis/WriteReflections.cpp b/image_analysis/WriteReflections.cpp index e36b5dfff..8d0b3f5a7 100644 --- a/image_analysis/WriteReflections.cpp +++ b/image_analysis/WriteReflections.cpp @@ -205,6 +205,7 @@ struct MergedOutRow { int h = 0, k = 0, l = 0; float Imean = NAN, sImean = NAN, Ip = NAN, sIp = NAN, Im = NAN, sIm = NAN; float Fmean = NAN, sFmean = NAN, Fp = NAN, sFp = NAN, Fm = NAN, sFm = NAN; + int n = 0, np = 0, nm = 0; // observations merged into Imean, Ip and Im // The value written into FreeR_flag: 0 for the TEST set, 1 for the working set. That is the CCP4 // convention the column NAME belongs to - CCP4's own freerflag writes 0..19 with 0 as the ~5% // test bin, and REFMAC's default FREE 0 reads it that way, so the opposite (phenix/CNS) numbering @@ -233,7 +234,7 @@ std::vector BuildMergedRows(const std::vector &r for (const auto& r : reflections) out_rows.push_back({r.h, r.k, r.l, r.I, r.sigma, r.I_plus, r.sigma_plus, r.I_minus, r.sigma_minus, r.F, r.sigmaF, r.F_plus, r.sigmaF_plus, r.F_minus, - r.sigmaF_minus, r.rfree_flag ? 0 : 1}); + r.sigmaF_minus, r.n_obs, r.n_plus, r.n_minus, r.rfree_flag ? 0 : 1}); } else { // Anomalous: group the two mates by their (shared) Friedel-merged ASU representative, then form // IMEAN / F as their inverse-variance Friedel mean. A single generator gives both the group key @@ -243,6 +244,7 @@ std::vector BuildMergedRows(const std::vector &r int h = 0, k = 0, l = 0; float Ip = NAN, sIp = NAN, Im = NAN, sIm = NAN; float Fp = NAN, sFp = NAN, Fm = NAN, sFm = NAN; + int np = 0, nm = 0; int rfree = 1; }; std::map, AnomRow> rows; @@ -251,8 +253,8 @@ std::vector BuildMergedRows(const std::vector &r AnomRow& row = rows[{key.h, key.k, key.l}]; row.h = key.h; row.k = key.k; row.l = key.l; row.rfree = r.rfree_flag ? 0 : 1; - if (key.plus) { row.Ip = r.I; row.sIp = r.sigma; row.Fp = r.F; row.sFp = r.sigmaF; } - else { row.Im = r.I; row.sIm = r.sigma; row.Fm = r.F; row.sFm = r.sigmaF; } + if (key.plus) { row.Ip = r.I; row.sIp = r.sigma; row.Fp = r.F; row.sFp = r.sigmaF; row.np = r.n_obs; } + else { row.Im = r.I; row.sIm = r.sigma; row.Fm = r.F; row.sFm = r.sigmaF; row.nm = r.n_obs; } } // Friedel-mean of the two mates by inverse variance (the single mate, if only one was measured). @@ -275,7 +277,8 @@ std::vector BuildMergedRows(const std::vector &r combine(row.Ip, row.sIp, row.Im, row.sIm, i_mean, sig_i_mean); combine(row.Fp, row.sFp, row.Fm, row.sFm, f_mean, sig_f_mean); out_rows.push_back({row.h, row.k, row.l, i_mean, sig_i_mean, row.Ip, row.sIp, row.Im, - row.sIm, f_mean, sig_f_mean, row.Fp, row.sFp, row.Fm, row.sFm, row.rfree}); + row.sIm, f_mean, sig_f_mean, row.Fp, row.sFp, row.Fm, row.sFm, + row.np + row.nm, row.np, row.nm, row.rfree}); } } return out_rows; @@ -665,13 +668,16 @@ MtzTable MergedMtzTable(const std::vector &reflections, {"native", experiment.GetSampleName(), "native", experiment.GetWavelength_A()}}; // One row per reflection in the CCP4 anomalous layout (IMEAN + I(+)/I(-), and the same split for - // the French-Wilson amplitude), which aimless / ctruncate / mtz2sca / ANODE read directly. + // the French-Wilson amplitude), which aimless / ctruncate / mtz2sca / ANODE read directly. N is the + // number of observations merged into IMEAN and N(+)/N(-) into each hand, the labels and the integer + // type dials.merge gives them. bool has_anom = true; const std::vector out_rows = BuildMergedRows(reflections, experiment, has_anom); std::vector> columns{{"H", 'H'}, {"K", 'H'}, {"L", 'H'}, - {"IMEAN", 'J'}, {"SIGIMEAN", 'Q'}}; + {"IMEAN", 'J'}, {"SIGIMEAN", 'Q'}, {"N", 'I'}}; if (has_anom) - columns.insert(columns.end(), {{"I(+)", 'K'}, {"SIGI(+)", 'M'}, {"I(-)", 'K'}, {"SIGI(-)", 'M'}}); + columns.insert(columns.end(), {{"I(+)", 'K'}, {"SIGI(+)", 'M'}, {"I(-)", 'K'}, {"SIGI(-)", 'M'}, + {"N(+)", 'I'}, {"N(-)", 'I'}}); columns.insert(columns.end(), {{"F", 'F'}, {"SIGF", 'Q'}}); // F: the French-Wilson amplitude if (has_anom) columns.insert(columns.end(), {{"F(+)", 'G'}, {"SIGF(+)", 'L'}, {"F(-)", 'G'}, {"SIGF(-)", 'L'}}); @@ -680,9 +686,9 @@ MtzTable MergedMtzTable(const std::vector &reflections, m.columns.push_back({label, type, type == 'H' ? 0 : 1, {}}); for (const auto &row : out_rows) { std::vector v{static_cast(row.h), static_cast(row.k), static_cast(row.l), - row.Imean, row.sImean}; + row.Imean, row.sImean, static_cast(row.n)}; if (has_anom) - v.insert(v.end(), {row.Ip, row.sIp, row.Im, row.sIm}); + v.insert(v.end(), {row.Ip, row.sIp, row.Im, row.sIm, static_cast(row.np), static_cast(row.nm)}); v.insert(v.end(), {row.Fmean, row.sFmean}); if (has_anom) v.insert(v.end(), {row.Fp, row.sFp, row.Fm, row.sFm}); diff --git a/image_analysis/scale_merge/Merge.cpp b/image_analysis/scale_merge/Merge.cpp index 6ee398eb2..cf69a1229 100644 --- a/image_analysis/scale_merge/Merge.cpp +++ b/image_analysis/scale_merge/Merge.cpp @@ -568,7 +568,8 @@ std::vector MergeOnTheFly::ExportIntensities() { .I_half = {NAN, NAN}, .sigma_half = {NAN, NAN}, .d = accum.d, - .on_ice_ring = accum.on_ice_ring + .on_ice_ring = accum.on_ice_ring, + .n_obs = static_cast(accum.n_half[0] + accum.n_half[1]) }; if (accum.exists_half[0] && accum.exists_half[1]) { diff --git a/image_analysis/scale_merge/ReindexAmbiguity.cpp b/image_analysis/scale_merge/ReindexAmbiguity.cpp index 8089346dc..53b1c60e4 100644 --- a/image_analysis/scale_merge/ReindexAmbiguity.cpp +++ b/image_analysis/scale_merge/ReindexAmbiguity.cpp @@ -101,6 +101,7 @@ std::vector ReindexMergedIntoAsu(const std::vector(a.nh[0] + a.nh[1]); if (a.nh[0] + a.nh[1] > 0 && a.swh[0] > 0.0 && a.swh[1] > 0.0) { for (int i = 0; i < 2; ++i) { mr.I_half[i] = static_cast(a.swIh[i] / a.swh[i]); @@ -6662,7 +6663,7 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool // N_uniq. ---- sub("statistics"); const int n_shells = report_shell_count; - struct AnomExport { float Ip = NAN, sIp = NAN, Im = NAN, sIm = NAN; }; + struct AnomExport { float Ip = NAN, sIp = NAN, Im = NAN, sIm = NAN; int32_t np = 0, nm = 0; }; std::unordered_map anom_export; // filled by the run's own table only auto statistics_over = [&](const std::vector &merged, float grid_d_min, float grid_d_max, float d_max_label, double d_floor, @@ -7031,6 +7032,8 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool const double swp = a.sw[0][0] + a.sw[0][1], swm = a.sw[1][0] + a.sw[1][1]; const double swIp = a.swI[0][0] + a.swI[0][1], swIm = a.swI[1][0] + a.swI[1][1]; AnomExport ex; + ex.np = a.nh[0][0] + a.nh[0][1]; + ex.nm = a.nh[1][0] + a.nh[1][1]; if (swp > 0.0) { ex.Ip = static_cast(swIp / swp); ex.sIp = static_cast(1.0 / std::sqrt(swp)); } if (swm > 0.0) { ex.Im = static_cast(swIm / swm); ex.sIm = static_cast(1.0 / std::sqrt(swm)); } if (own_table && (std::isfinite(ex.Ip) || std::isfinite(ex.Im))) anom_export[fkey] = ex; @@ -7275,6 +7278,7 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool if (it == anom_export.end()) continue; r.I_plus = it->second.Ip; r.sigma_plus = it->second.sIp; r.I_minus = it->second.Im; r.sigma_minus = it->second.sIm; + r.n_plus = it->second.np; r.n_minus = it->second.nm; } } diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index ca17fdff9..86024f63c 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -4938,6 +4938,7 @@ std::vector ExpandToSubgroup(const std::vector END blocks -> CBOR -> writer, WritePlacedModel(WithJungfraujoch(TestModel(), gemmi::SoftwareItem::Phasing), TEST_CELL, experiment.GetSpaceGroupOrP1(), original, logger); end.placed_model = PlacedModelFromStructure(TestModel(), TEST_CELL, experiment.GetSpaceGroupOrP1().xhm()); - REQUIRE(end.merged->columns.size() == 16); // with the anomalous columns + REQUIRE(end.merged->columns.size() == 19); // with the anomalous columns and the three N CHECK(end.merged->columns[0].values.size() == reflections.size()); CHECK(end.placed_model->atom_name.size() == 2 * 3 * 6 + 2); @@ -195,9 +195,9 @@ TEST_CASE("RugnuxResultFiles: rugnux's outputs -> END blocks -> CBOR -> writer, CHECK(ReadFile(written + "_model.pdb") == ReadFile(original + "_model.pdb")); const gemmi::Mtz mtz = gemmi::read_mtz_file(written + ".mtz"); - CHECK(Labels(mtz) == std::vector{"H", "K", "L", "IMEAN", "SIGIMEAN", "I(+)", "SIGI(+)", "I(-)", - "SIGI(-)", "F", "SIGF", "F(+)", "SIGF(+)", "F(-)", "SIGF(-)", - "FreeR_flag"}); + CHECK(Labels(mtz) == std::vector{"H", "K", "L", "IMEAN", "SIGIMEAN", "N", "I(+)", "SIGI(+)", "I(-)", + "SIGI(-)", "N(+)", "N(-)", "F", "SIGF", "F(+)", "SIGF(+)", "F(-)", + "SIGF(-)", "FreeR_flag"}); CHECK(mtz.nreflections == static_cast(reflections.size())); CHECK(mtz.datasets.back().wavelength == Catch::Approx(experiment.GetWavelength_A()).epsilon(1e-5)); const gemmi::Mtz maps_mtz = gemmi::read_mtz_file(written + "_maps.mtz"); @@ -236,7 +236,7 @@ TEST_CASE("RugnuxResultFiles: an existing file is kept when overwrite is off", " WriteRugnuxResultFiles(end, prefix, true, logger); const gemmi::Mtz mtz = gemmi::read_mtz_file(prefix + ".mtz"); CHECK(mtz.nreflections == 1); - CHECK(Labels(mtz) == std::vector{"H", "K", "L", "IMEAN", "SIGIMEAN", "F", "SIGF", "FreeR_flag"}); + CHECK(Labels(mtz) == std::vector{"H", "K", "L", "IMEAN", "SIGIMEAN", "N", "F", "SIGF", "FreeR_flag"}); std::filesystem::remove_all(dir); } diff --git a/tests/SyntheticMergedReflections.h b/tests/SyntheticMergedReflections.h index 395c487a5..4e8d69477 100644 --- a/tests/SyntheticMergedReflections.h +++ b/tests/SyntheticMergedReflections.h @@ -224,6 +224,7 @@ namespace jfjoch_test { const double i_merged = sum_n_i / n_obs; r.I = static_cast(i_merged); + r.n_obs = n_obs; // The error model on one observation, averaged down by the merge, then thrown off // by the error-model miscalibration. r.sigma = static_cast(std::hypot(sigma_one, p.error_model_b * i_merged) / diff --git a/tests/WriteReflectionsTest.cpp b/tests/WriteReflectionsTest.cpp index c47f310a0..289ec395a 100644 --- a/tests/WriteReflectionsTest.cpp +++ b/tests/WriteReflectionsTest.cpp @@ -63,12 +63,19 @@ TEST_CASE("Merged MTZ: the data dataset is id 1 and carries the wavelength", "[w // The wavelength is read off the dataset the data columns belong to, so they have to be on the // data dataset and not on the base. - for (const char *label : {"IMEAN", "SIGIMEAN", "F", "SIGF", "FreeR_flag"}) { + for (const char *label : {"IMEAN", "SIGIMEAN", "N", "F", "SIGF", "FreeR_flag"}) { const gemmi::Mtz::Column *col = mtz.column_with_label(label); REQUIRE(col != nullptr); CHECK(col->dataset_id == 1); } + // N is the number of observations merged into IMEAN, an integer column as dials.merge writes it. + const gemmi::Mtz::Column *n_col = mtz.column_with_label("N"); + CHECK(n_col->type == 'I'); + for (size_t i = 0; i < reflections.size(); i++) + CHECK(mtz.data[i * mtz.columns.size() + n_col->idx] == static_cast(reflections[i].n_obs)); + CHECK(reflections.front().n_obs == std::max(2, params.multiplicity)); + // Cell and space group travel in the same header. CHECK(mtz.spacegroup != nullptr); CHECK(mtz.spacegroup->number == 96); -- 2.54.1 From a63676247ec42208c81011369cbe6e5b82e84f41 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sat, 21 Nov 2026 13:51:43 +0100 Subject: [PATCH 02/24] 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 Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3 (cherry picked from commit a1926aea754adb6ce6c3455f54ccaddd61fbb0de) (cherry picked from commit 9049ad66ec83a7a69ee8718949ecc3096b00ed2e) --- docs/HDF5.md | 6 ++ reader/HDF5MetadataSource.cpp | 50 +++++++++------ reader/NXmxModules.cpp | 92 +++++++++++++++++++++++++--- reader/NXmxModules.h | 19 ++++++ tests/JFJochReaderTest.cpp | 111 ++++++++++++++++++++++++++++++++++ 5 files changed, 252 insertions(+), 26 deletions(-) diff --git a/docs/HDF5.md b/docs/HDF5.md index fa6640edc..750e3cf08 100644 --- a/docs/HDF5.md +++ b/docs/HDF5.md @@ -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 diff --git a/reader/HDF5MetadataSource.cpp b/reader/HDF5MetadataSource.cpp index 03dfb2211..d0aefd36d 100644 --- a/reader/HDF5MetadataSource.cpp +++ b/reader/HDF5MetadataSource.cpp @@ -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(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 &names) { +std::optional ReadLengthWithFallback_m(HDF5Object &file, const std::vector &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 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 diff --git a/reader/NXmxModules.cpp b/reader/NXmxModules.cpp index 10df4b2bf..1e3a760e9 100644 --- a/reader/NXmxModules.cpp +++ b/reader/NXmxModules.cpp @@ -4,6 +4,8 @@ #include "NXmxModules.h" #include +#include +#include #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(-vec[0]), static_cast(-vec[1]), static_cast(vec[2])); return delta.transpose() * (static_cast(len_px) * mcstas); } +Coord ReadCoord(const std::vector &v) { + return {static_cast(v[0]), static_cast(v[1]), static_cast(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(LengthUnit_m(ds, "offset_units", path)); + if (with_value && ds.AttrExists("transformation_type") && ds.ReadAttrStr("transformation_type") == "translation") { + std::vector value; + ds.ReadVector(value); + t += ReadCoord(ds.ReadAttrVec("vector")) * static_cast(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 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 pixel; + fast.ReadVector(pixel); + const auto pixel_size_m = static_cast(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 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(base + "data_origin"); + return { + .beam_x_pxl = static_cast(origin[1]) + ((b - p) * f) / pixel_size_m, + .beam_y_pxl = static_cast(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. diff --git a/reader/NXmxModules.h b/reader/NXmxModules.h index 1afe71ae6..40459f743 100644 --- a/reader/NXmxModules.h +++ b/reader/NXmxModules.h @@ -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_/" 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); diff --git a/tests/JFJochReaderTest.cpp b/tests/JFJochReaderTest.cpp index 9517b96fc..29869adb0 100644 --- a/tests/JFJochReaderTest.cpp +++ b/tests/JFJochReaderTest.cpp @@ -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 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(65535)); + HDF5Group transformations(detector, "transformations"); + transformations.SaveVector("det_z", std::vector{120.0}) + ->Transformation("mm", ".", "detector", "", "translation", {0, 0, 1}); + transformations.SaveVector("axis", std::vector{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{0, 0}); + module.SaveVector("data_size", std::vector{static_cast(ny), static_cast(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{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{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 master = std::make_unique(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 -- 2.54.1 From 601594de7b595dac2d401d6b57aef90e52479fbb Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sun, 22 Nov 2026 09:19:54 +0100 Subject: [PATCH 03/24] SMV: read an ADSC header with a d*TREK block appended as ADSC Some ADSC Quantum beamlines write a complete ADSC header (TYPE=, PIXEL_SIZE, DISTANCE, BEAM_CENTER_X/Y, per-frame OSC_START) followed by a d*TREK block. Any DETECTOR_NAMES sent the file down the d*TREK path, which either refused it (translation names it does not know) or read its vectors as a mirrored image: the sweep then indexes at the right cell with the hand inverted - invisible to R-free, but the anomalous map at the heavy-atom sites comes out negative. The d*TREK path is now taken only for Rigaku's own headers, which carry Data_type= in place of ADSC's TYPE=, as dxtbx decides it. On the affected sets the anomalous peaks at the Se sites turn positive and R-free is unchanged; d*TREK files with Data_type= are read as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3 (cherry picked from commit 06aad37a7f264a45cf6685fa0907fc60ae03c989) --- reader/SMV.cpp | 6 +++++- tests/JFJochReaderTest.cpp | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/reader/SMV.cpp b/reader/SMV.cpp index db520b463..1d6eedea7 100644 --- a/reader/SMV.cpp +++ b/reader/SMV.cpp @@ -266,7 +266,11 @@ Header Parse(const std::map &kv, const std::string &pa std::transform(a.begin(), a.end(), a.begin(), [](unsigned char c) { return std::tolower(c); }); h.axis_name = a; } - if (kv.count("DETECTOR_NAMES")) + // Only Rigaku's own d*TREK headers (Data_type= in place of ADSC's TYPE=) are read as d*TREK, as + // dxtbx decides it. Some ADSC Quantum beamlines append a d*TREK block to a complete ADSC header, + // and its vectors mirror the image: read that way the sweep indexes with the hand inverted, which + // R-free cannot see but the anomalous map at the heavy-atom sites shows as negative peaks. + if (kv.count("DETECTOR_NAMES") && kv.count("DATA_TYPE")) ParseDtrek(kv, path, h); return h; } diff --git a/tests/JFJochReaderTest.cpp b/tests/JFJochReaderTest.cpp index 29869adb0..c4bd5ed20 100644 --- a/tests/JFJochReaderTest.cpp +++ b/tests/JFJochReaderTest.cpp @@ -4929,6 +4929,7 @@ namespace { std::string byte_order = "little_endian"; int saturation = 65535; // CCD_IMAGE_SATURATION; 0 leaves the line out bool write_header = true; + std::string extra; // further header lines, written after the ADSC ones std::vector pixels; // empty: all zero }; @@ -4944,6 +4945,7 @@ namespace { << "BEAM_CENTER_X=" << f.beam_x_mm << ";\nBEAM_CENTER_Y=" << f.beam_y_mm << ";\n"; if (f.saturation > 0) h << "CCD_IMAGE_SATURATION=" << f.saturation << ";\n"; + h << f.extra; } else { h << "SOMETHING_ELSE=1;\n"; // a brace block that is not an image header } @@ -5017,6 +5019,38 @@ TEST_CASE("JFJochSMVReader_Geometry", "[HDF5][Full][portable]") { RemoveSMVSweep("smv_", ".img"); } + SECTION("an ADSC header with a d*TREK block appended is read as ADSC") { + // Some ADSC Quantum beamlines append a d*TREK block (no Data_type=) to a complete ADSC header. + // Its translation names are not ones the d*TREK path knows, and its vectors mirror the image; + // the ADSC fields are what the file is read by. + WriteSMVSweep("smvplain_", ".img"); + JFJochSMVReader plain; + REQUIRE_NOTHROW(plain.ReadFiles("smvplain_001.img")); + const auto p = plain.GetDataset()->experiment; + + SMVFields f; + f.extra = "DETECTOR_NAMES=ADSC_;\nADSC_GONIO_NAMES=RotZ RotX/Swing RotY TransX TransY TransZ/Dist;\n" + "ROTATION_VECTOR=-1 0 0;\n"; + WriteSMVSweep("smvdtrek_", ".img", f); + JFJochSMVReader reader; + REQUIRE_NOTHROW(reader.ReadFiles("smvdtrek_001.img")); + const auto x = reader.GetDataset()->experiment; + CHECK(x.GetDetectorDistance_mm() == Catch::Approx(250.0)); + CHECK(x.GetBeamX_pxl() == Catch::Approx(12.0)); + CHECK(x.GetBeamY_pxl() == Catch::Approx(8.0)); + CHECK(x.GetDiffractionGeometry().GetOrientation().IsMirrorY() + == p.GetDiffractionGeometry().GetOrientation().IsMirrorY()); + CHECK(x.GetDiffractionGeometry().GetOrientation().GetQuarterTurns() + == p.GetDiffractionGeometry().GetOrientation().GetQuarterTurns()); + REQUIRE(x.GetGoniometer().has_value()); + CHECK((x.GetGoniometer()->GetAxis() - p.GetGoniometer()->GetAxis()).Length() < 1e-5f); + CHECK(x.GetGoniometer()->GetStart_deg() == Catch::Approx(5.0)); + plain.Close(); + reader.Close(); + RemoveSMVSweep("smvplain_", ".img"); + RemoveSMVSweep("smvdtrek_", ".img"); + } + SECTION("a d*TREK header: vectors, a swung arm, a counted wavelength and encoded overflows") { // The vocabulary Rigaku's CrystalClear writes for a Saturn: the detector as named circles with // their vectors in the imgCIF frame, the beam position in pixels, and the wavelength behind a -- 2.54.1 From 6cfebfd2d079c151cbab4931ebaa1d928e9e4beb Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Mon, 23 Nov 2026 18:49:50 +0100 Subject: [PATCH 04/24] Stills merge: a reflection's resolution is the reference cell's, not the image's Stills each carry their own cell (and an XFEL pulse its own wavelength), merged while it is within the indexing tolerance of the reference cell (5 % by default). The merge cut each observation at the high-resolution limit by the d of the image that measured it, and gave the merged reflection the d of its first observation, while the completeness counted the possible reflections in the reference cell. A reflection just past the limit was then merged from whichever image's cell put it inside, and the outermost shell counted more reflections than it could hold: measured, 204 % and 147 % in the last shell of a four-run --mode scale merge at multiplicities in the thousands, with a CC1/2 in those shells that meant nothing. The inner shells read 99-101 % from the same shuffling across shell boundaries. The merge now takes a reflection's d in the reference cell, where there is one, for the resolution cut, the d it reports and the shell it is counted in - the cell the possible reflections are counted in - so a reflection has one d whichever image measured it and no shell can exceed complete. Without a reference cell nothing changes. New test: images on cells 2 % either side of the reference, every reflection to past the limit; it fails before (reflections past the limit, shells over 100 %) and passes now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3 (cherry picked from commit 5172955cb4504e7d374010b57d8810842d7f038a) --- image_analysis/scale_merge/Merge.cpp | 34 +++++++++++++--- image_analysis/scale_merge/Merge.h | 10 +++++ tests/MergeScaleTest.cpp | 61 ++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 6 deletions(-) diff --git a/image_analysis/scale_merge/Merge.cpp b/image_analysis/scale_merge/Merge.cpp index cf69a1229..40e37e45c 100644 --- a/image_analysis/scale_merge/Merge.cpp +++ b/image_analysis/scale_merge/Merge.cpp @@ -83,9 +83,31 @@ MergeOnTheFly::MergeOnTheFly(const DiffractionExperiment &x) MergeOnTheFly &MergeOnTheFly::ReferenceCell(const std::optional &cell) { reference_cell = cell; + reference_reciprocal.reset(); + if (cell) { + const CrystalLattice lattice(*cell); + reference_reciprocal = {lattice.Astar(), lattice.Bstar(), lattice.Cstar()}; + } return *this; } +float MergeOnTheFly::Resolution(const Reflection &r) const { + if (!reference_reciprocal) + return r.d; + const auto &[astar, bstar, cstar] = *reference_reciprocal; + const float q = (static_cast(r.h) * astar + static_cast(r.k) * bstar + + static_cast(r.l) * cstar).Length(); + return q > 0.0f ? 1.0f / q : NAN; +} + +bool MergeOnTheFly::Accept(const Reflection &r, std::optional d_min_limit, + std::optional d_max_limit) const { + if (!AcceptReflection(r, std::nullopt, std::nullopt)) + return false; + const float d = Resolution(r); + return std::isfinite(d) && !(d_min_limit && d < *d_min_limit) && !(d_max_limit && d > *d_max_limit); +} + size_t MergeOnTheFly::Contributions(const IntegrationOutcome &outcome, std::vector &out) const { size_t rejected = 0; for (const auto &r: outcome.reflections) { @@ -94,7 +116,7 @@ size_t MergeOnTheFly::Contributions(const IntegrationOutcome &outcome, std::vect if (r.image_scale_corr <= 0.0 || !std::isfinite(r.image_scale_corr)) continue; - if (!AcceptReflection(r, high_resolution_limit, std::nullopt)) + if (!Accept(r, high_resolution_limit, std::nullopt)) continue; if (exclude_ice_rings && r.on_ice_ring) continue; @@ -130,7 +152,7 @@ size_t MergeOnTheFly::Contributions(const IntegrationOutcome &outcome, std::vect .l = hkl.plus ? hkl.l : -hkl.l, .w = w, .wI = w * I_corr, - .d = r.d, + .d = Resolution(r), .on_ice_ring = r.on_ice_ring, .exists = r.partiality >= existence_min_partiality, .far_tail = r.partiality < FAR_TAIL_PARTIALITY @@ -151,7 +173,7 @@ std::vector> MergeOnTheFly::Verdicts(const std:: const bool scaled = r.image_scale_corr > 0.0 && std::isfinite(r.image_scale_corr); if (!scaled) v.flags |= OBS_NO_SCALE; - if (!AcceptReflection(r, high_resolution_limit, std::nullopt)) + if (!Accept(r, high_resolution_limit, std::nullopt)) v.flags |= OBS_RESOLUTION; if (exclude_ice_rings && r.on_ice_ring) v.flags |= OBS_ICE_EXCLUDED; @@ -328,7 +350,7 @@ void MergeOnTheFly::RefineErrorModel(const std::vector &outc continue; if (r.image_scale_corr <= 0.0 || !std::isfinite(r.image_scale_corr)) continue; - if (!AcceptReflection(r, high_resolution_limit, std::nullopt)) + if (!Accept(r, high_resolution_limit, std::nullopt)) continue; if (exclude_ice_rings && r.on_ice_ring) continue; @@ -899,7 +921,7 @@ MergeStatistics MergeOnTheFly::MergeStats(const std::vector &m continue; if (r.image_scale_corr <= 0.0 || !std::isfinite(r.image_scale_corr)) continue; - if (!AcceptReflection(r, d_min_limit_A, d_max_limit_A)) + if (!Accept(r, d_min_limit_A, d_max_limit_A)) continue; if (BelowMergeFloor(r.partiality)) continue; @@ -908,7 +930,7 @@ MergeStatistics MergeOnTheFly::MergeStats(const std::vector &m if (w == 0.0) continue; - const auto shell = shells.GetShell(r.d); + const auto shell = shells.GetShell(Resolution(r)); if (!shell.has_value()) continue; const int s = *shell; diff --git a/image_analysis/scale_merge/Merge.h b/image_analysis/scale_merge/Merge.h index d81ad5e2d..aa9a7cdf0 100644 --- a/image_analysis/scale_merge/Merge.h +++ b/image_analysis/scale_merge/Merge.h @@ -348,6 +348,7 @@ class MergeOnTheFly { IndexingSettings indexing_settings; std::optional reference_cell; + std::optional> reference_reciprocal; // a*, b*, c* of reference_cell std::optional high_resolution_limit; std::optional image_cc_limit; // Apply image_cc_limit in Mask(). One flag for the whole engine, not a per-call argument, so the @@ -367,6 +368,15 @@ class MergeOnTheFly { static constexpr double EXISTENCE_MIN_PARTIALITY = 0.2; double min_partiality = 0.02; double existence_min_partiality = 0.02; + // A reflection's resolution in the merge: in the reference cell where there is one, not in the cell of the + // image that measured it. Stills each carry their own cell (and an XFEL pulse its own wavelength), so the + // same reflection reads a slightly different d on every image; cut and binned by those, a reflection just + // past the limit is merged from whichever image puts it inside, and the outermost shell counts more of + // them than the reference cell, which the completeness counts the possible reflections in, allows. + [[nodiscard]] float Resolution(const Reflection &r) const; + // AcceptReflection, with the limits applied to Resolution(r). + [[nodiscard]] bool Accept(const Reflection &r, std::optional d_min_limit, + std::optional d_max_limit) const; [[nodiscard]] bool BelowMergeFloor(float partiality) const { return error_model_active ? partiality <= 0.0f : partiality < min_partiality; } diff --git a/tests/MergeScaleTest.cpp b/tests/MergeScaleTest.cpp index 77a05dd2d..0d3696446 100644 --- a/tests/MergeScaleTest.cpp +++ b/tests/MergeScaleTest.cpp @@ -1679,3 +1679,64 @@ TEST_CASE("MergeOnTheFly_StillsAnomalousStatistics") { CHECK(stats.overall.abs_diff_over_sigma_anomalous > 5.0); CHECK(stats.overall.anomalous_measurability > 0.9); } + +// Stills each carry their own cell, merged while it is within the tolerance of the reference cell. Cut and +// binned by those cells, a reflection just past the limit is merged from the image whose cell puts it inside, +// and the outermost shell counted more reflections than the reference cell - the one the possible +// reflections are counted in - allows (measured: 204 % in the last shell of a four-run merge). Cut and +// binned in the reference cell, every shell is at most complete and every reflection has one d. +TEST_CASE("MergeStats_StillsOnCellsAroundTheReferenceStayAtMostComplete") { + const auto &sg = TestSpaceGroup(); + const UnitCell reference{40.0f, 45.0f, 50.0f, 90.0f, 100.0f, 90.0f}; + constexpr double LIMIT = 2.0; + + DiffractionExperiment x; + x.SetSpaceGroup(sg); + ScalingSettings s = x.GetScalingSettings(); + x.ImportScalingSettings(s.HighResolutionLimit_A(LIMIT)); + + // Every reflection to 1.9 A on its image's own cell, on images 2 % larger and 2 % smaller than the + // reference. + const auto image = [&sg](float scale) { + const UnitCell own{40.0f * scale, 45.0f * scale, 50.0f * scale, 90.0f, 100.0f, 90.0f}; + const gemmi::UnitCell gemmi_cell = own; + IntegrationOutcome o; + o.latt = CrystalLattice(own); + for (const auto &hkl: gemmi::make_miller_vector(gemmi_cell, &sg, 1.9, 50.0, true)) { + Reflection r{}; + r.h = hkl[0]; + r.k = hkl[1]; + r.l = hkl[2]; + r.d = static_cast(gemmi_cell.calculate_d(hkl)); + r.I = 100.0f; + r.sigma = 10.0f; + r.prescaling_corr = 1.0f; + r.partiality = 1.0f; + r.image_scale_corr = 1.0f; + o.reflections.push_back(r); + } + return o; + }; + std::vector outcomes; + for (int i = 0; i < 4; ++i) + outcomes.push_back(image(i % 2 ? 1.02f : 0.98f)); + + MergeOnTheFly merge(x); + merge.ReferenceCell(reference); + merge.AddImages(outcomes); + const auto merged = merge.ExportIntensities(); + REQUIRE(!merged.empty()); + + const gemmi::UnitCell gemmi_reference = reference; + for (const auto &m: merged) { + const double d = gemmi_reference.calculate_d({m.h, m.k, m.l}); + CHECK(m.d == Catch::Approx(d).epsilon(1e-4)); + CHECK(m.d >= LIMIT); + } + + const auto stats = merge.MergeStats(merged, outcomes); + CHECK(Completeness(stats.overall) <= 100.0); + CHECK(Completeness(stats.overall) > 99.0); + for (const auto &sh: stats.shells) + CHECK(Completeness(sh) <= 100.0); +} -- 2.54.1 From 3c750767c9064a84b732fc410730f2b50e9c40fa Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Mon, 23 Nov 2026 19:09:40 +0100 Subject: [PATCH 05/24] JUNGFRAU: configurable timing master module With module_sync on, the module made timing master was always module 0. The detector entry of the broker settings now takes master_module (default 0, must be below the module count; checked in DetectorSetup::MasterModule), and the SLS wrapper makes that module master. Deactivate now clears the master flag on all modules instead of only on module 0, so it no longer depends on which module was master. Regenerated from jfjoch_api.yaml: C++ server model (broker/gen), frontend client, Redoc page and the python-client Detector doc page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3 (cherry picked from commit e46242de37c32a354b7e4fdf56727867e79c5de6) --- broker/JFJochBrokerParser.cpp | 1 + broker/gen/model/Detector.cpp | 43 +++++++++++++++++++++++++ broker/gen/model/Detector.h | 11 ++++++- broker/jfjoch_api.yaml | 10 +++++- broker/redoc-static.html | 2 +- common/DetectorSetup.cpp | 11 +++++++ common/DetectorSetup.h | 3 ++ detector_control/SLSDetectorWrapper.cpp | 4 +-- docs/JFJOCH_BROKER.md | 4 ++- docs/python_client/docs/Detector.md | 3 +- frontend/src/client/types.gen.ts | 8 ++++- frontend/src/client/zod.gen.ts | 1 + tests/CMakeLists.txt | 1 + tests/DetectorSetupTest.cpp | 17 +++++++++- tests/JFJochBrokerParserTest.cpp | 34 +++++++++++++++++++ 15 files changed, 144 insertions(+), 9 deletions(-) create mode 100644 tests/JFJochBrokerParserTest.cpp diff --git a/broker/JFJochBrokerParser.cpp b/broker/JFJochBrokerParser.cpp index 9ffe0d121..c3bf0bee4 100644 --- a/broker/JFJochBrokerParser.cpp +++ b/broker/JFJochBrokerParser.cpp @@ -125,6 +125,7 @@ DetectorSetup ParseDetectorSetup(const org::openapitools::server::model::Detecto setup.UDPInterfaceCount(d.getUdpInterfaceCount()) .SerialNumber(d.getSerialNumber()) .ModuleSync(d.isModuleSync()) + .MasterModule(d.getMasterModule()) .MirrorY(d.isMirrorY()); // Only override the sensor from the request when it explicitly sets these. The API model defaults diff --git a/broker/gen/model/Detector.cpp b/broker/gen/model/Detector.cpp index 81a3c4a5c..657f9182f 100644 --- a/broker/gen/model/Detector.cpp +++ b/broker/gen/model/Detector.cpp @@ -31,6 +31,8 @@ Detector::Detector() m_Udp_interface_countIsSet = false; m_Module_sync = true; m_Module_syncIsSet = false; + m_Master_module = 0L; + m_Master_moduleIsSet = false; m_Sensor_thickness_um = 320.0f; m_Sensor_thickness_umIsSet = false; m_Readout_time_ns = 0L; @@ -145,6 +147,20 @@ bool Detector::validate(std::stringstream& msg, const std::string& pathPrefix) c } + if (masterModuleIsSet()) + { + const int64_t& value = m_Master_module; + const std::string currentValuePath = _pathPrefix + ".masterModule"; + + + if (value < 0ll) + { + success = false; + msg << currentValuePath << ": must be greater than or equal to 0;"; + } + + } + if (sensorThicknessUmIsSet()) { const float& value = m_Sensor_thickness_um; @@ -357,6 +373,9 @@ bool Detector::operator==(const Detector& rhs) const ((!moduleSyncIsSet() && !rhs.moduleSyncIsSet()) || (moduleSyncIsSet() && rhs.moduleSyncIsSet() && isModuleSync() == rhs.isModuleSync())) && + ((!masterModuleIsSet() && !rhs.masterModuleIsSet()) || (masterModuleIsSet() && rhs.masterModuleIsSet() && getMasterModule() == rhs.getMasterModule())) && + + ((!sensorThicknessUmIsSet() && !rhs.sensorThicknessUmIsSet()) || (sensorThicknessUmIsSet() && rhs.sensorThicknessUmIsSet() && getSensorThicknessUm() == rhs.getSensorThicknessUm())) && @@ -426,6 +445,8 @@ void to_json(nlohmann::json& j, const Detector& o) j["udp_interface_count"] = o.m_Udp_interface_count; if(o.moduleSyncIsSet()) j["module_sync"] = o.m_Module_sync; + if(o.masterModuleIsSet()) + j["master_module"] = o.m_Master_module; if(o.sensorThicknessUmIsSet()) j["sensor_thickness_um"] = o.m_Sensor_thickness_um; if(o.readoutTimeNsIsSet()) @@ -489,6 +510,11 @@ void from_json(const nlohmann::json& j, Detector& o) j.at("module_sync").get_to(o.m_Module_sync); o.m_Module_syncIsSet = true; } + if(j.find("master_module") != j.end()) + { + j.at("master_module").get_to(o.m_Master_module); + o.m_Master_moduleIsSet = true; + } if(j.find("sensor_thickness_um") != j.end()) { j.at("sensor_thickness_um").get_to(o.m_Sensor_thickness_um); @@ -665,6 +691,23 @@ void Detector::unsetModule_sync() { m_Module_syncIsSet = false; } +int64_t Detector::getMasterModule() const +{ + return m_Master_module; +} +void Detector::setMasterModule(int64_t const value) +{ + m_Master_module = value; + m_Master_moduleIsSet = true; +} +bool Detector::masterModuleIsSet() const +{ + return m_Master_moduleIsSet; +} +void Detector::unsetMaster_module() +{ + m_Master_moduleIsSet = false; +} float Detector::getSensorThicknessUm() const { return m_Sensor_thickness_um; diff --git a/broker/gen/model/Detector.h b/broker/gen/model/Detector.h index bd1896b73..290797a78 100644 --- a/broker/gen/model/Detector.h +++ b/broker/gen/model/Detector.h @@ -97,13 +97,20 @@ public: bool udpInterfaceCountIsSet() const; void unsetUdp_interface_count(); /// - /// Use module 0 as master for timing. Only applies to JUNGFRAU detector (this cannot be turned off for EIGER). + /// Use one module (`master_module`) as master for timing. Only applies to JUNGFRAU detector (this cannot be turned off for EIGER). /// bool isModuleSync() const; void setModuleSync(bool const value); bool moduleSyncIsSet() const; void unsetModule_sync(); /// + /// Index of the module that acts as timing master when `module_sync` is enabled; must be below the number of modules. Only applies to JUNGFRAU detector. + /// + int64_t getMasterModule() const; + void setMasterModule(int64_t const value); + bool masterModuleIsSet() const; + void unsetMaster_module(); + /// /// /// float getSensorThicknessUm() const; @@ -231,6 +238,8 @@ protected: bool m_Udp_interface_countIsSet; bool m_Module_sync; bool m_Module_syncIsSet; + int64_t m_Master_module; + bool m_Master_moduleIsSet; float m_Sensor_thickness_um; bool m_Sensor_thickness_umIsSet; int64_t m_Readout_time_ns; diff --git a/broker/jfjoch_api.yaml b/broker/jfjoch_api.yaml index e147ffb4f..e3200c68c 100644 --- a/broker/jfjoch_api.yaml +++ b/broker/jfjoch_api.yaml @@ -2541,7 +2541,15 @@ components: module_sync: type: boolean default: true - description: Use module 0 as master for timing. Only applies to JUNGFRAU detector (this cannot be turned off for EIGER). + description: Use one module (`master_module`) as master for timing. Only applies to JUNGFRAU detector (this cannot be turned off for EIGER). + master_module: + type: integer + format: int64 + minimum: 0 + default: 0 + description: | + Index of the module that acts as timing master when `module_sync` is enabled; must be below the number of modules. + Only applies to JUNGFRAU detector. sensor_thickness_um: type: number format: float diff --git a/broker/redoc-static.html b/broker/redoc-static.html index 9a7f8d9ff..7bfb8d85c 100644 --- a/broker/redoc-static.html +++ b/broker/redoc-static.html @@ -542,7 +542,7 @@ This format doesn't transmit information about X-axis, only values, so it i