Files
Jungfraujoch/image_analysis/MXAnalysisAfterFPGA.cpp
T
leonarski_fandClaude Opus 5 a7d3ada3ab analysis: what runs over the images is one stated mode, shared by broker, rugnux and viewer
Until now nothing in the tree said what analysis a run performed. The answer was composed
at each site out of four independent scalars - the detector type, two separate "spot finding
off" switches, an indexing flag and a rotation flag - so what was configured and what
actually ran were different things, and no single place could be read to find out which.

AnalysisMode {None, MXRotation, MXStills, Azint, Grid, PowderCalibration} is that statement,
in common/ because all three programs configure the DiffractionExperiment that carries it.
AnalysisSettings sits on the experiment beside IndexingSettings, outside the DatasetSettings
member, which is the one thing a /start replaces wholesale - so the mode is persistent by
construction rather than by a rule someone has to remember.

The mode does not label a run, it decides it. AnalysisModeStages() is a table - modes as
rows, pipeline stages as columns - and every gate reads that table instead of testing the
mode: spot finding in DiffractionExperiment::IsSpotFindingEnabled, indexing (and with it
prediction and integration, which never run without a lattice) in one gate inside
IndexAndRefine that serves all three front ends, azimuthal integration where the CPU engine
is built. Two rows carry a judgement worth reviewing: powder calibration keeps spot finding,
because --calibration spots fits the pooled spots; grid does not index, because a raster is
thousands of frames and the per-image scoring it ranks on deliberately avoids an indexer that
fires on ice.

There is deliberately no Auto value. GetIndexingAlgorithm() resolves Auto at read time, which
is exactly why an indexing setting cannot be read back off the configuration; removing that
kind of implicitness is the point here, so the mode getter stays a plain accessor. MXStills
is the default because None would silently switch analysis off on every deployment whose
configuration predates the field.

Rotation MX is absent from the OpenAPI schema rather than present and refused: jfjoch_broker
has no rotation analysis path, so the REST and configuration-file routes cannot express it at
all. The shared enum can still carry the value from elsewhere, so CheckAnalysisSettingsOnline
refuses it on both routes with a message naming rugnux. A sweep collected under an MX mode is
not refused - collecting rotation data online is normal and live spot counts are useful - but
it is said out loud in the log, since the mistake worth preventing is the silence about what
was done to it, not the acquisition.

Powder calibration forces azimuthal integration onto the CPU and supplies 32 sectors where
fewer than four were asked for. The FPGA integration core holds 2048 bins in total, so 32
sectors would leave 64 q bins - far too coarse to fit a ring. Frame rate is what this costs
and a calibration exposure does not need it.

The two existing "no analysis" switches, per-dataset dataset_settings.spot_finding and
persistent SpotFindingSettings::enable, are interfaces in too many places to remove now. They
are marked deprecated in the schema and in both headers, and the mode takes precedence over
them: a mode that analyses no spots wins outright, while under a mode that does find spots
they remain the finer control. The precedence is written where it is enforced.

rugnux's ProcessMode is gone, replaced by the shared enum; RugnuxMode stays as the CLI
spelling layer and no existing spelling changes. --mode gains mx_rotation and mx_stills, which
are spellings of -R and --force-still rather than new switches; plain mx still chooses between
them from the goniometer. scale keeps no shared counterpart, since it runs no analysis over
images at all.

The mode reaches the CBOR start message and /entry/MX/analysis_mode in the HDF5 master, so a
written file records which analysis produced it. It is read back as provenance only - what a
stored file was produced by is not what the next run should do.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFEJG6WBQv8th4UJFNe53N
2026-09-08 00:16:26 +02:00

173 lines
6.5 KiB
C++

// SPDX-FileCopyrightText: 2024 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "MXAnalysisAfterFPGA.h"
#include <span>
#include "spot_finding/DetModuleSpotFinder_cpu.h"
#include "../common/CUDAWrapper.h"
#include "../common/JFJochException.h"
#include "spot_finding/SpotUtils.h"
#include "bragg_prediction/BraggPredictionFactory.h"
double stddev(const std::vector<float> &v) {
if (v.size() <= 1)
return 0.0;
double mean = 0.0f;
for (const auto &i: v)
mean += i;
mean /= v.size();
double stddev = 0.0f;
for (const auto &i: v)
stddev += (i - mean) * (i - mean);
return sqrt(stddev / (v.size() - 1));
}
MXAnalysisAfterFPGA::MXAnalysisAfterFPGA(const DiffractionExperiment &in_experiment,
const AzimuthalIntegrationMapping &in_integration,
IndexAndRefine &indexer)
: experiment(in_experiment),
integration(in_integration),
indexer(indexer),
prediction(CreateBraggPrediction(experiment.IsRotationIndexing())),
bragg_engine(std::make_unique<BraggIntegrationEngineCPU>(in_experiment)) {
if (experiment.IsSpotFindingEnabled())
find_spots = true;
// AnalysisMode::None analyses nothing at all, azimuthal integration included; every other mode
// keeps it (see the table in common/AnalysisSettings.cpp). Note this only governs the CPU engine -
// on the FPGA path the integration is a stage of the hardware pipeline and is not switched here.
if (experiment.GetAnalysisStages().azimuthal_integration
&& experiment.GetAzimuthalIntegrationSettings().IsForceCPUinFPGAWorkflow())
cpu_azint = std::make_unique<AzIntEngineCPU>(integration);
}
void MXAnalysisAfterFPGA::RunAzimuthalIntegration(const void *image, AzimuthalIntegrationProfile &profile) {
if (!cpu_azint)
return;
const size_t npixel = experiment.GetPixelsNum();
auto run = [&](auto tag) {
using pixel_t = decltype(tag);
cpu_azint->RunAzint(std::span<const pixel_t>(static_cast<const pixel_t *>(image), npixel), profile);
};
switch (experiment.GetByteDepthImage()) {
case 1:
experiment.IsPixelSigned() ? run(int8_t{}) : run(uint8_t{});
break;
case 2:
experiment.IsPixelSigned() ? run(int16_t{}) : run(uint16_t{});
break;
case 4:
experiment.IsPixelSigned() ? run(int32_t{}) : run(uint32_t{});
break;
default:
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Pixel depth unsupported");
}
}
void MXAnalysisAfterFPGA::ReadFromFPGA(const DeviceOutput *output, const SpotFindingSettings &settings, size_t module_number) {
if (state == State::Disabled || !find_spots || !settings.enable) {
state = State::Disabled;
} else {
const auto t0 = std::chrono::steady_clock::now();
StrongPixelSet strong_pixel_set;
strong_pixel_set.ReadFPGAOutput(experiment, *output);
strong_pixel_set.FindSpots(experiment, settings, spots, module_number);
const auto t1 = std::chrono::steady_clock::now();
spot_finding_time_total += (t1 - t0);
spot_finding_timing_active = true;
state = State::Enabled;
}
}
void MXAnalysisAfterFPGA::ReadFromCPU(DeviceOutput *output, const SpotFindingSettings &settings, size_t module_number) {
std::unique_lock ul(read_from_cpu_mutex);
if (state == State::Disabled || !find_spots || !settings.enable) {
state = State::Disabled;
} else {
const auto t0 = std::chrono::steady_clock::now();
state = State::Enabled;
std::vector<float> d_map(RAW_MODULE_SIZE);
experiment.CalcSpotFinderResolutionMap(d_map.data(), module_number);
arr_mean.resize(RAW_MODULE_SIZE);
arr_sttdev.resize(RAW_MODULE_SIZE);
arr_valid_count.resize(RAW_MODULE_SIZE);
arr_strong_pixel.resize(RAW_MODULE_SIZE);
if (experiment.GetByteDepthImage() == 2)
FindSpots(*output,
settings,
d_map.data(),
arr_mean.data(),
arr_sttdev.data(),
arr_valid_count.data(),
arr_strong_pixel.data());
else if (experiment.GetByteDepthImage() == 4)
FindSpots<int32_t>(*output,
settings,
d_map.data(),
arr_mean.data(),
arr_sttdev.data(),
arr_valid_count.data(),
arr_strong_pixel.data());
else if (experiment.GetByteDepthImage() == 1)
FindSpots<int8_t>(*output,
settings,
d_map.data(),
arr_mean.data(),
arr_sttdev.data(),
arr_valid_count.data(),
arr_strong_pixel.data());
StrongPixelSet strong_pixel_set;
strong_pixel_set.ReadFPGAOutput(experiment, *output);
strong_pixel_set.FindSpots(experiment, settings, spots, module_number);
const auto t1 = std::chrono::steady_clock::now();
spot_finding_time_total += (t1 - t0);
spot_finding_timing_active = true;
}
}
void MXAnalysisAfterFPGA::Process(DataMessage &message, const SpotFindingSettings& spot_finding_settings) {
if (find_spots && (state == State::Enabled)) {
const auto t0 = std::chrono::steady_clock::now();
SpotAnalyze(experiment, spot_finding_settings, spots, message);
const auto t1 = std::chrono::steady_clock::now();
spot_finding_time_total += (t1 - t0);
if (spot_finding_settings.indexing)
indexer.ProcessImage(message, spot_finding_settings, *prediction,
[this, &message](const std::vector<Reflection> &predicted, size_t npredicted, int64_t image_number) {
return bragg_engine->Run(message.image, predicted, npredicted, image_number);
});
}
if (spot_finding_timing_active) {
// total spot-finding time for the whole image
message.spot_finding_time_s = spot_finding_time_total.count() / 1e6;
// report/store ms here
spot_finding_time_total = std::chrono::duration<double, std::micro>{0.0};
spot_finding_timing_active = false;
}
spots.clear();
state = State::Idle;
}