The rc178 branch continued after #88 was squash-merged; this is its content fromb9ada7914(the tree #88 squashed) to094eee31a, 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 rc1780cf62452c- 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
290 lines
12 KiB
C++
290 lines
12 KiB
C++
// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#pragma once
|
|
|
|
#include <cmath>
|
|
#include <memory>
|
|
|
|
#include <QElapsedTimer>
|
|
#include <QTimer>
|
|
#include <QGraphicsView>
|
|
#include <QGraphicsItem>
|
|
#include <QImage>
|
|
#include <QMouseEvent>
|
|
#include <QPainterPath>
|
|
#include <QTransform>
|
|
#include <QPointF>
|
|
#include "../../common/ColorScale.h"
|
|
#include "../../common/JFJochMessages.h"
|
|
|
|
// Q_DECLARE_METATYPE(ROIMessage)
|
|
|
|
// Maps one pixel value to a colour. Shared by the generic float path and by subclasses that
|
|
// colour straight out of their own buffer, so the two cannot drift apart. Apply() takes a
|
|
// real value; the callers handle their own gap/bad/saturated encoding.
|
|
struct PixelColorMap {
|
|
const rgb *lut = nullptr;
|
|
int lut_size = 0;
|
|
float minv = 0.0f;
|
|
float range = 0.0f;
|
|
float inv_range = 0.0f;
|
|
float inv_range_log = 0.0f;
|
|
bool hdr = false;
|
|
rgb gap{}, bad{}, saturated{}, beam_stop{};
|
|
|
|
[[nodiscard]] rgb Apply(float v) const {
|
|
float f;
|
|
const float v_minv = v - minv;
|
|
|
|
if (hdr) {
|
|
if (v_minv <= 0.0f)
|
|
f = 0.0f;
|
|
else if (v_minv >= range)
|
|
f = static_cast<float>(lut_size);
|
|
else
|
|
f = std::log1p(v_minv) * inv_range_log;
|
|
} else
|
|
f = v_minv * inv_range;
|
|
|
|
if (f < 0.0f) f = 0.0f;
|
|
|
|
auto idx = static_cast<int>(f + 0.5f);
|
|
if (idx <= 0) idx = 0;
|
|
else if (idx >= lut_size) idx = lut_size - 1;
|
|
return lut[idx];
|
|
}
|
|
};
|
|
|
|
// Draws a rendered frame. A QGraphicsPixmapItem would mean converting the whole image into a
|
|
// QPixmap on every recolour, which costs one extra allocation and a full pass over the pixels.
|
|
// The frame is held by shared_ptr so that several views can show the same pixels.
|
|
class JFJochImageItem : public QGraphicsItem {
|
|
std::shared_ptr<const QImage> img_;
|
|
public:
|
|
explicit JFJochImageItem(std::shared_ptr<const QImage> img) : img_(std::move(img)) {}
|
|
QRectF boundingRect() const override;
|
|
QPainterPath opaqueArea() const override;
|
|
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
|
|
void refresh(); // the buffer behind the item changed
|
|
};
|
|
|
|
class JFJochImage : public QGraphicsView {
|
|
Q_OBJECT
|
|
|
|
bool m_adjustForegroundWithWheel = false;
|
|
bool m_adjustBackgroundWithWheel = false;
|
|
|
|
// Viewport-lock support: guard prevents the emit<->apply ping-pong between
|
|
// two linked views, and the helper broadcasts the current transform+center.
|
|
bool m_applyingViewport = false;
|
|
void emitViewportChanged();
|
|
|
|
void DrawROI();
|
|
virtual void addCustomOverlay();
|
|
void updateROI();
|
|
void drawPixelLabels(QPainter *painter, const QRectF &rect);
|
|
void wheelEvent(QWheelEvent* event) override;
|
|
void resizeEvent(QResizeEvent *event) override;
|
|
void contextMenuEvent(QContextMenuEvent *event) override;
|
|
|
|
void mousePressEvent(QMouseEvent *event) override;
|
|
void mouseMoveEvent(QMouseEvent *event) override;
|
|
void mouseReleaseEvent(QMouseEvent *event) override;
|
|
|
|
protected:
|
|
// Only the view that owns detector counts offers a region of interest; for the others a
|
|
// shift-drag would draw a box that means nothing.
|
|
[[nodiscard]] virtual bool AllowROI() const { return false; }
|
|
|
|
bool show_saturation = false;
|
|
// Beam-stop shadow drawn in its own colour; off shows it as an ordinary masked pixel.
|
|
bool show_beam_stop = true;
|
|
|
|
bool auto_bg = false;
|
|
bool auto_fg = false;
|
|
bool hdr_mode = false;
|
|
|
|
double scale_factor = 1.0;
|
|
|
|
size_t W = 0, H = 0;
|
|
// Scene position of the image's top-left pixel: the image covers [origin_, origin_ + (W, H)) of the
|
|
// scene. Zero but for a detector plane raster that starts elsewhere (JFJochDiffractionImage).
|
|
QPointF origin_{0, 0};
|
|
[[nodiscard]] QRectF ImageRect() const { return {origin_, QSizeF(static_cast<qreal>(W), static_cast<qreal>(H))}; }
|
|
size_t prev_W = 0, prev_H = 0;
|
|
|
|
// Height of one pixel as it is drawn, in units of its width. 1.0 for a detector image, where
|
|
// pixels are square; a grid scan whose x and y steps differ sets it so that a cell is drawn
|
|
// in the proportion of the area it covers. Only the view transform is anisotropic - scene
|
|
// coordinates stay one unit per pixel everywhere.
|
|
qreal pixel_aspect_ = 1.0;
|
|
qreal prev_aspect_ = 1.0;
|
|
|
|
// Track initial fit state and last image size
|
|
bool initial_fit_done_ = false;
|
|
|
|
QColor feature_color = Qt::magenta;
|
|
|
|
// Decimal places for non-integer per-pixel value labels. Float images are
|
|
// unreadable with many decimals, so subclasses can lower this.
|
|
int label_decimals_ = 3;
|
|
|
|
float foreground = 10.0;
|
|
float background = 0.0;
|
|
ColorScale color_scale;
|
|
std::vector<float> image_fp;
|
|
// The rendered RGB frame. Reused across frames (no per-frame allocation) and held by
|
|
// shared_ptr so follower views can display the very same pixels - see JFJochFollowerImage.
|
|
// The pointer itself is stable for the lifetime of the widget; only its contents change.
|
|
std::shared_ptr<QImage> frame_ = std::make_shared<QImage>();
|
|
|
|
// Persistent image item — never destroyed/recreated on overlay update
|
|
JFJochImageItem *image_item_ = nullptr;
|
|
// Overlay items managed separately
|
|
QList<QGraphicsItem *> overlay_items_;
|
|
|
|
// Helper: add an overlay item to the scene and track it for selective removal
|
|
void addOverlayItem(QGraphicsItem *item);
|
|
|
|
enum class MouseEventType {None, Panning, DrawingROI, MovingROI, ResizingROI, EditingExternalROI};
|
|
MouseEventType mouse_event_type = MouseEventType::None;
|
|
|
|
// Hooks for editing a named, persistent ROI drawn by a subclass (the base only
|
|
// owns the mouse events; the subclass knows the loaded ROIs). roiEditPress returns
|
|
// true to claim the gesture for ROI editing.
|
|
virtual bool roiEditPress(const QPointF &scenePos) { return false; }
|
|
virtual void roiEditMove(const QPointF &scenePos) {}
|
|
virtual void roiEditRelease() {}
|
|
virtual void roiScratchDrawn() {} // a shift/ctrl-drag finished drawing a new box/circle
|
|
QPoint lastMousePos; // To track panning movement
|
|
|
|
// Resizing which edge/corner
|
|
enum class ResizeHandle { None, Left, Right, Top, Bottom, TopLeft, TopRight, BottomLeft, BottomRight, Inside };
|
|
ResizeHandle active_handle_ = ResizeHandle::None;
|
|
ResizeHandle hover_handle_ = ResizeHandle::None;
|
|
|
|
enum class RoiType {RoiBox, RoiCircle};
|
|
RoiType roi_type = RoiType::RoiBox;
|
|
QPointF roiStartPos;
|
|
QPointF roiEndPos;
|
|
QRectF roiBox;
|
|
|
|
// Text for the per-pixel value label at (x, y). The base reads image_fp, which is what the
|
|
// float-valued views hold; a view whose source is exact integers overrides this so the label
|
|
// is exact and no float copy of the image has to exist at all.
|
|
[[nodiscard]] virtual QString PixelLabel(int x, int y) const;
|
|
void drawForeground(QPainter *painter, const QRectF &rect) override;
|
|
|
|
static QPointF RoundPoint(const QPointF& p);
|
|
virtual void mouseHover(const QPointF &scenePos, Qt::KeyboardModifiers modifiers) = 0;
|
|
|
|
// Hover feedback (status bar, resolution readout, magnifier) used to be regenerated on every
|
|
// single mouse motion. Each regeneration dirties the window, and on a remote X session every
|
|
// repaint costs a full-window pixel upload, so the thing to minimise is the number of
|
|
// repaints. ~15 Hz is far below the motion event rate and well above what the eye follows.
|
|
//
|
|
// The rate limit is applied inline rather than from a timer on purpose: running the update
|
|
// inside the mouse event keeps its damage in the same repaint as anything else that event
|
|
// triggers (a pan), instead of costing a second one. The timer only covers the tail, so the
|
|
// final position is still reported once the pointer stops.
|
|
static constexpr int kHoverIntervalMs = 66;
|
|
void ScheduleHoverUpdate(const QPointF &scenePos, Qt::KeyboardModifiers modifiers);
|
|
void UpdateHover();
|
|
void leaveEvent(QEvent *event) override;
|
|
QPointF hover_scene_pos_;
|
|
Qt::KeyboardModifiers hover_modifiers_ = Qt::NoModifier;
|
|
QElapsedTimer hover_rate_;
|
|
QTimer *hover_tail_timer_ = nullptr;
|
|
|
|
// Panning and wheel zooming repaint once per input event, which is fine locally and hopeless
|
|
// on a remote display (see ScheduleHoverUpdate above - same reasoning, same cadence, same
|
|
// inline-plus-tail shape). On a remote session the skipped events only accumulate - a pan its
|
|
// pixel delta, a zoom its wheel steps - and the accumulated gesture is applied whole, so the
|
|
// view ends exactly where the same gesture would have put it unthrottled. Locally every event
|
|
// is still applied inline and nothing changes.
|
|
void ApplyPendingPan();
|
|
QPoint pending_pan_;
|
|
QElapsedTimer pan_rate_;
|
|
QTimer *pan_tail_timer_ = nullptr;
|
|
|
|
void ApplyPendingZoom();
|
|
int pending_zoom_steps_ = 0;
|
|
QPoint zoom_anchor_vp_;
|
|
QElapsedTimer zoom_rate_;
|
|
QTimer *zoom_tail_timer_ = nullptr;
|
|
|
|
ResizeHandle hitTestROIHandle(const QPointF& scenePos, qreal tol = 3.0) const;
|
|
|
|
void updateOverlay();
|
|
void RenderImage();
|
|
PixelColorMap MakeColorMap() const;
|
|
// Colour one row into `out`. Called from worker threads, so it must stay const. The base
|
|
// maps image_fp; a subclass whose source is already a compact buffer can map that directly
|
|
// and skip materialising the float image.
|
|
virtual void ColorRow(size_t y, const PixelColorMap &map, QRgb *out) const;
|
|
// Re-render once the event queue drains. The foreground slider and the wheel emit far
|
|
// faster than a large image can be recoloured, so intermediate values are dropped
|
|
// instead of queueing a full recolour per event. On a remote display the drain still
|
|
// repaints once per event, so there the recolour is additionally held to the hover cadence.
|
|
void ScheduleRenderImage();
|
|
bool render_pending_ = false;
|
|
QElapsedTimer render_rate_;
|
|
QTimer *render_tail_timer_ = nullptr;
|
|
bool image_dirty_ = false; // frame_ changed since the item was last refreshed
|
|
void ClearFrame(); // drop the pixels and tell followers
|
|
// Set while a pan/zoom moves the scrollbars, so onScroll() does not rebuild the overlay
|
|
// once per scrollbar; the gesture rebuilds it once itself.
|
|
bool suppress_overlay_update_ = false;
|
|
void Redraw();
|
|
|
|
// Invalidate image_item_ and overlay tracking after scene()->clear()
|
|
void resetScenePointers();
|
|
|
|
// Perform initial fit-to-view (shorter direction), once per image size
|
|
void fitToViewShorterSideOnce();
|
|
|
|
// Render the current frame to an image at native resolution, optionally including the overlay
|
|
// (spots, predictions, rings, ROIs). Used by both the clipboard and save-to-file actions.
|
|
QImage renderToImage(bool with_overlay);
|
|
void copyImageToClipboard();
|
|
void copyImageWithOverlayToClipboard();
|
|
void saveImageToFile(bool with_overlay);
|
|
void clearROIInternal();
|
|
signals:
|
|
void autoForegroundChanged(bool input);
|
|
void foregroundChanged(float v);
|
|
void backgroundChanged(float v);
|
|
void writeStatusBar(QString string, int timeout_ms = 0);
|
|
void roiBoxUpdated(QRect box);
|
|
void roiCircleUpdated(double x, double y, double radius);
|
|
void viewportChanged(QTransform transform, QPointF center);
|
|
// A new frame has been rendered into Frame(). Follower views repaint on this.
|
|
void frameRendered();
|
|
// Asks for a move through the dataset (e.g. Home/End/PageUp/PageDown in a subclass'
|
|
// keyPressEvent): the navigation toolbar applies the step, clamped to the dataset's range.
|
|
void stepImage(int steps);
|
|
private slots:
|
|
void onScroll(int value);
|
|
public slots:
|
|
void setFeatureColor(QColor input);
|
|
void setColorMap(int color_map);
|
|
virtual void changeForeground(float val);
|
|
void changeBackground(float val);
|
|
|
|
void SetROIBox(QRect box);
|
|
void SetROICircle(double x, double y, double radius);
|
|
|
|
void centerOnSpot(QPointF point);
|
|
void applyViewport(QTransform transform, QPointF center);
|
|
void fitToView();
|
|
|
|
void adjustForeground(bool input);
|
|
void adjustBackground(bool input);
|
|
void setZoom(double input);
|
|
public:
|
|
explicit JFJochImage(QWidget *parent = nullptr);
|
|
double GetScaleFactor() const;
|
|
// The rendered frame, for views that want to show the same pixels without redoing the work
|
|
[[nodiscard]] std::shared_ptr<const QImage> Frame() const { return frame_; }
|
|
}; |