aegir
Phlex-based simulation framework for the SHiP experiment.
Loading...
Searching...
No Matches
philox_rng.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 CERN for the benefit of the SHiP Collaboration
2//
3// SPDX-License-Identifier: LGPL-3.0-or-later
4
5// philox_rng.hpp — counter-based RNG shared by the event-generator sources
6//
7// Random123 Philox 4x32 is deterministic per seed with no shared state, so
8// each event seeds a fresh instance and generation is reproducible and
9// thread-safe by construction.
10//
11// The counter advances sequentially (ctr[0]++ per 4-word block) and the
12// Philox output block is buffered; uniform() returns successive words of the
13// buffered output. This preserves Philox's guaranteed period — an earlier
14// version fed the output back into the counter (output-feedback mode) and
15// returned ctr[0] + 1 as its first word, forfeiting both the period and the
16// intended first draw.
17
18#pragma once
19
20#include <Random123/philox.h>
21
22#include <cstdint>
23
24namespace aegir {
25
26class PhiloxRng {
27 public:
28 // key_hi selects an independent stream, so different generators seeded with
29 // the same event number draw uncorrelated sequences.
30 explicit PhiloxRng(std::uint32_t seed, std::uint32_t key_hi = 0xBEEFCAFE)
31 : key_{{seed, key_hi}}, ctr_{{0, 0, 0, 0}} {}
32
33 double uniform() {
34 if (idx_ >= 4) {
35 buf_ = rng_(ctr_, key_);
36 ctr_[0]++;
37 idx_ = 0;
38 }
39 // Map a 32-bit word to [0, 1)
40 return buf_[idx_++] * (1.0 / 4294967296.0);
41 }
42
43 double uniform(double lo, double hi) { return lo + (hi - lo) * uniform(); }
44
45 private:
46 r123::Philox4x32 rng_;
47 r123::Philox4x32::key_type key_;
48 r123::Philox4x32::ctr_type ctr_;
49 r123::Philox4x32::ctr_type buf_{};
50 int idx_ = 4;
51};
52
53} // namespace aegir
Definition philox_rng.hpp:26
PhiloxRng(std::uint32_t seed, std::uint32_t key_hi=0xBEEFCAFE)
Definition philox_rng.hpp:30
double uniform(double lo, double hi)
Definition philox_rng.hpp:43
double uniform()
Definition philox_rng.hpp:33
Definition math_utils.hpp:12