Files
Jungfraujoch/viewer/image_viewer/JFJochDiffractionImage.h
T
leonarski_fandClaude Opus 5 16bf3408f0 Address code-review findings; make detection limits detector-driven
One changeset, developed together in response to a review of this branch, so the
files carry several of the changes at once. Full test suite passes (733 cases).

Spot finding
- Split ImageSpotFinder into Detect() (flag strong pixels - the expensive
  per-pixel pass) and ExtractSpots() (CCL + min/max-pix + resolution mask), with
  Run() = both. The per-image min-pix escalation now detects ONCE and repeats
  only the cheap extraction, instead of re-running the whole finder four times
  per frame as it did on the default path. It also keeps the winning attempt's
  spot list rather than re-extracting it, so the frame that is integrated is
  exactly the frame that was scored - which a GPU re-extract could not guarantee
  (float atomic ordering).
- spot_finding_time_s no longer swallows indexing time, and indexing_time_s now
  sums every escalation call instead of reporting only the last.

Detection limits follow the detector
- The azimuthal-integration upper q and the spot-finding high-resolution limit
  are now std::optional, in the C++ structs AND in the OpenAPI schema, and
  resolve to the detector's own maximum (DiffractionExperiment::GetDetectorMaxQ_
  recipA). Adaptive detection reads a pixel's ring from the azimuthal bins, so a
  pixel outside that q range could never be strong - the integration range
  silently bounded what detection could see, regardless of the requested
  resolution limit. Regenerated the C++ and TypeScript clients; the viewer and
  the web frontend each gained a "to detector edge" switch.

Detection defaults are now per workflow (measured, not assumed)
- Stills: adaptive detection, min-pix chosen per image, no resolution clipping.
- Rotation: fixed-threshold finder, min-pix 2, 1.5 A limit.
  On a 33-crystal rotation battery, adaptive detection helped four hard crystals
  but deterministically broke three (a lost space group, a halved indexing rate,
  a collapsed merge), and the detector-edge limit cost indexing on a strong
  rotation set (100.0 -> 96.8%). Each is still overridable by its flag, and
  --no-adaptive-spots is new.

Indexer seed escalation
- Stop escalating once a seed's lattice explains >= 90% of the seed spots.
  Previously any frame with >= 80 spots always paid three indexer calls, online
  broker included.

Merge-consistency filter
- --min-image-cc gated on a per-image CC computed BEFORE the stills partiality
  post-refinement and never refreshed; the refiner now recomputes it, so the
  reported CC describes the data that are actually merged.
- Replaced the per-call cc_mask argument with one MergeOnTheFly flag, so the
  merge, the error model and MergeStats can no longer disagree about which
  images are in (the --scale path merged unfiltered while its statistics were
  filtered).

Per-image B-factor refinement (-B) removed
- Measured on four serial-stills datasets: it is a no-op where the per-image fit
  is well conditioned and actively harmful where it is not (CC1/2 -8.1, R_meas
  +23.2 on the weakest large-cell set, whose fits hit their [-50, 200] bounds on
  14-25% of images). It had also been silently DISCARDED since the partiality
  post-refinement landed - reported but not applied. Rather than fix and keep a
  knob with no demonstrated benefit, the flag and the whole image_scale_b_factor
  chain are gone: setting, scaling fit, message field, CBOR, HDF5 write and
  read-back, per-image plot, OpenAPI enum, viewer column and checkbox, docs.
  ScaleOnTheFly no longer needs Ceres at all - the fit is a linear IRLS.
  (The Wilson per-image b_factor is a different quantity and stays.)

Stills partiality width now fits both of its components
- sigma^2 = gamma0^2 + (gamma_e*d*)^2 instead of a purely angular gamma_e*d*
  with gamma0 pinned to 0. Fitted per crystal by least squares of dist_ewald^2
  on d*^2. The angular-only width is fitted over a d*^2-dense population, so it
  was pinned by the high-resolution edge and collapsed at low d*: median
  partiality 0.008 beyond 13 A for reflections that were plainly recorded, 55%
  of them under the merge's partiality floor, and the survivors divided by those
  values - which inflated the merged low-resolution intensity scale 3.6x
  (~ +9 A^2 of apparent B). Measured on 5000 stills: the ramp flattens to 0.89x,
  no observation is dropped any more (701750 -> 716811), shell-mean CC1/2 and
  R-free improve slightly. Note CC1/2, R_meas, completeness and a B-refining
  R-free are all blind to that ramp, which is why it survived earlier validation;
  the cost is high-resolution R_meas (98.5 -> 101.9 shell-averaged).

Removed dead code from add-then-remove churn
- Prediction-time "still partiality" (unreachable: no setter), the phantom
  IndexingSettings::min_indexed_spot_fraction knob (getter, no setter - now the
  constant it always was), StillsPartialityRefine's caller-less Settings
  constructor and its reference to a long-gone env var, ProcessImage's unread
  bool return, an unused include, and a dead viewer overlay hook.

Also
- Viewer: the magnifier compared a QImage with itself, so its scene rect was set
  once ever and it could not pan into a larger dataset; the hover tail timer
  could fire after leaveEvent and resurrect the resolution readout outside the
  image.
- update_version.sh regenerated the frontend lock file BEFORE bumping the
  version (every release shipped an off-by-one lock), and did git rm/git add on
  a path that has not existed since the client moved to src/client - with no
  set -e, both failed silently.
- fpga/pcie_driver/postinstall.sh tested "[ ! occurrences > 0 ]", which is a
  redirect, not a test, so dkms add never ran.
- Unit tests for the adaptive-threshold host functions, which had none.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 09:07:00 +02:00

142 lines
5.3 KiB
C++

// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <QPainterPath>
#include "JFJochImage.h"
#include "../../reader/JFJochReaderImage.h"
#include "../../common/ROIDefinition.h"
class ROIAzimuthal;
class DiffractionGeometry;
class JFJochDiffractionImage : public JFJochImage {
Q_OBJECT
QColor spot_color = Qt::green;
QColor prediction_color = Qt::darkRed;
QColor ice_ring_color = Qt::cyan;
QColor second_lattice_color = QColor(0xFA, 0x72, 0x68); // coral, the viewer "finishing" accent
float hover_resolution = NAN;
// The "d = ... A" readout is painted in drawForeground() in viewport pixels rather than kept
// as a scene item, so updating it dirties only its own rect. hover_text_rect_ is where it
// currently sits, in viewport coordinates.
QRect hover_text_rect_;
[[nodiscard]] QString HoverResolutionLabel() const;
// Counts are exact integers: label them from the int32 image rather than from a float copy,
// which both avoids materialising that copy and cannot round large summed values.
[[nodiscard]] QString PixelLabel(int x, int y) const override;
// This is the view that has detector counts, so it is the one that offers an ROI
[[nodiscard]] bool AllowROI() const override { return true; }
void drawForeground(QPainter *painter, const QRectF &rect) override;
public:
enum class RingMode {Auto, Estimation, Manual, None, IceRings};
Q_ENUM(RingMode)
JFJochDiffractionImage(QWidget *parent = nullptr);
private:
void addCustomOverlay() override;
void LoadImageInternal();
// Colour straight from the int32 detector image; no float copy of it is ever built
void ColorRow(size_t y, const PixelColorMap &map, QRgb *out) const override;
void DrawResolutionRings();
void DrawROIs();
void DrawAzimuthalROI(const ROIAzimuthal &az, const QColor &color, const DiffractionGeometry &geom);
void AddROILabel(const std::string &name, const QColor &color, float px, float py);
// Interactive editing of the selected (named) ROI: move box/circle for now.
bool roiEditPress(const QPointF &scenePos) override;
void roiEditMove(const QPointF &scenePos) override;
void roiEditRelease() override;
void roiScratchDrawn() override;
void keyPressEvent(QKeyEvent *event) override; // Delete removes the selected ROI
[[nodiscard]] ROIDefinition BuildEditedROIDefinition() const; // current ROIs with the edit applied
[[nodiscard]] ResizeHandle hitTestBoxHandle(const QRectF &r, const QPointF &p, qreal tol) const;
// Grab points for an azimuthal ROI: inner/outer arc (resize Q/d) and the two phi
// edges (rotate). The phi handles are only meaningful for a sector (HasPhi()).
void azimuthalHandles(const ROIAzimuthal &az, const DiffractionGeometry &geom,
QPointF &inner, QPointF &outer, QPointF &phimin, QPointF &phimax) const;
QString selected_roi_;
enum class RoiEdit { None, MoveBox, ResizeBox, MoveCircle, ResizeCircle,
AzimInner, AzimOuter, RotatePhiMin, RotatePhiMax };
RoiEdit roi_edit_ = RoiEdit::None;
ResizeHandle box_handle_ = ResizeHandle::None;
QString edit_name_;
QRectF edit_box_;
QPointF edit_center_;
double edit_radius_ = 0;
float edit_d_min_ = 0, edit_d_max_ = 0, edit_phi_min_ = 0, edit_phi_max_ = 0; // azimuthal edit state
bool edit_has_phi_ = false;
QPointF move_last_;
bool live_pending_ = false; // a live edit is being recomputed; throttles emissions
void DrawSpots();
void DrawPredictions();
void DrawBeamCenter();
void DrawTopPixels();
void DrawSaturation();
void DrawResolutionText();
void DrawCross(float x, float y, float size, float width, float z = 1);
void UpdateForeground();
void leaveEvent(QEvent *event) override;
std::shared_ptr<const JFJochReaderImage> image;
int32_t show_highest_pixels = 0;
QVector<float> res_ring = {};
// Constant-d contours traced for res_ring, kept across overlay rebuilds; see DrawResolutionRings
QVector<float> ring_cache_key_ = {};
QVector<std::pair<float, QPainterPath>> ring_cache_ = {};
RingMode ring_mode = RingMode::Estimation;
bool show_spots = false;
bool show_predictions = false;
bool show_roi_labels = false;
bool show_roi_fill = false;
bool highlight_ice_rings = true;
float ice_ring_width_Q_recipA = 0.01;
void mouseHover(const QPointF &scenePos, Qt::KeyboardModifiers modifiers) override;
signals:
void roiGeometryEdited(ROIDefinition rois);
void roiSelected(QString name); // user picked an ROI by clicking it on the image
public slots:
void setSelectedROI(QString name);
void loadImage(std::shared_ptr<const JFJochReaderImage> image);
void setAutoForeground(bool input);
void setResolutionRing(QVector<float> v);
void setResolutionRingMode(RingMode mode);
void showSpots(bool input);
void showPredictions(bool input);
void showROILabels(bool input);
void showROIFill(bool input);
void setSpotColor(QColor input);
void setPredictionColor(QColor input);
void showHighestPixels(int32_t v);
void showSaturation(bool input);
void highlightIceRings(bool input);
void setHDRMode(bool input);
};