diff --git a/common/AzimuthalIntegrationMapping.cpp b/common/AzimuthalIntegrationMapping.cpp index 7027a5d24..36bffbc62 100644 --- a/common/AzimuthalIntegrationMapping.cpp +++ b/common/AzimuthalIntegrationMapping.cpp @@ -125,6 +125,8 @@ void AzimuthalIntegrationMapping::SetupConvGeomCached(const DiffractionGeometry settings.GetLowQ_recipA(), settings.GetHighQ_recipA(), settings.GetQSpacing_recipA(), polarization_factor.value_or(0.0f)}) key.push_back(std::bit_cast(f)); + key.insert(key.end(), {static_cast(settings.GetQBinSpacing()), + static_cast(settings.GetQBinCount())}); for (const float f: geom.GetDetectorMatrix().arr()) key.push_back(std::bit_cast(f)); key.insert(key.end(), {static_cast(settings.GetAzimuthalBinCount()), @@ -268,9 +270,10 @@ void AzimuthalIntegrationMapping::UpdateMaxBinNumber() { bin_to_2theta.resize(settings.GetBinCount()); bin_to_phi.resize(settings.GetBinCount()); + const auto q_centre = settings.GetQBinCentres_recipA(); for (int j = 0; j < settings.GetAzimuthalBinCount(); j++) { for (int i = 0; i < settings.GetQBinCount(); i++) { - bin_to_q[j * settings.GetQBinCount() + i] = static_cast(settings.GetQSpacing_recipA() * (i + 0.5) + settings.GetLowQ_recipA()); + bin_to_q[j * settings.GetQBinCount() + i] = static_cast(q_centre[i]); bin_to_d[j * settings.GetQBinCount() + i] = 2.0f * static_cast(PI) / bin_to_q[j * settings.GetQBinCount() + i]; bin_to_2theta[j * settings.GetQBinCount() + i] = 2.0f * asinf(bin_to_q[i] * wavelength / (4.0f * static_cast(PI))) * 180.0f / static_cast(PI); diff --git a/common/AzimuthalIntegrationProfile.cpp b/common/AzimuthalIntegrationProfile.cpp index 412eea018..9b37c4a73 100644 --- a/common/AzimuthalIntegrationProfile.cpp +++ b/common/AzimuthalIntegrationProfile.cpp @@ -210,7 +210,12 @@ float AzimuthalIntegrationProfile::IceRingScore(const std::vector &profil if (nq < 12 || !(dq > 0.0f)) return 1.0f; - auto q_of = [&](int i) { return low_q + (static_cast(i) + 0.5f) * dq; }; + // Linear bins keep their own float arithmetic, which the scores have always been computed with. + const bool linear = settings.GetQBinSpacing() == QBinSpacing::Linear; + const std::vector q_centre = linear ? std::vector() : settings.GetQBinCentres_recipA(); + auto q_of = [&](int i) { + return linear ? low_q + (static_cast(i) + 0.5f) * dq : static_cast(q_centre[i]); + }; auto on_ice = [&](float q) { for (const float d : ICE_RING_RES_A) if (std::fabs(q - two_pi / d) < 1.5f * half_width_q) @@ -243,7 +248,11 @@ float AzimuthalIntegrationProfile::IceRingScore(const std::vector &profil float score = 1.0f; for (const float d : ICE_RING_RES_A) { const float qr = two_pi / d; - const int b = static_cast(std::lround((qr - low_q) / dq - 0.5f)); + int b = -1; + if (linear) + b = static_cast(std::lround((qr - low_q) / dq - 0.5f)); + else if (const uint16_t bin = settings.GetBin(qr, 0.0f); bin != UINT16_MAX) + b = bin; if (b < 0 || b >= nq || !std::isfinite(prof[b]) || prof[b] <= 0.0f) continue; // Linear-interpolate the smooth background to the ring position. diff --git a/common/AzimuthalIntegrationSettings.cpp b/common/AzimuthalIntegrationSettings.cpp index 54f23bf5f..6f73cdc68 100644 --- a/common/AzimuthalIntegrationSettings.cpp +++ b/common/AzimuthalIntegrationSettings.cpp @@ -52,9 +52,32 @@ void AzimuthalIntegrationSettings::ResolveHighQ(float detector_max_q_recipA) { } AzimuthalIntegrationSettings &AzimuthalIntegrationSettings::QSpacing_recipA(float input) { - check_finite("Q spacing for azimuthal integration", input); - check_min("Q spacing for azimuthal integration", input, minQ_recipA); - q_spacing = input; + return QBinning(QBinSpacing::Linear, input, std::nullopt); +} + +AzimuthalIntegrationSettings &AzimuthalIntegrationSettings::QBinning(QBinSpacing type, std::optional spacing, + std::optional q_bin_count) { + if (spacing.has_value()) { + check_finite("Q spacing for azimuthal integration", *spacing); + check_min("Q spacing for azimuthal integration", *spacing, minQ_recipA); + } + if (q_bin_count.has_value()) { + check_min("Number of Q bins for azimuthal integration", *q_bin_count, 1); + check_max("Number of Q bins for azimuthal integration", *q_bin_count, UINT16_MAX - 1); + } + if (type == QBinSpacing::Linear && spacing.has_value() && q_bin_count.has_value()) + throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, + "Linear Q binning takes either the Q spacing or the number of Q bins, not both"); + if (type != QBinSpacing::Linear && spacing.has_value()) + throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, + "Q spacing applies only to linear Q binning; give the number of Q bins instead"); + if (type != QBinSpacing::Linear && !q_bin_count.has_value()) + throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, + "Logarithmic Q binning needs the number of Q bins"); + + q_bin_spacing = type; + q_spacing = spacing.value_or(q_spacing); + requested_q_bins = q_bin_count; UpdateBinCount(); return *this; } @@ -76,7 +99,43 @@ float AzimuthalIntegrationSettings::GetLowQ_recipA() const { } float AzimuthalIntegrationSettings::GetQSpacing_recipA() const { - return q_spacing; + return q_bin_spacing == QBinSpacing::Linear ? bin_step : q_spacing; +} + +QBinSpacing AzimuthalIntegrationSettings::GetQBinSpacing() const { + return q_bin_spacing; +} + +std::optional AzimuthalIntegrationSettings::GetRequestedQSpacing_recipA() const { + if (q_bin_spacing == QBinSpacing::Linear && !requested_q_bins.has_value()) + return q_spacing; + return std::nullopt; +} + +std::optional AzimuthalIntegrationSettings::GetRequestedQBinCount() const { + return requested_q_bins; +} + +std::vector AzimuthalIntegrationSettings::GetQBinCentres_recipA() const { + std::vector ret(q_bins); + for (int32_t i = 0; i < q_bins; i++) { + if (q_bin_spacing == QBinSpacing::Linear) + ret[i] = bin_step * (i + 0.5) + low_q_recipA; + else + ret[i] = std::pow(10.0, std::log10(static_cast(low_q_recipA)) + bin_step * (i + 0.5)); + } + return ret; +} + +std::vector AzimuthalIntegrationSettings::GetQBinEdges_recipA() const { + std::vector ret(q_bins + 1); + for (int32_t i = 0; i <= q_bins; i++) { + if (q_bin_spacing == QBinSpacing::Linear) + ret[i] = bin_step * static_cast(i) + low_q_recipA; + else + ret[i] = std::pow(10.0, std::log10(static_cast(low_q_recipA)) + bin_step * static_cast(i)); + } + return ret; } AzimuthalIntegrationSettings &AzimuthalIntegrationSettings::BkgEstimateQRange_recipA(float low, float high) { @@ -140,8 +199,14 @@ int32_t AzimuthalIntegrationSettings::GetBinCount() const { return total_bins; } +float AzimuthalIntegrationSettings::BinCoordinate(float q) const { + if (q_bin_spacing == QBinSpacing::Linear) + return (q - low_q_recipA) / bin_step; + return (std::log10(q) - std::log10(low_q_recipA)) / bin_step; +} + uint16_t AzimuthalIntegrationSettings::QToBin(float q) const { - return std::min(GetBinCount() - 1, std::floor(std::max(0.0f, (q - GetLowQ_recipA()) / GetQSpacing_recipA()))); + return std::min(GetBinCount() - 1, std::floor(std::max(0.0f, BinCoordinate(q)))); } uint16_t AzimuthalIntegrationSettings::GetBin(float q, float phi_deg) const { @@ -150,12 +215,22 @@ uint16_t AzimuthalIntegrationSettings::GetBin(float q, float phi_deg) const { if (phi_deg < 0.0 || phi_deg >= 360) return UINT16_MAX; - int16_t q_bin = std::floor((q - low_q_recipA) / q_spacing); - int16_t phi_bin = std::floor(phi_deg / 360.0f * azim_bins); + // Rounding can put a q just below high Q on the far edge of the last bin. + int32_t q_bin = std::min(std::floor(BinCoordinate(q)), q_bins - 1); + int32_t phi_bin = std::floor(phi_deg / 360.0f * azim_bins); return q_bin + phi_bin * GetQBinCount(); } void AzimuthalIntegrationSettings::UpdateBinCount() { - q_bins = std::ceil((high_q_recipA - low_q_recipA) / q_spacing); + if (!requested_q_bins.has_value()) { + bin_step = q_spacing; + q_bins = std::ceil((high_q_recipA - low_q_recipA) / q_spacing); + } else { + q_bins = requested_q_bins.value(); + if (q_bin_spacing == QBinSpacing::Linear) + bin_step = (high_q_recipA - low_q_recipA) / static_cast(q_bins); + else + bin_step = (std::log10(high_q_recipA) - std::log10(low_q_recipA)) / static_cast(q_bins); + } total_bins = q_bins * azim_bins; } diff --git a/common/AzimuthalIntegrationSettings.h b/common/AzimuthalIntegrationSettings.h index 638352311..6c4ebe2c4 100644 --- a/common/AzimuthalIntegrationSettings.h +++ b/common/AzimuthalIntegrationSettings.h @@ -6,6 +6,11 @@ #include "JFJochMath.h" #include #include +#include + +// How the Q bins are laid out between low and high Q: equal steps in Q, or equal steps in log10(Q) - +// fine bins at low Q and coarse ones at high Q, for scattering whose features are at low Q. +enum class QBinSpacing {Linear, Log10}; class AzimuthalIntegrationSettings { constexpr static float minQ_recipA = 1e-5; @@ -23,7 +28,13 @@ class AzimuthalIntegrationSettings { float low_q_recipA = 0.1; float bkg_estimate_high_q_recipA = 2.0f * PI / 3.0; float bkg_estimate_low_q_recipA = 2.0f * PI / 5.0; + QBinSpacing q_bin_spacing = QBinSpacing::Linear; + // Linear binning is given either by its Q spacing or by its number of Q bins; log10 binning only + // by the number of bins. Unset number: the spacing sets the bins. float q_spacing = 0.01; + std::optional requested_q_bins; + // Width of a bin in the variable the bins are equally spaced in: Q, or log10(Q). + float bin_step = 0.01; int32_t azim_bins = 1; // Compute azimuthal integration on the CPU instead of the FPGA during the FPGA // acquisition workflow. Lifts the FPGA bin-count limit and adds standard-deviation output. @@ -33,6 +44,8 @@ class AzimuthalIntegrationSettings { int32_t total_bins = 0; void UpdateBinCount(); + // Where q falls on the bin scale: bin i spans [i, i + 1). + [[nodiscard]] float BinCoordinate(float q) const; public: AzimuthalIntegrationSettings(); AzimuthalIntegrationSettings& SolidAngleCorrection(bool input); @@ -40,7 +53,12 @@ public: AzimuthalIntegrationSettings& QRange_recipA(float low, std::optional high); // Substitute the detector's own maximum q for an unset high q. No-op if one was requested. void ResolveHighQ(float detector_max_q_recipA); + // Linear binning with this Q spacing. AzimuthalIntegrationSettings& QSpacing_recipA(float input); + // Linear: exactly one of spacing and bin count may be given (neither keeps the current spacing). + // Log10: the bin count is required and a spacing is refused. + AzimuthalIntegrationSettings& QBinning(QBinSpacing type, std::optional spacing, + std::optional q_bin_count); AzimuthalIntegrationSettings& BkgEstimateQRange_recipA(float low, float high); AzimuthalIntegrationSettings& AzimuthalBinCount(int32_t input); AzimuthalIntegrationSettings& ForceCPUinFPGAWorkflow(bool input); @@ -50,7 +68,15 @@ public: [[nodiscard]] float GetHighQ_recipA() const; [[nodiscard]] std::optional GetRequestedHighQ_recipA() const; [[nodiscard]] float GetLowQ_recipA() const; + // The width of a linear bin (as given, or as the bin count makes it). [[nodiscard]] float GetQSpacing_recipA() const; + [[nodiscard]] QBinSpacing GetQBinSpacing() const; + // The spacing and the bin count as they were given; one of them is unset. + [[nodiscard]] std::optional GetRequestedQSpacing_recipA() const; + [[nodiscard]] std::optional GetRequestedQBinCount() const; + // Centre of every Q bin (mid-point of its edges on the bin scale), and its GetQBinCount() + 1 edges. + [[nodiscard]] std::vector GetQBinCentres_recipA() const; + [[nodiscard]] std::vector GetQBinEdges_recipA() const; [[nodiscard]] int32_t GetBinCount() const; [[nodiscard]] int32_t GetQBinCount() const; diff --git a/docs/RUGNUX_CLI.md b/docs/RUGNUX_CLI.md index fef62bf79..bfe348b8e 100644 --- a/docs/RUGNUX_CLI.md +++ b/docs/RUGNUX_CLI.md @@ -231,7 +231,9 @@ The radial profile behind the per-image ice-ring score, and what `--mode azint` | Option | Description | | --- | --- | -| `-q, --azim-q-spacing ` | Q bin spacing, 1/Å (default: 0.01; finer resolves the narrow ice rings) | +| `-q, --azim-q-spacing ` | Q bin spacing, 1/Å, for linear binning (default: 0.01; finer resolves the narrow ice rings). Not together with `--azim-q-bins` | +| `--azim-q-bins ` | Number of Q bins between minimum and maximum Q, instead of a spacing. Required for `--azim-q-binning log10` | +| `--azim-q-binning ` | How the Q bins are laid out: `linear` (equal steps in Q, the default) \| `log10` (equal steps in log10 Q: fine bins at low Q, coarse at high Q). `--mode calibration` needs `linear` | | `--azim-min-q ` | Minimum Q, 1/Å | | `--azim-max-q ` | Maximum Q, 1/Å. Omitted: integration extends to the highest Q the detector reaches. The adaptive spot finder shares these Q bins, so this also sets how far self-calibrating detection can see | | `--azim-phi-bins ` | Number of azimuthal (phi) bins (default: 1) | diff --git a/image_analysis/MXAnalysisWithoutFPGA.cpp b/image_analysis/MXAnalysisWithoutFPGA.cpp index 3c228fba2..010d895c3 100644 --- a/image_analysis/MXAnalysisWithoutFPGA.cpp +++ b/image_analysis/MXAnalysisWithoutFPGA.cpp @@ -258,9 +258,7 @@ void MXAnalysisWithoutFPGA::Analyze(DataMessage &output, const std::vector &ring_bkg = spot_finding_settings.adaptive_threshold ? adaptiveSpotFinder->GetRingBackground() : no_rings; const bool stills = !experiment.IsRotationIndexing(); - bragg_engine->RadialBackgroundFromRings(ring_bkg, integration.GetQBinCount(), - integration.Settings().GetLowQ_recipA(), - integration.Settings().GetQSpacing_recipA()); + bragg_engine->RadialBackgroundFromRings(ring_bkg, integration.Settings().GetQBinCentres_recipA()); if (!bragg_engine->IsBackgroundRadialAuto() || ring_bkg.empty()) return; output.ice_ring_score = AzimuthalIntegrationProfile::IceRingScore( diff --git a/image_analysis/bragg_integration/BraggIntegrationEngine.cpp b/image_analysis/bragg_integration/BraggIntegrationEngine.cpp index 9f63e44a8..aef472661 100644 --- a/image_analysis/bragg_integration/BraggIntegrationEngine.cpp +++ b/image_analysis/bragg_integration/BraggIntegrationEngine.cpp @@ -221,10 +221,10 @@ void BraggIntegrationEngine::BuildRadialKernel(float grow) { k_diff.push_back(static_cast(hist_ann[k] / sa - hist_disk[k] / sd)); } -void BraggIntegrationEngine::RadialBackgroundFromRings(const std::vector &ring_bkg, int32_t q_bins, - float low_q, float dq) { +void BraggIntegrationEngine::RadialBackgroundFromRings(const std::vector &ring_bkg, + const std::vector &q_centre) { radial_curve.clear(); - const RingBackground rings(ring_bkg, q_bins, low_q, dq); + const RingBackground rings(ring_bkg, q_centre); if (rings.empty()) return; // The same bins as the engines' own curve: one per pixel of distance from the beam, out to the far diff --git a/image_analysis/bragg_integration/BraggIntegrationEngine.h b/image_analysis/bragg_integration/BraggIntegrationEngine.h index 06ebfd4eb..0938c61fc 100644 --- a/image_analysis/bragg_integration/BraggIntegrationEngine.h +++ b/image_analysis/bragg_integration/BraggIntegrationEngine.h @@ -303,12 +303,12 @@ public: // The radial background curve for the images that follow, from a peak-excluded background per // resolution ring of the whole detector (the adaptive spot finder's GetRingBackground): q bin i - // holds the ring at low_q + (i + 0.5) * dq, entries past the first q_bins are further azimuthal + // holds the ring at q_centre[i], entries past the first q_centre.size() are further azimuthal // bins and are averaged in, and a ring with no value (NAN) is bridged by its neighbours. On a // serial frame the predicted reflections' own ring pixels are a sparse sample of the same curve - // a few dozen reflections, against every pixel of the frame here. An empty profile goes back to // accumulating the curve from the reflections. - void RadialBackgroundFromRings(const std::vector &ring_bkg, int32_t q_bins, float low_q, float dq); + void RadialBackgroundFromRings(const std::vector &ring_bkg, const std::vector &q_centre); // Where a reflection sits on that curve. The curve is tabulated against F_px tan(2 theta), so this is // the 2 theta of the reflection's position, read off the geometry as the curve's rings and the empty // apertures read every pixel's; a pixel of its stencil is at that radius plus its radial offset. Not diff --git a/image_analysis/bragg_integration/RingBackground.cpp b/image_analysis/bragg_integration/RingBackground.cpp index 746ba8e21..af62a37b0 100644 --- a/image_analysis/bragg_integration/RingBackground.cpp +++ b/image_analysis/bragg_integration/RingBackground.cpp @@ -6,8 +6,9 @@ #include #include -RingBackground::RingBackground(const std::vector &ring_bkg, int32_t q_bins, float low_q, float dq) { - if (q_bins <= 0 || !(dq > 0.0f)) +RingBackground::RingBackground(const std::vector &ring_bkg, const std::vector &q_centre) { + const size_t q_bins = q_centre.size(); + if (q_bins == 0) return; std::vector sum(q_bins, 0.0); std::vector cnt(q_bins, 0); @@ -16,9 +17,9 @@ RingBackground::RingBackground(const std::vector &ring_bkg, int32_t q_bin sum[i % q_bins] += ring_bkg[i]; ++cnt[i % q_bins]; } - for (int i = 0; i < q_bins; ++i) + for (size_t i = 0; i < q_bins; ++i) if (cnt[i] > 0) { - q.push_back(low_q + (i + 0.5) * dq); + q.push_back(q_centre[i]); b.push_back(sum[i] / cnt[i]); } } diff --git a/image_analysis/bragg_integration/RingBackground.h b/image_analysis/bragg_integration/RingBackground.h index 58b2bb206..27c40936b 100644 --- a/image_analysis/bragg_integration/RingBackground.h +++ b/image_analysis/bragg_integration/RingBackground.h @@ -7,14 +7,15 @@ #include // A frame's background as a function of q, from a peak-excluded background per resolution ring of the -// whole detector (the adaptive spot finder's GetRingBackground): ring i holds low_q + (i + 0.5) * dq, -// entries past the first q_bins are further azimuthal bins and are averaged in, and a ring with no +// whole detector (the adaptive spot finder's GetRingBackground): ring i holds the q of q_centre[i] +// (AzimuthalIntegrationSettings::GetQBinCentres_recipA), entries past the first q_centre.size() are +// further azimuthal bins and are averaged in, and a ring with no // value (NAN) is bridged by its neighbours. Between rings the value is interpolated linearly; beyond // the first and the last ring the end value is held, which has no curvature. struct RingBackground { std::vector q, b; - RingBackground(const std::vector &ring_bkg, int32_t q_bins, float low_q, float dq); + RingBackground(const std::vector &ring_bkg, const std::vector &q_centre); [[nodiscard]] bool empty() const { return q.size() < 2; } [[nodiscard]] double At(double q_recipA) const; }; diff --git a/rugnux/RugnuxCommandLine.cpp b/rugnux/RugnuxCommandLine.cpp index a668d774a..c44d3f6b4 100644 --- a/rugnux/RugnuxCommandLine.cpp +++ b/rugnux/RugnuxCommandLine.cpp @@ -124,7 +124,12 @@ std::string RugnuxCommandLine(const ProcessConfig &config, // to this run's geometry, so leave the flag out and let it resolve again. if (const auto high_q = a.GetRequestedHighQ_recipA()) add("--azim-max-q", num(*high_q)); - add("--azim-q-spacing", num(a.GetQSpacing_recipA())); + if (const auto spacing = a.GetRequestedQSpacing_recipA()) + add("--azim-q-spacing", num(*spacing)); + else + add("--azim-q-bins", std::to_string(a.GetQBinCount())); + if (a.GetQBinSpacing() == QBinSpacing::Log10) + add("--azim-q-binning", "log10"); add("--azim-phi-bins", std::to_string(a.GetAzimuthalBinCount())); add("--polarization-correction", a.IsPolarizationCorrection() ? "on" : "off"); add("--solid-angle-correction", a.IsSolidAngleCorrection() ? "on" : "off"); diff --git a/rugnux/RugnuxPreScan.cpp b/rugnux/RugnuxPreScan.cpp index d56ffb537..248a018ff 100644 --- a/rugnux/RugnuxPreScan.cpp +++ b/rugnux/RugnuxPreScan.cpp @@ -317,6 +317,7 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru {static_cast(want_shadow), static_cast(experiment_.GetSaturationLimit()), goniometer ? goniometer->GetIncrement_deg() : 0.0, a.GetLowQ_recipA(), a.GetHighQ_recipA(), a.GetQSpacing_recipA(), + static_cast(a.GetQBinSpacing()), static_cast(a.GetQBinCount()), static_cast(a.GetAzimuthalBinCount()), static_cast(a.IsSolidAngleCorrection()), static_cast(a.IsPolarizationCorrection()), static_cast(f.enable), f.signal_to_noise_threshold, @@ -493,9 +494,7 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru const std::vector no_rings; const RingBackground rings(config_.spot_finding.adaptive_threshold ? w.spot_finder->GetRingBackground() : no_rings, - prescan_mapping->GetQBinCount(), - prescan_mapping->Settings().GetLowQ_recipA(), - prescan_mapping->Settings().GetQSpacing_recipA()); + prescan_mapping->Settings().GetQBinCentres_recipA()); apertures.resize(aperture_stencils.size()); for (size_t k = 0; k < aperture_stencils.size(); ++k) background_aperture::MeasureFrame(*w.preprocessed, static_cast(prescan_x.GetXPixelsNumConv()), diff --git a/rugnux/rugnux_cli.cpp b/rugnux/rugnux_cli.cpp index e6920ea91..b6c4dce8c 100644 --- a/rugnux/rugnux_cli.cpp +++ b/rugnux/rugnux_cli.cpp @@ -288,6 +288,8 @@ enum { OPT_AZIM_MIN_Q, OPT_AZIM_MAX_Q, OPT_AZIM_PHI_BINS, + OPT_AZIM_Q_BINS, + OPT_AZIM_Q_BINNING, OPT_MODE, OPT_CALIBRANT, OPT_CALIBRATION, @@ -376,6 +378,8 @@ static option long_options[] = { {"azim-min-q", required_argument, nullptr, OPT_AZIM_MIN_Q}, {"azim-max-q", required_argument, nullptr, OPT_AZIM_MAX_Q}, {"azim-phi-bins", required_argument, nullptr, OPT_AZIM_PHI_BINS}, + {"azim-q-bins", required_argument, nullptr, OPT_AZIM_Q_BINS}, + {"azim-q-binning", required_argument, nullptr, OPT_AZIM_Q_BINNING}, {"polarization-correction", required_argument, nullptr, OPT_POLARIZATION_CORRECTION}, {"solid-angle-correction", required_argument, nullptr, OPT_SOLID_ANGLE_CORRECTION}, {"flight-path", required_argument, nullptr, OPT_FLIGHT_PATH}, @@ -904,6 +908,8 @@ struct RugnuxCli { std::optional fft_min_unit_cell_A; // --fft-min-unit-cell: shortest axis the FFT search accepts std::optional min_q, max_q, q_spacing; // azimuthal integration range / -q spacing (1/A) std::optional azimuthal_bins; // --azimuthal-bins + std::optional q_bin_count; // --azim-q-bins + std::optional q_binning; // --azim-q-binning std::optional polarization_correction; // --polarization-correction (azimuthal integration) std::optional solid_angle_correction; // --solid-angle-correction (azimuthal integration) std::optional flight_path; // --flight-path (Bragg prediction) @@ -1613,6 +1619,19 @@ int RugnuxCli::Parse(int argc, char **argv) { case OPT_AZIM_PHI_BINS: azimuthal_bins = atoi(optarg); break; + case OPT_AZIM_Q_BINS: + q_bin_count = atoi(optarg); + break; + case OPT_AZIM_Q_BINNING: { + const std::string b = optarg ? optarg : ""; + if (b == "linear") q_binning = QBinSpacing::Linear; + else if (b == "log10") q_binning = QBinSpacing::Log10; + else { + logger.Error("Invalid --azim-q-binning: {} (expected linear|log10)", b); + return 1; + } + break; + } case OPT_POLARIZATION_CORRECTION: { bool value; if (!parse_on_off(optarg, value)) { @@ -3000,8 +3019,8 @@ int RugnuxInputRun::PrepareRugnuxInput() { if (min_q || max_q) azint_settings.QRange_recipA(min_q.value_or(azint_settings.GetLowQ_recipA()), max_q ? max_q : azint_settings.GetRequestedHighQ_recipA()); - if (q_spacing) - azint_settings.QSpacing_recipA(q_spacing.value()); + if (q_spacing || q_bin_count || q_binning) + azint_settings.QBinning(q_binning.value_or(QBinSpacing::Linear), q_spacing, q_bin_count); if (azimuthal_bins) azint_settings.AzimuthalBinCount(azimuthal_bins.value()); if (polarization_correction) @@ -3009,10 +3028,15 @@ int RugnuxInputRun::PrepareRugnuxInput() { if (solid_angle_correction) azint_settings.SolidAngleCorrection(solid_angle_correction.value()); experiment.ImportAzimuthalIntegrationSettings(azint_settings); - logger.Info("Azimuthal integration: Q [{:.4f}, {:.4f}] 1/A, spacing {:.4f}, {} Q x {} azimuthal bins", - azint_settings.GetLowQ_recipA(), azint_settings.GetHighQ_recipA(), - azint_settings.GetQSpacing_recipA(), azint_settings.GetQBinCount(), - azint_settings.GetAzimuthalBinCount()); + if (azint_settings.GetQBinSpacing() == QBinSpacing::Linear) + logger.Info("Azimuthal integration: Q [{:.4f}, {:.4f}] 1/A, spacing {:.5f}, {} Q x {} azimuthal bins", + azint_settings.GetLowQ_recipA(), azint_settings.GetHighQ_recipA(), + azint_settings.GetQSpacing_recipA(), azint_settings.GetQBinCount(), + azint_settings.GetAzimuthalBinCount()); + else + logger.Info("Azimuthal integration: Q [{:.4f}, {:.4f}] 1/A, log10 spacing, {} Q x {} azimuthal bins", + azint_settings.GetLowQ_recipA(), azint_settings.GetHighQ_recipA(), + azint_settings.GetQBinCount(), azint_settings.GetAzimuthalBinCount()); } // --mode azint: azimuthal integration only (no spot finding / indexing / scaling). Rugnux reads @@ -3064,6 +3088,11 @@ int RugnuxInputRun::PrepareRugnuxInput() { // --mode calibration: fit the detector geometry to the calibrant's powder rings, measured over // every selected image, and write it as a PONI file. if (mode == RugnuxMode::Calibration) { + // The ring search measures its windows in equal steps of Q. + if (experiment.GetAzimuthalIntegrationSettings().GetQBinSpacing() != QBinSpacing::Linear) { + logger.Error("--mode calibration needs linear Q bins (--azim-q-binning linear)"); + return 1; + } // The same analysis defaults every other mode gets (configure_offline_output applies them for // the MX path further down). The polarization factor is one of them and it enters the summed // azimuthal profile the rings are measured in, so without this the CLI and the viewer's diff --git a/tests/AzimuthalIntegrationTest.cpp b/tests/AzimuthalIntegrationTest.cpp index 5151c4faf..084a2bdbc 100644 --- a/tests/AzimuthalIntegrationTest.cpp +++ b/tests/AzimuthalIntegrationTest.cpp @@ -631,3 +631,226 @@ TEST_CASE("AzimuthalIntegrationProfile_IceRingScore_Azimuthal","[AzimuthalIntegr CHECK(AzimuthalIntegrationProfile::IceRingScore(sectors, q_bins, settings, 0.03f) == Catch::Approx(AzimuthalIntegrationProfile::IceRingScore(flat, q_bins, settings, 0.03f))); } + +TEST_CASE("AzimuthalIntegrationSettings_QBinning_Validation","[AzimuthalIntegration]") { + AzimuthalIntegrationSettings s; + s.QRange_recipA(0.01f, 1.0f); + + // Linear takes either the spacing or the bin count, not both. + REQUIRE_THROWS(s.QBinning(QBinSpacing::Linear, 0.01f, 100)); + // Log10 takes only the bin count, and needs it. + REQUIRE_THROWS(s.QBinning(QBinSpacing::Log10, 0.01f, 100)); + REQUIRE_THROWS(s.QBinning(QBinSpacing::Log10, 0.01f, std::nullopt)); + REQUIRE_THROWS(s.QBinning(QBinSpacing::Log10, std::nullopt, std::nullopt)); + REQUIRE_THROWS(s.QBinning(QBinSpacing::Log10, std::nullopt, 0)); + REQUIRE_THROWS(s.QBinning(QBinSpacing::Log10, std::nullopt, 65535)); + REQUIRE_THROWS(s.QBinning(QBinSpacing::Linear, 0.0f, std::nullopt)); + // log10(q) needs q > 0: a low Q of zero or below is refused (minimum 1e-5 1/A, for every spacing). + { + AzimuthalIntegrationSettings log_s; + log_s.QBinning(QBinSpacing::Log10, std::nullopt, 100); + REQUIRE_THROWS(log_s.QRange_recipA(0.0f, 1.0f)); + REQUIRE_THROWS(log_s.QRange_recipA(-0.1f, 1.0f)); + REQUIRE_NOTHROW(log_s.QRange_recipA(1e-5f, 1.0f)); + CHECK(std::isfinite(log_s.GetQBinCentres_recipA().front())); + } + + // A refused call leaves the settings as they were. + CHECK(s.GetQBinSpacing() == QBinSpacing::Linear); + CHECK(s.GetRequestedQSpacing_recipA() == 0.01f); + CHECK(!s.GetRequestedQBinCount()); + + REQUIRE_NOTHROW(s.QBinning(QBinSpacing::Log10, std::nullopt, 200)); + CHECK(s.GetQBinSpacing() == QBinSpacing::Log10); + CHECK(s.GetQBinCount() == 200); + CHECK(s.GetRequestedQBinCount() == 200); + CHECK(!s.GetRequestedQSpacing_recipA()); + + REQUIRE_NOTHROW(s.QBinning(QBinSpacing::Linear, std::nullopt, 99)); + CHECK(s.GetQBinCount() == 99); + CHECK(s.GetQSpacing_recipA() == Catch::Approx(0.01)); + CHECK(!s.GetRequestedQSpacing_recipA()); + + // Linear with neither keeps the spacing it had. + REQUIRE_NOTHROW(s.QSpacing_recipA(0.02f)); + REQUIRE_NOTHROW(s.QBinning(QBinSpacing::Linear, std::nullopt, std::nullopt)); + CHECK(s.GetRequestedQSpacing_recipA() == 0.02f); + CHECK(s.GetQBinCount() == 50); +} + +// The linear spacing bins exactly as it always has: the same count, the same bin for every q and the +// same centres, compared bit for bit with the formulas it used before log10 binning was added. +TEST_CASE("AzimuthalIntegrationSettings_Linear_Unchanged","[AzimuthalIntegration]") { + const float low = 0.1f, high = 4.5f, spacing = 0.01f; + AzimuthalIntegrationSettings s; + s.QSpacing_recipA(spacing).QRange_recipA(low, high).AzimuthalBinCount(3); + + const int32_t q_bins = std::ceil((high - low) / spacing); + REQUIRE(s.GetQBinCount() == q_bins); + REQUIRE(s.GetBinCount() == 3 * q_bins); + + const auto centres = s.GetQBinCentres_recipA(); + REQUIRE(centres.size() == q_bins); + for (int i = 0; i < q_bins; i++) + CHECK(static_cast(centres[i]) == static_cast(spacing * (i + 0.5) + low)); + + for (int k = 0; k < 100000; k++) { + const float q = low + (high - low) * static_cast(k) / 100000.0f; + const float phi = 359.9f * static_cast(k % 97) / 97.0f; + const int16_t q_bin = std::floor((q - low) / spacing); + const int16_t phi_bin = std::floor(phi / 360.0f * 3); + REQUIRE(s.GetBin(q, phi) == static_cast(q_bin + phi_bin * q_bins)); + REQUIRE(s.QToBin(q) == std::min(s.GetBinCount() - 1, std::floor(std::max(0.0f, (q - low) / spacing)))); + } +} + +TEST_CASE("AzimuthalIntegrationSettings_Linear_BinCount","[AzimuthalIntegration]") { + AzimuthalIntegrationSettings s; + s.QRange_recipA(0.1f, 4.1f).QBinning(QBinSpacing::Linear, std::nullopt, 40); + + const auto edges = s.GetQBinEdges_recipA(); + REQUIRE(edges.size() == 41); + CHECK(edges.front() == Catch::Approx(0.1)); + CHECK(edges.back() == Catch::Approx(4.1)); + const auto centres = s.GetQBinCentres_recipA(); + CHECK(centres[0] == Catch::Approx(0.15)); + CHECK(centres[39] == Catch::Approx(4.05)); + + CHECK(s.GetBin(0.1f, 0.0f) == 0); + CHECK(s.GetBin(std::nextafter(4.1f, 0.0f), 0.0f) == 39); + CHECK(s.GetBin(4.1f, 0.0f) == UINT16_MAX); + CHECK(s.GetBin(0.0999f, 0.0f) == UINT16_MAX); +} + +TEST_CASE("AzimuthalIntegrationSettings_Log10","[AzimuthalIntegration]") { + const float low = 0.001f, high = 1.0f; + const int32_t n = 30; + AzimuthalIntegrationSettings s; + s.QRange_recipA(low, high).QBinning(QBinSpacing::Log10, std::nullopt, n).AzimuthalBinCount(2); + REQUIRE(s.GetQBinCount() == n); + REQUIRE(s.GetBinCount() == 2 * n); + + const auto edges = s.GetQBinEdges_recipA(); + const auto centres = s.GetQBinCentres_recipA(); + REQUIRE(edges.size() == n + 1); + REQUIRE(centres.size() == n); + CHECK(edges.front() == Catch::Approx(low)); + CHECK(edges.back() == Catch::Approx(high)); + // Equal steps in log10(q): three decades in 30 bins, every edge 10^0.1 times the one before. + for (int i = 0; i < n; i++) { + CHECK(edges[i + 1] > edges[i]); + CHECK(edges[i + 1] / edges[i] == Catch::Approx(std::pow(10.0, 0.1))); + // The centre is the mid-point on the log scale: the geometric mean of the edges. + CHECK(centres[i] == Catch::Approx(std::sqrt(edges[i] * edges[i + 1]))); + // So the width of a bin grows with q, in proportion to its left edge. + CHECK((edges[i + 1] - edges[i]) / edges[i] == Catch::Approx(std::pow(10.0, 0.1) - 1.0)); + if (i > 0) + CHECK(edges[i + 1] - edges[i] > edges[i] - edges[i - 1]); + } + + // Every q in range lands in the one bin whose edges hold it. + for (int k = 0; k < 100000; k++) { + const float q = low * std::pow(high / low, static_cast(k) / 100000.0f); + if (q >= high) + continue; + const uint16_t bin = s.GetBin(q, 0.0f); + REQUIRE(bin < n); + REQUIRE(q >= edges[bin] * (1 - 1e-5)); + REQUIRE(q < edges[bin + 1] * (1 + 1e-5)); + REQUIRE(s.QToBin(q) == bin); + // The second azimuthal sector is the same q bins one row further. + REQUIRE(s.GetBin(q, 270.0f) == bin + n); + } + CHECK(s.GetBin(std::nextafter(high, 0.0f), 0.0f) == n - 1); + CHECK(s.GetBin(high, 0.0f) == UINT16_MAX); + CHECK(s.GetBin(0.99f * low, 0.0f) == UINT16_MAX); + CHECK(s.QToBin(0.0f) == 0); +} + +// Every pixel of the detector whose q is within the range is assigned to exactly the bin whose edges +// hold its q, and the mapping's Q axis is the bins' true centres. +TEST_CASE("AzimuthalIntegrationMapping_Log10","[AzimuthalIntegration]") { + DiffractionExperiment x(DetJF4M()); + x.DetectorDistance_mm(200).BeamX_pxl(1000).BeamY_pxl(1000); + AzimuthalIntegrationSettings settings; + settings.QRange_recipA(0.01f, 2.0f).QBinning(QBinSpacing::Log10, std::nullopt, 100).AzimuthalBinCount(4); + x.ImportAzimuthalIntegrationSettings(settings); + + PixelMask pixel_mask(x); + AzimuthalIntegrationMapping mapping(x, pixel_mask); + const auto &s = mapping.Settings(); + const auto edges = s.GetQBinEdges_recipA(); + const auto centres = s.GetQBinCentres_recipA(); + REQUIRE(mapping.GetQBinCount() == 100); + + const auto &bin_to_q = mapping.GetBinToQ(); + REQUIRE(bin_to_q.size() == 400); + for (int az = 0; az < 4; az++) + for (int i = 0; i < 100; i++) { + CHECK(bin_to_q[az * 100 + i] == static_cast(centres[i])); + CHECK(mapping.GetBinToD()[az * 100 + i] == Catch::Approx(2.0 * PI / centres[i])); + } + + const auto &pixel_to_bin = mapping.GetPixelToBin(); + const auto &resolution = mapping.Resolution(); + std::vector per_bin(mapping.GetBinNumber(), 0); + int64_t in_range = 0; + for (size_t i = 0; i < pixel_to_bin.size(); i++) { + if (pixel_mask.GetMask()[i] != 0 || !(resolution[i] > 0)) { + REQUIRE(pixel_to_bin[i] == UINT16_MAX); + continue; + } + const float q = 2.0f * static_cast(PI) / resolution[i]; + if (q < 0.01f || q >= 2.0f) { + REQUIRE(pixel_to_bin[i] == UINT16_MAX); + continue; + } + in_range++; + REQUIRE(pixel_to_bin[i] < mapping.GetBinNumber()); + per_bin[pixel_to_bin[i]]++; + const int q_bin = pixel_to_bin[i] % 100; + REQUIRE(q >= edges[q_bin] * (1 - 1e-5)); + REQUIRE(q < edges[q_bin + 1] * (1 + 1e-5)); + } + REQUIRE(in_range > 0); + int64_t sum = 0; + for (auto c: per_bin) + sum += c; + CHECK(sum == in_range); +} + +// The linear mapping assigns every pixel to the bin the old formula gave it. +TEST_CASE("AzimuthalIntegrationMapping_Linear_Unchanged","[AzimuthalIntegration]") { + DiffractionExperiment x(DetJF4M()); + x.DetectorDistance_mm(75).BeamX_pxl(1000).BeamY_pxl(1000); + x.QSpacingForAzimInt_recipA(0.01).QRangeForAzimInt_recipA(0.05, 4.0); + + PixelMask pixel_mask(x); + AzimuthalIntegrationMapping mapping(x, pixel_mask); + const auto &pixel_to_bin = mapping.GetPixelToBin(); + const auto &resolution = mapping.Resolution(); + for (size_t i = 0; i < pixel_to_bin.size(); i++) { + if (!(resolution[i] > 0)) + continue; + const float q = 2.0f * static_cast(PI) / resolution[i]; + uint16_t expected = UINT16_MAX; + if (q >= 0.05f && q < 4.0f) + expected = static_cast(std::floor((q - 0.05f) / 0.01f)); + REQUIRE(pixel_to_bin[i] == expected); + } + const auto &bin_to_q = mapping.GetBinToQ(); + for (size_t i = 0; i < bin_to_q.size(); i++) + REQUIRE(bin_to_q[i] == static_cast(0.01f * (i + 0.5) + 0.05f)); +} + +TEST_CASE("AzimuthalIntegrationProfile_IceRingScore_Log10","[AzimuthalIntegration]") { + AzimuthalIntegrationSettings settings; + settings.QRange_recipA(0.1f, 4.5f).QBinning(QBinSpacing::Log10, std::nullopt, 800); + const int q_bins = settings.GetQBinCount(); + + std::vector profile(q_bins, 100.0f); + CHECK(AzimuthalIntegrationProfile::IceRingScore(profile, q_bins, settings, 0.03f) == Catch::Approx(1.0f)); + + profile[settings.GetBin(6.283185307f / 2.249f, 0.0f)] = 250.0f; + CHECK(AzimuthalIntegrationProfile::IceRingScore(profile, q_bins, settings, 0.03f) == Catch::Approx(2.5f)); +} diff --git a/tests/BackgroundApertureTest.cpp b/tests/BackgroundApertureTest.cpp index 788e712fc..f53efc813 100644 --- a/tests/BackgroundApertureTest.cpp +++ b/tests/BackgroundApertureTest.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only #include +#include "LinearQCentres.h" #include #include @@ -26,7 +27,7 @@ ImagePreprocessorBuffer Frame(double level, double ripple, uint32_t seed) { return img; } -const RingBackground no_rings({}, 0, 0.0f, 0.0f); +const RingBackground no_rings({}, {}); DiffractionGeometry Geometry() { DiffractionGeometry g; @@ -102,7 +103,7 @@ TEST_CASE("BackgroundAperture_RadialCorrectionHelpsOnARadialBackground", "[Integ const double r = 60.0 / 0.075 * std::tan(2.0 * std::asin(q * 1.0 / (4.0 * PI))); profile[i] = static_cast(background(r)); } - const RingBackground rings(profile, static_cast(profile.size()), low_q, dq); + const RingBackground rings(profile, LinearQCentres(profile.size(), low_q, dq)); const auto r3 = background_aperture::CandidateR3(8.0f, 14.0f); background_aperture::Tally tally; // Unclipped: a gradient this steep would put the high side of the ring above a photon clip. @@ -140,7 +141,7 @@ TEST_CASE("BackgroundAperture_CorrectedClipFollowsTheCurve", "[Integration]") { const double r = 60.0 / 0.075 * std::tan(2.0 * std::asin(q * 1.0 / (4.0 * PI))); profile[i] = static_cast(background(r)); } - const RingBackground rings(profile, static_cast(profile.size()), low_q, dq); + const RingBackground rings(profile, LinearQCentres(profile.size(), low_q, dq)); background_aperture::Tally tally; background_aperture::MeasureFrame(img, W, H, {}, 6.0f, 8.0f, {14.0f}, 4.0f, 1.0f, rings, g, DetectorModules(), tally); diff --git a/tests/BraggIntegrationEngineCPUTest.cpp b/tests/BraggIntegrationEngineCPUTest.cpp index 81ea24326..7c7102262 100644 --- a/tests/BraggIntegrationEngineCPUTest.cpp +++ b/tests/BraggIntegrationEngineCPUTest.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only #include +#include "LinearQCentres.h" #include #include @@ -18,6 +19,7 @@ #include "../image_analysis/bragg_integration/BraggIntegrationEngineCPU.h" #include "../image_analysis/image_preprocessing/ImagePreprocessorBuffer.h" + // One spot on a flat background, inside a grid of predictions 8 px apart that put no flux on the // frame - the tails of reflections recorded on the frames either side of a finely sliced one. Their // r2 regions cover every background ring, so whether the spot keeps a clean ring depends only on @@ -225,7 +227,7 @@ TEST_CASE("BraggIntegrationEngineCPU_RadialCurveFromRings", "[Integration][porta experiment.ImportBraggIntegrationSettings( BraggIntegrationSettings().Integrator(IntegratorMode::BoxSum).BackgroundRadialCorrection(correct)); BraggIntegrationEngineCPU engine(experiment, PixelMask(experiment)); - engine.RadialBackgroundFromRings(rings, static_cast(rings.size()), low_q, dq); + engine.RadialBackgroundFromRings(rings, LinearQCentres(rings.size(), low_q, dq)); REQUIRE(!engine.GetRadialBackground().empty()); const auto out = engine.Run(image, predicted, predicted.size(), 0); REQUIRE(out.size() == 1); @@ -242,7 +244,7 @@ TEST_CASE("BraggIntegrationEngineCPU_RadialCurveFromRings", "[Integration][porta // An empty profile hands the curve back to the reflections' own rings. BraggIntegrationEngineCPU engine(experiment, PixelMask(experiment)); - engine.RadialBackgroundFromRings({}, 500, low_q, dq); + engine.RadialBackgroundFromRings({}, LinearQCentres(500, low_q, dq)); CHECK(engine.GetRadialBackground().empty()); } @@ -277,7 +279,7 @@ TEST_CASE("BraggIntegrationEngineCPU_ClipFollowsRadialCurve", "[Integration][por auto background_read = [&](bool correct) { experiment.ImportBraggIntegrationSettings(BraggIntegrationSettings().BackgroundRadialCorrection(correct)); BraggIntegrationEngineCPU engine(experiment, PixelMask(experiment)); - engine.RadialBackgroundFromRings(rings, static_cast(rings.size()), low_q, dq); + engine.RadialBackgroundFromRings(rings, LinearQCentres(rings.size(), low_q, dq)); const auto out = engine.Run(image, predicted, predicted.size(), 0); REQUIRE(out.size() == 1); return out[0].bkg; @@ -339,7 +341,7 @@ TEST_CASE("BraggIntegrationEngineCPU_RadialCurveOverThePixelsRead", "[Integratio experiment.ImportBraggIntegrationSettings( BraggIntegrationSettings().Integrator(IntegratorMode::BoxSum).BackgroundRadialCorrection(correct)); BraggIntegrationEngineCPU engine(experiment, PixelMask(experiment)); - engine.RadialBackgroundFromRings(rings, static_cast(rings.size()), low_q, dq); + engine.RadialBackgroundFromRings(rings, LinearQCentres(rings.size(), low_q, dq)); const auto out = engine.Run(image, predicted, predicted.size(), 0); REQUIRE(out.size() == 1); return out[0]; diff --git a/tests/BraggIntegrationEngineGPUTest.cpp b/tests/BraggIntegrationEngineGPUTest.cpp index b979522d6..4a622f704 100644 --- a/tests/BraggIntegrationEngineGPUTest.cpp +++ b/tests/BraggIntegrationEngineGPUTest.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only #include +#include "LinearQCentres.h" #include #include "../common/CUDAWrapper.h" @@ -525,8 +526,8 @@ TEST_CASE("BraggIntegrationEngineGPU_RadialCurveFromRingsMatchesCPU", "[Integrat experiment.ImportBraggIntegrationSettings(BraggIntegrationSettings().Integrator(mode).BackgroundRadialCorrection(true)); BraggIntegrationEngineCPU cpu(experiment, PixelMask(experiment)); BraggIntegrationEngineGPU gpu(experiment, stream, PixelMask(experiment)); - cpu.RadialBackgroundFromRings(rings, static_cast(rings.size()), low_q, dq); - gpu.RadialBackgroundFromRings(rings, static_cast(rings.size()), low_q, dq); + cpu.RadialBackgroundFromRings(rings, LinearQCentres(rings.size(), low_q, dq)); + gpu.RadialBackgroundFromRings(rings, LinearQCentres(rings.size(), low_q, dq)); const auto out_cpu = cpu.Run(cpu_image, predicted, predicted.size(), 0); const auto out_gpu = gpu.Run(gpu_image, predicted, predicted.size(), 0); REQUIRE(out_cpu.size() == predicted.size()); diff --git a/tests/BraggIntegrationEngineMetalTest.cpp b/tests/BraggIntegrationEngineMetalTest.cpp index f03fa87ba..f178c73a9 100644 --- a/tests/BraggIntegrationEngineMetalTest.cpp +++ b/tests/BraggIntegrationEngineMetalTest.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only #include +#include "LinearQCentres.h" #include #include @@ -123,7 +124,7 @@ void HandOverCurve(BraggIntegrationEngine &engine) { std::vector rings(400); for (size_t i = 0; i < rings.size(); ++i) rings[i] = 1.0f + 0.01f * static_cast(i * i); - engine.RadialBackgroundFromRings(rings, static_cast(rings.size()), 0.05f, 0.01f); + engine.RadialBackgroundFromRings(rings, LinearQCentres(rings.size(), 0.05f, 0.01f)); } DiffractionExperiment MakeExperiment(const DetectorSetup &det, const Case &c) { @@ -262,7 +263,7 @@ TEST_CASE("BraggIntegrationEngineMetal_ShadowEdgeReachesItsModes", "[portable][I std::copy(e.f.image.begin(), e.f.image.end(), image.data()); auto integrate = [&](bool correct) { BraggIntegrationEngineCPU engine(e.x, mask); - engine.RadialBackgroundFromRings(e.rings, static_cast(e.rings.size()), e.low_q, e.dq); + engine.RadialBackgroundFromRings(e.rings, LinearQCentres(e.rings.size(), e.low_q, e.dq)); engine.BackgroundRadial(correct); return engine.Run(image, e.f.predicted, e.f.predicted.size(), 0); }; @@ -483,7 +484,7 @@ TEST_CASE("BraggIntegrationEngineMetal_ShadowEdgeBitIdenticalToCPU", "[portable] BraggIntegrationEngineMetal metal(e.x, mask); for (BraggIntegrationEngine *engine : {static_cast(&cpu), static_cast(&metal)}) { - engine->RadialBackgroundFromRings(e.rings, static_cast(e.rings.size()), e.low_q, e.dq); + engine->RadialBackgroundFromRings(e.rings, LinearQCentres(e.rings.size(), e.low_q, e.dq)); engine->BackgroundRadial(true); } ImagePreprocessorBuffer image(e.x.GetPixelsNum()); diff --git a/tests/JFJochReaderTest.cpp b/tests/JFJochReaderTest.cpp index a751f14a0..926aa853a 100644 --- a/tests/JFJochReaderTest.cpp +++ b/tests/JFJochReaderTest.cpp @@ -15,6 +15,8 @@ #include "../reader/MiniCBF.h" #include "../rugnux/RugnuxDefaults.h" #include "../compression/JFJochCompressor.h" +#include "../frame_serialize/CBORStream2Serializer.h" +#include "../frame_serialize/CBORStream2Deserializer.h" #include #include @@ -1315,6 +1317,78 @@ TEST_CASE("JFJochReader_Azint", "[HDF5][Full]") { REQUIRE(H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL) == 0); } +// Log10 Q bins end to end: the Q axis in the CBOR start message and in the HDF5 file is the bins' own +// (non-uniform) centres, and reads back as written. +TEST_CASE("JFJochReader_Azint_Log10", "[HDF5][Full]") { + DiffractionExperiment x(DetJF(1)); + x.FilePrefix("test27log").ImagesPerTrigger(2).OverwriteExistingFiles(true); + x.BitDepthImage(16).ImagesPerFile(2).SetFileWriterFormat(FileWriterFormat::NXmxVDS).PixelSigned(false); + x.Compression(CompressionAlgorithm::NO_COMPRESSION); + + AzimuthalIntegrationSettings azint_settings; + azint_settings.QRange_recipA(0.01f, 2.0f).QBinning(QBinSpacing::Log10, std::nullopt, 50).AzimuthalBinCount(2); + x.ImportAzimuthalIntegrationSettings(azint_settings); + + AzimuthalIntegrationMapping azint(x, PixelMask(x)); + const auto centres = azint.Settings().GetQBinCentres_recipA(); + REQUIRE(centres.size() == 50); + std::vector expected_q(100); + for (int i = 0; i < 100; i++) + expected_q[i] = static_cast(centres[i % 50]); + // Non-uniform: the last bin is far wider than the first. + CHECK(centres[49] - centres[48] > 50 * (centres[1] - centres[0])); + + StartMessage start_message; + x.FillMessage(start_message); + start_message.az_int_bin_to_q = azint.GetBinToQ(); + start_message.az_int_bin_to_phi = azint.GetBinToPhi(); + start_message.az_int_q_bin_count = azint.GetQBinCount(); + start_message.az_int_phi_bin_count = azint.GetAzimuthalBinCount(); + REQUIRE(start_message.az_int_bin_to_q == expected_q); + + { + std::vector buffer(16 * 1024 * 1024); + CBORStream2Serializer serializer(buffer.data(), buffer.size()); + serializer.SerializeSequenceStart(start_message); + auto deserialized = CBORStream2Deserialize(buffer.data(), serializer.GetBufferSize()); + REQUIRE(deserialized->start_message); + CHECK(deserialized->start_message->az_int_bin_to_q == expected_q); + CHECK(deserialized->start_message->az_int_q_bin_count == 50); + } + + RegisterHDF5Filter(); + { + FileWriter file_set(start_message); + std::vector image(x.GetPixelsNum()); + for (int i = 0; i < x.GetImageNum(); i++) { + DataMessage message{}; + message.image = CompressedImage(image, x.GetXPixelsNum(), x.GetYPixelsNum()); + message.number = i; + message.az_int_profile = std::vector(azint_settings.GetBinCount(), 57); + REQUIRE_NOTHROW(file_set.WriteHDF5(message)); + } + EndMessage end_message; + end_message.max_image_number = x.GetImageNum(); + file_set.WriteHDF5(end_message); + file_set.Finalize(); + } + { + JFJochHDF5Reader reader; + REQUIRE_NOTHROW(reader.ReadFile("test27log_master.h5")); + std::shared_ptr reader_image; + REQUIRE_NOTHROW(reader_image = reader.LoadImage(0)); + CHECK(reader_image->Dataset().az_int_bin_to_q == expected_q); + CHECK(reader_image->Dataset().q_bins == 50); + const auto q_1d = reader_image->GetAzInt1D_BinToQ(); + REQUIRE(q_1d.size() == 50); + for (int i = 0; i < 50; i++) + CHECK(q_1d[i] == expected_q[i]); + } + remove("test27log_master.h5"); + remove("test27log_data_000001.h5"); + REQUIRE(H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL) == 0); +} + TEST_CASE("JFJochReader_NiggliClass", "[HDF5][Full]") { DiffractionExperiment x(DetJF(1)); x.FilePrefix("test95").ImagesPerTrigger(4).OverwriteExistingFiles(true); diff --git a/tests/LinearQCentres.h b/tests/LinearQCentres.h new file mode 100644 index 000000000..598a8e4d6 --- /dev/null +++ b/tests/LinearQCentres.h @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +#include +#include + +// Centres of n linear q bins, as AzimuthalIntegrationSettings::GetQBinCentres_recipA lays them out. +inline std::vector LinearQCentres(size_t n, float low_q, float dq) { + std::vector ret(n); + for (size_t i = 0; i < n; i++) + ret[i] = low_q + (i + 0.5) * dq; + return ret; +}