Files
Jungfraujoch/viewer/image_viewer/JFJochDiffractionImage.cpp
T
leonarski_f 9aae0c2ba7
Build Packages / Create release (push) Successful in 21s
Build Packages / build:rugnux-tgz (x86_64) (push) Successful in 9m40s
Build Packages / build:rugnux:aarch64 (cross) (push) Successful in 9m49s
Build Packages / build:viewer-tgz:cpu (push) Successful in 11m37s
Build Packages / build:viewer-tgz:cuda (push) Successful in 12m40s
Build Packages / build:windows:nocuda (push) Successful in 17m44s
Build Packages / build:windows:cuda (push) Successful in 20m13s
Build Packages / build:rpm (rocky8_nocuda) (push) Successful in 14m41s
Build Packages / HDF5 consumer tests (DIALS, XDS) (push) Successful in 25m59s
Build Packages / build:rpm (ubuntu2204_nocuda) (push) Successful in 15m5s
Build Packages / build:rpm (ubuntu2404_nocuda) (push) Successful in 14m35s
Build Packages / build:rpm (rocky9_nocuda) (push) Successful in 15m53s
Build Packages / build:rugnux:windows (push) Successful in 11m29s
Build Packages / build:rpm (rocky8_sls9) (push) Successful in 18m51s
Build Packages / build:rpm (rocky9_sls9) (push) Successful in 18m43s
Build Packages / Generate python client (push) Successful in 51s
Build Packages / build:rpm (rocky8) (push) Successful in 18m51s
Build Packages / Build documentation (push) Successful in 1m21s
Build Packages / build:rpm (ubuntu2204) (push) Successful in 18m38s
Build Packages / build:rpm (ubuntu2404) (push) Successful in 18m24s
Build Packages / build:rpm (rocky9) (push) Successful in 19m19s
Build Packages / Unit tests (push) Successful in 1h37m15s
v1.0.0-rc.169 (#79)
* Building Jungfraujoch no longer needs zlib or Eigen installed on the machine, and the dependencies the build fetches are pinned and updated to current releases.
* rugnux: improvements in indexing, lattice selection and geometry post-refinement, which index crystals that previously returned no lattice and keep the better of the two geometries a run measures.
* rugnux: improvements in beam-centre measurement, beam-stop detection and space-group determination.
* rugnux: the unit cell reported with a determined space group now obeys that group - a cell whose symmetry was confirmed from the intensities is re-refined under it, and a cell the group cannot describe is reported with a warning rather than as it stands.
* rugnux drops the stretches of a rotation sweep whose removal measurably improves the merged intensities and reports what became of every frame, and decides the resolution cut on the crystal's own diffraction rather than on its ice rings.
* The rugnux results report is machine-readable - every line that is not `KEY= value` data starts with `#` - and states the build it was written by, its authorship and its terms of use (`REPORT_VERSION= 8`).
* `jfjoch_viewer`: improvements in the file manager (CBF frames beside HDF5 datasets, a remembered root), the dataset plots, the inspector and the image statistics, plus a settable font size, a view of the rugnux results report, usable performance over a remote display (`ssh -X`) and a reset of all settings to defaults; the reciprocal-space window is removed.
* Broker fixes around DECTRIS collections and dark-mask calibration: re-initialising after a run that never started no longer freezes the broker, a cancelled calibration is abandoned instead of reported as done, and a collection whose start message never arrives ends by itself.

Reviewed-on: #79
Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
2026-09-15 17:09:31 +02:00

1172 lines
45 KiB
C++

// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include <set>
#include "JFJochDiffractionImage.h"
#include "../../common/DiffractionGeometry.h"
#include "../../common/JFJochMath.h"
#include "../../common/ROIAzimuthal.h"
#include "../../image_analysis/bragg_integration/SystematicAbsence.h"
#include "../widgets/ROIColorPalette.h"
#include <QPainterPath>
#include <QBrush>
#include <QKeyEvent>
#include <QGraphicsPixmapItem>
#include <QGraphicsSimpleTextItem>
#include <QGraphicsScene>
#include <QWheelEvent>
#include <QScrollBar>
#include <QMenu>
#include <cmath>
#include <limits>
#include <QMouseEvent>
#include "JFJochSimpleImage.h"
// Constructor
static bool InPhiSector(float phi, float phi_min, float phi_max) {
if (phi_min <= phi_max)
return phi >= phi_min && phi <= phi_max;
return phi >= phi_min || phi <= phi_max;
}
JFJochDiffractionImage::JFJochDiffractionImage(QWidget *parent) : JFJochImage(parent) {
setFocusPolicy(Qt::StrongFocus); // so the Delete key reaches the view
}
JFJochImage::ResizeHandle JFJochDiffractionImage::hitTestBoxHandle(const QRectF &r, const QPointF &p, qreal tol) const {
auto on = [&](qreal a, qreal b) { return std::abs(a - b) <= tol; };
const bool L = on(p.x(), r.left()), R = on(p.x(), r.right());
const bool T = on(p.y(), r.top()), B = on(p.y(), r.bottom());
const bool inX = p.x() >= r.left() - tol && p.x() <= r.right() + tol;
const bool inY = p.y() >= r.top() - tol && p.y() <= r.bottom() + tol;
if (L && T) return ResizeHandle::TopLeft;
if (R && T) return ResizeHandle::TopRight;
if (L && B) return ResizeHandle::BottomLeft;
if (R && B) return ResizeHandle::BottomRight;
if (L && inY) return ResizeHandle::Left;
if (R && inY) return ResizeHandle::Right;
if (T && inX) return ResizeHandle::Top;
if (B && inX) return ResizeHandle::Bottom;
if (r.contains(p)) return ResizeHandle::Inside;
return ResizeHandle::None;
}
void JFJochDiffractionImage::azimuthalHandles(const ROIAzimuthal &az, const DiffractionGeometry &geom,
QPointF &inner, QPointF &outer, QPointF &phimin, QPointF &phimax) const {
const float d2r = static_cast<float>(PI) / 180.0f;
const float phi0 = az.GetPhiMin_deg();
const float phi1 = az.GetPhiMax_deg();
const float mid_phi = az.HasPhi()
? (phi1 >= phi0 ? (phi0 + phi1) / 2.0f : std::fmod((phi0 + phi1 + 360.0f) / 2.0f, 360.0f))
: 0.0f;
const float r_inner = geom.ResToPxl(az.GetDMax_A());
const float r_outer = geom.ResToPxl(az.GetDMin_A());
const float d_mid = geom.PxlToRes((r_inner + r_outer) / 2.0f);
auto pt = [&](float d, float phi_deg) -> QPointF {
try {
auto [x, y] = geom.ResPhiToPxl(d, phi_deg * d2r);
return QPointF(x, y);
} catch (...) {
return QPointF(-1e9, -1e9); // off-image: never matches a handle hit-test
}
};
inner = pt(az.GetDMax_A(), mid_phi);
outer = pt(az.GetDMin_A(), mid_phi);
phimin = pt(d_mid, phi0);
phimax = pt(d_mid, phi1);
}
void JFJochDiffractionImage::mouseHover(const QPointF &coord, Qt::KeyboardModifiers) {
if (image && (coord.x() >= 0)
&& (coord.x() < image->Dataset().experiment.GetXPixelsNum())
&& (coord.y() >= 0)
&& (coord.y() < image->Dataset().experiment.GetYPixelsNum())) {
float res = image->Dataset().experiment.GetDiffractionGeometry().PxlToRes(coord.x(), coord.y());
int32_t intensity = image->Image()[std::floor(coord.x()) +
std::floor(coord.y()) * image->Dataset().experiment.GetXPixelsNum()];
QString intensity_str = QString("I=%1").arg(intensity, 9);
if (intensity == SATURATED_PXL_VALUE)
intensity_str = "I=Saturated";
else if (intensity == GAP_PXL_VALUE)
intensity_str = " Gap ";
else if (intensity == ERROR_PXL_VALUE)
intensity_str = " Bad pxl ";
else if (intensity == BEAM_STOP_PXL_VALUE)
intensity_str = " Beam stop ";
emit writeStatusBar(QString("x=%1 y=%2 %3 d=%4 Å")
.arg(coord.x(), 0, 'f', 1)
.arg(coord.y(), 0, 'f', 1)
.arg(intensity_str)
.arg(res, 0, 'f', 2));
// Update hovered resolution text without rebuilding the whole overlay
hover_resolution = res;
DrawResolutionText();
} else {
emit writeStatusBar("");
// Clear hover resolution text when outside image
if (std::isfinite(hover_resolution)) {
hover_resolution = NAN;
DrawResolutionText();
}
}
}
void JFJochDiffractionImage::LoadImageInternal() {
if (!image)
return;
W = image->Dataset().experiment.GetXPixelsNum();
H = image->Dataset().experiment.GetYPixelsNum();
}
void JFJochDiffractionImage::ColorRow(size_t y, const PixelColorMap &map, QRgb *out) const {
const int32_t *row = &image->Image()[y * W];
for (size_t x = 0; x < W; ++x) {
const int32_t v = row[x];
// The markers occupy the extremes of the int32 range, so one range test separates them
// from every real pixel value (MIN_REAL_PXL_VALUE moves when a marker is added)
rgb c;
if (v >= MIN_REAL_PXL_VALUE && v < SATURATED_PXL_VALUE)
c = map.Apply(static_cast<float>(v));
else if (v == GAP_PXL_VALUE)
c = map.gap;
else if (v == BEAM_STOP_PXL_VALUE)
c = map.beam_stop;
else
c = (v == ERROR_PXL_VALUE) ? map.bad : map.saturated;
out[x] = qRgb(c.r, c.g, c.b);
}
}
void JFJochDiffractionImage::DrawSpots() {
// Compute current visible area in scene coordinates
const QRectF visibleRect = mapToScene(viewport()->geometry()).boundingRect();
QPen casing_pen(Qt::black, 3 + MARKER_CASING_EXTRA_WIDTH);
casing_pen.setCosmetic(true);
for (const auto &s: image->ImageData().spots) {
// Skip reflections outside the viewport
if (!visibleRect.contains(QPointF{s.x, s.y}))
continue;
if (hide_unindexed_spots && !s.indexed)
continue;
if (hide_ice_ring_spots && s.ice_ring)
continue;
const qreal desired_half_px = 8.0;
const qreal spot_size = desired_half_px / std::sqrt(std::max(0.0001, scale_factor));
QColor pen_color = spot_color;
if (s.indexed)
pen_color = (s.lattice >= 1) ? second_lattice_color : feature_color;
else if (highlight_ice_rings && s.ice_ring)
pen_color = ice_ring_color;
QPen pen(pen_color, 3);
pen.setCosmetic(true);
const QRectF box(s.x - spot_size + 0.5, s.y - spot_size + 0.5, 2 * spot_size, 2 * spot_size);
addOverlayItem(scene()->addRect(box, casing_pen)); // added first, so it stays underneath
addOverlayItem(scene()->addRect(box, pen));
}
}
void JFJochDiffractionImage::DrawPredictions() {
QFont font("Arial", 2); // Font for pixel value text
font.setPixelSize(2); // This will render very small text (1-pixel high).
const qreal desired_half_px = 8.0;
const qreal spot_size = desired_half_px / std::sqrt(std::max(0.0001, scale_factor));
QColor pen_color = prediction_color;
QPen pen(pen_color, 3);
pen.setCosmetic(true);
// Compute current visible area in scene coordinates
const QRectF visibleRect = mapToScene(viewport()->geometry()).boundingRect();
// In space-group search mode the centering-absent reflections are integrated (to confirm the
// centering), but they are not real predictions - keep them out of the overlay.
const char centering = image->ImageData().lattice_type.has_value()
? image->ImageData().lattice_type->centering : 'P';
for (const auto &s: image->ImageData().reflections) {
if (systematic_absence(s.h, s.k, s.l, centering))
continue;
// Skip reflections outside the viewport
if (!visibleRect.contains(QPointF{s.predicted_x, s.predicted_y}))
continue;
auto *ellipse = scene()->addEllipse(s.predicted_x - spot_size + 0.5f,
s.predicted_y - spot_size + 0.5f,
2.0f * spot_size,
2.0f * spot_size,
pen);
addOverlayItem(ellipse);
// When zoomed in enough, draw "h k l" above the box
if (scale_factor >= 10.0) {
// Format label
QString label = QString("%1, %2, %3").arg(s.h).arg(s.k).arg(s.l);
// Position slightly above the top side of the box
const qreal text_x = s.predicted_x - 5.5f;
const qreal text_y = s.predicted_y - 10.0f;
// Use QGraphicsSimpleTextItem for much better performance
auto *textItem = new QGraphicsSimpleTextItem(label);
textItem->setFont(font);
textItem->setBrush(pen_color);
textItem->setPos(text_x, text_y);
scene()->addItem(textItem);
addOverlayItem(textItem);
}
}
}
void JFJochDiffractionImage::DrawResolutionRings() {
if (ring_mode == RingMode::None)
return;
// Get the visible area in the scene coordinates (viewport()->rect(), not geometry():
// mapToScene takes viewport coordinates, and geometry() is offset by the viewport's
// position in its parent).
QRectF visibleRect = mapToScene(viewport()->rect()).boundingRect();
int startX = std::max(0, static_cast<int>(std::floor(visibleRect.left())));
int endX = std::min(static_cast<int>(image->Dataset().experiment.GetXPixelsNum()),
static_cast<int>(std::ceil(visibleRect.right())));
int startY = std::max(0, static_cast<int>(std::floor(visibleRect.top())));
int endY = std::min(static_cast<int>(image->Dataset().experiment.GetYPixelsNum()),
static_cast<int>(std::ceil(visibleRect.bottom())));
auto geom = image->Dataset().experiment.GetDiffractionGeometry();
QColor ring_color = feature_color;
if (ring_mode == RingMode::IceRings) {
ring_color = ice_ring_color;
res_ring = QVector<float>{ICE_RING_RES_A.begin(), ICE_RING_RES_A.end()};
} else if (ring_mode == RingMode::Auto) {
float radius_x_0 = geom.GetBeamX_pxl() - startX;
float radius_x_1 = endX - geom.GetBeamX_pxl();
float radius_x = std::max(radius_x_0, radius_x_1);
float radius_y_0 = geom.GetBeamY_pxl() - startY;
float radius_y_1 = endY - geom.GetBeamY_pxl();
float radius_y = std::max(radius_y_0, radius_y_1);
float radius = std::min(radius_x, radius_y);
if (radius_x <= 0)
radius = radius_y;
if (radius_y <= 0)
radius = radius_x;
if (radius > 0)
res_ring = {
geom.PxlToRes(radius / 2.0f),
geom.PxlToRes(radius / 1.02f)
};
else
res_ring = {};
} else if (ring_mode == RingMode::Estimation) {
if (image
&& image->ImageData().resolution_estimate
&& std::isfinite(image->ImageData().resolution_estimate.value())
&& image->ImageData().resolution_estimate.value() > 0.0)
res_ring = {*image->ImageData().resolution_estimate};
else
res_ring = {};
}
if (res_ring.empty())
return;
QPen pen(ring_color, 5);
pen.setCosmetic(true);
QVector<qreal> dashPattern = {10, 15};
pen.setDashPattern(dashPattern);
int label_stagger = 0;
// Tracing the contours costs 361 geometry evaluations per ring, and they only move when the
// ring list or the geometry changes - not when the view is panned or zoomed, which is when
// most overlay rebuilds happen. Keep them until the ring list changes; loadImage() clears
// the cache so a new geometry re-traces.
if (ring_cache_key_ != res_ring) {
ring_cache_key_ = res_ring;
ring_cache_.clear();
float res1 = geom.PxlToRes(0,0);
float res2 = geom.PxlToRes(image->Dataset().experiment.GetXPixelsNum(),0);
float res3 = geom.PxlToRes(image->Dataset().experiment.GetXPixelsNum(),image->Dataset().experiment.GetYPixelsNum());
float res4 = geom.PxlToRes(0,image->Dataset().experiment.GetYPixelsNum());
float min_res = std::min({res1, res2, res3, res4});
for (const auto &d: res_ring) {
if (d < min_res)
continue;
// Trace the constant-d contour through the geometry - a circle on an untilted detector,
// a conic on a tilted one - the same way an azimuthal ROI arc is drawn, instead of
// approximating it with an axis-aligned bounding-box ellipse. ResPhiToPxl throws when d is
// too high for the wavelength, and returns NaN where the contour leaves the detector plane.
QPainterPath path;
bool started = false;
bool valid = true;
constexpr int steps = 360;
for (int i = 0; i <= steps; i++) {
const float phi = 2.0f * static_cast<float>(PI) * static_cast<float>(i) / static_cast<float>(steps);
try {
auto [x, y] = geom.ResPhiToPxl(d, phi);
if (!std::isfinite(x) || !std::isfinite(y)) {
started = false; // break the subpath where the ring leaves the detector
continue;
}
if (!started) { path.moveTo(x, y); started = true; }
else path.lineTo(x, y);
} catch (...) {
valid = false;
break;
}
}
if (!valid || path.isEmpty())
continue;
ring_cache_.push_back({d, path});
}
}
for (const auto &[d, path]: ring_cache_) {
addOverlayItem(scene()->addPath(path, pen));
// The "d Å" label is drawn in device coordinates (ItemIgnoresTransformations), so it
// keeps a constant on-screen size - the application font, a step up and bold - at every
// zoom; shrinking a scene-space font by 1/zoom instead breaks glyph rendering once the
// point size drops below one. No outline; the colour is picked from what ends up under
// the label, white only over the image of a dark colour map. It is centred on the first
// sampled azimuth (staggered per ring) where the whole text fits in the viewport;
// failing that, on the visible ring point closest to the viewport centre, clamped
// inside - never half a label off the edge.
QFont font = this->font();
font.setPointSizeF(font.pointSizeF() * 1.6);
font.setBold(true);
auto *textItem = new QGraphicsSimpleTextItem(
QString("%1 Å").arg(QString::number(d, 'f', 2)));
textItem->setFont(font);
textItem->setFlag(QGraphicsItem::ItemIgnoresTransformations);
textItem->setPen(Qt::NoPen); // brush is chosen below, from what ends up under the label
// Device-size text: convert to scene units for the placement math below.
const qreal sx = std::max(1e-6, transform().m11());
const qreal sy = std::max(1e-6, transform().m22());
const QSizeF dev = textItem->boundingRect().size();
const QSizeF sz(dev.width() / sx, dev.height() / sy);
QRectF inner = visibleRect.adjusted(sz.height() * 0.3, sz.height() * 0.3,
-sz.height() * 0.3, -sz.height() * 0.3);
if (!inner.isValid())
inner = visibleRect;
bool have_label = false;
bool fits = false;
QPointF label_center;
double best_dist = std::numeric_limits<double>::max();
// Walk the ring's own traced points (dense enough that a narrow visible arc is never
// missed), starting at a per-ring stagger so neighbouring rings label different azimuths.
const int n = path.elementCount();
for (int k = 0; k < n; k++) {
const auto e = path.elementAt((k + label_stagger) % n);
const QPointF p(e.x, e.y);
if (!visibleRect.contains(p))
continue;
const QRectF r(p - QPointF(sz.width() / 2, sz.height() / 2), sz);
if (inner.contains(r)) {
label_center = p;
have_label = true;
fits = true;
break;
}
const double dist = QLineF(p, visibleRect.center()).length();
if (dist < best_dist) {
best_dist = dist;
label_center = p;
have_label = true;
}
}
if (have_label) {
QRectF r(label_center - QPointF(sz.width() / 2, sz.height() / 2), sz);
if (!fits) {
if (r.left() < inner.left()) r.moveLeft(inner.left());
if (r.right() > inner.right()) r.moveRight(inner.right());
if (r.top() < inner.top()) r.moveTop(inner.top());
if (r.bottom() > inner.bottom()) r.moveBottom(inner.bottom());
}
// The label prints dark unless it lands on the image with a dark colour map: off the
// image the canvas is white whatever the map, and on its own magenta dashes either
// colour separates where the ring colour would blend.
const auto map_zero = color_scale.Apply(0.0f);
const double zero_luminance = 0.2126 * map_zero.r + 0.7152 * map_zero.g + 0.0722 * map_zero.b;
const bool dark_under = zero_luminance <= 127.0
&& QRectF(0, 0, static_cast<qreal>(W), static_cast<qreal>(H)).contains(r.center());
textItem->setBrush(dark_under ? QColor(Qt::white) : QColor(0x20, 0x20, 0x20));
textItem->setPos(r.topLeft());
scene()->addItem(textItem);
addOverlayItem(textItem);
} else {
delete textItem;
}
label_stagger += 29;
}
}
void JFJochDiffractionImage::DrawBeamCenter() {
auto geom = image->Dataset().experiment.GetDiffractionGeometry();
auto [beam_x, beam_y] = geom.GetDirectBeam_pxl();
// + 0.5 as everywhere else in the overlay: our coordinates are pixel-centred, the scene's are
// pixel-cornered (pixel i covers [i, i+1)), so the cross would otherwise sit half a pixel off the
// spots and the image.
DrawCross(beam_x + 0.5f, beam_y + 0.5f, 25, 5, 2);
}
void JFJochDiffractionImage::DrawTopPixels() {
int i = 0;
for (const auto& p : image->GetTopPixels()) {
if (i >= show_highest_pixels)
break;
const int32_t idx = p.second;
DrawCross(idx % image->Dataset().experiment.GetXPixelsNum() + 0.5,
idx / image->Dataset().experiment.GetXPixelsNum() + 0.5, 15, 3);
i++;
}
}
void JFJochDiffractionImage::addCustomOverlay() {
DrawResolutionRings();
DrawROIs();
DrawTopPixels();
DrawBeamCenter();
if (show_spots)
DrawSpots();
if (show_predictions)
DrawPredictions();
if (show_saturation)
DrawSaturation();
}
void JFJochDiffractionImage::DrawROIs() {
if (!image)
return;
const auto &rois = image->Dataset().experiment.ROI().GetROIDefinition();
auto geom = image->Dataset().experiment.GetDiffractionGeometry();
// Distinct colours per ROI (shared with the ROI-list swatches via ROIAnnotationColor); loaded
// ROIs use solid lines (the interactively drawn scratch ROI keeps its dashed feature_color).
// TODO: align this palette with the ROI colours in the bottom-panel plots.
int color_index = 0;
auto fill_brush = [&](const QColor &c) {
return show_roi_fill ? QBrush(QColor(c.red(), c.green(), c.blue(), 60)) : QBrush(Qt::NoBrush);
};
auto draw_handle = [&](const QPointF &p, const QColor &c) {
const qreal s = 4.0 / std::sqrt(std::max(1e-4, scale_factor));
addOverlayItem(scene()->addRect(QRectF(p.x() - s, p.y() - s, 2 * s, 2 * s), QPen(c, 1), QBrush(c)));
};
for (const auto &b : rois.boxes) {
QColor c = ROIAnnotationColor(color_index++);
const bool selected = (QString::fromStdString(b.GetName()) == selected_roi_);
const bool editing = b.GetName() == edit_name_.toStdString()
&& (roi_edit_ == RoiEdit::MoveBox || roi_edit_ == RoiEdit::ResizeBox);
QPen pen(c, selected ? 3 : 2);
pen.setCosmetic(true);
if (selected) pen.setStyle(Qt::DashLine); // highlight the editable ROI
const QRectF rect = editing ? edit_box_
: QRectF(b.GetXMin(), b.GetYMin(), b.GetWidth(), b.GetHeight());
addOverlayItem(scene()->addRect(rect, pen, fill_brush(c)));
AddROILabel(b.GetName(), c, rect.left(), rect.top());
if (selected) {
draw_handle(rect.topLeft(), c); draw_handle(rect.topRight(), c);
draw_handle(rect.bottomLeft(), c); draw_handle(rect.bottomRight(), c);
draw_handle({rect.center().x(), rect.top()}, c);
draw_handle({rect.center().x(), rect.bottom()}, c);
draw_handle({rect.left(), rect.center().y()}, c);
draw_handle({rect.right(), rect.center().y()}, c);
}
}
for (const auto &c_roi : rois.circles) {
QColor c = ROIAnnotationColor(color_index++);
const bool selected = (QString::fromStdString(c_roi.GetName()) == selected_roi_);
const bool editing = c_roi.GetName() == edit_name_.toStdString()
&& (roi_edit_ == RoiEdit::MoveCircle || roi_edit_ == RoiEdit::ResizeCircle);
QPen pen(c, selected ? 3 : 2);
pen.setCosmetic(true);
if (selected) pen.setStyle(Qt::DashLine);
const QPointF center = editing ? edit_center_ : QPointF(c_roi.GetX(), c_roi.GetY());
const double r = editing ? edit_radius_ : c_roi.GetRadius_pxl();
addOverlayItem(scene()->addEllipse(center.x() - r, center.y() - r, 2 * r, 2 * r, pen, fill_brush(c)));
AddROILabel(c_roi.GetName(), c, center.x(), center.y());
if (selected) {
draw_handle({center.x() + r, center.y()}, c);
draw_handle({center.x() - r, center.y()}, c);
draw_handle({center.x(), center.y() + r}, c);
draw_handle({center.x(), center.y() - r}, c);
}
}
for (const auto &az_committed : rois.azimuthal) {
QColor c = ROIAnnotationColor(color_index++);
const bool selected = (QString::fromStdString(az_committed.GetName()) == selected_roi_);
const bool editing = az_committed.GetName() == edit_name_.toStdString()
&& (roi_edit_ == RoiEdit::AzimInner || roi_edit_ == RoiEdit::AzimOuter
|| roi_edit_ == RoiEdit::RotatePhiMin || roi_edit_ == RoiEdit::RotatePhiMax);
const ROIAzimuthal az = editing
? (edit_has_phi_ ? ROIAzimuthal(az_committed.GetName(), edit_d_min_, edit_d_max_, edit_phi_min_, edit_phi_max_)
: ROIAzimuthal(az_committed.GetName(), edit_d_min_, edit_d_max_))
: az_committed;
DrawAzimuthalROI(az, c, geom);
if (selected) {
QPointF inner, outer, pmin, pmax;
azimuthalHandles(az, geom, inner, outer, pmin, pmax);
draw_handle(inner, c);
draw_handle(outer, c);
if (az.HasPhi()) {
draw_handle(pmin, c);
draw_handle(pmax, c);
}
}
}
}
void JFJochDiffractionImage::AddROILabel(const std::string &name, const QColor &color, float px, float py) {
if (!show_roi_labels)
return;
// Just the name; per-ROI statistics are shown in the side-panel ROI list.
auto *text = scene()->addText(QString::fromStdString(name));
text->setDefaultTextColor(color);
text->setFlag(QGraphicsItem::ItemIgnoresTransformations); // constant on-screen size
text->setPos(px, py);
addOverlayItem(text);
}
void JFJochDiffractionImage::DrawAzimuthalROI(const ROIAzimuthal &az, const QColor &color,
const DiffractionGeometry &geom) {
const bool selected = (QString::fromStdString(az.GetName()) == selected_roi_);
QPen pen(color, selected ? 3 : 2); pen.setCosmetic(true);
if (selected) pen.setStyle(Qt::DashLine);
QBrush brush = show_roi_fill ? QBrush(QColor(color.red(), color.green(), color.blue(), 60))
: QBrush(Qt::NoBrush);
const float d_inner = az.GetDMax_A(); // larger d -> smaller radius
const float d_outer = az.GetDMin_A();
auto deg2rad = [](float d) { return d * static_cast<float>(PI) / 180.0f; };
// Sample the boundary through the geometry so the wedge matches the ROI footprint.
// ResPhiToPxl throws when the resolution is too high for the wavelength; skip such ROIs.
// move_to_start == true begins a new subpath (no connecting line); false continues
// the current one (used for the radial edge between a sector's outer and inner arc).
auto add_arc = [&](QPainterPath &path, float d, float phi_a, float phi_b, int steps, bool move_to_start) -> bool {
for (int i = 0; i <= steps; i++) {
float phi = phi_a + (phi_b - phi_a) * static_cast<float>(i) / static_cast<float>(steps);
try {
auto [px, py] = geom.ResPhiToPxl(d, phi);
if (move_to_start && i == 0)
path.moveTo(px, py);
else
path.lineTo(px, py);
} catch (...) { return false; }
}
return true;
};
QPainterPath path;
if (az.HasPhi()) {
float phi0 = deg2rad(az.GetPhiMin_deg());
float phi1 = deg2rad(az.GetPhiMax_deg());
if (phi1 < phi0) phi1 += 2.0f * static_cast<float>(PI); // unwrap the sector
int steps = std::max(8, static_cast<int>((phi1 - phi0) * 180.0f / static_cast<float>(PI) / 2.0f));
if (!add_arc(path, d_outer, phi0, phi1, steps, true)) return; // outer arc
if (!add_arc(path, d_inner, phi1, phi0, steps, false)) return; // inner arc; radial edges close it
path.closeSubpath();
} else {
path.setFillRule(Qt::OddEvenFill); // annulus: two concentric rings
const float two_pi = 2.0f * static_cast<float>(PI);
if (!add_arc(path, d_outer, 0, two_pi, 180, true)) return;
path.closeSubpath();
if (!add_arc(path, d_inner, 0, two_pi, 180, true)) return;
path.closeSubpath();
}
addOverlayItem(scene()->addPath(path, pen, brush));
if (show_roi_labels) {
try {
auto [px, py] = geom.ResPhiToPxl(d_outer, az.HasPhi() ? deg2rad(az.GetPhiMin_deg()) : 0.0f);
AddROILabel(az.GetName(), color, px, py);
} catch (...) {}
}
}
void JFJochDiffractionImage::showROILabels(bool input) {
show_roi_labels = input;
updateOverlay();
}
void JFJochDiffractionImage::showROIFill(bool input) {
show_roi_fill = input;
updateOverlay();
}
void JFJochDiffractionImage::setSelectedROI(QString name) {
selected_roi_ = name;
updateOverlay();
}
bool JFJochDiffractionImage::roiEditPress(const QPointF &scenePos) {
if (!image)
return false;
const auto &rois = image->Dataset().experiment.ROI().GetROIDefinition();
auto geom = image->Dataset().experiment.GetDiffractionGeometry();
const qreal tol = 6.0 / std::sqrt(std::max(1e-4, scale_factor));
auto start = [&](const std::string &name) {
edit_name_ = QString::fromStdString(name);
selected_roi_ = edit_name_;
move_last_ = scenePos;
emit roiSelected(edit_name_);
setCursor(Qt::ClosedHandCursor);
};
// Box: corners/edges resize, interior moves.
for (const auto &b : rois.boxes) {
const QRectF r(QPointF(b.GetXMin(), b.GetYMin()), QPointF(b.GetXMax(), b.GetYMax()));
const ResizeHandle h = hitTestBoxHandle(r, scenePos, tol);
if (h == ResizeHandle::None)
continue;
start(b.GetName());
edit_box_ = r;
if (h == ResizeHandle::Inside) {
roi_edit_ = RoiEdit::MoveBox;
} else {
roi_edit_ = RoiEdit::ResizeBox;
box_handle_ = h;
}
return true;
}
// Circle: perimeter resizes, interior moves.
for (const auto &c : rois.circles) {
const QPointF center(c.GetX(), c.GetY());
const double dist = QLineF(center, scenePos).length();
if (dist > c.GetRadius_pxl() + tol)
continue;
start(c.GetName());
edit_center_ = center;
edit_radius_ = c.GetRadius_pxl();
roi_edit_ = (std::abs(dist - c.GetRadius_pxl()) <= tol) ? RoiEdit::ResizeCircle : RoiEdit::MoveCircle;
return true;
}
// Azimuthal: grab one of the discrete handles to resize Q/d (inner/outer arc) or
// rotate a phi edge. Larger tolerance than the thin arcs would give.
const qreal tol_h = 9.0 / std::sqrt(std::max(1e-4, scale_factor));
for (const auto &az : rois.azimuthal) {
QPointF inner, outer, pmin, pmax;
azimuthalHandles(az, geom, inner, outer, pmin, pmax);
auto grab = [&](const QPointF &h) { return QLineF(h, scenePos).length() <= tol_h; };
RoiEdit mode = RoiEdit::None;
if (grab(inner)) mode = RoiEdit::AzimInner;
else if (grab(outer)) mode = RoiEdit::AzimOuter;
else if (az.HasPhi() && grab(pmin)) mode = RoiEdit::RotatePhiMin;
else if (az.HasPhi() && grab(pmax)) mode = RoiEdit::RotatePhiMax;
if (mode == RoiEdit::None)
continue;
start(az.GetName());
edit_d_min_ = az.GetDMin_A();
edit_d_max_ = az.GetDMax_A();
edit_has_phi_ = az.HasPhi();
edit_phi_min_ = az.GetPhiMin_deg();
edit_phi_max_ = az.GetPhiMax_deg();
roi_edit_ = mode;
return true;
}
// Inside an azimuthal ROI but not on a handle: select it and let the base pan
// (these ROIs are large and should not capture the panning gesture).
for (const auto &az : rois.azimuthal) {
const auto [bx, by] = geom.GetDirectBeam_pxl();
const double cursor_r = QLineF(QPointF(bx, by), scenePos).length();
const float phi = geom.Phi_rad(scenePos.x(), scenePos.y()) * 180.0f / static_cast<float>(PI);
if (cursor_r < geom.ResToPxl(az.GetDMax_A()) || cursor_r > geom.ResToPxl(az.GetDMin_A()))
continue;
if (az.HasPhi() && !InPhiSector(phi, az.GetPhiMin_deg(), az.GetPhiMax_deg()))
continue;
selected_roi_ = QString::fromStdString(az.GetName());
emit roiSelected(selected_roi_);
break;
}
return false;
}
void JFJochDiffractionImage::roiEditMove(const QPointF &scenePos) {
if (!image)
return;
auto geom = image->Dataset().experiment.GetDiffractionGeometry();
const auto [bx, by] = geom.GetDirectBeam_pxl();
const float cursor_r = QLineF(QPointF(bx, by), scenePos).length();
switch (roi_edit_) {
case RoiEdit::MoveBox:
edit_box_.translate(scenePos - move_last_);
move_last_ = scenePos;
break;
case RoiEdit::ResizeBox: {
QRectF r = edit_box_;
switch (box_handle_) {
case ResizeHandle::Left: r.setLeft(scenePos.x()); break;
case ResizeHandle::Right: r.setRight(scenePos.x()); break;
case ResizeHandle::Top: r.setTop(scenePos.y()); break;
case ResizeHandle::Bottom: r.setBottom(scenePos.y()); break;
case ResizeHandle::TopLeft: r.setTopLeft(scenePos); break;
case ResizeHandle::TopRight: r.setTopRight(scenePos); break;
case ResizeHandle::BottomLeft: r.setBottomLeft(scenePos); break;
case ResizeHandle::BottomRight: r.setBottomRight(scenePos); break;
default: break;
}
edit_box_ = r.normalized();
break;
}
case RoiEdit::MoveCircle:
edit_center_ += (scenePos - move_last_);
move_last_ = scenePos;
break;
case RoiEdit::ResizeCircle:
edit_radius_ = std::max(1.0, QLineF(edit_center_, scenePos).length());
break;
case RoiEdit::AzimInner:
edit_d_max_ = geom.PxlToRes(cursor_r);
break;
case RoiEdit::AzimOuter:
edit_d_min_ = geom.PxlToRes(cursor_r);
break;
case RoiEdit::RotatePhiMin:
edit_phi_min_ = geom.Phi_rad(scenePos.x(), scenePos.y()) * 180.0f / static_cast<float>(PI);
break;
case RoiEdit::RotatePhiMax:
edit_phi_max_ = geom.Phi_rad(scenePos.x(), scenePos.y()) * 180.0f / static_cast<float>(PI);
break;
default:
return; // None: select only, nothing to drag
}
updateOverlay();
// Live recompute, but keep at most one in flight (cleared in loadImage) so the
// worker is not flooded with edits faster than it can recompute them.
if (!live_pending_) {
live_pending_ = true;
emit roiGeometryEdited(BuildEditedROIDefinition());
}
}
void JFJochDiffractionImage::roiEditRelease() {
if (roi_edit_ == RoiEdit::None)
return;
const ROIDefinition rois = BuildEditedROIDefinition();
roi_edit_ = RoiEdit::None;
setCursor(Qt::ArrowCursor);
emit roiGeometryEdited(rois); // final, exact geometry
}
ROIDefinition JFJochDiffractionImage::BuildEditedROIDefinition() const {
ROIDefinition rois;
if (image)
rois = image->Dataset().experiment.ROI().GetROIDefinition();
const std::string sel = edit_name_.toStdString();
switch (roi_edit_) {
case RoiEdit::MoveBox:
case RoiEdit::ResizeBox:
for (auto &b : rois.boxes)
if (b.GetName() == sel) {
b = ROIBox(sel, std::lround(edit_box_.left()), std::lround(edit_box_.right()),
std::lround(edit_box_.top()), std::lround(edit_box_.bottom()));
break;
}
break;
case RoiEdit::MoveCircle:
case RoiEdit::ResizeCircle:
for (auto &c : rois.circles)
if (c.GetName() == sel) {
c = ROICircle(sel, edit_center_.x(), edit_center_.y(), edit_radius_);
break;
}
break;
case RoiEdit::AzimInner:
case RoiEdit::AzimOuter:
case RoiEdit::RotatePhiMin:
case RoiEdit::RotatePhiMax:
for (auto &a : rois.azimuthal)
if (a.GetName() == sel) {
a = edit_has_phi_
? ROIAzimuthal(sel, edit_d_min_, edit_d_max_, edit_phi_min_, edit_phi_max_)
: ROIAzimuthal(sel, edit_d_min_, edit_d_max_);
break;
}
break;
default:
break;
}
return rois;
}
void JFJochDiffractionImage::roiScratchDrawn() {
// The base just drew a scratch box/circle (roiBox/roi_type, in pixel coords);
// turn it into a new persistent ROI in the list.
if (!image || roiBox.isNull() || roiBox.width() <= 0 || roiBox.height() <= 0)
return;
ROIDefinition rois = image->Dataset().experiment.ROI().GetROIDefinition();
if (rois.boxes.size() + rois.circles.size() + rois.azimuthal.size() >= 16)
return;
std::set<std::string> used;
for (const auto &b : rois.boxes) used.insert(b.GetName());
for (const auto &c : rois.circles) used.insert(c.GetName());
for (const auto &a : rois.azimuthal) used.insert(a.GetName());
std::string name;
for (int i = 1; ; i++) {
name = "roi" + std::to_string(i);
if (!used.count(name)) break;
}
if (roi_type == RoiType::RoiBox) {
const QRectF r = roiBox.normalized();
rois.boxes.emplace_back(name, std::lround(r.left()), std::lround(r.right()),
std::lround(r.top()), std::lround(r.bottom()));
} else {
const QPointF c = roiBox.center();
const double rad = 0.5 * std::min(roiBox.width(), roiBox.height());
rois.circles.emplace_back(name, c.x(), c.y(), std::max(0.1, rad));
}
roiBox = QRectF(); // clear the scratch overlay
selected_roi_ = QString::fromStdString(name);
emit roiSelected(selected_roi_);
emit roiGeometryEdited(rois);
}
void JFJochDiffractionImage::keyPressEvent(QKeyEvent *event) {
// Home/End/PageUp/PageDown dataset navigation lives in the main window's application-wide
// event filter, so it works with any panel focused - this handler never sees those keys.
if (event->key() == Qt::Key_Delete && image && !selected_roi_.isEmpty()) {
ROIDefinition rois = image->Dataset().experiment.ROI().GetROIDefinition();
const std::string sel = selected_roi_.toStdString();
auto erase = [&sel](auto &vec) {
for (auto it = vec.begin(); it != vec.end(); ++it)
if (it->GetName() == sel) { vec.erase(it); return true; }
return false;
};
if (erase(rois.boxes) || erase(rois.circles) || erase(rois.azimuthal)) {
selected_roi_.clear();
emit roiGeometryEdited(rois);
}
event->accept();
return;
}
QGraphicsView::keyPressEvent(event);
}
std::optional<float> JFJochDiffractionImage::AutoForegroundValue() const {
if (!image)
return {};
if (!hdr_mode)
return static_cast<float>(image->GetAutoContrastValue());
const auto val_range = image->ValidMinMax();
if (!val_range.has_value())
return {};
return static_cast<float>(val_range->second);
}
void JFJochDiffractionImage::UpdateForeground() {
if (!image || !auto_fg)
return;
if (const auto val = AutoForegroundValue())
foreground = *val;
emit foregroundChanged(foreground);
}
void JFJochDiffractionImage::setHDRMode(bool input) {
hdr_mode = input;
UpdateForeground();
RenderImage();
Redraw();
}
void JFJochDiffractionImage::loadImage(std::shared_ptr<const JFJochReaderImage> in_image) {
live_pending_ = false; // a live ROI edit (if any) has now been recomputed
ring_cache_key_.clear(); // geometry may differ, re-trace the resolution rings
one_shot_auto_ = false; // a new image has its own auto value: `A` is a one-shot again
if (in_image) {
image = in_image;
UpdateForeground();
LoadImageInternal();
RenderImage();
Redraw();
} else {
image.reset();
W = 0; H = 0;
ClearFrame(); // followers (magnifier) must not keep showing the old frame
if (scene())
scene()->clear();
resetScenePointers();
hover_resolution = NAN;
DrawResolutionText();
}
}
void JFJochDiffractionImage::setAutoForeground(bool input) {
auto_fg = input;
one_shot_auto_ = false; // whatever `A` did before, the next press starts as a one-shot again
// If auto_foreground is not set, then view stays with the current settings till these are explicitly changed
UpdateForeground();
RenderImage();
Redraw();
emit autoForegroundChanged(auto_fg);
}
void JFJochDiffractionImage::oneShotAutoForeground() {
if (auto_fg)
return; // Auto already follows every image: there is nothing to apply, and nothing to undo
if (one_shot_auto_) {
setAutoForeground(true); // second press on the same image: keep it on from now on
return;
}
const auto val = AutoForegroundValue();
if (!val)
return;
// Unlike a manual foreground change this leaves auto_fg alone (it is off here either way).
foreground = *val;
one_shot_auto_ = true;
ScheduleRenderImage();
emit foregroundChanged(foreground);
}
void JFJochDiffractionImage::setResolutionRing(QVector<float> v) {
res_ring = v;
ring_mode = RingMode::Manual;
updateOverlay();
}
void JFJochDiffractionImage::showSpots(bool input) {
show_spots = input;
updateOverlay();
}
void JFJochDiffractionImage::showPredictions(bool input) {
show_predictions = input;
updateOverlay();
}
void JFJochDiffractionImage::setSpotColor(QColor input) {
spot_color = input;
updateOverlay();
}
void JFJochDiffractionImage::setPredictionColor(QColor input) {
prediction_color = input;
updateOverlay();
}
void JFJochDiffractionImage::showHighestPixels(int32_t v) {
show_highest_pixels = v;
updateOverlay();
}
void JFJochDiffractionImage::DrawSaturation() {
// Cull to the viewport like DrawSpots/DrawPredictions, and cap the count. Unlike spots, the
// saturated set is unbounded - an over-exposed frame or a missing beamstop saturates a
// sizeable fraction of the detector - and every cross is two QGraphicsLineItems rebuilt on
// each pan, zoom and frame change.
constexpr size_t max_crosses = 5000;
const QRectF visibleRect = mapToScene(viewport()->geometry()).boundingRect();
const auto x_pixels = image->Dataset().experiment.GetXPixelsNum();
size_t drawn = 0;
for (const auto &iter: image->SaturatedPixels()) {
const float x = iter % x_pixels + 0.5;
const float y = iter / x_pixels + 0.5;
if (!visibleRect.contains(QPointF{x, y}))
continue;
if (drawn++ >= max_crosses)
break;
DrawCross(x, y, 20, 4);
}
}
void JFJochDiffractionImage::DrawCross(float x, float y, float size, float width, float z) {
float sc_size = size / sqrt(scale_factor);
QPen pen(feature_color, width);
pen.setCosmetic(true);
QGraphicsLineItem *horizontalLine = scene()->addLine(x - sc_size, y, x + sc_size, y, pen);
QGraphicsLineItem *verticalLine = scene()->addLine(x, y - sc_size, x, y + sc_size, pen);
horizontalLine->setZValue(z); // Ensure it appears above other items
verticalLine->setZValue(z); // Ensure it appears above other items
addOverlayItem(horizontalLine);
addOverlayItem(verticalLine);
}
void JFJochDiffractionImage::showSaturation(bool input) {
show_saturation = input;
RenderImage();
updateOverlay();
}
void JFJochDiffractionImage::showBeamStop(bool input) {
show_beam_stop = input;
RenderImage();
updateOverlay();
}
void JFJochDiffractionImage::highlightIceRings(bool input) {
highlight_ice_rings = input;
updateOverlay();
}
void JFJochDiffractionImage::hideUnindexedSpots(bool input) {
hide_unindexed_spots = input;
updateOverlay();
}
void JFJochDiffractionImage::hideIceRingSpots(bool input) {
hide_ice_ring_spots = input;
updateOverlay();
}
void JFJochDiffractionImage::setResolutionRingMode(RingMode mode) {
ring_mode = mode;
updateOverlay();
}
static QFont HoverResolutionFont() {
QFont font("Arial");
font.setPixelSize(32); // big, constant size on screen
return font;
}
QString JFJochDiffractionImage::HoverResolutionLabel() const {
if (!image || !std::isfinite(hover_resolution) || hover_resolution <= 0.0f)
return {};
return QString("d = %1 \u00C5").arg(QString::number(hover_resolution, 'f', 2));
}
QString JFJochDiffractionImage::PixelLabel(int x, int y) const {
if (!image)
return {};
const int32_t v = image->Image()[static_cast<size_t>(y) * W + x];
if (v == GAP_PXL_VALUE)
return QStringLiteral("Gap");
if (v == ERROR_PXL_VALUE)
return QStringLiteral("Err");
if (v == BEAM_STOP_PXL_VALUE)
return QStringLiteral("Stop");
if (v == SATURATED_PXL_VALUE)
return QStringLiteral("Sat");
return QString::number(v);
}
void JFJochDiffractionImage::drawForeground(QPainter *painter, const QRectF &rect) {
JFJochImage::drawForeground(painter, rect);
const QString label = HoverResolutionLabel();
if (label.isEmpty())
return;
painter->save();
painter->resetTransform(); // lay the readout out in viewport pixels, not scene units
painter->setFont(HoverResolutionFont());
painter->setPen(feature_color);
painter->drawText(hover_text_rect_, Qt::AlignLeft | Qt::AlignTop, label);
painter->restore();
}
void JFJochDiffractionImage::scrollContentsBy(int dx, int dy) {
JFJochImage::scrollContentsBy(dx, dy);
if (hover_text_rect_.isEmpty())
return;
// QWidget::scroll moves the pending update region too, so the repaint DrawResolutionText asked for
// is dragged away from the corner along with the pixels already there. Dirty both places.
viewport()->update(hover_text_rect_.united(hover_text_rect_.translated(dx, dy)).adjusted(-2, -2, 2, 2));
}
void JFJochDiffractionImage::DrawResolutionText() {
const QRect previous = hover_text_rect_;
const QString label = HoverResolutionLabel();
if (label.isEmpty())
hover_text_rect_ = QRect();
else {
constexpr int margin_px = 10;
const QFontMetrics fm(HoverResolutionFont());
hover_text_rect_ = QRect(QPoint(margin_px, margin_px), fm.size(0, label));
}
// Repaint just the readout. The previous version was a QGraphicsItem flagged
// ItemIgnoresTransformations, which makes Qt mark the whole viewport dirty every time the
// item moves or its text changes - and it moved on every mouse motion.
const QRect dirty = previous.united(hover_text_rect_).adjusted(-2, -2, 2, 2);
if (!dirty.isEmpty())
viewport()->update(dirty);
}
void JFJochDiffractionImage::leaveEvent(QEvent *event) {
// Mouse left the view: clear hover resolution and hide text
if (std::isfinite(hover_resolution)) {
hover_resolution = NAN;
DrawResolutionText();
}
JFJochImage::leaveEvent(event);
}