Files
Jungfraujoch/rugnux/DiagnosticOutput.cpp
T
leonarski_fandClaude Opus 5.5 0a515bb086 rc179: everything on rc178 after its merge into main (#88), except the CHANGELOG
The rc178 branch continued after #88 was squash-merged; this is its content from b9ada7914 (the tree
#88 squashed) to 094eee31a, as one change on main. The individual commits stay on the rc178 branch:

- still battery: --cold evicts each set's input from the page cache; Alvra pixel masks; manifest fixes
- AGIPD: converter to one rigid panel per module, int16 photons, mask folded in; still battery reads the converted sets
- DetectorModules: panel look-up by id, plane -> panel, plane bounds and a per-pixel walk; mask size checked
- tests: [PanelLayout] equivalence harness, stacked vs assembled panel layout
- Dense per-pixel maps through the panel table (panel layout stage 1)
- Panel id on spots and the panel table in the start message
- Viewer and preview show a panel detector as it lies on the detector plane
- Panel layout stage 3: per-panel spot finding (CPU+GPU, CCL) and raster algorithms on the plane raster
- Panel layout stage 2: prediction and Bragg integration through the panel table
- XTC reader: frames handed up as stored, streams indexed in parallel
- XFEL reader: integer frames stay integer, one gain, placement by panel
- EXTERNAL_TEST_DATA_STILLS.md: images used vs the entry for every set; drop "Not in the battery"
- still battery: EuXFEL sets read the depositors' Cheetah CXI files directly; AGIPD converter removed
- float32_to_int16.py: a non-finite pixel becomes -32768, the int16 error marker, not a zero count
- CrystFEL geometry: read the pixel masks and bad regions instead of ignoring them
- Panel layout stage 5: the XFEL reader hands up the stored frame and its panel table
- Panel table persisted in NXmx; modulation grid and pre-scan memo key on the plane
- still battery: Alvra sets take their pixel mask from the CrystFEL geometry, not --mask-good
- still battery: take the deposited model as mmCIF where the RCSB has no PDB-format file
- still battery: dimple gets PDB-format coordinates converted from an mmCIF-only deposition
- stills fixed cost: geometry refinement and pre-scan do the same work in less wall time
- stills geometry sample and trial spot finding run as many workers as the image pass
- Stills integration: background ring reach measured on empty apertures, radial curvature from the whole frame
- StillsPartialityRefine: the partiality width is the run's, measured on the crystals, not the prediction window's
- MergeOnTheFly: capture term and multiplicative outlier band for the stills merge (both opt-in)
- Stills given a cell: the written cell is the mean over the frames that are merged
- Stills: the radial curvature correction decided per run on the same empty apertures
- StillsPartialityRefine: measure the run width only on shells with signal
- Stills pre-scan: report the paired z of the radial-correction comparison
- module placement: the five concurrent fits each keep every thread
- still battery: score R-free against the deposited data through the same dimple protocol
- still battery: the R-free target is the lower of the deposition's dimple and published values
- Stills: background clip follows the radial curve; signal disk from the lattice spacing
- Stills keep an overloaded observation as a lower bound instead of dropping it
- Stills: drop the lattice-spacing signal disk; the correction decision back on the plain clip
- battery: R-free against the deposition without refinement only, one protocol for rotation and stills
- still battery: EuXFEL sets run on a 2,000-image subset for now
- stills geometry refinement: fit the detector distance and the cell together
- stills geometry refinement: a distance given with --detector-distance is held in the joint fit
- Metal integration engine: back to its panel-s5 kernels; Mac stills keep the old clip, no saturation count
- Metal integration test: the CPU comparison runs on a rotation experiment
- Stills: kept overloads go back to the drop where they are not concentrated at low resolution
- stills distance search: an absolute 30-3000 mm scan, a sample found without d-limits, the fit iterated
- battery results: XFEL still battery 20261022-1358 on rc178 0cf62452c - 12 sets, cold, R_free unrefined
- battery results: still summary gains the resolution of our merge and of the deposition
- Pre-scan masks a pixel at the saturation limit on most frames, as one holding the error value
- Stills keep an overload as a lower bound only where it has pixels at the limit; run-level gate removed
- XFEL reader: a per-frame mask is read the way the frames are, its chunk inflated outside the HDF5 lock
- stills distance search: every centre scanned with a wider acceptance, a larger sample where nothing indexes
- rugnux usage: --beam-center-check describes the absolute 30-3000 mm stills distance scan, not the old 60-160 % grid
- stills: detector tilt refined in the geometry pre-pass, kept where held-out frames agree
- CLAUDE.md: the changelog is written once, just before the merge into main - condensed one-liners of what users get
- broker: serve the placed model and its maps of the last rugnux live run (/rugnux/model.cif, /rugnux/map.ccp4)
- frontend: Mol* viewer of the placed model and its density on the Rugnux live page
- writer: _model.cif from rugnux live keeps the input model's metadata, as the served model.cif does
- rugnux live maps: one unit cell centred on the model; the viewer opens on all of it
- Anomalous difference map: ANOM/PHANOM in _maps.mtz, /rugnux/map.ccp4?type=anom, a magenta mesh in the viewer
- Mol* viewer: open with the maps drawn within 10 A of the centre of view
- Mol* viewer: aaredb's structure-viewer setup, on a black stage
- rugnux: the gain of a stills file that states none is read off its single-photon peak where the background resolves photons
- Mol* viewer: in line with AareDB's StructureView at its current head (8ece2c2)
- ACKNOWLEDGEMENT: the web frontend's Mol* viewer follows AareDB's setup (G. Gotthard, PSI)
- stills tilt decision: the modules stay where the run placed them
- still battery: no distance pins and no per-set tuning flags; gain from the data except where a file's baseline hides it
- battery results: rc178 6f6f69 - full still battery and full rotation battery with REFMAC
- Bragg integration: a CCD rotation sweep's sigmas at the measured gain, intensities in photons
- BackgroundGain: the gain of a frame that resolves photons is the spacing of its photon peaks, so a baseline left in the frame no longer hides it
- ShadowFinder: measure the background's azimuthal modulation instead of predicting it from the polarization
- BackgroundGain: one gain estimate for rotation and stills; the still battery no longer gives EuXFEL 152 its gain
- ShadowFinder: measure the modulation robustly under a wide one-sided shadow
- ShadowFinderTest: a one-sided shadow is not fitted as part of the background's modulation
- ShadowFinder: back to the predicted polarization factor, in the plane the background shows
- MXAnalysisAfterFPGA: the Bragg engine's edge mask in the image's layout, so raw / untransformed FPGA runs start again
- battery results: still battery on rc178 e54f55 replaces the earlier rc178 still tables
- XFELReader: per-frame mask and photon conversion without a library call or a branch per pixel
- stills geometry trial: the hypotheses a search asks are indexed side by side
- stills tilt decision: the fits start beside the pre-scan and the geometry trial
- XFELReader: a deflated frame is inflated and converted a piece at a time, while it is in the cache
- XFELReader: a byte-shuffled frame is unshuffled a piece at a time, a whole pixel per step
- GeometryRefiner: residuals carry only the blocks a fit moves; beam and distance one block
- GeometryRefiner: a spot's residual differentiates its observed and predicted halves apart
- docs: EXTERNAL_TEST_DATA lists every open-arm battery set, with corrected values and counts
- battery: doc_check.py cross-checks the manifests against the dataset pages
- stills module placement: the placement fit gets half the threads, each held-out fit an eighth
- still battery: the EuXFEL sets run on all their frames, as the published still runs did
- battery results: still battery on rc178 a0ce6c, cold on a quiet machine, replaces the earlier rc178 table
- macOS build: explicit size_t in the XFEL reader's row bounds; parentheses in the CPU preprocessor's select

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015CeEGgpKdfkCTJb3YNMJcu
2026-10-23 17:56:42 +02:00

166 lines
9.0 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "DiagnosticOutput.h"
#include <algorithm>
#include <cmath>
#include <spdlog/fmt/fmt.h>
#include "../common/AssembleToPlane.h"
#include "../common/ColorScale.h"
#include "../common/CompressedImage.h"
#include "../common/JFJochException.h"
#include "../image_analysis/scale_merge/Merge.h"
#include "../preview/JFJochJPEG.h"
namespace {
// The top of the ramp is eight times the MEDIAN of the measured pixels, not the brightest 0.1 %
// the preview and the viewer saturate at (preview/PreviewImage.cpp). That percentile belongs to
// the Bragg peaks, and with it setting the range the background lands in the first few per cent
// of the scale and reads as a flat white - which is exactly what the picture has to be read for,
// since a shadow is a place the background is MISSING. The median is pure background whatever
// the crystal, and eight times it lands between the 94th and the 99th percentile of the
// projection on every test set measured, which is the top of the background: the background
// spans the ramp radially, and the spots clip, which costs nothing here as they are not what is
// being judged. Twice the median - the first value tried - lands at the 73rd to 90th percentile
// instead and floods the whole inner half of the detector to a flat indigo, hiding the deficit
// just as the old contrast did, at the other end of the scale.
float SaturationValue(const std::vector<float> &projection, const std::vector<uint32_t> &mask) {
std::vector<float> valid;
valid.reserve(projection.size());
for (size_t i = 0; i < projection.size(); i++)
if (mask[i] == 0 && std::isfinite(projection[i]))
valid.push_back(projection[i]);
if (valid.empty())
return 1.0f;
const size_t mid = valid.size() / 2;
std::nth_element(valid.begin(), valid.begin() + mid, valid.end());
return std::max(8.0f * valid[mid], 1.0f);
}
float Element(const std::vector<float> &v, size_t i) {
return i < v.size() ? v[i] : NAN;
}
int Element(const std::vector<int> &v, size_t i) {
return i < v.size() ? v[i] : 0;
}
}
std::vector<rgb> DetectorDiagnosticRGB(const PixelMask &pixel_mask,
const std::vector<float> &mean_projection) {
constexpr uint32_t gap_bits = (1u << PixelMask::ModuleGapPixelBit)
| (1u << PixelMask::ChipGapPixelBit)
| (1u << PixelMask::ModuleEdgePixelBit);
constexpr uint32_t beam_stop_bit = 1u << PixelMask::BeamStopPixelBit;
const auto &mask = pixel_mask.GetMask();
if (mask.size() != mean_projection.size())
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
"Mask and projection are of different size");
// Untouched: the viewer's defaults are the point, so that the JPEG and the picture the user
// knows from jfjoch_viewer say the same thing with the same colours.
ColorScale scale;
const rgb gap_color = scale.Apply(ColorScaleSpecial::Gap);
const rgb bad_color = scale.Apply(ColorScaleSpecial::BadPixel);
const rgb beam_stop_color = scale.Apply(ColorScaleSpecial::BeamStop);
const auto &lut = scale.LUTData();
const auto lut_size = static_cast<int64_t>(lut.size());
const float inv_range = static_cast<float>(lut_size - 1) / SaturationValue(mean_projection, mask);
// The shadow is tested BEFORE the rest of the mask, so a pixel the detection claims is never
// hidden under a noisy- or user-masked bit it also carries - the whole point is to see what
// the detection did. Gaps come first because nothing can be shadowed there: they carry no
// background for the comparison to miss.
std::vector<rgb> image(mean_projection.size());
for (size_t i = 0; i < image.size(); i++) {
if ((mask[i] & gap_bits) != 0)
image[i] = gap_color;
else if ((mask[i] & beam_stop_bit) != 0)
image[i] = beam_stop_color;
else if (mask[i] != 0 || !std::isfinite(mean_projection[i]))
image[i] = bad_color;
else {
const auto idx = static_cast<int64_t>(mean_projection[i] * inv_range + 0.5f);
image[i] = lut[std::clamp<int64_t>(idx, 0, lut_size - 1)];
}
}
return image;
}
std::string RenderDetectorDiagnostic(const DiffractionExperiment &experiment,
const PixelMask &pixel_mask,
const std::vector<float> &mean_projection) {
// The picture is of the detector as it is: with panels, the stored layout put together on the plane
// raster, the space between panels in the gap colour. Without, the image itself.
const DetectorModules &modules = experiment.GetModules();
const int64_t width = experiment.GetXPixelsNumConv(), height = experiment.GetYPixelsNumConv();
const PlaneRaster raster = PlaneRasterOf(modules, width, height);
const rgb gap_color = ColorScale().Apply(ColorScaleSpecial::Gap);
// Named, because CompressedImage does not own the pixels it is handed.
const std::vector<rgb> image = AssembleToPlane(modules, DetectorDiagnosticRGB(pixel_mask, mean_projection),
width, height, raster, gap_color);
const CompressedImage rgb_image(image, raster.width, raster.height);
return WriteJPEGToMem(rgb_image, 85);
}
std::string PerImagePlotText(const PerImagePlot &plot) {
const std::optional<GoniometerAxis> &goniometer = plot.goniometer;
std::string file;
// One comment line, its names over their own columns, and nothing else a plotting program has
// to be told to skip. The '#' takes the first character of the image-number field.
file += "#" + fmt::format("{:>5} {:>10} {:>12} {:>12} {:>8} {:>12} {:>13} {:>12} {:>8}"
" {:>7} {:>11}\n",
"image", "angle_deg", "bkg", "resolution_A", "spots", "scale_G",
"sigma_M_deg", "cc_to_merge", "cc_n", "merged", "disposition");
// Whether "merged" has anything to answer at all. With no merge behind the run - --no-merge, or
// a sweep nothing indexed on - a column of zeros would read as a sweep every frame of which was
// thrown out, which is a different statement from "no merge was made".
const bool merge_ran = !plot.frame_disposition.empty()
|| std::any_of(plot.scale_g.begin(), plot.scale_g.end(),
[](float g) { return std::isfinite(g); });
for (size_t i = 0; i < plot.image_count; i++) {
const float angle = goniometer
? goniometer->GetAngle_deg(static_cast<float>(i))
+ goniometer->GetWedge_deg() / 2.0f
: NAN;
const float scale_g = Element(plot.scale_g, i);
// Did this image's observations reach the merged data? The sweep-quality diagnostic says so
// outright; where it did not run, an image with no fitted scale contributed nothing, which
// is the same statement by a weaker route.
const int merged = i < plot.frame_disposition.size()
? plot.frame_disposition[i]
!= static_cast<uint8_t>(FrameDisposition::Rejected)
: std::isfinite(scale_g);
// The same answer graded, to plot directly: 1 merged, 0.5 downgraded, 0 rejected. 0.5 marks
// "downgraded" and is not a weight - the merge applies no factor of its own to those frames,
// they are carried at whatever weight their scale and sigmas give them. A frame that never got
// a scale never reached the merge at all and is nan, like any other value nothing measured.
float disposition = NAN;
if (merge_ran && i < plot.frame_disposition.size()) {
switch (static_cast<FrameDisposition>(plot.frame_disposition[i])) {
case FrameDisposition::Merged: disposition = 1.0f; break;
case FrameDisposition::Downgraded: disposition = 0.5f; break;
case FrameDisposition::Rejected: disposition = std::isfinite(scale_g) ? 0.0f : NAN; break;
}
} else if (merge_ran && std::isfinite(scale_g))
disposition = 1.0f;
file += fmt::format("{:>6} {:>10.4f} {:>12.4g} {:>12.4g} {:>8.0f} {:>12.5g} {:>13.4f}"
" {:>12.4f} {:>8} {:>7} {:>11}\n",
i, angle, Element(plot.bkg_estimate, i), Element(plot.resolution_A, i),
Element(plot.spot_count, i), scale_g, Element(plot.mosaicity_deg, i),
Element(plot.cc_to_merge, i), Element(plot.cc_n, i),
merge_ran ? std::to_string(merged) : "nan", disposition);
}
return file;
}