Files
leonarski_fandClaude Opus 5.5 04baa16060 CPU FFTs on pocketfft instead of FFTW (prototype)
Every CPU FFT site - the FFT indexer's batched 1D r2c, the beam-centre 2D r2c/c2r,
the model-path 3D transforms (MapToFPhi, MapFromFPhi(Execute), MapToFPhiInParallel),
the tNCS Patterson c2r and the viewer's 1D chart - goes through common/CpuFFT, a
plan-free wrapper over the pocketfft header already vendored with gemmi. The header
is included under a namespace of its own: gemmi includes it with
POCKETFFT_NO_MULTITHREADING, and the linker otherwise merges the two sets of
templates (MapToFPhiInParallel with 4 threads gave garbage until it was renamed).
MapToFPhiInParallel uses pocketfft's own threads (one call per stage) instead of a
ParallelFor over FFTW plans. The programs no longer link fftw3f; FFTW stays fetched
for jfjoch_test only, where [fft] checks pocketfft against it (rel. error < 1e-5).

Measured (Ryzen 5950X, --no-gpu -N 16, one run each, against rc187 aa898ac0f):
cytc_x10sa --model --no-refine 100.7 -> 99.5 s; euxfel83 first 6 files --no-refine
81.7 -> 83.3 s (noise level); full cytc refinement 1514 -> ~1399 s. Merged results
identical (same hkl md5, SG, cell, R-work/R-free/CC of model validation).
Microbench, single thread, FFTW_ESTIMATE as the call sites plan: pocketfft 0.4-0.6x
FFTW's time on the 2D/3D shapes; with FFTW_MEASURE the two are equal on 3D.
Indexer length 3142 = 2 x 1571 is 2.4x SLOWER on pocketfft (Bluestein); a smooth
length (3150) is 0.06 s vs FFTW's 0.25 s at 3142.

BeamCenterFFTGPU_MatchesTheCPUEngine: gate mismatches over 4M centres on the
threshold 7 (FFTW) -> 17 (pocketfft); bound raised to 30. pocketfft's float error
is FFTW's or lower (rms 1.4e-7 vs 1.5e-7 against double).
Known: "A near-extinct class is reported as a sub-lattice" [tncs] fails - its
synthetic reads modulation 20.0x against a 20.0x gate; FFT rounding tips it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UqXYdJDrM65gxsCn2PrbfK
2026-11-15 21:23:40 +01:00

120 lines
5.3 KiB
C++

// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "FFTIndexerCPU.h"
#include <cmath>
#include <algorithm>
#include <stdexcept>
#include <cassert>
#include <vector>
#include "../../common/CpuFFT.h"
#include "../../common/ParallelFor.h"
static inline double dot_abs(const Coord& a, const Coord& b) {
return std::fabs(a.x * b.x + a.y * b.y + a.z * b.z);
}
FFTIndexerCPU::FFTIndexerCPU(const IndexingSettings& settings)
: FFTIndexer(settings) {
// Allocate host buffers
h_input_fft.resize(input_size, 0.0);
h_output_fft.resize(output_size);
// Validate allocations vs. expected sizes
if (h_input_fft.size() != input_size)
throw std::runtime_error("FFTIndexerCPU: input buffer size mismatch");
if (h_output_fft.size() != output_size)
throw std::runtime_error("FFTIndexerCPU: output buffer size mismatch");
}
void FFTIndexerCPU::ExecuteFFT(const std::vector<Coord> &coord, size_t nspots) {
// Build histograms: one per direction
const int H = static_cast<int>(histogram_size);
const int D = nDirections;
const int out_len = (H / 2) + 1;
std::fill(h_input_fft.begin(), h_input_fft.end(), 0.0);
// Every direction has a histogram and a spectrum of its own, so the directions are split over the
// refinement threads; each one is still filled and scanned in the same order.
const size_t nthreads = std::max(1u, refine_threads);
ParallelChunks(D, nthreads, [&](int d0, int d1) {
for (int d = d0; d < d1; ++d) {
float* hist = h_input_fft.data() + static_cast<size_t>(d) * H;
for (size_t i = 0; i < nspots; i++) {
const auto& r = coord[i];
double dot = dot_abs(direction_vectors[d], r);
long long bin = static_cast<long long>(dot / histogram_spacing);
if (bin >= 0 && bin < H) {
hist[bin] += 1.0;
}
}
}
});
// One real transform per direction, all in one call.
cpu_fft::R2C({static_cast<size_t>(D), static_cast<size_t>(H)}, {1}, h_input_fft.data(), h_output_fft.data());
// Post-process: pick the peak past min_length_A by PROMINENCE above a local background.
// The projected histogram has a broad low-frequency ENVELOPE (spots cluster near the
// origin) whose magnitude can exceed the true lattice peaks; a plain argmax|spec| then
// returns a short envelope vector (~10A) on weak/pink-beam frames and the real axes are
// lost. Subtracting a running-mean background of half-width BG_HALF bins removes that
// smooth envelope (it cancels to ~0) while sharp lattice peaks - fundamentals AND
// harmonics - keep their height. The prominence is also reported as the magnitude so
// FilterFFTResults ranks directions by real-peak strength, not by envelope.
const double len_coeff = 2.0 * static_cast<double>(max_length_A) / static_cast<double>(H);
// Background half-window ~15 A (in length, so it is independent of the histogram sizing);
// wide enough to span the envelope yet narrow enough not to smooth real peaks. Validated
// optimum on serial-still jet data (de-novo indexing improved markedly vs FFBIDX); a second dataset unchanged.
constexpr double BG_HALF_WIDTH_A = 15.0;
const int bg_half = std::max(1, static_cast<int>(std::lround(BG_HALF_WIDTH_A / len_coeff)));
ParallelChunks(D, nthreads, [&](int d0, int d1) {
std::vector<double> mag(out_len), pref(out_len + 1);
for (int d = d0; d < d1; ++d) {
const auto* spec = h_output_fft.data() + static_cast<size_t>(d) * out_len;
pref[0] = 0.0;
for (int j = 0; j < out_len; ++j) {
mag[j] = std::hypot(spec[j].real(), spec[j].imag());
pref[j + 1] = pref[j] + mag[j];
}
double best_prom = 0.0;
double best_len = -1.0;
for (int j = 0; j < out_len; ++j) {
double len = len_coeff * static_cast<double>(j);
if (len <= static_cast<double>(min_length_A)) continue;
// Slide the background window inward at the ends rather than truncating it. A peak within
// bg_half bins of either end - which is where the LONGEST cells sit, the last usable bin
// being max_length_A itself - otherwise gets its background from a one-sided window, and
// the prominence it is judged on is biased by however much the spectrum slopes there.
int lo = j - bg_half, hi = j + bg_half + 1;
if (lo < 0) { hi = std::min(out_len, hi - lo); lo = 0; }
if (hi > out_len) { lo = std::max(0, lo - (hi - out_len)); hi = out_len; }
const double background = (pref[hi] - pref[lo]) / static_cast<double>(hi - lo);
const double prominence = mag[j] - background;
if (prominence > best_prom) {
best_prom = prominence;
best_len = len;
}
}
result_fft[d] = FFTResult{
.magnitude = static_cast<float>(best_prom),
.direction = d,
.length = static_cast<float>(best_len)
};
}
});
}