AzimuthalIntegrationMapping: reuse the per-pixel geometry of the last mapping; pre-scan's off the critical path

Building a mapping evaluates the geometry of every pixel (resolution, azimuth, solid-angle and
polarization corrections, bin) - about 2 CPU-s and 0.1-0.25 s of wall on a 16 Mpx detector - and a
rotation run built seven, several for a geometry it had already evaluated: the first pass repeats the
pre-scan's, and the canonical pass and the second of two concurrent probes repeat the probes'. None of
it depends on the mask beyond skipping masked pixels, so AzimuthalIntegrationGeometryCache keeps the
unmasked tables of the last geometry (keyed bit for bit on everything SetupPixel reads), and a
mapping for the same geometry copies them and blanks its own masked pixels to what SetupPixel leaves
there. One entry, shared by the run's copies; on myob four of the seven builds now evaluate, three
copy (~40-120 ms against ~240+ ms on a loaded box).

The pre-scan's mapping is only read by the spot measurement, so it is built at the start of that
background task rather than on the main thread ahead of the projection read. It also fills the cache
for the first pass.

Output identical on the three GPU reference sweeps; a new test checks cached against fresh mappings
under different masks and centres.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D1G8gJVAy6gp1K5Dz3NE5C
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-09-27 09:12:25 +02:00
1 parent 3e68ed8c4a
commit 4616921087
5 files changed
+151 -16

No files matched your search

+70 -9
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "JFJochMath.h"
#include <bit>
#include <cmath>
#include <thread>
#include <future>
@@ -11,9 +12,22 @@
#include "DiffractionGeometry.h"
#include "RawToConvertedGeometry.h"
#include "TableChecksum.h"
#include "ParallelFor.h"
AzimuthalIntegrationMapping::AzimuthalIntegrationMapping(const DiffractionExperiment &experiment,
const PixelMask &mask,
size_t in_nthreads)
: AzimuthalIntegrationMapping(experiment, mask, nullptr, in_nthreads) {}
AzimuthalIntegrationMapping::AzimuthalIntegrationMapping(const DiffractionExperiment &experiment,
const PixelMask &mask,
AzimuthalIntegrationGeometryCache &cache,
size_t in_nthreads)
: AzimuthalIntegrationMapping(experiment, mask, &cache, in_nthreads) {}
AzimuthalIntegrationMapping::AzimuthalIntegrationMapping(const DiffractionExperiment &experiment,
const PixelMask& mask,
AzimuthalIntegrationGeometryCache *cache,
size_t in_nthreads)
: settings(experiment.GetAzimuthalIntegrationSettings()),
wavelength(experiment.GetWavelength_A()),
@@ -46,8 +60,10 @@ AzimuthalIntegrationMapping::AzimuthalIntegrationMapping(const DiffractionExperi
if (!experiment.IsGeometryTransformed())
SetupRawGeom(experiment, mask.GetMaskRaw());
else if (cache)
SetupConvGeomCached(experiment.GetDiffractionGeometry(), mask.GetMask(), *cache);
else
SetupConvGeom(experiment.GetDiffractionGeometry(),mask.GetMask());
SetupConvGeom(experiment.GetDiffractionGeometry(), &mask.GetMask());
UpdateMaxBinNumber();
@@ -55,7 +71,7 @@ AzimuthalIntegrationMapping::AzimuthalIntegrationMapping(const DiffractionExperi
corrections_checksum = TableChecksum(corrections.data(), corrections.size() * sizeof(float));
}
void AzimuthalIntegrationMapping::SetupConvGeomRows(const DiffractionGeometry &geom, const std::vector<uint32_t> &mask,
void AzimuthalIntegrationMapping::SetupConvGeomRows(const DiffractionGeometry &geom, const std::vector<uint32_t> *mask,
size_t row0, size_t row_end) {
for (size_t row = row0; row < row_end && row < height; row++) {
for (size_t col = 0; col < width; col++)
@@ -63,12 +79,12 @@ void AzimuthalIntegrationMapping::SetupConvGeomRows(const DiffractionGeometry &g
}
}
void AzimuthalIntegrationMapping::SetupConvGeom(const DiffractionGeometry &geom, const std::vector<uint32_t> &mask) {
void AzimuthalIntegrationMapping::SetupConvGeom(const DiffractionGeometry &geom, const std::vector<uint32_t> *mask) {
pixel_to_bin.resize(width * height, UINT16_MAX);
pixel_resolution.resize(width * height, 0);
corrections.resize(width * height, 0);
if (mask.size() != width * height)
if (mask && mask->size() != width * height)
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Mask size invalid");
if (nthreads <= 1) {
@@ -81,7 +97,7 @@ void AzimuthalIntegrationMapping::SetupConvGeom(const DiffractionGeometry &geom,
for (size_t t = 0; t < local_nthreads; ++t)
futures.emplace_back(std::async(std::launch::async,
&AzimuthalIntegrationMapping::SetupConvGeomRows,
this, std::cref(geom), std::cref(mask),
this, std::cref(geom), mask,
t * height / local_nthreads,
(t + 1) * height / local_nthreads));
@@ -90,6 +106,51 @@ void AzimuthalIntegrationMapping::SetupConvGeom(const DiffractionGeometry &geom,
}
}
void AzimuthalIntegrationMapping::SetupConvGeomCached(const DiffractionGeometry &geom,
const std::vector<uint32_t> &mask,
AzimuthalIntegrationGeometryCache &cache) {
if (mask.size() != width * height)
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Mask size invalid");
// Everything SetupPixel reads, compared bit for bit.
std::vector<uint32_t> key;
for (const float f: {geom.GetBeamX_pxl(), geom.GetBeamY_pxl(), geom.GetDetectorDistance_mm(),
geom.GetPixelSize_mm(), geom.GetWavelength_A(),
settings.GetLowQ_recipA(), settings.GetHighQ_recipA(), settings.GetQSpacing_recipA(),
polarization_factor.value_or(0.0f)})
key.push_back(std::bit_cast<uint32_t>(f));
for (const float f: geom.GetDetectorMatrix().arr())
key.push_back(std::bit_cast<uint32_t>(f));
key.insert(key.end(), {static_cast<uint32_t>(settings.GetAzimuthalBinCount()),
static_cast<uint32_t>(settings.IsSolidAngleCorrection()),
static_cast<uint32_t>(settings.IsPolarizationCorrection()),
static_cast<uint32_t>(polarization_factor.has_value()),
static_cast<uint32_t>(width), static_cast<uint32_t>(height)});
std::lock_guard lock(cache.m);
if (cache.key != key) {
SetupConvGeom(geom, nullptr);
cache.key = key;
cache.pixel_to_bin = pixel_to_bin;
cache.pixel_resolution = pixel_resolution;
cache.corrections = corrections;
} else {
pixel_to_bin = cache.pixel_to_bin;
pixel_resolution = cache.pixel_resolution;
corrections = cache.corrections;
}
// What SetupPixel leaves at a masked pixel.
ParallelChunks(static_cast<int>(mask.size()), nthreads, [&](int lo, int hi) {
for (int i = lo; i < hi; i++)
if (mask[i] != 0) {
pixel_to_bin[i] = UINT16_MAX;
pixel_resolution[i] = 0;
corrections[i] = 0;
}
});
}
void AzimuthalIntegrationMapping::SetupRawGeom(const DiffractionExperiment &experiment,
const std::vector<uint32_t> &mask) {
if (mask.size() != RAW_MODULE_SIZE * experiment.GetModulesNum())
@@ -105,7 +166,7 @@ void AzimuthalIntegrationMapping::SetupRawGeom(const DiffractionExperiment &expe
for (int m = 0; m < experiment.GetModulesNum(); m++) {
for (int pxl = 0; pxl < RAW_MODULE_SIZE; pxl++) {
auto [x,y] = RawToConvertedCoordinate(experiment, m, pxl);
SetupPixel(geom, mask, m * RAW_MODULE_SIZE + pxl, x, y);
SetupPixel(geom, &mask, m * RAW_MODULE_SIZE + pxl, x, y);
}
}
} else {
@@ -121,7 +182,7 @@ void AzimuthalIntegrationMapping::SetupRawGeom(const DiffractionExperiment &expe
for (size_t m = module_begin; m < module_end; ++m) {
for (int pxl = 0; pxl < RAW_MODULE_SIZE; ++pxl) {
auto [x, y] = RawToConvertedCoordinate(experiment, m, pxl);
SetupPixel(geom, mask, m * RAW_MODULE_SIZE + pxl, x, y);
SetupPixel(geom, &mask, m * RAW_MODULE_SIZE + pxl, x, y);
}
}
}));
@@ -133,9 +194,9 @@ void AzimuthalIntegrationMapping::SetupRawGeom(const DiffractionExperiment &expe
}
void AzimuthalIntegrationMapping::SetupPixel(const DiffractionGeometry &geom,
const std::vector<uint32_t> &mask,
const std::vector<uint32_t> *mask,
uint32_t pxl, uint32_t col, uint32_t row) {
if (mask[pxl] != 0)
if (mask && (*mask)[pxl] != 0)
return;
auto x = static_cast<float>(col);
+32 -3
View File
@@ -9,6 +9,21 @@
#include "DiffractionExperiment.h"
#include "PixelMask.h"
// The per-pixel geometry of the last mapping built through it, before the mask: every pixel's
// resolution, correction and bin. None of these depends on the mask - a masked pixel is only left
// out - so a mapping for the same geometry under another mask takes them from here and blanks its own
// masked pixels, instead of evaluating the geometry of every pixel again. Building a mapping is that
// evaluation, and on a 16 Mpx detector it is a tenth of a second on every core. One entry; a mapping
// being built holds it, so two built at once for the same geometry evaluate it once.
class AzimuthalIntegrationGeometryCache {
friend class AzimuthalIntegrationMapping;
std::mutex m;
std::vector<uint32_t> key; // bit patterns of everything SetupPixel reads
std::vector<uint16_t> pixel_to_bin;
std::vector<float> pixel_resolution;
std::vector<float> corrections;
};
class AzimuthalIntegrationMapping {
protected:
const AzimuthalIntegrationSettings settings;
@@ -47,17 +62,31 @@ protected:
void UpdateMaxBinNumber();
// A null mask sets up every pixel.
void SetupRawGeom(const DiffractionExperiment& experiment, const std::vector<uint32_t> &mask);
void SetupConvGeomRows(const DiffractionGeometry &geom, const std::vector<uint32_t> &mask, size_t row0, size_t row_end);
void SetupConvGeom(const DiffractionGeometry &geom, const std::vector<uint32_t> &mask);
void SetupConvGeomRows(const DiffractionGeometry &geom, const std::vector<uint32_t> *mask, size_t row0, size_t row_end);
void SetupConvGeom(const DiffractionGeometry &geom, const std::vector<uint32_t> *mask);
void SetupConvGeomCached(const DiffractionGeometry &geom, const std::vector<uint32_t> &mask,
AzimuthalIntegrationGeometryCache &cache);
void SetupPixel(const DiffractionGeometry &geom, const std::vector<uint32_t> &mask,
void SetupPixel(const DiffractionGeometry &geom, const std::vector<uint32_t> *mask,
uint32_t pxl, uint32_t col, uint32_t row);
AzimuthalIntegrationMapping(const DiffractionExperiment& experiment,
const PixelMask& mask,
AzimuthalIntegrationGeometryCache *cache,
size_t nthreads);
public:
AzimuthalIntegrationMapping(const DiffractionExperiment& experiment,
const PixelMask& mask,
size_t nthreads = 0);
// The same mapping, with the geometry of the pixels taken from `cache` when it holds this geometry
// (AzimuthalIntegrationGeometryCache), and left there for the next one when it does not.
AzimuthalIntegrationMapping(const DiffractionExperiment& experiment,
const PixelMask& mask,
AzimuthalIntegrationGeometryCache &cache,
size_t nthreads = 0);
[[nodiscard]] uint16_t GetBinNumber() const;
[[nodiscard]] const std::vector<uint16_t>& GetPixelToBin() const;
+7 -4
View File
@@ -918,9 +918,9 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru
// it used to finish before any of them started.
const DiffractionExperiment prescan_x = experiment_;
const PixelMask prescan_mask = pixel_mask_;
// Built by the spot measurement, the only thing that reads it, so that it is built beside the
// shadow rather than ahead of it.
std::unique_ptr<AzimuthalIntegrationMapping> prescan_mapping;
if (want_spots)
prescan_mapping = std::make_unique<AzimuthalIntegrationMapping>(prescan_x, prescan_mask);
// Everything reading one frame needs that cannot be shared between threads: its own scratch for
// each of the two decompressions, its own preprocessed image and its own spot finder.
@@ -1063,6 +1063,8 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru
}
const auto spot_measurement = [&] {
prescan_mapping = std::make_unique<AzimuthalIntegrationMapping>(prescan_x, prescan_mask,
*azint_geometry_);
std::vector<std::vector<BeamCenterSpot>> spots_of(ordinals.size());
std::vector<std::vector<spot_width::FluxCurve>> curves_of(ordinals.size());
std::vector<std::vector<float>> spot_q_of(ordinals.size());
@@ -3318,7 +3320,7 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b
}
}
AzimuthalIntegrationMapping mapping(experiment_, pixel_mask_);
AzimuthalIntegrationMapping mapping(experiment_, pixel_mask_, *azint_geometry_);
JFJochReceiverPlots plots;
plots.Setup(experiment_, mapping);
@@ -3685,7 +3687,8 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b
home_spot_cache.swap(spot_cache);
experiment_.BeamX_pxl(x).BeamY_pxl(y);
release_spot_engines();
trial_mapping = std::make_unique<AzimuthalIntegrationMapping>(experiment_, pixel_mask_);
trial_mapping = std::make_unique<AzimuthalIntegrationMapping>(experiment_, pixel_mask_,
*azint_geometry_);
spot_mapping = trial_mapping.get();
};
const auto restore_beam_center = [&](float x, float y) {
+6
View File
@@ -17,6 +17,7 @@
#include "../common/DiffractionExperiment.h"
#include "../common/PixelMask.h"
#include "../common/AzimuthalIntegrationMapping.h"
#include "../common/CrystalLattice.h"
#include "../common/JFJochException.h"
#include "../common/Reflection.h" // MergedReflection
@@ -737,6 +738,11 @@ class Rugnux {
std::vector<std::pair<std::vector<double>, std::map<int, std::vector<SpotToSave>>>> entries;
};
std::shared_ptr<FirstPassSpots> first_pass_spots_ = std::make_shared<FirstPassSpots>();
// The per-pixel geometry of the last azimuthal mapping the run built, so that the next one for the
// same geometry - the first pass after the pre-scan, a probe and the canonical pass after it - does
// not evaluate it again. Shared with the copies the run makes of itself.
std::shared_ptr<AzimuthalIntegrationGeometryCache> azint_geometry_ =
std::make_shared<AzimuthalIntegrationGeometryCache>();
[[nodiscard]] std::vector<double> SpotFindingKey(const AzimuthalIntegrationMapping &mapping) const;
void AddFirstPassMemo(const FirstPassMemo &memo);
// The geometry walk's next indexing probe, started on a copy of the run as soon as the canonical
+36
View File
@@ -547,6 +547,42 @@ TEST_CASE("AzimuthalIntegrationMapping_Threading_ConvertedGeometry_18Modules", "
CheckAzimuthalIntegrationMappingThreadingExact(x);
}
// A mapping that takes its geometry from the cache - built there under another mask, or at another
// centre before - is the mapping built from scratch, bit for bit.
TEST_CASE("AzimuthalIntegrationMapping_GeometryCacheExact", "[AzimuthalIntegration]") {
DiffractionExperiment x(DetDECTRIS(2000, 2000, "E16M", ""));
x.DetectorDistance_mm(50).BeamX_pxl(1000).BeamY_pxl(1000);
x.QSpacingForAzimInt_recipA(0.1).QRangeForAzimInt_recipA(0.1, 10);
x.PolarizationFactor(0.99f);
PixelMask plain_mask(x);
PixelMask user_mask(x);
std::vector<uint32_t> blocked(x.GetPixelsNum(), 0);
for (int row = 900; row < 1100; row++)
for (int col = 0; col < 1100; col++)
blocked[row * x.GetXPixelsNum() + col] = 1;
user_mask.LoadUserMask(x, blocked);
AzimuthalIntegrationGeometryCache cache;
const auto check = [&](const DiffractionExperiment &experiment, const PixelMask &mask) {
const AzimuthalIntegrationMapping ref(experiment, mask);
const AzimuthalIntegrationMapping cached(experiment, mask, cache);
RequireVectorsEqual(ref.GetPixelToBin(), cached.GetPixelToBin(), "pixel_to_bin", 0);
RequireVectorsEqual(ref.Resolution(), cached.Resolution(), "resolution", 0);
RequireVectorsEqual(ref.Corrections(), cached.Corrections(), "corrections", 0);
CHECK(ref.GetPixelToBinChecksum() == cached.GetPixelToBinChecksum());
CHECK(ref.GetCorrectionsChecksum() == cached.GetCorrectionsChecksum());
};
check(x, plain_mask); // computed
check(x, user_mask); // taken from the cache, under another mask
check(x, plain_mask);
DiffractionExperiment moved(x);
moved.BeamX_pxl(1003.5f);
check(moved, user_mask); // another centre: computed again
check(x, user_mask);
}
// The ice score on an explicit profile: flat means no ice (1.0), and a bump planted on a hexagonal
// ring is reported at its own height over the background. Uses the static entry point, which is what
// feeds the score the peak-excluded per-ring background instead of the plain profile.