1#ifndef POLYSPECTRUMBINNING_HEADER
2#define POLYSPECTRUMBINNING_HEADER
13 namespace CORRELATIONFUNCTIONS {
43 template <
int N,
int ORDER,
bool COMPACT = false>
90 if (bin < 0 || bin >=
n)
91 throw std::invalid_argument(
"[PolyspectrumBinning] Selected bin is out of range");
92 std::sort(cfg.begin(), cfg.end());
100 if constexpr (COMPACT) {
101 std::vector<Configuration>().swap(compact_configs);
102 std::vector<Configuration>().swap(cached_selected);
103 std::vector<double>().swap(
P123);
104 std::vector<double>().swap(
N123);
108 std::vector<Configuration> result;
109 if (!selected.empty()) {
110 for (
const auto & cfg : selected)
112 result.push_back(cfg);
116 std::function<void(
int,
int)> enumerate = [&](
int depth,
int first) {
117 if (depth == ORDER) {
119 result.push_back(cfg);
122 for (
int bin = first; bin <
n; bin++) {
124 enumerate(depth + 1, bin);
133 if constexpr (COMPACT) {
135 if (configs != compact_configs ||
P123.size() != configs.size() ||
N123.size() != configs.size()) {
136 std::vector<double> powers(configs.size(), 0.0), counts(configs.size(), 0.0);
137 compact_configs = std::move(configs);
138 P123 = std::move(powers);
139 N123 = std::move(counts);
147 return sizeof(*this) +
149 cached_low.capacity() + cached_high.capacity()) *
151 (compact_configs.capacity() + selected.capacity() + cached_selected.capacity()) *
157 throw std::invalid_argument(
"[PolyspectrumBinning] At least two bins are required");
159 const size_t limit = std::vector<double>().max_size();
160 for (
int d = 0; d < ORDER; ++d) {
161 if (entries > limit /
size_t(nbins))
162 throw std::length_error(
"[PolyspectrumBinning] Dense result exceeds addressable storage");
163 entries *= size_t(nbins);
168 const size_t entries = COMPACT ? compact_configs.size() :
dense_entries(
n);
169 return P123.size() == entries &&
N123.size() == entries;
176 cached_selected != selected)
178 if (cached_mesh == 0)
180 return cached_mesh == nmesh;
187 cached_selected = selected;
192 template <
int,
int,
bool>
194 std::vector<Configuration> compact_configs;
197 if (bin < 0 || bin >=
n)
198 throw std::out_of_range(
"[PolyspectrumBinning] Bin is out of range");
199 std::sort(cfg.begin(), cfg.end());
200 auto found = std::lower_bound(compact_configs.begin(), compact_configs.end(), cfg);
201 return found != compact_configs.end() && *found == cfg ? size_t(found - compact_configs.begin()) :
202 compact_configs.size();
204 std::vector<Configuration> selected, cached_selected;
206 std::vector<double> cached_low, cached_high;
207 bool cached_dealias{
true};
256 void set_bincount(
const std::vector<double> & N123_external);
278 template <
int N,
int ORDER,
bool COMPACT>
282 template <
int N,
int ORDER,
bool COMPACT>
287 assert_mpi(nbins >= 2,
"[PolyspectrumBinning] We need at least 2 bins");
288 this->bin_type = bin_type;
292 if constexpr (!COMPACT) {
293 const size_t ntot = dense_entries(n);
294 P123.resize(ntot, 0.0);
295 N123.resize(ntot, 0.0);
300 khigh.resize(n, 0.0);
301 kmean.resize(n, 0.0);
305 std::vector<double> k(n);
306 for (
int i = 0; i < n; i++) {
307 if (bin_type == LINEAR_SPACING) {
308 k[i] = kmin + (
kmax - kmin) * i /
double(n - 1);
309 }
else if (bin_type == LOG_SPACING) {
310 assert_mpi(kmin > 0.0,
"[PolyspectrumBinning] For log spacing we cannot have kmin = 0.0");
311 k[i] = std::exp(std::log(kmin) + std::log(
kmax / kmin) * i /
double(n - 1));
314 assert_mpi(
false,
"[PolyspectrumBinning] Unknown bintype (not LINEAR_SPACING or LOG_SPACING)");
319 for (
int i = 0; i < n; i++) {
321 klow[i] = std::min(k[0], 0.0);
322 khigh[i] = k[0] + (k[1] - k[0]) / 2.0;
323 if (bin_type == LOG_SPACING)
324 khigh[i] = std::exp(std::log(k[0]) + std::log(k[1] / k[0]) / 2.0);
325 }
else if (i < n - 1) {
326 klow[i] = khigh[i - 1];
327 khigh[i] = k[i] + (k[i + 1] - k[i]) / 2.0;
328 if (bin_type == LOG_SPACING)
329 khigh[i] = std::exp(std::log(k[i]) + std::log(k[i + 1] / k[i]) / 2.0);
331 klow[i] = khigh[i - 1];
332 khigh[i] = k[nbins - 1];
334 kbin[i] = (klow[i] + khigh[i]) / 2.0;
338 template <
int N,
int ORDER,
bool COMPACT>
340 if constexpr (COMPACT)
341 return compact_configs.at(index);
342 std::array<int, ORDER> ik;
343 for (
int ii = ORDER - 1;
ii >= 0;
ii--) {
344 ik[
ii] = int(index % n);
350 template <
int N,
int ORDER,
bool COMPACT>
352 if constexpr (COMPACT) {
353 const size_t index = compact_index(ik);
354 if (index == compact_configs.size())
355 throw std::out_of_range(
"[PolyspectrumBinning] Configuration has no stored slot");
359 for (
int i = 0; i < ORDER; i++)
360 index = index * n + ik[i];
365 template <
int N,
int ORDER,
bool COMPACT>
367 if (!selected.empty() && !std::binary_search(selected.begin(), selected.end(), ik))
370 for (
int ii = 1;
ii < ORDER;
ii++) {
371 if (ik[
ii - 1] > ik[
ii]) {
374 ksum += khigh[ik[
ii - 1]];
379 if (ksum < klow[ik[ORDER - 1]] and ORDER > 2)
385 template <
int N,
int ORDER,
bool COMPACT>
387 for (
int i = 0; i < n; i++) {
395 double scale = std::pow(
boxsize, N * (ORDER - 1));
396 for (
auto & p : P123)
401 for (
auto & p : pofk)
409 template <
int N,
int ORDER,
bool COMPACT>
411 std::fill(P123.begin(), P123.end(), 0.0);
412 std::fill(N123.begin(), N123.end(), 0.0);
413 std::fill(pofk.begin(), pofk.end(), 0.0);
414 std::fill(kmean.begin(), kmean.end(), 0.0);
417 bincount_is_set =
false;
420 template <
int N,
int ORDER,
bool COMPACT>
423 bincount_is_set =
false;
425 P123.shrink_to_fit();
427 N123.shrink_to_fit();
428 if constexpr (COMPACT) {
429 std::vector<Configuration>().swap(compact_configs);
430 std::vector<Configuration>().swap(cached_selected);
458 template <
int N,
int ORDER,
bool COMPACT>
460 assert_mpi(ORDER == 2,
"[PolyspectrumBinning::get_spectrum] This method can only be called for ORDER=2\n");
461 std::array<int, 2> ik{i, j};
462 return get_spectrum(ik);
465 template <
int N,
int ORDER,
bool COMPACT>
467 assert_mpi(ORDER == 3,
"[PolyspectrumBinning::get_spectrum] This method can only be called for ORDER=3\n");
468 std::array<int, 3> ik{i, j, k};
469 return get_spectrum(ik);
472 template <
int N,
int ORDER,
bool COMPACT>
474 assert_mpi(ORDER == 4,
"[PolyspectrumBinning::get_spectrum] This method can only be called for ORDER=4\n");
475 std::array<int, 4> ik{i, j, k, l};
476 return get_spectrum(ik);
479 template <
int N,
int ORDER,
bool COMPACT>
481 if constexpr (COMPACT) {
482 const size_t index = compact_index(ik);
483 return index < P123.size() ? P123[index] : 0.0;
485 assert_mpi(ik.size() == ORDER,
"[PolyspectrumBinning::get_spectrum] ik != ORDER has the wrong size\n");
486 return P123[get_index_from_coord(ik)];
489 template <
int N,
int ORDER,
bool COMPACT>
491 assert_mpi(ORDER == 2,
492 "[PolyspectrumBinning::get_reduced_spectrum] This method can only be called for ORDER=2\n");
493 std::array<int, 2> ik{i, j};
494 return get_reduced_spectrum(ik);
497 template <
int N,
int ORDER,
bool COMPACT>
499 assert_mpi(ORDER == 3,
500 "[PolyspectrumBinning::get_reduced_spectrum] This method can only be called for ORDER=3\n");
501 std::array<int, 3> ik{i, j, k};
502 return get_reduced_spectrum(ik);
505 template <
int N,
int ORDER,
bool COMPACT>
507 assert_mpi(ORDER == 4,
508 "[PolyspectrumBinning::get_reduced_spectrum] This method can only be called for ORDER=4\n");
509 std::array<int, 4> ik{i, j, k, l};
510 return get_reduced_spectrum(ik);
513 template <
int N,
int ORDER,
bool COMPACT>
515 const double P = get_spectrum(ik);
519 std::vector<double> pi(ORDER);
521 for (
int i = 0; i < ORDER; i++)
526 return P / std::sqrt(pofk[ik[0]] * pofk[ik[1]]);
527 }
else if (ORDER == 3 or ORDER == 4) {
530 double pipj = pi[ORDER - 1] * pi[0];
531 for (
int i = 0; i < ORDER - 1; i++)
532 pipj += pi[i] * pi[i + 1];
539 assert_mpi(
false,
"[PolyspectrumBinning::get_reduced_spectrum] Not implemented\n");
544 template <
int N,
int ORDER,
bool COMPACT>
546 if constexpr (COMPACT) {
547 const size_t index = compact_index(ik);
548 return index < N123.size() ? N123[index] : 0.0;
550 assert_mpi(ik.size() == ORDER,
"[PolyspectrumBinning::get_bincount] ik != ORDER has the wrong size\n");
551 return N123[get_index_from_coord(ik)];
554 template <
int N,
int ORDER,
bool COMPACT>
556 assert_mpi(ORDER == 2,
"[PolyspectrumBinning::get_bincount] This method can only be called for ORDER=2\n");
557 std::array<int, 2> ik{i, j};
558 return get_bincount(ik);
561 template <
int N,
int ORDER,
bool COMPACT>
563 assert_mpi(ORDER == 3,
"[PolyspectrumBinning::get_bincount] This method can only be called for ORDER=3\n");
564 std::array<int, 3> ik{i, j, k};
565 return get_bincount(ik);
568 template <
int N,
int ORDER,
bool COMPACT>
570 assert_mpi(ORDER == 4,
"[PolyspectrumBinning::get_bincount] This method can only be called for ORDER=4\n");
571 std::array<int, 4> ik{i, j, k, l};
572 return get_bincount(ik);
575 template <
int N,
int ORDER,
bool COMPACT>
578 rhs.prepare_storage();
579 assert_mpi(n == rhs.n and bin_type == rhs.bin_type && klow == rhs.klow && khigh == rhs.khigh &&
580 dealias == rhs.dealias && selected == rhs.selected && compact_configs == rhs.compact_configs,
581 "[PolyspectrumBinning::combine] Incompatible binnings\n");
582 if (nbinnings == 0) {
588 for (
size_t i = 0; i < P123.size(); i++)
589 P123[i] = (P123[i] * nbinnings + rhs.P123[i]) / (nbinnings + 1.0);
590 for (
size_t i = 0; i < N123.size(); i++)
591 N123[i] += rhs.N123[i];
592 for (
size_t i = 0; i < pofk.size(); i++)
593 pofk[i] = (pofk[i] * nbinnings + rhs.pofk[i]) / (nbinnings + 1.0);
596 bincount_is_set =
false;
599 template <
int N,
int ORDER,
bool COMPACT>
602 assert_mpi(N123_external.size() == N123.size(),
"[set_bincount] Incompatible size of N123 array");
603 N123 = N123_external;
604 if (!selected.empty() && !COMPACT) {
605 const auto requested = configurations();
606 std::vector<double> values;
607 for (
const auto & cfg : requested)
608 values.push_back(N123[get_index_from_coord(cfg)]);
609 std::fill(N123.begin(), N123.end(), 0.0);
610 for (
size_t i = 0; i < requested.size(); i++) {
611 auto cfg = requested[i];
613 N123[get_index_from_coord(cfg)] = values[i];
614 }
while (std::next_permutation(cfg.begin(), cfg.end()));
617 mark_bincount_computed(0);
620 template <
int N,
int ORDER,
bool COMPACT>
622 if constexpr (!COMPACT) {
625 if (P123.size() != compact_configs.size() || N123.size() != compact_configs.size())
626 throw std::invalid_argument(
"[PolyspectrumBinning] Inconsistent compact result storage");
638 dense.selected = selected;
639 for (
size_t i = 0; i < compact_configs.size(); ++i) {
640 auto cfg = compact_configs[i];
643 dense.
P123[index] = P123[i];
644 dense.
N123[index] = N123[i];
645 }
while (std::next_permutation(cfg.begin(), cfg.end()));
648 dense.cached_mesh = cached_mesh;
649 dense.cached_low = cached_low;
650 dense.cached_high = cached_high;
651 dense.cached_dealias = cached_dealias;
652 dense.cached_selected = cached_selected;
657 template <
int N,
int ORDER>
Dense results by default; COMPACT stores one slot per canonical tuple.
PolyspectrumBinning()=default
void set_bincount(const std::vector< double > &counts, int nmesh)
Import with an explicit mesh identity (preferred to the legacy overload).
std::vector< double > pofk
The power-spectrum.
size_t metadata_storage_bytes() const
static constexpr bool compact_storage
std::array< int, ORDER > get_coord_from_index(size_t index)
The coord (k1,k2,...) corresponding to a given index in the P123 and N123 array These methods determi...
size_t get_index_from_coord(const std::array< int, ORDER > &ik)
PolyspectrumBinning< N, ORDER, false > to_dense()
Explicit dense allocation and symmetry expansion; never used by estimators.
std::vector< double > khigh
khigh is higher bin edge
double kmin
The minimum k to bin from (should be 0!)
double get_bincount(const std::array< int, ORDER > &ik)
Returns the volume factor N123.
std::vector< Configuration > configurations()
bool valid_storage() const
PolyspectrumOptions options
size_t result_storage_bytes() const
std::vector< double > P123
The polyspectrum.
void free()
Release result arrays/canonical slots, retaining shell metadata and selection.
std::array< int, ORDER > Configuration
std::vector< double > kmean
kmean is the mean of wavenumbers added to the bin
void set_configurations(std::vector< Configuration > configurations)
Empty restores all configurations. Inputs are canonicalized and deduplicated.
void combine(PolyspectrumBinning &rhs)
This is just to make it easier to add binning of several spectra... just for testing.
std::vector< double > kbin
kbin is center of bin
friend class PolyspectrumBinning
std::vector< double > N123
The volume (number of generalized triangles) of each bin.
const std::vector< Configuration > & stored_configurations() const
PolyspectrumStatistics statistics
void scale(const double boxsize)
To physical units: k *= 1/boxsize and P *= boxsize^((ORDER-1) NDIM)
double kmax
The maximum k to bin to.
double get_spectrum(const std::array< int, ORDER > &ik)
Get the polyspectra at (k[ik1], k[ik2], ...)
void reset()
Clears the arrays.
bool has_bincount(int nmesh)
void prepare_storage()
Allocate compact results only when needed. No dense tensor is constructed.
std::vector< double > klow
klow is lower bin edge
int bin_type
Type of bins (LINEAR_SPACING or LOG_SPACING)
void set_bincount(const std::vector< double > &N123_external)
Copy over the volume factor N123 (useful to save computations if we do many calculations with the sam...
bool dealias
True integer-wavevector closure.
void mark_bincount_computed(int nmesh)
bool compute_this_configuration(const std::array< int, ORDER > &ik)
Symmetry: we only need to compute ik1 <= ik2 <= ... This function tells algorithms which configuratio...
bool subtract_shotnoise
Subtract shotnoise? Algorithms (compute_polyspectrum) using this class checks this value.
bool bincount_is_set
If we have precomputed the volume factor (N123) or not and have it available for algorithms to use.
double get_reduced_spectrum(const std::array< int, ORDER > &ik)
Get the reduced polyspectrum: P / fac where fac = sqrt(P(k1)P(k2)) for order=2 and P(k1)P(k2) + cyc f...
static size_t dense_entries(int nbins)
size_t fft_workspace_allowance_bytes
size_t configuration_bytes
size_t cache_metadata_bytes
std::optional< size_t > estimated_peak_bytes
size_t metadata_work_bytes
size_t bin_metadata_bytes
size_t accounted_peak_bytes
size_t padding_source_bytes
size_t max_cached_shells
Zero retains all needed shells. Otherwise cap the resident shell count.
size_t reduction_batch_size
Canonical configurations per collective; zero requests one batch (up to INT_MAX).
size_t shell_memory_budget_bytes
Per-rank cache budget; zero is unlimited.
std::optional< size_t > fft_workspace_allowance_bytes
Optional caller estimate for opaque FFT plans/workspace, in bytes per rank.
size_t geometry_shell_builds
size_t geometry_reduction_batches
size_t peak_cached_shells
size_t field_reduction_batches
size_t field_shell_builds
PolyspectrumMemory memory
size_t metadata_reduction_batches