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>
159 lines
5.3 KiB
C++
159 lines
5.3 KiB
C++
// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#include "../../common/JFJochMath.h"
|
|
#include "SpotUtils.h"
|
|
#include "../../common/ResolutionShells.h"
|
|
|
|
void CountSpots(DataMessage &msg,
|
|
const std::vector<SpotToSave> &spots,
|
|
float d_min_A) {
|
|
int64_t low_res = 0;
|
|
int64_t ice_ring = 0;
|
|
for (auto &s: spots) {
|
|
if (s.ice_ring)
|
|
ice_ring++;
|
|
|
|
if (s.d_A > d_min_A)
|
|
low_res++;
|
|
}
|
|
msg.spot_count = spots.size();
|
|
msg.spot_count_low_res = low_res;
|
|
msg.spot_count_ice_rings = ice_ring;
|
|
}
|
|
|
|
void MarkIceRings(std::vector<SpotToSave> &spots, float tolerance_q_recipA) {
|
|
std::vector<float> ice_rings_q;
|
|
|
|
for (const auto &i: ICE_RING_RES_A)
|
|
ice_rings_q.push_back(2 * PI / i);
|
|
|
|
for (auto &s: spots) {
|
|
auto spot_q = 2 * PI / s.d_A;
|
|
bool tmp = false;
|
|
for (const auto &q: ice_rings_q)
|
|
tmp |= (fabs(spot_q - q) < tolerance_q_recipA);
|
|
s.ice_ring = tmp;
|
|
}
|
|
}
|
|
|
|
void FilterSpotsByCount(std::vector<SpotToSave> &input, int64_t count) {
|
|
size_t output_size = std::min<size_t>(input.size(), count);
|
|
|
|
std::ranges::partial_sort(input, input.begin() + output_size,
|
|
std::ranges::less{}, // comparator on the projected key
|
|
[](const SpotToSave &s) {
|
|
// projection: non-ice first (false < true), then strongest intensity first.
|
|
return std::tuple{s.ice_ring, -s.intensity};
|
|
});
|
|
input.resize(output_size);
|
|
}
|
|
|
|
void FilterSpuriousHighResolutionSpots(std::vector<SpotToSave> &spots, float threshold) {
|
|
std::ranges::sort(spots, [](SpotToSave &a, SpotToSave &b) {
|
|
return a.d_A > b.d_A;
|
|
});
|
|
|
|
// Apply 1/d gap threshold: find first gap in q = 1/d exceeding dist_threshold and ignore spots after it
|
|
if (spots.size() >= 2 && threshold > 0.0f) {
|
|
size_t cut_index = spots.size(); // default: keep all
|
|
// d_A sorted descending → q = 1/d_A sorted ascending
|
|
// We check consecutive q gaps: Δq_i = (1/d_i) - (1/d_{i+1})
|
|
for (size_t i = 0; i + 1 < spots.size(); ++i) {
|
|
float d1 = spots[i].d_A;
|
|
float d2 = spots[i + 1].d_A;
|
|
// Avoid division by zero; d_A should be > 0 in valid data
|
|
if (d1 <= 0.0f || d2 <= 0.0f)
|
|
continue;
|
|
float q1 = 2 * PI / d1;
|
|
float q2 = 2 * PI / d2;
|
|
float dq = q2 - q1; // should be >= 0 due to sorting
|
|
if (dq > threshold) {
|
|
cut_index = i + 1; // keep up to i inclusive
|
|
break;
|
|
}
|
|
}
|
|
if (cut_index < spots.size())
|
|
spots.resize(cut_index);
|
|
}
|
|
}
|
|
|
|
std::optional<float> GetResolution(const std::vector<SpotToSave> &spots) {
|
|
std::vector<float> resolutions;
|
|
resolutions.reserve(spots.size());
|
|
|
|
for (const auto &spot: spots) {
|
|
if (!spot.ice_ring)
|
|
resolutions.push_back(spot.d_A);
|
|
}
|
|
|
|
std::ranges::sort(resolutions);
|
|
|
|
if (resolutions.size() < 4)
|
|
return std::nullopt;
|
|
if (resolutions.size() < 20)
|
|
return resolutions[2];
|
|
return resolutions[static_cast<size_t>(resolutions.size() * 0.05)];
|
|
}
|
|
|
|
void GenerateSpotPlot(DataMessage &msg, const std::vector<SpotToSave> &spots, float d_min_A) {
|
|
const int nshells = 20;
|
|
ResolutionShells shells(d_min_A, 50.0, nshells);
|
|
|
|
std::vector<float> intensity(nshells);
|
|
std::vector<float> count(nshells);
|
|
|
|
for (const auto &s: spots) {
|
|
if (s.ice_ring)
|
|
continue;
|
|
|
|
if (auto shell = shells.GetShell(s.d_A)) {
|
|
intensity[*shell] += s.intensity;
|
|
count[*shell] += 1.0f;
|
|
}
|
|
}
|
|
|
|
std::vector<float> result(nshells);
|
|
for (int i = 0; i < nshells; ++i) {
|
|
if (count[i] > 0)
|
|
result[i] = intensity[i] / count[i];
|
|
else
|
|
result[i] = 0.0f;
|
|
}
|
|
|
|
msg.spot_plot_one_over_d_square = shells.GetShellMeanOneOverResSq();
|
|
msg.spot_plot_intensity = result;
|
|
msg.spot_plot_count = count;
|
|
}
|
|
|
|
void SpotAnalyze(const DiffractionExperiment &experiment,
|
|
const SpotFindingSettings &spot_finding_settings,
|
|
const std::vector<DiffractionSpot> &spots,
|
|
DataMessage &output) {
|
|
auto geom = experiment.GetDiffractionGeometry();
|
|
|
|
std::vector<SpotToSave> spots_out;
|
|
|
|
for (const auto &spot: spots) {
|
|
if (auto s = spot.Export(geom, output.number); s.has_value())
|
|
spots_out.push_back(s.value());
|
|
}
|
|
|
|
if (spot_finding_settings.high_res_gap_Q_recipA.has_value())
|
|
FilterSpuriousHighResolutionSpots(spots_out, spot_finding_settings.high_res_gap_Q_recipA.value());
|
|
|
|
if (experiment.GetDatasetSettings().IsDetectIceRings() && spot_finding_settings.ice_ring_width_Q_recipA > 0.0f)
|
|
MarkIceRings(spots_out, spot_finding_settings.ice_ring_width_Q_recipA);
|
|
|
|
CountSpots(output, spots_out, spot_finding_settings.cutoff_spot_count_low_res);
|
|
|
|
GenerateSpotPlot(output, spots_out,
|
|
spot_finding_settings.high_resolution_limit.value_or(experiment.GetDetectorMaxResolution_A()));
|
|
|
|
output.resolution_estimate = GetResolution(spots_out);
|
|
|
|
FilterSpotsByCount(spots_out, experiment.GetMaxSpotCount());
|
|
|
|
output.spots = spots_out;
|
|
}
|