Files
Jungfraujoch/viewer/windows/JFJochViewerImageListWindow.cpp
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

212 lines
7.6 KiB
C++

// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "JFJochViewerImageListWindow.h"
#include <QVBoxLayout>
#include <QHeaderView>
#include <QCloseEvent>
namespace {
constexpr int ScaleSortRole = Qt::UserRole + 1;
constexpr double ScaleNotAvailableSortValue = -1.0e100;
}
JFJochViewerImageListWindow::JFJochViewerImageListWindow(QWidget *parent) : JFJochHelperWindow(parent) {
QWidget *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
QVBoxLayout *layout = new QVBoxLayout(centralWidget);
tableView = new QTableView(this);
tableModel = new QStandardItemModel(this);
setupTableModel();
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(tableModel);
proxyModel->setSortRole(ScaleSortRole);
tableView->setModel(proxyModel);
tableView->sortByColumn(0, Qt::AscendingOrder);
tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
tableView->setSortingEnabled(true);
tableView->verticalHeader()->setVisible(false);
tableView->horizontalHeader()->setSectionsClickable(true);
tableView->horizontalHeader()->setSortIndicatorShown(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::SingleSelection);
tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
layout->addWidget(tableView);
setWindowTitle("Image statistics");
resize(800, 600);
connect(tableView, &QTableView::doubleClicked, this, &JFJochViewerImageListWindow::onTableRowDoubleClicked);
}
void JFJochViewerImageListWindow::setupTableModel()
{
tableModel->setColumnCount(8);
tableModel->setHeaderData(0, Qt::Horizontal, "#");
tableModel->setHeaderData(1, Qt::Horizontal, "Bkg");
tableModel->setHeaderData(2, Qt::Horizontal, "Index");
tableModel->setHeaderData(3, Qt::Horizontal, "Spots");
tableModel->setHeaderData(4, Qt::Horizontal, "Res. [A]");
tableModel->setHeaderData(5, Qt::Horizontal, "Max val");
tableModel->setHeaderData(6, Qt::Horizontal, "Scale factor");
tableModel->setHeaderData(7, Qt::Horizontal, "Scale CC");
}
void JFJochViewerImageListWindow::addDataRow(int imageNumber, double backgroundEstimate,
const QString& indexingResult,
int spotCount,
double resolutionEstimate,
int64_t max_value,
double image_scale_factor,
double image_scale_cc_percent) {
QList<QStandardItem*> rowItems;
QStandardItem *imageItem = new QStandardItem();
imageItem->setData(imageNumber, Qt::DisplayRole);
imageItem->setData(imageNumber, ScaleSortRole);
rowItems.append(imageItem);
QStandardItem *bgItem = new QStandardItem();
bgItem->setData(backgroundEstimate, Qt::DisplayRole);
bgItem->setData(backgroundEstimate, ScaleSortRole);
rowItems.append(bgItem);
QStandardItem *indexingItem = new QStandardItem(indexingResult);
if (indexingResult == "Yes")
indexingItem->setData(1, ScaleSortRole);
else if (indexingResult == "No")
indexingItem->setData(0, ScaleSortRole);
else
indexingItem->setData(-1, ScaleSortRole);
rowItems.append(indexingItem);
QStandardItem *spotItem = new QStandardItem();
spotItem->setData(spotCount, Qt::DisplayRole);
spotItem->setData(spotCount, ScaleSortRole);
rowItems.append(spotItem);
QStandardItem *resolutionItem = new QStandardItem();
resolutionItem->setData(QString::number(resolutionEstimate, 'f', 2), Qt::DisplayRole);
resolutionItem->setData(resolutionEstimate, ScaleSortRole);
rowItems.append(resolutionItem);
QStandardItem *maxValueItem = new QStandardItem();
maxValueItem->setData(static_cast<int32_t>(max_value), Qt::DisplayRole);
maxValueItem->setData(static_cast<int32_t>(max_value), ScaleSortRole);
rowItems.append(maxValueItem);
QStandardItem *scaleFactorItem = new QStandardItem();
if (std::isfinite(image_scale_factor)) {
scaleFactorItem->setData(image_scale_factor, Qt::DisplayRole);
scaleFactorItem->setData(image_scale_factor, ScaleSortRole);
} else {
scaleFactorItem->setData("N/A", Qt::DisplayRole);
scaleFactorItem->setData(ScaleNotAvailableSortValue, ScaleSortRole);
}
rowItems.append(scaleFactorItem);
QStandardItem *scaleCCItem = new QStandardItem();
if (std::isfinite(image_scale_cc_percent)) {
scaleCCItem->setData(QString::number(image_scale_cc_percent, 'f', 1) + "%", Qt::DisplayRole);
scaleCCItem->setData(image_scale_cc_percent, ScaleSortRole);
} else {
scaleCCItem->setData("N/A", Qt::DisplayRole);
scaleCCItem->setData(ScaleNotAvailableSortValue, ScaleSortRole);
}
rowItems.append(scaleCCItem);
tableModel->appendRow(rowItems);
}
void JFJochViewerImageListWindow::clearAllData() {
tableModel->removeRows(0, tableModel->rowCount());
}
void JFJochViewerImageListWindow::datasetLoaded(std::shared_ptr<const JFJochReaderDataset> dataset) {
clearAllData();
if (!dataset)
return;
for (int i = 0; i < dataset->experiment.GetImageNum(); i++) {
float bkg_estimate = 0;
if (dataset->bkg_estimate.size() > i)
bkg_estimate = dataset->bkg_estimate[i];
int32_t spot_count = 0;
if (dataset->spot_count.size() > i)
spot_count = dataset->spot_count[i];
float res_estimation = 0.0f;
if (dataset->resolution_estimate.size() > i)
res_estimation = dataset->resolution_estimate[i];
QString indexing_result = "N/A";
if (dataset->indexing_result.size() > i) {
if (dataset->indexing_result[i] == 0)
indexing_result = "No";
else
indexing_result = "Yes";
}
int64_t max_value = 0;
if (dataset->max_value.size() > i)
max_value = dataset->max_value[i];
double image_scale_factor = NAN;
if (dataset->image_scale_factor.size() > i)
image_scale_factor = dataset->image_scale_factor[i];
double image_scale_cc_percent = NAN;
if (dataset->image_scale_cc.size() > i)
image_scale_cc_percent = dataset->image_scale_cc[i] * 100.0;
addDataRow(i + 1,
bkg_estimate,
indexing_result,
spot_count,
res_estimation,
max_value,
image_scale_factor,
image_scale_cc_percent);
}
}
void JFJochViewerImageListWindow::imageLoaded(std::shared_ptr<const JFJochReaderImage> image) {
int curr_row = -1;
if (image)
curr_row = image->ImageData().number;
for (int row = 0; row < tableModel->rowCount(); row++) {
for (int col = 0; col < tableModel->columnCount(); ++col) {
QStandardItem *item = tableModel->item(row, col);
if (item) {
if (row == curr_row)
item->setBackground(Qt::blue);
else
item->setBackground(Qt::white);
}
}
}
}
void JFJochViewerImageListWindow::onTableRowDoubleClicked(const QModelIndex &index) {
if (!index.isValid())
return;
QModelIndex sourceIndex = proxyModel->mapToSource(index);
int imageNumber = tableModel->item(sourceIndex.row(), 0)->data(Qt::DisplayRole).toInt();
emit imageSelected(imageNumber - 1, 1);
}