diff --git a/docs/CPU_DATA_ANALYSIS_INTEGRATION.md b/docs/CPU_DATA_ANALYSIS_INTEGRATION.md index 8d7942dad..37d85b306 100644 --- a/docs/CPU_DATA_ANALYSIS_INTEGRATION.md +++ b/docs/CPU_DATA_ANALYSIS_INTEGRATION.md @@ -161,7 +161,7 @@ The integrator is selected by `--integrator boxsum|gaussian|empirical` (default ### 9.4 The prescaling correction -The deterministic per-reflection corrections are carried as three multiplicative factors. `prescaling_corr` holds the reciprocal Lorentz factor (rotation only — a still's Lorentz factor is one) times the reciprocal polarization factor from the geometry-based term (§2.2), and nothing else: it is Lorentz x polarization, which is what `LP` means in every format the field reads. Beside it sit the two terms that describe what happened to the photon between leaving the sample and being counted, and that are kept apart from `LP` because detector response and beam/crystal geometry are different things: `qe_corr`, the sensor's angle-dependent efficiency, and `flight_corr`, the medium in the flight path (§9.6). The total deterministic correction on a reflection is the product `prescaling_corr * qe_corr * flight_corr`, and every site that corrects an intensity — the integrator, the scaling fits, the merge ingest, the anisotropy analysis and the unmerged export — multiplies all three. None of them is a scale: the fitted per-image scale and the partiality are separate. The three reach the unmerged MTZ as its `LP`, `QE` and `FLIGHT` columns unchanged (`QE` and `FLIGHT` as divisors normalised to 1 at normal incidence), so raw counts are `I / LP * QE * FLIGHT`. +The deterministic per-reflection corrections are carried as three multiplicative factors. `prescaling_corr` holds the reciprocal Lorentz factor (rotation only — a still's Lorentz factor is one) times the reciprocal polarization factor from the geometry-based term (§2.2), and nothing else: it is Lorentz x polarization, which is what `LP` means in every format the field reads. Beside it sit the two terms that describe what happened to the photon between leaving the sample and being counted, and that are kept apart from `LP` because detector response and beam/crystal geometry are different things: `qe_corr`, the sensor's angle-dependent efficiency, and `flight_corr`, the medium in the flight path (§9.7). The total deterministic correction on a reflection is the product `prescaling_corr * qe_corr * flight_corr`, and every site that corrects an intensity — the integrator, the scaling fits, the merge ingest, the anisotropy analysis and the unmerged export — multiplies all three. None of them is a scale: the fitted per-image scale and the partiality are separate. The three reach the unmerged MTZ as its `LP`, `QE` and `FLIGHT` columns unchanged (`QE` and `FLIGHT` as divisors normalised to 1 at normal incidence), so raw counts are `I / LP * QE * FLIGHT`. One term is deliberately **not** in it. The **per-pixel solid angle**, which the azimuthal profile does divide out (§2.2), is correctly absent here: a Bragg integration sums all the photons in a @@ -195,7 +195,19 @@ Every integration pass, adaptive or not, now logs the radii it used together wit --- -### 9.6 The flight path +### 9.6 Measuring the bandwidth (rotation, reported only) + +A finite energy spread $\sigma$ ($\Delta\lambda/\lambda$, rms) smears a reflection along its own radius by $2\tan\theta\,\sigma$ radians of $2\theta$ and not at all across it. Most files do not state it — a multilayer monochromator is a beamline option, not a header field — so Rugnux reads it off the spots, on the same isolated strong spots the width of §9.5 is measured on (`spot_width::EstimateBandwidth`), and **reports** it in the log; the run itself uses the file's value or `--bandwidth`, and 0 otherwise. For each spot, with $u$ along the radius and $v$ across it, the second moments about its centroid are + +$$m_u = \tfrac1{12} + p_u + j_r^2\big(s^2 + 4\tan^2\theta\,\sigma^2\big),\qquad m_v = \tfrac1{12} + p_v + j_t^2 s^2,$$ + +with $j_r$, $j_t$ the exact pixels per radian of $2\theta$ and of the angle across the scattering plane at that spot, $s$ everything isotropic in angle (divergence, crystal size, mosaic spread), and $p_u$, $p_v$ the sensor parallax, fixed from the sensor's physics: a photon converting at depth $z$ (exponential with length $L\cos\psi$ at angle $\psi$ to the normal, truncated at the thickness) lands $z\tan\psi$ along the ray's in-plane direction. Then + +$$y = (m_u - \tfrac1{12} - p_u) - (j_r/j_t)^2\,(m_v - \tfrac1{12} - p_v) = a + \sigma^2\,(2 j_r\tan\theta)^2$$ + +is a straight line whose slope is the bandwidth. It is fitted over eight equal-count bins of the abscissa, each a 20 %-trimmed mean weighted by its own scatter; the slope's error is the spread of 200 bootstrap re-draws of the spots, inflated by the reduced $\chi^2$ of the binned fit where the line fits worse than the scatter says, and the log calls the estimate significant at $z>3$. It is a **lower bound** — mosaic spread seen along the radius subtracts — and a spread of cell edges is exactly degenerate with it, so what it measures is the effective radial broadening. + +### 9.7 The flight path A reflection leaving the sample at incidence angle $\alpha$ to the detector normal reaches its pixel after $D/\cos\alpha$ of flight rather than $D$, so it crosses more of whatever fills the flight path diff --git a/docs/RUGNUX_OVERVIEW.md b/docs/RUGNUX_OVERVIEW.md index 87274be27..68f8028ba 100644 --- a/docs/RUGNUX_OVERVIEW.md +++ b/docs/RUGNUX_OVERVIEW.md @@ -13,7 +13,9 @@ it ([§1.5](CPU_DATA_ANALYSIS_IMAGE.md)), masks pixels its frames show to be def ([§1.6](CPU_DATA_ANALYSIS_IMAGE.md)), measures the beam centre from the isotropy of the scattered background and compares it with the file's ([§1.4](CPU_DATA_ANALYSIS_IMAGE.md)), and reads how wide this crystal's spots are, which sets the integration radius -([§9.5](CPU_DATA_ANALYSIS_INTEGRATION.md)). +([§9.5](CPU_DATA_ANALYSIS_INTEGRATION.md)), and how much longer they are along their radius than +across it, which is the beam's bandwidth - reported in the log, not yet used +([§9.6](CPU_DATA_ANALYSIS_INTEGRATION.md)). **Spots.** Every image is decoded — on the GPU straight from the compressed chunk ([§0](CPU_DATA_ANALYSIS_IMAGE.md)) — and one fused pass computes the azimuthal profile and finds diff --git a/image_analysis/SensorAbsorption.h b/image_analysis/SensorAbsorption.h index 378d0105e..7ff580b7b 100644 --- a/image_analysis/SensorAbsorption.h +++ b/image_analysis/SensorAbsorption.h @@ -4,6 +4,7 @@ #ifndef JUNGFRAUJOCH_SENSORABSORPTION_H #define JUNGFRAUJOCH_SENSORABSORPTION_H +#include #include #include @@ -123,6 +124,20 @@ inline double AttenuationLength_um(const std::string &material, double lambda_A) return mu_cm > 0.0 ? 1e4 / mu_cm : 0.0; } +// Variance [um^2] of the depth at which a photon converts: exponential with length L_um, truncated +// at the sensor thickness. A photon arriving at angle psi to the normal travels z/cos(psi) to reach +// depth z, so its depth length is L*cos(psi) - pass that for an oblique ray. Zero without a sensor. +inline double ConversionDepthVariance_um2(double L_um, double thickness_um) { + if (!(thickness_um > 0.0) || !(L_um > 0.0)) + return 0.0; + const double a = thickness_um / L_um, e = std::exp(-a); + if (1.0 - e <= 0.0) + return 0.0; + const double mean = L_um * (1.0 - (1.0 + a) * e) / (1.0 - e); + const double ez2 = L_um * L_um * (2.0 - (a * a + 2.0 * a + 2.0) * e) / (1.0 - e); + return std::max(0.0, ez2 - mean * mean); +} + // Everything the per-reflection correction needs, reduced to the two numbers that are constant for // a dataset. Built once on the host; the GPU predictor takes the two floats. struct SensorQE { diff --git a/image_analysis/bragg_integration/BraggIntegrationEngine.cpp b/image_analysis/bragg_integration/BraggIntegrationEngine.cpp index ced5d0caf..af9ad59ac 100644 --- a/image_analysis/bragg_integration/BraggIntegrationEngine.cpp +++ b/image_analysis/bragg_integration/BraggIntegrationEngine.cpp @@ -27,15 +27,7 @@ double parallax_var_px2(const std::string &material, double thickness_um, double if (!(thickness_um > 0.0) || !(pixel_um > 0.0) || !(lambda_A > 0.0)) return 0.0; const double L = sensor_absorption::AttenuationLength_um(material, lambda_A); - if (!(L > 0.0)) - return 0.0; - const double a = thickness_um / L, e = std::exp(-a); - if (1.0 - e <= 0.0) - return 0.0; - const double mean = L * (1.0 - (1.0 + a) * e) / (1.0 - e); - const double ez2 = L * L * (2.0 - (a * a + 2.0 * a + 2.0) * e) / (1.0 - e); - const double var = std::max(0.0, ez2 - mean * mean); // um^2 - return var / (pixel_um * pixel_um); + return sensor_absorption::ConversionDepthVariance_um2(L, thickness_um) / (pixel_um * pixel_um); } // The radial-offset kernels below are a pure function of these six numbers, and one engine is built diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index cd419d874..6c5fdcc3f 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -8,6 +8,7 @@ #include "SpindleCuspLoss.h" #include "SpotWidth.h" #include "HotPixels.h" +#include "../image_analysis/SensorAbsorption.h" #include "DiagnosticOutput.h" #include @@ -1146,6 +1147,25 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru } } + // The X-ray bandwidth, read off the shapes of the same spots (spot_width::EstimateBandwidth). + // Reported only: the run uses what the file or --bandwidth states, 0 otherwise, as it always has. + if (want_width) { + const auto &det = experiment_.GetDetectorSetup(); + const double lambda = experiment_.GetWavelength_A(); + const auto estimate = spot_width::EstimateBandwidth( + width_curves, sensor_absorption::AttenuationLength_um(det.GetSensorMaterial(), lambda), + det.GetSensorThickness_um(), experiment_.GetPixelSize_mm() * 1000.0); + const float used = experiment_.GetBandwidthFWHM().value_or(0.0f); + if (!estimate) + logger.Info("Bandwidth: not measurable on {} spots; the run uses {:.4f}", width_curves.size(), + used); + else + logger.Info("Bandwidth: spot shapes give FWHM {:.4f} from {} spots (one standard error is " + "FWHM {:.4f}; z = {:.1f}, chi2 {:.1f}) - {}; the run uses {:.4f}", estimate->fwhm, + estimate->spots, estimate->fwhm_floor, estimate->z, estimate->chi2, + estimate->z > spot_width::BANDWIDTH_Z ? "significant" : "not significant", used); + } + // Powder contamination, measured on every run that finds spots here. A crystalline phase other // than the crystal - hexagonal ice, a shower of microcrystals, salt out of the cryoprotectant - // diffracts as rings, and its spots are handed to the indexer and to scaling as if they were this diff --git a/rugnux/SpotWidth.cpp b/rugnux/SpotWidth.cpp index 9095f6dbf..e933a0573 100644 --- a/rugnux/SpotWidth.cpp +++ b/rugnux/SpotWidth.cpp @@ -8,8 +8,12 @@ #include #include #include +#include #include +#include "../common/JFJochMath.h" +#include "../image_analysis/SensorAbsorption.h" + using namespace spot_width; namespace { @@ -94,6 +98,113 @@ float interpolate_radius(double frac, const std::array &prof) { return static_cast(R_MAX); } +// The disk the second moments are taken over, px. +constexpr int R_MOMENT = 9; + +// The spot's second moments along and across its radius, about its own flux-weighted centroid. +// (cx, cy) is the pixel the spot is centred on, (mx, my) the core centroid relative to it, `ring` +// the background ring's counts. The background is the ring's mean with anything 5 sigma above it +// clipped: a median is biased low on sparse Poisson counts, and a bias here adds the same flux at +// every radius of the disk - an extra second moment that does not cancel between the two directions +// once they are weighted by the obliquity. +SpotShape shape_of(const int32_t *centre_px, int width, int cx, int cy, double mx, double my, + const std::vector &ring, const DiffractionGeometry &geometry) { + SpotShape shape; + double sum = 0.0; + for (const int32_t v : ring) sum += v; + const double clip = sum / static_cast(ring.size()) + + 5.0 * std::sqrt(std::abs(sum / static_cast(ring.size())) + 0.5) + 2.0; + sum = 0.0; + size_t n = 0; + for (const int32_t v : ring) + if (v < clip) { sum += v; n++; } + if (n == 0) return shape; + const double bkg = sum / static_cast(n); + + // Centroid over the moment disk, three times, then the moments about it. + constexpr double R2 = static_cast(R_MOMENT) * R_MOMENT; + double flux = 0.0, sxx = 0.0, syy = 0.0, sxy = 0.0; + for (int iter = 0; iter < 4; iter++) { + double f = 0.0, sx = 0.0, sy = 0.0, qxx = 0.0, qyy = 0.0, qxy = 0.0; + for (int dy = -R_MOMENT - 2; dy <= R_MOMENT + 2; dy++) { + const int32_t *row = centre_px + static_cast(dy) * width; + for (int dx = -R_MOMENT - 2; dx <= R_MOMENT + 2; dx++) { + const double ddx = dx - mx, ddy = dy - my; + if (ddx * ddx + ddy * ddy >= R2) continue; + const double w = row[dx] - bkg; + f += w; + sx += w * ddx; + sy += w * ddy; + qxx += w * ddx * ddx; + qyy += w * ddy * ddy; + qxy += w * ddx * ddy; + } + } + if (!(f > 0.0)) return shape; + if (iter < 3) { + mx += sx / f; + my += sy / f; + if (std::abs(mx) > 2.0 || std::abs(my) > 2.0) return shape; + } else { + flux = f; + // About the centroid of this last pass, not the disk's centre. + const double ox = sx / f, oy = sy / f; + sxx = qxx / f - ox * ox; + syy = qyy / f - oy * oy; + sxy = qxy / f - ox * oy; + } + } + if (!(flux > 0.0)) return shape; + + // Where one radian of 2theta, and of the angle across the scattering plane, moves the spot. + const float x = static_cast(cx + mx), y = static_cast(cy + my); + const Coord s0(0, 0, 1); + const Coord s1 = geometry.LabCoord(x, y).Normalize(); + const float two_theta = std::acos(std::clamp(s1 * s0, -1.0f, 1.0f)); + if (!(two_theta > 1.0f * static_cast(PI) / 180.0f)) return shape; + const Coord across = (s0 % s1).Normalize(); + const Coord along = across % s1; // in the scattering plane, away from the beam + const float lambda = geometry.GetWavelength_A(); + constexpr float EPS = 1e-3f; + const auto hit = [&](const Coord &dir) { + return geometry.RecipToDetector(dir / lambda - s0 / lambda); + }; + const auto p0 = hit(s1); + const auto pr = hit(s1 * std::cos(EPS) + along * std::sin(EPS)); + const auto pt = hit(s1 * std::cos(EPS) + across * std::sin(EPS)); + const double jrx = (pr.first - p0.first) / EPS, jry = (pr.second - p0.second) / EPS; + const double jr = std::hypot(jrx, jry); + if (!(jr > 0.0)) return shape; + const double ux = jrx / jr, uy = jry / jr, vx = -uy, vy = ux; + const double jt = std::abs((pt.first - p0.first) / EPS * vx + (pt.second - p0.second) / EPS * vy); + if (!(jt > 0.0)) return shape; + + // Parallax: the ray's in-plane direction on the sensor, and tan^2 of its angle to the normal. + const Coord normal = geometry.GetNormalAxis(); + const float cos_psi = std::abs(s1 * normal); + const Coord in_plane = s1 - normal * (s1 * normal); + const double e_len = in_plane.Length(); + double par_u = 0.0, par_v = 0.0; + if (e_len > 1e-6 && cos_psi > 1e-3f) { + const double ex = in_plane * geometry.GetFastAxis() / e_len; + const double ey = in_plane * geometry.GetSlowAxis() / e_len; + const double tan2 = e_len * e_len / (static_cast(cos_psi) * cos_psi); + par_u = tan2 * (ex * ux + ey * uy) * (ex * ux + ey * uy); + par_v = tan2 * (ex * vx + ey * vy) * (ex * vx + ey * vy); + } + + shape.valid = true; + shape.two_theta = two_theta; + shape.jr = static_cast(jr); + shape.jt = static_cast(jt); + shape.m_rad = static_cast(ux * ux * sxx + 2.0 * ux * uy * sxy + uy * uy * syy); + shape.m_tan = static_cast(vx * vx * sxx + 2.0 * vx * vy * sxy + vy * vy * syy); + shape.cos_psi = cos_psi; + shape.par_u = static_cast(par_u); + shape.par_v = static_cast(par_v); + return shape; +} + template double median_of(std::vector &v) { if (v.empty()) return 0.0; @@ -267,6 +378,7 @@ void MeasureSpotFluxCurves(const ImagePreprocessorBuffer &image, int width, int if (!(curve.c[R_NORM - 1] > 0.0f) || !(curve.c[R_MAX - 1] > 0.0f)) continue; const float norm = curve.c[R_NORM - 1]; for (float &v : curve.c) v /= norm; + curve.shape = shape_of(centre_px, width, cx, cy, mx, my, ring, geometry); out.push_back(curve); } } @@ -352,3 +464,125 @@ bool spot_width::WidthSettled(float r80, float r80_before) { && std::abs(r80 - 2.25f) > SWITCH_CLEARANCE_PX && std::abs(r80 - 2.75f) > SWITCH_CLEARANCE_PX; } + +namespace { + +struct BandwidthPoint { double x, y; }; + +// numpy's default (linear) quantile of sorted values. +double quantile_sorted(const std::vector &v, double p) { + const double pos = p * static_cast(v.size() - 1); + const size_t lo = static_cast(std::floor(pos)); + const size_t hi = std::min(lo + 1, v.size() - 1); + return v[lo] + (pos - static_cast(lo)) * (v[hi] - v[lo]); +} + +// The line y = a + s2 x through eight equal-count bins of x, each a 20 %-trimmed mean weighted by its +// own scatter; returns {s2, reduced chi^2}. Nothing where fewer than two bins could be formed. +std::optional> fit_bandwidth_line(std::vector points) { + constexpr size_t N_BIN = 8; + constexpr size_t MIN_PER_BIN = 10; + constexpr double TRIM = 0.2; + std::stable_sort(points.begin(), points.end(), + [](const BandwidthPoint &a, const BandwidthPoint &b) { return a.x < b.x; }); + std::vector bx, by, bw, ys; + size_t begin = 0; + for (size_t b = 0; b < N_BIN; b++) { + const size_t len = points.size() / N_BIN + (b < points.size() % N_BIN ? 1 : 0); + const size_t end = begin + len; + if (len >= MIN_PER_BIN) { + ys.clear(); + for (size_t i = begin; i < end; i++) ys.push_back(points[i].y); + std::sort(ys.begin(), ys.end()); + const double lo = quantile_sorted(ys, TRIM), hi = quantile_sorted(ys, 1.0 - TRIM); + double n = 0.0, sx = 0.0, sy = 0.0, syy = 0.0; + for (size_t i = begin; i < end; i++) + if (points[i].y >= lo && points[i].y <= hi) { + n += 1.0; + sx += points[i].x; + sy += points[i].y; + syy += points[i].y * points[i].y; + } + const double mean = sy / n, var = syy / n - mean * mean; + bx.push_back(sx / n); + by.push_back(mean); + bw.push_back(n / std::max(var, 1e-6)); + } + begin = end; + } + if (bx.size() < 2) return std::nullopt; + + double sw = 0.0, sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0; + for (size_t i = 0; i < bx.size(); i++) { + sw += bw[i]; + sx += bw[i] * bx[i]; + sy += bw[i] * by[i]; + sxx += bw[i] * bx[i] * bx[i]; + sxy += bw[i] * bx[i] * by[i]; + } + const double det = sw * sxx - sx * sx; + if (!(std::abs(det) > 0.0)) return std::nullopt; + const double slope = (sw * sxy - sx * sy) / det; + const double intercept = (sy - slope * sx) / sw; + double chi2 = 0.0; + for (size_t i = 0; i < bx.size(); i++) { + const double r = by[i] - intercept - slope * bx[i]; + chi2 += bw[i] * r * r; + } + chi2 /= std::max(1.0, static_cast(bx.size()) - 2.0); + return std::make_pair(slope, chi2); +} + +} // namespace + +std::optional spot_width::EstimateBandwidth(const std::vector &curves, + double attenuation_um, + double thickness_um, + double pixel_um) { + constexpr double PIXEL_VAR = 1.0 / 12.0; + constexpr double FWHM_PER_SIGMA = 2.3548; + constexpr int N_BOOTSTRAP = 200; + + std::vector points; + for (const auto &c : curves) { + const SpotShape &s = c.shape; + if (!s.valid) continue; + // The conversion depth's variance for this ray: its depth length is L cos(psi). + const double depth_var_px2 = sensor_absorption::ConversionDepthVariance_um2( + attenuation_um * s.cos_psi, thickness_um) / (pixel_um * pixel_um); + const double obliquity = (static_cast(s.jr) / s.jt) * (static_cast(s.jr) / s.jt); + const double x = 2.0 * s.jr * std::tan(0.5 * s.two_theta); + points.push_back({x * x, (s.m_rad - PIXEL_VAR - depth_var_px2 * s.par_u) + - obliquity * (s.m_tan - PIXEL_VAR - depth_var_px2 * s.par_v)}); + } + if (points.size() < BANDWIDTH_MIN_SPOTS) return std::nullopt; + + const auto fit = fit_bandwidth_line(points); + if (!fit) return std::nullopt; + + // The slope's spread over re-draws of the spots. The generator is seeded, so the answer is the + // same on every run of the same data. + std::mt19937 rng(1); + std::vector redraw(points.size()); + double sum = 0.0, sum2 = 0.0; + int n = 0; + for (int b = 0; b < N_BOOTSTRAP; b++) { + for (auto &p : redraw) p = points[rng() % points.size()]; + if (const auto f = fit_bandwidth_line(redraw)) { + sum += f->first; + sum2 += f->first * f->first; + n++; + } + } + const double mean = n > 0 ? sum / n : 0.0; + const double sd = n > 1 ? std::sqrt(std::max(0.0, sum2 / n - mean * mean)) : 0.0; + const double se = sd * std::sqrt(std::max(1.0, fit->second)); + + BandwidthEstimate e; + e.spots = points.size(); + e.chi2 = fit->second; + e.fwhm = (fit->first < 0.0 ? -1.0 : 1.0) * FWHM_PER_SIGMA * std::sqrt(std::abs(fit->first)); + e.fwhm_floor = FWHM_PER_SIGMA * std::sqrt(se); + e.z = se > 0.0 ? fit->first / se : 0.0; + return e; +} diff --git a/rugnux/SpotWidth.h b/rugnux/SpotWidth.h index 00fdb3d60..29a1d7898 100644 --- a/rugnux/SpotWidth.h +++ b/rugnux/SpotWidth.h @@ -45,11 +45,25 @@ constexpr int R_BKG_OUT = R_MAX + 6; // Resolution the widths are compared at. Inside the measured range of essentially every crystal. constexpr float D_REF_A = 5.0f; +// One spot's second moments along and across its own radius, and the exact geometry that turns +// them into a bandwidth (EstimateBandwidth). jr and jt are the pixels one radian of 2theta, and of +// the angle across the scattering plane, moves the spot by; cos_psi is the angle of the ray to the +// sensor normal, and par_u/par_v are tan^2(psi) times the square of the in-plane ray direction's +// component along the radius and across it - the conversion depth's lateral smear, per um^2 of depth +// variance, in the two directions. +struct SpotShape { + bool valid = false; + float two_theta = 0.0f, jr = 0.0f, jt = 0.0f; + float m_rad = 0.0f, m_tan = 0.0f; // px^2, about the flux-weighted centroid + float cos_psi = 1.0f, par_u = 0.0f, par_v = 0.0f; +}; + // One spot's encircled flux C(1), C(2), ... C(R_MAX), divided by C(R_NORM), with the resolution it -// was recorded at. +// was recorded at, and its shape. struct FluxCurve { float d_A = 0.0f; std::array c{}; + SpotShape shape; }; // The fitted width law: r80(d) = c0 + c1/d over resolution bands, weighted by the spots in each, so @@ -120,10 +134,52 @@ constexpr float SETTLED_STEP_PX = 0.40f; // does not move with r1, and would put four of the rule's six wins within a factor of two of the // loss. Splitting the two apart takes the separation from 2x to 13x. constexpr double BKG_STARVED_MAX_FRACTION = 0.0113; + +// ----------------------------------------------------------------------------------------------- +// The X-ray bandwidth, read off the same spots. +// +// A spread dlambda/lambda of sigma smears a reflection along its own radius by 2 tan(theta) sigma +// radians of 2theta and not at all across it. Per spot, with u along the radius and v across it, +// +// m_rad = 1/12 + par_u + jr^2 (s_ang^2 + 4 tan^2(theta) sigma^2) +// m_tan = 1/12 + par_v + jt^2 s_ang^2 +// +// (1/12: the pixel; par: the sensor parallax, fixed from the sensor's physics; s_ang: everything +// isotropic in angle - divergence, crystal size, mosaic spread seen edge-on). So +// +// y = (m_rad - 1/12 - par_u) - (jr/jt)^2 (m_tan - 1/12 - par_v) = a + sigma^2 (2 jr tan theta)^2 +// +// is a straight line whose slope is the bandwidth. It is fitted over eight equal-count bins of the +// abscissa, each a 20 %-trimmed mean, weighted by its own scatter, and the slope's error is the +// spread of 200 bootstrap re-draws of the spots, inflated by the fit's reduced chi^2 where the line +// fits worse than the scatter says. The slope is significant at BANDWIDTH_Z standard errors - over +// the whole battery that separates the multilayer beamlines from every monochromatic one. +// +// It is a LOWER bound: mosaic spread seen along the radius subtracts, and a spread of cell edges +// (strain) is exactly degenerate with it. What it measures is the effective radial broadening. The +// run reports it and does not use it (yet): the bandwidth it integrates with is the file's or +// --bandwidth's. +constexpr size_t BANDWIDTH_MIN_SPOTS = 80; +constexpr double BANDWIDTH_Z = 3.0; + +struct BandwidthEstimate { + double fwhm = 0.0; // relative FWHM of dlambda/lambda; negative where the slope is + double fwhm_floor = 0.0; // the FWHM one standard error of sigma^2 amounts to + double z = 0.0; // slope / its standard error + double chi2 = 0.0; // reduced chi^2 of the binned line + size_t spots = 0; +}; + +// The bandwidth from the shapes of a pool of spots, or nothing where too few were measured. +// attenuation_um is the sensor's attenuation length at this wavelength, thickness_um its thickness +// (0 = no depth, no parallax), pixel_um the pixel size. +[[nodiscard]] std::optional EstimateBandwidth(const std::vector &curves, + double attenuation_um, double thickness_um, + double pixel_um); } // namespace spot_width -// Every isolated, strong, fully readable spot of one image, as a normalised encircled-flux curve, -// appended to `out`. Called on one worker's own vector, so the pool is independent of the order the +// Every isolated, strong, fully readable spot of one image, as a normalised encircled-flux curve +// with its shape, appended to `out`. Called on one worker's own vector, so the pool is independent of the order the // workers finish in. void MeasureSpotFluxCurves(const ImagePreprocessorBuffer &image, int width, int height, const DiffractionGeometry &geometry, diff --git a/tests/BandwidthEstimateTest.cpp b/tests/BandwidthEstimateTest.cpp new file mode 100644 index 000000000..a5aa8691c --- /dev/null +++ b/tests/BandwidthEstimateTest.cpp @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include + +#include +#include +#include + +#include "../common/DiffractionGeometry.h" +#include "../image_analysis/SensorAbsorption.h" +#include "../rugnux/SpotWidth.h" + +namespace { + constexpr int W = 3000, H = 3000, C = 1500; + constexpr double DIST_MM = 100.0, PIXEL_MM = 0.075, LAMBDA_A = 1.0; + constexpr double THICKNESS_UM = 450.0; + constexpr double ANGULAR_SIGMA = 1.5e-4; // rad: divergence and crystal, the same in every direction + + // Spots on an untilted detector, each an elliptical Gaussian with its long axis along the radius: + // the isotropic angular width, the bandwidth's radial streak 2 tan(theta) sigma, and the sensor + // parallax - a conversion depth z moves the photon by z tan(psi) along the radius, and on an + // untilted detector psi = 2theta. Worked out here from the flat-detector geometry, independently + // of the estimator's own Jacobians: R = D tan(2theta), so one radian of 2theta is D/cos^2(2theta) + // along the radius and one radian across the scattering plane D/cos(2theta) across it. Painted + // with 4x4 sub-pixel sampling so each pixel carries the box it integrates, and Poisson noise. + void PaintSpots(std::vector &image, std::vector &spots, double bw_fwhm, + int offset, std::mt19937 &rng) { + const double sigma_bw = bw_fwhm / 2.3548; + const double L_um = sensor_absorption::AttenuationLength_um("Si", LAMBDA_A); + std::vector mean(image.size(), 3.0); + for (int cy = 40 + offset; cy < H - 40; cy += 60) + for (int cx = 40 + offset; cx < W - 40; cx += 60) { + const double rx = (cx - C) * PIXEL_MM, ry = (cy - C) * PIXEL_MM, r = std::hypot(rx, ry); + if (r < 8.0) continue; + const double tt = std::atan2(r, DIST_MM), c2 = std::cos(tt); + const double jr = DIST_MM / (PIXEL_MM * c2 * c2), jt = DIST_MM / (PIXEL_MM * c2); + const double depth_var = sensor_absorption::ConversionDepthVariance_um2(L_um * c2, THICKNESS_UM); + const double par = depth_var * std::tan(tt) * std::tan(tt) / (PIXEL_MM * 1000.0 * PIXEL_MM * 1000.0); + const double streak = 2.0 * std::tan(tt / 2.0) * sigma_bw; + const double var_u = jr * jr * (ANGULAR_SIGMA * ANGULAR_SIGMA + streak * streak) + par; + const double var_v = jt * jt * ANGULAR_SIGMA * ANGULAR_SIGMA; + const double ux = rx / r, uy = ry / r; + const double total = 20000.0; + const double norm = total / (2.0 * M_PI * std::sqrt(var_u * var_v) * 16.0); + for (int dy = -14; dy <= 14; dy++) + for (int dx = -14; dx <= 14; dx++) { + double v = 0.0; + for (int sy = 0; sy < 4; sy++) + for (int sx = 0; sx < 4; sx++) { + const double px = dx - 0.375 + 0.25 * sx, py = dy - 0.375 + 0.25 * sy; + const double u = px * ux + py * uy, t = -px * uy + py * ux; + v += std::exp(-0.5 * (u * u / var_u + t * t / var_v)); + } + mean[static_cast(cy + dy) * W + cx + dx] += norm * v; + } + spots.emplace_back(static_cast(cx), static_cast(cy), + static_cast(total)); + } + for (size_t i = 0; i < image.size(); i++) + image[i] = std::poisson_distribution(mean[i])(rng); + } + + std::optional Estimate(double bw_fwhm) { + DiffractionGeometry geometry; + geometry.BeamX_pxl(C).BeamY_pxl(C).DetectorDistance_mm(DIST_MM).PixelSize_mm(PIXEL_MM) + .Wavelength_A(LAMBDA_A); + std::mt19937 rng(7); + std::vector curves; + for (int offset : {0, 20, 40}) { + ImagePreprocessorBuffer image(static_cast(W) * H); + std::vector spots; + PaintSpots(image.getBuffer(), spots, bw_fwhm, offset, rng); + MeasureSpotFluxCurves(image, W, H, geometry, spots, curves); + } + return spot_width::EstimateBandwidth(curves, sensor_absorption::AttenuationLength_um("Si", LAMBDA_A), + THICKNESS_UM, PIXEL_MM * 1000.0); + } +} + +// A 0.45 % FWHM bandwidth - a multilayer's - on a thick silicon sensor, whose parallax elongates the +// spots along the radius as well and grows with angle much as the bandwidth does. The estimator has +// to take the parallax out from the sensor's physics and return the bandwidth, significantly. +TEST_CASE("BandwidthEstimate_RecoversBandwidthPastParallax", "[SpotWidth]") { + const auto e = Estimate(0.0045); + REQUIRE(e.has_value()); + CHECK(e->spots >= spot_width::BANDWIDTH_MIN_SPOTS); + CHECK(e->fwhm == Catch::Approx(0.0045).margin(0.0006)); + CHECK(e->z > spot_width::BANDWIDTH_Z); +} + +// The same spots from a monochromatic beam: the parallax alone must not read as a bandwidth. +TEST_CASE("BandwidthEstimate_MonochromaticIsNotSignificant", "[SpotWidth]") { + const auto e = Estimate(0.0); + REQUIRE(e.has_value()); + CHECK(e->z < spot_width::BANDWIDTH_Z); + CHECK(std::abs(e->fwhm) < 0.0015); +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2992aa624..ae752e42e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -53,6 +53,7 @@ ADD_EXECUTABLE(jfjoch_test SweepLayoutTest.cpp ShadowFinderTest.cpp HotPixelFinderTest.cpp + BandwidthEstimateTest.cpp ParallelForTest.cpp RugnuxTest.cpp ResultReportTest.cpp