Beam-centre FFT capture: the 1D line-mirror surfaces removed, as nothing ever read them

The capture scored three surfaces: the 2D point inversion and a 1D line mirror per detector axis
(the Friedel-mate part along the spindle). Only the point surface is used - its strongest candidate
seeds the background walk that measures the beam centre. The line mirrors and their margins were
wired report-only when the capture was added and a consumer for them never landed; their one reader
was the pre-scan's "Beam centre capture:" log line. Removed from the scorer, both engines (fftw3f and
cuFFT: the 1D plans, the gather/accumulate/pack kernels and the line phase of the device-memory
estimate), the tests and the docs; the log line now gives the point centre and its margin.

Output unchanged: p.hkl byte-identical on lysozyme, cytochrome C, myoglobin and 5reo; [BeamCenter]
and [BeamCenterFFTGPU] pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PXc1zD1yxHqaR1DGdCTHL4
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-10-15 22:48:01 +02:00
1 parent 2ddba078e3
commit f1ed8997d5
11 files changed
+23 -427

No files matched your search

+5 -7
View File
@@ -175,12 +175,10 @@ The fit starts with a **whole-detector capture**. The centrosymmetry score of th
candidate centre $\mathbf{c}$, $\sum_\mathbf{x} I(\mathbf{x})\,I(2\mathbf{c}-\mathbf{x})$, is the
self-convolution $(I*I)(2\mathbf{c})$, so **one FFT pair scores every candidate centre on the
detector** at half-pixel spacing: the cost is $O(N\log N)$ and independent of how far the header is
from the truth. Three surfaces are scored — the 2D point inversion, which measures the same isotropic
background the walk below fits, and a 1D line mirror per detector axis, which along the spindle is
exact Friedel physics (a reflection's mate half a turn later lands mirrored in the line through the
beam across the spindle). The beam-stop shadow is blanked out of the scored image, a one-sided opaque
from the truth. The surface scored is the 2D point inversion, which measures the same isotropic
background the walk below fits. The beam-stop shadow is blanked out of the scored image, a one-sided opaque
obstruction being a centrosymmetry defect in its own right. What comes back is a shortlist and a
margin per surface, not a centre: the surface can be locally flat over tens of pixels, and the
margin, not a centre: the surface can be locally flat over tens of pixels, and the
peak-to-runner-up margin says so. A **local walk** is then seeded at the capture and refines it; where
it declines there it is started again from the file's centre, and only where neither start gives it
something to fit does the capture stand alone. The transforms run on the GPU where one is present and
@@ -188,8 +186,8 @@ on FFTW otherwise, with everything that decides anything shared between the two.
The run log then carries:
- `Beam centre capture:` the strongest point-symmetry centre, the two line-mirror coordinates and the
three margins (under about 3 % the surface is flat).
- `Beam centre capture:` the strongest point-symmetry centre and its margin (under about 3 % the
surface is flat).
- `Beam centre check: the file puts the direct beam at (x,y), the scattered background puts it at
(x,y) +- σ px - a difference of d px, against the t px this geometry asks the centre to be right to.`
The comparison is against the **direct beam**, not the PONI: `beam_x_pxl` is the point of normal
@@ -73,57 +73,12 @@ Prepared PrepareImage(const std::vector<float> &mean) {
return out;
}
std::vector<BeamCenterFFTCandidate> Shortlist1D(std::vector<float> &surface, float nms_pxl,
int budget, bool is_x) {
std::vector<BeamCenterFFTCandidate> out;
const int64_t n = static_cast<int64_t>(surface.size());
const int64_t d = std::lround(2.0f * nms_pxl);
for (int k = 0; k < budget; k++) {
int64_t best = -1;
float best_v = -std::numeric_limits<float>::infinity();
for (int64_t i = 0; i < n; i++)
if (surface[i] > best_v) {
best_v = surface[i];
best = i;
}
if (best < 0 || !std::isfinite(best_v))
break;
const float c = static_cast<float>(best) / 2.0f;
const float nan = std::numeric_limits<float>::quiet_NaN();
out.push_back(is_x ? BeamCenterFFTCandidate{c, nan, best_v}
: BeamCenterFFTCandidate{nan, c, best_v});
for (int64_t i = std::max<int64_t>(0, best - d); i <= std::min(n - 1, best + d); i++)
surface[i] = -std::numeric_limits<float>::infinity();
}
return out;
}
float Margin(const std::vector<BeamCenterFFTCandidate> &peaks) {
if (peaks.size() < 2 || peaks[0].score <= 0.0f)
return 0.0f;
return (peaks[0].score - peaks[1].score) / peaks[0].score;
}
// The same score for a 1D line mirror, whose accumulators were summed over the other coordinate.
std::vector<float> PearsonLine(const BeamCenterConvSurfaces1D &conv, float min_pair_fraction,
double global_variance) {
const size_t n = conv.C.size();
double d_max = 0.0;
for (double d : conv.D)
d_max = std::max(d_max, d);
const double lim = min_pair_fraction * d_max;
std::vector<float> r(n, -std::numeric_limits<float>::infinity());
for (size_t i = 0; i < n; i++) {
const double num = conv.D[i] * conv.C[i] - conv.S[i] * conv.S[i];
const double den = conv.D[i] * conv.Q[i] - conv.S[i] * conv.S[i];
// Same no-evidence floor as the 2D surface: see BEAM_CENTER_VARIANCE_FLOOR.
if (conv.D[i] > lim
&& den > conv.D[i] * conv.D[i] * BEAM_CENTER_VARIANCE_FLOOR * global_variance)
r[i] = static_cast<float>(num / den);
}
return r;
}
} // namespace
std::vector<float> BeamCenterPointScore(const BeamCenterConvSurfaces2D &conv,
@@ -227,22 +182,7 @@ BeamCenterFFTResult BeamCenterFFTScore(int64_t width, int64_t height,
const Prepared prep = PrepareImage(mean);
result.point = engine.PointShortlist(prep.a, prep.m, height, width, settings, prep.variance);
{
const auto conv_y = engine.LineSurfaces(prep.a, prep.m, height, width,
BeamCenterMirror::Rows);
auto ry = PearsonLine(conv_y, settings.min_pair_fraction, prep.variance);
result.line_y = Shortlist1D(ry, settings.nms_radius_pxl, settings.candidates_line, false);
const auto conv_x = engine.LineSurfaces(prep.a, prep.m, height, width,
BeamCenterMirror::Columns);
auto rx = PearsonLine(conv_x, settings.min_pair_fraction, prep.variance);
result.line_x = Shortlist1D(rx, settings.nms_radius_pxl, settings.candidates_line, true);
}
result.margin_point = Margin(result.point);
result.margin_line_x = Margin(result.line_x);
result.margin_line_y = Margin(result.line_y);
return result;
}
+9 -20
View File
@@ -14,16 +14,10 @@
// The centrosymmetry score of the image about a candidate centre c, sum_x I(x) I(2c - x), is the
// self-convolution (I * I)(2c), so one FFT pair scores EVERY candidate centre on the detector at
// half-pixel spacing in a single transform set - the cost is O(N log N) and independent of how far
// the true centre is from the value in the file. Three surfaces are computed:
//
// * the 2D point-inversion score - a measurement of the isotropic background (air and solvent
// scatter), point-symmetric about the beam whatever the crystal does. It shares its physics
// with FindBeamCenterFromBackground, so their agreement is not two votes;
// * two 1D line-mirror scores, one per detector axis, mirroring that coordinate only. For the
// coordinate along the spindle this is exact Bragg physics: a reflection's Friedel mate
// half a turn later lands mirrored in the line through the beam across the spindle
// (R_m(180)(-q) = q - 2(q.m)m), so accumulating frames over the sweep makes this score sharp
// where the indexing count is blind.
// the true centre is from the value in the file. The score is a 2D point inversion - a
// measurement of the isotropic background (air and solvent scatter), point-symmetric about the beam
// whatever the crystal does. It shares its physics with FindBeamCenterFromBackground, so their
// agreement is not two votes: the strongest candidate seeds that walk.
//
// The score is a CAPTURE device, not a decision device: measured on 17 datasets its shortlist
// holds the true centre in the top candidates every time (three gross header errors of 71-351 px
@@ -42,27 +36,22 @@
// whole of its cost, so which engine runs them is the difference between seconds and milliseconds.
struct BeamCenterFFTCandidate {
float beam_x_pxl = 0.0f; // NAN in a line_y candidate
float beam_y_pxl = 0.0f; // NAN in a line_x candidate
float beam_x_pxl = 0.0f;
float beam_y_pxl = 0.0f;
float score = 0.0f; // masked Pearson r of the image with its mirror about this centre
};
struct BeamCenterFFTResult {
// Non-maximum-suppressed shortlists, strongest first.
std::vector<BeamCenterFFTCandidate> point; // 2D point-inversion score
std::vector<BeamCenterFFTCandidate> line_x; // beam-x from the x line mirror
std::vector<BeamCenterFFTCandidate> line_y; // beam-y from the y line mirror
// Non-maximum-suppressed shortlist of the 2D point-inversion score, strongest first.
std::vector<BeamCenterFFTCandidate> point;
// (best - runner_up) / best per surface; 0 when fewer than two peaks survive.
// (best - runner_up) / best; 0 when fewer than two peaks survive.
float margin_point = 0.0f;
float margin_line_x = 0.0f;
float margin_line_y = 0.0f;
};
struct BeamCenterFFTSettings {
float nms_radius_pxl = 25.0f; // peak separation; tracks the score's plateau width
int candidates_point = 8;
int candidates_line = 4;
// Fraction of the maximum mirror-pair count below which a centre is not scored - centres so
// far out that almost no pixel has a valid mirror partner correlate noise with noise.
float min_pair_fraction = 0.25f;
@@ -78,14 +78,6 @@ public:
}
};
std::vector<float> Transpose(const std::vector<float> &src, int64_t h, int64_t w) {
std::vector<float> out(src.size());
for (int64_t y = 0; y < h; y++)
for (int64_t x = 0; x < w; x++)
out[static_cast<size_t>(x * h + y)] = src[static_cast<size_t>(y * w + x)];
return out;
}
} // namespace
BeamCenterConvSurfaces2D BeamCenterFFTCPU::PointSurfaces(const std::vector<float> &a,
@@ -122,90 +114,3 @@ BeamCenterConvSurfaces2D BeamCenterFFTCPU::PointSurfaces(const std::vector<float
return out;
}
// Each sequence is correlated with its own mirror and the four accumulators are summed over the
// other coordinate in double complex (the same cancellation argument as the 2D surface), so only
// four inverse transforms are needed however many sequences there are.
BeamCenterConvSurfaces1D BeamCenterFFTCPU::LineSurfaces(const std::vector<float> &a_in,
const std::vector<float> &m_in, int64_t h,
int64_t w, BeamCenterMirror mirror) {
// Mirroring the column coordinate is the same computation on the transposed image.
const std::vector<float> at = mirror == BeamCenterMirror::Rows ? std::vector<float>()
: Transpose(a_in, h, w);
const std::vector<float> mt = mirror == BeamCenterMirror::Rows ? std::vector<float>()
: Transpose(m_in, h, w);
const std::vector<float> &a = mirror == BeamCenterMirror::Rows ? a_in : at;
const std::vector<float> &m = mirror == BeamCenterMirror::Rows ? m_in : mt;
const int64_t nseq = mirror == BeamCenterMirror::Rows ? h : w;
const int64_t nbatch = mirror == BeamCenterMirror::Rows ? w : h;
const int64_t nfft = BeamCenterFFTPadSize(2 * nseq);
const int64_t nc = nfft / 2 + 1;
std::vector<float> in(static_cast<size_t>(nfft));
std::vector<std::complex<float>> A(static_cast<size_t>(nc)), M(static_cast<size_t>(nc)),
A2(static_cast<size_t>(nc));
std::vector<std::complex<double>> accC(static_cast<size_t>(nc)), accS(static_cast<size_t>(nc)),
accQ(static_cast<size_t>(nc)), accD(static_cast<size_t>(nc));
fftwf_plan fwd, bwd;
{
std::unique_lock lock(FFTWPlannerMutex());
fwd = fftwf_plan_dft_r2c_1d(static_cast<int>(nfft), in.data(),
reinterpret_cast<fftwf_complex *>(A.data()), FFTW_ESTIMATE);
bwd = fftwf_plan_dft_c2r_1d(static_cast<int>(nfft),
reinterpret_cast<fftwf_complex *>(A.data()), in.data(),
FFTW_ESTIMATE);
}
if (!fwd || !bwd)
throw std::runtime_error("BeamCenterFFT: fftwf 1D plan failed");
auto forward_into = [&](auto value_of, std::vector<std::complex<float>> &dst) {
for (int64_t y = 0; y < nseq; y++)
in[static_cast<size_t>(y)] = value_of(y);
std::fill(in.begin() + nseq, in.end(), 0.0f);
fftwf_execute_dft_r2c(fwd, in.data(), reinterpret_cast<fftwf_complex *>(A.data()));
dst = A;
};
for (int64_t x = 0; x < nbatch; x++) {
forward_into([&](int64_t y) { return a[static_cast<size_t>(y * nbatch + x)]; }, A2);
std::swap(A, A2); // A = spectrum of the sequence of a
std::vector<std::complex<float>> Acol = A;
forward_into([&](int64_t y) { return m[static_cast<size_t>(y * nbatch + x)]; }, M);
forward_into(
[&](int64_t y) {
const float v = a[static_cast<size_t>(y * nbatch + x)];
return v * v;
},
A2);
for (int64_t i = 0; i < nc; i++) {
const std::complex<double> ca(Acol[i]), cm(M[i]), ca2(A2[i]);
accC[i] += ca * ca;
accS[i] += ca * cm;
accQ[i] += ca2 * cm;
accD[i] += cm * cm;
}
}
const double norm = 1.0 / static_cast<double>(nfft);
auto inverse = [&](const std::vector<std::complex<double>> &acc) {
for (int64_t i = 0; i < nc; i++)
A[i] = std::complex<float>(acc[i]);
fftwf_execute_dft_c2r(bwd, reinterpret_cast<fftwf_complex *>(A.data()), in.data());
std::vector<double> out(static_cast<size_t>(2 * nseq));
for (int64_t i = 0; i < 2 * nseq; i++)
out[static_cast<size_t>(i)] = in[static_cast<size_t>(i)] * norm;
return out;
};
BeamCenterConvSurfaces1D out;
out.C = inverse(accC);
out.S = inverse(accS);
out.Q = inverse(accQ);
out.D = inverse(accD);
{
std::unique_lock lock(FFTWPlannerMutex());
fftwf_destroy_plan(fwd);
fftwf_destroy_plan(bwd);
}
return out;
}
@@ -11,6 +11,4 @@ class BeamCenterFFTCPU : public BeamCenterFFTEngine {
public:
BeamCenterConvSurfaces2D PointSurfaces(const std::vector<float> &a, const std::vector<float> &m,
int64_t h, int64_t w) override;
BeamCenterConvSurfaces1D LineSurfaces(const std::vector<float> &a, const std::vector<float> &m,
int64_t h, int64_t w, BeamCenterMirror mirror) override;
};
@@ -22,16 +22,6 @@ struct BeamCenterConvSurfaces2D {
std::vector<float> C, S, Q, D;
};
// The 1D line-mirror score: each sequence correlated with its own mirror and the four accumulators
// summed over the other coordinate, so each surface is 2 x (the mirrored extent) long.
struct BeamCenterConvSurfaces1D {
std::vector<double> C, S, Q, D;
};
// Which coordinate the 1D score mirrors: Rows mirrors y (each column is one sequence) and gives
// the beam's y; Columns mirrors x and gives its x.
enum class BeamCenterMirror { Rows, Columns };
class BeamCenterFFTEngine {
public:
virtual ~BeamCenterFFTEngine() = default;
@@ -40,9 +30,6 @@ public:
virtual BeamCenterConvSurfaces2D PointSurfaces(const std::vector<float> &a,
const std::vector<float> &m, int64_t h,
int64_t w) = 0;
virtual BeamCenterConvSurfaces1D LineSurfaces(const std::vector<float> &a,
const std::vector<float> &m, int64_t h, int64_t w,
BeamCenterMirror mirror) = 0;
// The 2D point score all the way to its shortlist. The default - and the whole of the CPU
// path - is PointSurfaces followed by BeamCenterPointScore and BeamCenterShortlist2D below.
@@ -15,8 +15,6 @@
namespace {
constexpr int BLOCK = 256;
// Threads per frequency in the 1D accumulation. A power of two, for the shared-memory reduction.
constexpr int ACCUMULATE_THREADS = 128;
// Blocks in the greedy search's reduction. Each returns one candidate, and the last step of the
// reduction is done on the host over that many - a thousand is far below what a download costs and
// far above what the card needs to stay busy.
@@ -46,7 +44,7 @@ std::vector<int> Dims(int64_t a) { return {static_cast<int>(a)}; }
std::vector<int> Dims(int64_t a, int64_t b) { return {static_cast<int>(a), static_cast<int>(b)}; }
// The transforms, as both the computation and its memory estimate take them: the point surfaces' 2D
// pair on an ny x nx grid, and the line surfaces' 1D pair of length nfft.
// pair on an ny x nx grid.
CudaFFTShape PointForward(int64_t ny, int64_t nx) {
const int64_t nxc = nx / 2 + 1;
return {.n = Dims(ny, nx), .inembed = Dims(ny, nx), .idist = static_cast<int>(ny * nx),
@@ -59,19 +57,6 @@ CudaFFTShape PointInverse(int64_t ny, int64_t nx) {
.onembed = Dims(ny, nx), .odist = static_cast<int>(ny * nx), .type = CUFFT_C2R};
}
CudaFFTShape LineForward(int64_t nfft, int64_t nbatch) {
const int64_t nc = nfft / 2 + 1;
return {.n = Dims(nfft), .inembed = Dims(nfft), .idist = static_cast<int>(nfft),
.onembed = Dims(nc), .odist = static_cast<int>(nc), .type = CUFFT_R2C,
.batch = static_cast<int>(nbatch)};
}
CudaFFTShape LineInverse(int64_t nfft) {
const int64_t nc = nfft / 2 + 1;
return {.n = Dims(nfft), .inembed = Dims(nc), .idist = static_cast<int>(nc),
.onembed = Dims(nfft), .odist = static_cast<int>(nfft), .type = CUFFT_C2R, .batch = 4};
}
__global__ void SquareInPlace(float *data, int64_t n) {
const int64_t i = blockIdx.x * static_cast<int64_t>(blockDim.x) + threadIdx.x;
if (i < n)
@@ -105,78 +90,6 @@ __global__ void CopyScaledCorner(const float *src, int64_t nx, int64_t out_h, in
dst[i] = src[y * nx + (i - y * out_w)] * norm;
}
// Lay each sequence out contiguously, zero-padded to nfft, so the 1D transforms are a plain batch:
// out[b * nfft + s] = img[b * stride_batch + s * stride_seq], squared where asked.
__global__ void GatherSequences(const float *img, int64_t nseq, int64_t nbatch, int64_t stride_seq,
int64_t stride_batch, int64_t nfft, int square, float *out) {
const int64_t i = blockIdx.x * static_cast<int64_t>(blockDim.x) + threadIdx.x;
if (i >= nbatch * nfft)
return;
const int64_t b = i / nfft;
const int64_t s = i - b * nfft;
float v = 0.0f;
if (s < nseq) {
v = img[b * stride_batch + s * stride_seq];
if (square)
v *= v;
}
out[i] = v;
}
// The four accumulators of the 1D score, summed over the batch in double - the same widening the
// host path does, and for the same reason: the numerator and denominator below are cancellations
// of large near-equal terms. One block per frequency.
__global__ void AccumulateSpectra(const cufftComplex *A, const cufftComplex *M,
const cufftComplex *A2, int64_t nbatch, int64_t nc, double2 *accC,
double2 *accS, double2 *accQ, double2 *accD) {
__shared__ double2 red[4][ACCUMULATE_THREADS];
const int64_t i = blockIdx.x;
double2 c = {0.0, 0.0}, s = {0.0, 0.0}, q = {0.0, 0.0}, d = {0.0, 0.0};
for (int64_t b = threadIdx.x; b < nbatch; b += blockDim.x) {
const cufftComplex fa = A[b * nc + i], fm = M[b * nc + i], fa2 = A2[b * nc + i];
const double ar = fa.x, ai = fa.y, mr = fm.x, mi = fm.y, qr = fa2.x, qi = fa2.y;
c.x += ar * ar - ai * ai;
c.y += ar * ai + ai * ar;
s.x += ar * mr - ai * mi;
s.y += ar * mi + ai * mr;
q.x += qr * mr - qi * mi;
q.y += qr * mi + qi * mr;
d.x += mr * mr - mi * mi;
d.y += mr * mi + mi * mr;
}
red[0][threadIdx.x] = c;
red[1][threadIdx.x] = s;
red[2][threadIdx.x] = q;
red[3][threadIdx.x] = d;
for (unsigned stride = blockDim.x / 2; stride > 0; stride /= 2) {
__syncthreads();
if (threadIdx.x < stride)
for (int k = 0; k < 4; k++) {
red[k][threadIdx.x].x += red[k][threadIdx.x + stride].x;
red[k][threadIdx.x].y += red[k][threadIdx.x + stride].y;
}
}
if (threadIdx.x == 0) {
accC[i] = red[0][0];
accS[i] = red[1][0];
accQ[i] = red[2][0];
accD[i] = red[3][0];
}
}
// The four accumulators narrowed back to single precision and packed as one batch of four, ready
// for the inverse transform - exactly what the host path does before its four inverses.
__global__ void PackAccumulators(const double2 *accC, const double2 *accS, const double2 *accQ,
const double2 *accD, int64_t nc, cufftComplex *out) {
const int64_t i = blockIdx.x * static_cast<int64_t>(blockDim.x) + threadIdx.x;
if (i >= nc)
return;
const double2 *acc[4] = {accC, accS, accQ, accD};
for (int k = 0; k < 4; k++)
out[k * nc + i] = make_cuFloatComplex(static_cast<float>(acc[k][i].x),
static_cast<float>(acc[k][i].y));
}
// The masked Pearson, elementwise in double, exactly as BeamCenterPointScore does it on the host -
// the numerator and the denominator are cancellations of large near-equal terms. Q is read out of
// the transform buffer where the last inverse left it, so it needs no surface of its own. The score
@@ -442,74 +355,6 @@ BeamCenterFFTGPU::PointShortlist(const std::vector<float> &a, const std::vector<
return out;
}
BeamCenterConvSurfaces1D BeamCenterFFTGPU::LineSurfaces(const std::vector<float> &a,
const std::vector<float> &m, int64_t h,
int64_t w, BeamCenterMirror mirror) {
const bool rows = mirror == BeamCenterMirror::Rows;
const int64_t nseq = rows ? h : w;
const int64_t nbatch = rows ? w : h;
const int64_t stride_seq = rows ? w : 1; // step between two samples of one sequence
const int64_t stride_batch = rows ? 1 : w; // step between two sequences
const int64_t nfft = BeamCenterFFTPadSize(2 * nseq);
const int64_t nc = nfft / 2 + 1;
BeamCenterConvSurfaces1D out;
CudaDevicePtr<double2> accC(nc, ALLOC), accS(nc, ALLOC), accQ(nc, ALLOC), accD(nc, ALLOC);
{
CudaDevicePtr<float> d_img(h * w, ALLOC), d_in(nfft * nbatch, ALLOC);
CudaDevicePtr<cufftComplex> d_a(nbatch * nc, ALLOC), d_m(nbatch * nc, ALLOC), d_a2(nbatch * nc, ALLOC);
CudaFFTPlan fwd(LineForward(nfft, nbatch));
auto transform = [&](int square, cufftComplex *dst) {
GatherSequences<<<Blocks(nfft * nbatch), BLOCK>>>(d_img.get(), nseq, nbatch, stride_seq,
stride_batch, nfft, square,
d_in.get());
CheckLastKernel("BeamCenterFFT: sequence gather failed");
Check(cufftExecR2C(fwd, d_in, dst), "BeamCenterFFT: forward transform failed");
};
auto upload = [&](const std::vector<float> &src) {
Check(cudaMemcpy(d_img.get(), src.data(), h * w * sizeof(float),
cudaMemcpyHostToDevice),
"BeamCenterFFT: image upload failed");
};
upload(a);
transform(0, d_a);
transform(1, d_a2);
upload(m);
transform(0, d_m);
AccumulateSpectra<<<static_cast<int>(nc), ACCUMULATE_THREADS>>>(d_a, d_m, d_a2, nbatch, nc,
accC, accS, accQ, accD);
CheckLastKernel("BeamCenterFFT: spectrum accumulation failed");
}
CudaDevicePtr<cufftComplex> d_pack(4 * nc, ALLOC);
CudaDevicePtr<float> d_out(4 * nfft, ALLOC);
PackAccumulators<<<Blocks(nc), BLOCK>>>(accC, accS, accQ, accD, nc, d_pack.get());
CheckLastKernel("BeamCenterFFT: accumulator packing failed");
CudaFFTPlan inv(LineInverse(nfft));
Check(cufftExecC2R(inv, d_pack, d_out), "BeamCenterFFT: inverse transform failed");
std::vector<float> host(static_cast<size_t>(4 * nfft));
Check(cudaMemcpy(host.data(), d_out.get(), host.size() * sizeof(float),
cudaMemcpyDeviceToHost),
"BeamCenterFFT: line surface download failed");
const double norm = 1.0 / static_cast<double>(nfft);
auto take = [&](int k) {
std::vector<double> v(static_cast<size_t>(2 * nseq));
for (int64_t i = 0; i < 2 * nseq; i++)
v[static_cast<size_t>(i)] = host[static_cast<size_t>(k * nfft + i)] * norm;
return v;
};
out.C = take(0);
out.S = take(1);
out.Q = take(2);
out.D = take(3);
return out;
}
size_t BeamCenterFFTGPU::DeviceMemoryNeeded(int64_t width, int64_t height) {
const int64_t ny = BeamCenterFFTPadSize(2 * height);
const int64_t nx = BeamCenterFFTPadSize(2 * width);
@@ -518,23 +363,9 @@ size_t BeamCenterFFTGPU::DeviceMemoryNeeded(int64_t width, int64_t height) {
const size_t work_inv = CudaFFTPlan::WorkBytes(PointInverse(ny, nx));
// One transform buffer, two spectra, three of the four convolution surfaces - the fourth stays in
// the transform buffer, where the last inverse leaves it - and one work area for both plans.
size_t needed = ny * nx * sizeof(float) + 2 * ny * nxc * sizeof(cufftComplex)
+ 3 * 4 * static_cast<size_t>(width) * height * sizeof(float)
+ std::max(work_fwd, work_inv);
// The two 1D phases, the larger of them: they run after the point surfaces, with its buffers
// already freed.
for (int pass = 0; pass < 2; pass++) {
const int64_t nseq = pass == 0 ? height : width;
const int64_t nbatch = pass == 0 ? width : height;
const int64_t nfft = BeamCenterFFTPadSize(2 * nseq);
const int64_t nc = nfft / 2 + 1;
const size_t work = CudaFFTPlan::WorkBytes(LineForward(nfft, nbatch));
const size_t line = (height * width + nfft * nbatch) * sizeof(float)
+ 3 * nbatch * nc * sizeof(cufftComplex) + work;
needed = std::max(needed, line);
}
return needed;
return ny * nx * sizeof(float) + 2 * ny * nxc * sizeof(cufftComplex)
+ 3 * 4 * static_cast<size_t>(width) * height * sizeof(float)
+ std::max(work_fwd, work_inv);
}
bool BeamCenterFFTGPU::FitsInDeviceMemory(int64_t width, int64_t height) {
@@ -17,8 +17,6 @@ class BeamCenterFFTGPU : public BeamCenterFFTEngine {
public:
BeamCenterConvSurfaces2D PointSurfaces(const std::vector<float> &a, const std::vector<float> &m,
int64_t h, int64_t w) override;
BeamCenterConvSurfaces1D LineSurfaces(const std::vector<float> &a, const std::vector<float> &m,
int64_t h, int64_t w, BeamCenterMirror mirror) override;
// The four convolutions are combined and searched where they already are, so the only thing
// that crosses PCIe is the shortlist. On a 16 Mpixel detector that is 1.16 GB of surfaces, a
@@ -39,7 +37,7 @@ public:
int64_t w, float min_pair_fraction,
double global_variance);
// Peak device memory the two phases need for an image of this size: buffers plus the cuFFT
// Peak device memory the point surfaces need for an image of this size: buffers plus the cuFFT
// plans' own workspace.
[[nodiscard]] static size_t DeviceMemoryNeeded(int64_t width, int64_t height);
// Whether that is at most half of the current device's TOTAL memory - the rest is the analysis
+3 -9
View File
@@ -1016,20 +1016,14 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru
std::chrono::steady_clock::now() - t0).count();
if (!capture.point.empty())
logger.Info("Beam centre capture: the strongest point-symmetry centre on the WHOLE "
"detector is ({:.1f},{:.1f}), {:.1f} px from the file's; line mirrors put x "
"at {:.1f} and y at {:.1f}; margins {:.1f}%/{:.1f}%/{:.1f}% (point/x/y, "
"under ~3% the surface is flat). One transform set scores every candidate "
"detector is ({:.1f},{:.1f}), {:.1f} px from the file's; margin {:.1f}% "
"(under ~3% the surface is flat). One transform set scores every candidate "
"centre, so this costs the same however wrong the file is - {} ms including "
"the walk that refines it",
capture.point[0].beam_x_pxl, capture.point[0].beam_y_pxl,
std::hypot(capture.point[0].beam_x_pxl - x.GetBeamX_pxl(),
capture.point[0].beam_y_pxl - x.GetBeamY_pxl()),
capture.line_x.empty() ? std::numeric_limits<float>::quiet_NaN()
: capture.line_x[0].beam_x_pxl,
capture.line_y.empty() ? std::numeric_limits<float>::quiet_NaN()
: capture.line_y[0].beam_y_pxl,
100.0f * capture.margin_point, 100.0f * capture.margin_line_x,
100.0f * capture.margin_line_y, capture_ms);
100.0f * capture.margin_point, capture_ms);
const float need = BeamCenterNeed_pxl(x);
if (!background_center) {
logger.Info("Beam centre check: neither the capture nor the walk places the centre on "
-4
View File
@@ -208,15 +208,11 @@ TEST_CASE("BeamCenterFFTGPU_MatchesTheCPUEngine", "[BeamCenter][BeamCenterFFTGPU
SECTION("the shortlists and the margins") {
REQUIRE(!cpu.point.empty());
CompareShortlist(gpu.point, cpu.point, "point surface");
CompareShortlist(gpu.line_x, cpu.line_x, "x line mirror");
CompareShortlist(gpu.line_y, cpu.line_y, "y line mirror");
// The margin is the surface's self-diagnostic, and it is a difference of two scores that sit
// within a fraction of a percent of each other - the quantity most exposed to a change of
// transform.
CHECK(gpu.margin_point == Catch::Approx(cpu.margin_point).margin(1e-5));
CHECK(gpu.margin_line_x == Catch::Approx(cpu.margin_line_x).margin(1e-5));
CHECK(gpu.margin_line_y == Catch::Approx(cpu.margin_line_y).margin(1e-5));
}
}
+1 -41
View File
@@ -51,12 +51,8 @@ TEST_CASE("BeamCenterFFT_SyntheticBackground", "[BeamCenter]") {
const auto r = BeamCenterFFTScore(w, h, mean);
REQUIRE(!r.point.empty());
REQUIRE(!r.line_x.empty());
REQUIRE(!r.line_y.empty());
// Whole-detector capture: the strongest point-symmetry centre is the true one.
CHECK(std::hypot(r.point[0].beam_x_pxl - cx, r.point[0].beam_y_pxl - cy) < 2.0f);
CHECK(std::abs(r.line_x[0].beam_x_pxl - cx) < 2.0f);
CHECK(std::abs(r.line_y[0].beam_y_pxl - cy) < 2.0f);
// A clean unimodal surface separates its argmax from the runner-up by a wide margin.
CHECK(r.margin_point > 0.05f);
}
@@ -79,8 +75,7 @@ TEST_CASE("BeamCenterFFT_SyntheticBackground", "[BeamCenter]") {
namespace {
// A value keyed on the distance from (cx, cy) in each coordinate, so the image is EXACTLY its own
// mirror about that centre under point inversion AND under either line mirror - the three symmetries
// the three surfaces measure. The preparation the score applies - clipping, median subtraction,
// mirror about that centre under point inversion - the symmetry the score measures. The preparation the score applies - clipping, median subtraction,
// clamping, the mean shift - is pointwise and monotone, so it preserves all of them, and the masked
// Pearson at the true centre is then exactly 1. Every other centre must score below it, because the
// score is a correlation coefficient and cannot exceed 1.
@@ -137,27 +132,6 @@ BeamCenterConvSurfaces2D BruteForcePoint(const std::vector<float> &a, const std:
return out;
}
// The same for the 1D mirror of the row coordinate: each column autoconvolved, summed over columns.
BeamCenterConvSurfaces1D BruteForceLine(const std::vector<float> &a, const std::vector<float> &m,
int64_t h, int64_t w) {
BeamCenterConvSurfaces1D out;
out.C.assign(static_cast<size_t>(2 * h), 0.0);
out.S.assign(static_cast<size_t>(2 * h), 0.0);
out.Q.assign(static_cast<size_t>(2 * h), 0.0);
out.D.assign(static_cast<size_t>(2 * h), 0.0);
for (int64_t t = 0; t < 2 * h; t++)
for (int64_t x = 0; x < w; x++)
for (int64_t y = std::max<int64_t>(0, t - h + 1); y <= std::min(h - 1, t); y++) {
const size_t i = static_cast<size_t>(y * w + x);
const size_t j = static_cast<size_t>((t - y) * w + x);
out.C[static_cast<size_t>(t)] += static_cast<double>(a[i]) * a[j];
out.S[static_cast<size_t>(t)] += static_cast<double>(a[i]) * m[j];
out.Q[static_cast<size_t>(t)] += static_cast<double>(a[i]) * a[i] * m[j];
out.D[static_cast<size_t>(t)] += static_cast<double>(m[i]) * m[j];
}
return out;
}
// Largest relative difference of two surfaces, scaled by the largest term of the reference - a
// convolution surface spans orders of magnitude and its small entries are differences of large
// ones, so an elementwise relative test measures roundoff and nothing else.
@@ -189,11 +163,6 @@ TEST_CASE("BeamCenterFFT_RecoversAnExactlySymmetricCentre", "[BeamCenter]") {
CHECK(r.point[0].beam_x_pxl == cx);
CHECK(r.point[0].beam_y_pxl == cy);
CHECK(r.point[0].score == Catch::Approx(1.0f).margin(1e-4));
// The two line mirrors see the same symmetry one coordinate at a time.
REQUIRE(!r.line_x.empty());
REQUIRE(!r.line_y.empty());
CHECK(r.line_x[0].beam_x_pxl == cx);
CHECK(r.line_y[0].beam_y_pxl == cy);
}
// Move the image and the answer moves with it, exactly. The score is a convolution, so this is a
@@ -214,8 +183,6 @@ TEST_CASE("BeamCenterFFT_IsShiftEquivariant", "[BeamCenter]") {
CHECK(shifted.point[0].beam_x_pxl == at_origin.point[0].beam_x_pxl + static_cast<float>(tx));
CHECK(shifted.point[0].beam_y_pxl == at_origin.point[0].beam_y_pxl + static_cast<float>(ty));
CHECK(shifted.line_x[0].beam_x_pxl == at_origin.line_x[0].beam_x_pxl + static_cast<float>(tx));
CHECK(shifted.line_y[0].beam_y_pxl == at_origin.line_y[0].beam_y_pxl + static_cast<float>(ty));
}
// The four convolutions the score is built from, against their definitions. The masked Pearson is a
@@ -258,13 +225,6 @@ TEST_CASE("BeamCenterFFT_ConvolutionsAgreeWithBruteForce", "[BeamCenter]") {
REQUIRE(std::isfinite(score[i]));
REQUIRE(score[i] == Catch::Approx(score_ref[i]).margin(5e-5));
}
const auto got_line = engine.LineSurfaces(a, m, h, w, BeamCenterMirror::Rows);
const auto ref_line = BruteForceLine(a, m, h, w);
CHECK(MaxScaledDifference(got_line.C, ref_line.C) < 1e-6);
CHECK(MaxScaledDifference(got_line.S, ref_line.S) < 1e-6);
CHECK(MaxScaledDifference(got_line.Q, ref_line.Q) < 1e-6);
CHECK(MaxScaledDifference(got_line.D, ref_line.D) < 1e-6);
}
// A mirror overlap with no variance in it - a region the preparation has flattened to a constant -