From 1c546e91dde9c6943f3c8c20c6e67ebe27650973 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Tue, 24 Nov 2026 16:07:53 +0100 Subject: [PATCH 1/2] Draw InteractionSampler random numbers directly instead of from fixed rings This fixes a problem in the uniform InteractionSampler and adds a unit test. - The BC jump, the collision multiplicity per crossing and the collision time came from RandomRing buffers filled once in init() and never refilled. - The multiplicities therefore repeated every 1000 occupied crossings, and triple collisions were missing at small mu. - These quantities are now drawn from gRandom on each use, with the same distributions. - FixedSkipBC_InteractionSampler and NonUniformMuInteractionSampler use the same time draw. - The new test compares the crossing multiplicities with Poisson at mu 0.05 and 0.3 and checks that they show no period of 1000. Co-Authored-By: Claude Opus 5.5 --- .../SimulationDataFormat/InteractionSampler.h | 10 +- .../simulation/src/InteractionSampler.cxx | 64 ++++++------ .../test/testInteractionSampler.cxx | 97 +++++++++++++++++++ 3 files changed, 136 insertions(+), 35 deletions(-) diff --git a/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h b/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h index a68d972a991c4..7523180e2c3d4 100644 --- a/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h +++ b/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h @@ -21,7 +21,6 @@ #include "CommonDataFormat/InteractionRecord.h" #include "CommonDataFormat/BunchFilling.h" #include "CommonConstants/LHCConstants.h" -#include "MathUtils/RandomRing.h" #include namespace o2 @@ -70,10 +69,9 @@ class InteractionSampler protected: virtual int simulateInteractingBC(); void nextCollidingBC(int n); - - o2::math_utils::RandomRing<10000> mBCJumpGenerator; // generator of random jumps in BC - o2::math_utils::RandomRing<1000> mNCollBCGenerator; // generator of number of interactions in BC - o2::math_utils::RandomRing<1000> mCollTimeGenerator; // generator of number of interactions in BC + int drawBCJump() const; ///< random jump in colliding BCs to the next interacting one + int drawNCollInBC() const; ///< random number of collisions in an interacting BC (>= 1) + float drawCollTimeInBC() const; ///< random collision time within a BC o2::InteractionTimeRecord mIR{{0, 0}, 0.}; o2::InteractionTimeRecord mFirstIR{{4, 0}, 0.}; @@ -90,7 +88,7 @@ class InteractionSampler static constexpr float DefIntRate = 50e3; ///< default interaction rate - ClassDef(InteractionSampler, 1); + ClassDef(InteractionSampler, 2); }; //_________________________________________________ diff --git a/DataFormats/simulation/src/InteractionSampler.cxx b/DataFormats/simulation/src/InteractionSampler.cxx index b690c63052647..bcd339ff2ecf0 100644 --- a/DataFormats/simulation/src/InteractionSampler.cxx +++ b/DataFormats/simulation/src/InteractionSampler.cxx @@ -47,30 +47,6 @@ void InteractionSampler::init() } } - auto mu = mMuBC; - // prob. of not having interaction in N consecutive BCs is P(N) = mu*exp(-(N-1)*mu), hence its cumulative distribution - // is T(N) = integral_1^N {P(N)} = 1. - exp(-(N-1)*mu) - // We generate random N using its inverse, N = 1 - log(1 - Rndm)/mu - mBCJumpGenerator.initialize([mu]() { return (1. - std::log(1. - gRandom->Rndm()) / mu); }); - - // Poisson distribution of number of collisions in the bunch excluding 0 - mNCollBCGenerator.initialize([mu]() { - int n = 0; - while ((n = gRandom->Poisson(mu)) == 0) { - ; - } - return n; - }); - - auto trms = mBCTimeRMS; - mCollTimeGenerator.initialize([trms]() { - float t; // make sure it does not go outside half bunch - while (std::abs(t = gRandom->Gaus(0, trms)) > o2::constants::lhc::LHCBunchSpacingNS / 2.1) { - ; - } - return t; - }); - mIntBCCache = 0; mCurrBCIdx = 0; mIR = mFirstIR; @@ -81,6 +57,36 @@ void InteractionSampler::init() mCurrBCIdx--; } +//_________________________________________________ +int InteractionSampler::drawBCJump() const +{ + // prob. of not having interaction in N consecutive BCs is P(N) = mu*exp(-(N-1)*mu), hence its cumulative distribution + // is T(N) = integral_1^N {P(N)} = 1. - exp(-(N-1)*mu) + // We generate random N using its inverse, N = 1 - log(1 - Rndm)/mu + return int(1. - std::log(1. - gRandom->Rndm()) / mMuBC); +} + +//_________________________________________________ +int InteractionSampler::drawNCollInBC() const +{ + // Poisson distribution of number of collisions in the bunch excluding 0 + int n = 0; + while ((n = gRandom->Poisson(mMuBC)) == 0) { + ; + } + return n; +} + +//_________________________________________________ +float InteractionSampler::drawCollTimeInBC() const +{ + float t; // make sure it does not go outside half bunch + while (std::abs(t = gRandom->Gaus(0, mBCTimeRMS)) > o2::constants::lhc::LHCBunchSpacingNS / 2.1) { + ; + } + return t; +} + //_________________________________________________ void InteractionSampler::print() const { @@ -115,14 +121,14 @@ const o2::InteractionTimeRecord& InteractionSampler::generateCollisionTime() int InteractionSampler::simulateInteractingBC() { // Returns number of collisions assigned to selected BC - nextCollidingBC(mBCJumpGenerator.getNextValue()); + nextCollidingBC(drawBCJump()); // once BC is decided, enforce at least one interaction - int ncoll = mNCollBCGenerator.getNextValue(); + int ncoll = drawNCollInBC(); // assign random time withing a bunch for (int i = ncoll; i--;) { - mTimeInBC.push_back(mCollTimeGenerator.getNextValue()); + mTimeInBC.push_back(drawCollTimeInBC()); } if (ncoll > 1) { // sort in DECREASING time order (we are reading vector from the end) std::sort(mTimeInBC.begin(), mTimeInBC.end(), [](const float a, const float b) { return a > b; }); @@ -140,7 +146,7 @@ int FixedSkipBC_InteractionSampler::simulateInteractingBC() // assign random time withing a bunch for (int i = ncoll; i--;) { - mTimeInBC.push_back(mCollTimeGenerator.getNextValue()); + mTimeInBC.push_back(drawCollTimeInBC()); } if (ncoll > 1) { // sort in DECREASING time order (we are reading vector from the end) std::sort(mTimeInBC.begin(), mTimeInBC.end(), [](const float a, const float b) { return a > b; }); @@ -252,7 +258,7 @@ int NonUniformMuInteractionSampler::simulateInteractingBC() // assign random time withing a bunch for (int i = ncoll; i--;) { - mTimeInBC.push_back(mCollTimeGenerator.getNextValue()); + mTimeInBC.push_back(drawCollTimeInBC()); } if (ncoll > 1) { // sort in DECREASING time order (we are reading vector from the end) std::sort(mTimeInBC.begin(), mTimeInBC.end(), [](const float a, const float b) { return a > b; }); diff --git a/DataFormats/simulation/test/testInteractionSampler.cxx b/DataFormats/simulation/test/testInteractionSampler.cxx index 74bf33a1b9e00..9c9bb7b8b9610 100644 --- a/DataFormats/simulation/test/testInteractionSampler.cxx +++ b/DataFormats/simulation/test/testInteractionSampler.cxx @@ -22,9 +22,11 @@ #include "TGrid.h" #include "TRandom.h" #include +#include #include #include #include +#include #include namespace o2 @@ -88,8 +90,103 @@ double poissonMultiGivenOccupied(double mu) const double p0 = std::exp(-mu); return (1. - p0 - mu * p0) / (1. - p0); } + +// Collisions per occupied crossing of a sampler, in time order +struct CrossingSequence { + std::vector mult; // collisions per occupied crossing + int64_t slots = 0; // colliding BCs passed over + std::set times; // distinct collision times within the BC +}; + +template +CrossingSequence sequenceOfCrossings(Sampler& sampler, int nColl) +{ + std::vector samples; + samples.reserve(nColl); + sampler.generateCollisionTimes(samples); + + const auto& filling = sampler.getBunchFilling(); + std::vector indexOfBC(o2::constants::lhc::LHCMaxBunches, -1); + int nColliding = 0; + for (int bc = 0; bc < o2::constants::lhc::LHCMaxBunches; ++bc) { + if (filling.testBC(bc)) { + indexOfBC[bc] = nColliding++; + } + } + + CrossingSequence seq; + int64_t firstKey = -1, prevKey = -1; + for (const auto& ir : samples) { + BOOST_REQUIRE(ir.bc < o2::constants::lhc::LHCMaxBunches && indexOfBC[ir.bc] >= 0); + const int64_t key = int64_t(ir.orbit) * nColliding + indexOfBC[ir.bc]; + BOOST_REQUIRE(key >= prevKey); + if (key != prevKey) { + seq.mult.push_back(0); + } + if (firstKey < 0) { + firstKey = key; + } + seq.mult.back()++; + seq.times.insert(ir.timeInBCNS); + prevKey = key; + } + seq.slots = prevKey - firstKey + 1; + return seq; +} + +// Poisson probability of k collisions in a crossing, given at least one +double poissonGivenOccupied(double mu, int k) +{ + return std::exp(-mu) * std::pow(mu, k) / std::tgamma(k + 1.) / (1. - std::exp(-mu)); +} + +// Checks that the uniform sampler gives Poisson crossing multiplicities without periodic patterns +void checkUniformSamplerIsPoisson(double muBC, unsigned int seed, const std::vector& tolPercent) +{ + const int nColl = 500000; + gRandom->SetSeed(seed); + o2::steer::InteractionSampler sampler; + sampler.setMuPerBC(muBC); + sampler.init(); + auto seq = sequenceOfCrossings(sampler, nColl); + const double mu = sampler.getMuPerBC(); + const double nOcc = seq.mult.size(); + + std::vector nK(4, 0.); + std::set residues; // positions modulo 1000 of the crossings with at least two collisions + for (size_t i = 0; i < seq.mult.size(); ++i) { + nK[std::min(seq.mult[i], 3)] += 1; + if (seq.mult[i] > 1) { + residues.insert(int(i % 1000)); + } + } + for (int k = 1; k <= 3; ++k) { + const double expK = k < 3 ? poissonGivenOccupied(mu, k) : 1. - poissonGivenOccupied(mu, 1) - poissonGivenOccupied(mu, 2); + BOOST_TEST_MESSAGE("mu " << mu << " k" << (k < 3 ? "=" : ">=") << k << " observed " << nK[k] << " expected " << expK * nOcc); + BOOST_CHECK(nK[k] > 0); + BOOST_CHECK_CLOSE(nK[k] / nOcc, expK, tolPercent[k - 1]); + } + BOOST_CHECK_CLOSE(nOcc / seq.slots, 1. - std::exp(-mu), 1.); + BOOST_TEST_MESSAGE("mu " << mu << " residues mod 1000 of k>=2 crossings " << residues.size() + << ", distinct times in BC " << seq.times.size()); + // pre-generated rings of 1000 values repeat the same multiplicities and times every 1000 draws + BOOST_CHECK(residues.size() > 900); + BOOST_CHECK(seq.times.size() > 10000); +} } // namespace +// Uniform sampler at small mu must reproduce Poisson statistics, including triple collisions +BOOST_AUTO_TEST_CASE(UniformSamplerIsPoissonSmallMu) +{ + checkUniformSamplerIsPoisson(0.05, 13579, {0.5, 5., 25.}); +} + +// Uniform sampler at large mu must reproduce Poisson statistics +BOOST_AUTO_TEST_CASE(UniformSamplerIsPoissonLargeMu) +{ + checkUniformSamplerIsPoisson(0.3, 24680, {0.5, 3., 7.}); +} + // Non-uniform sampler with uniform scales must reproduce Poisson statistics BOOST_AUTO_TEST_CASE(NonUniformSamplerUniformScalesIsPoisson) { From ded81ee3154d26451028286f3c73b780cca1c14e Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Tue, 24 Nov 2026 17:06:58 +0100 Subject: [PATCH 2/2] Draw the number of collisions per crossing by inverting its distribution This replaces the rejection loop for the zero-truncated Poisson draw and adds a unit test. - The number of collisions in an occupied crossing was drawn with gRandom->Poisson(mu) until it was not zero. - This needs about 1/mu calls, i.e. about 500 calls per crossing at Pb-Pb rates. - The new drawZeroTruncatedPoisson() inverts the cumulative distribution with one uniform number per call. - Above mu = 30 it keeps the Poisson draw, where a zero is negligible and exp(-mu) would underflow. - InteractionSampler and NonUniformMuInteractionSampler both use it. - init() now stops with a fatal error for a non-positive mu. - The new test checks the frequencies, mean and variance of the draw for mu from 2e-4 to 100. Co-Authored-By: Claude Opus 5.5 --- .../SimulationDataFormat/InteractionSampler.h | 3 ++ .../simulation/src/InteractionSampler.cxx | 40 ++++++++++++++----- .../test/testInteractionSampler.cxx | 37 +++++++++++++++++ 3 files changed, 71 insertions(+), 9 deletions(-) diff --git a/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h b/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h index 7523180e2c3d4..95cd0a5ed5cb6 100644 --- a/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h +++ b/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h @@ -66,6 +66,9 @@ class InteractionSampler void print() const; + /// Poisson number >= 1 for mean mu, drawn by inverting its cumulative distribution + static int drawZeroTruncatedPoisson(double mu); + protected: virtual int simulateInteractingBC(); void nextCollidingBC(int n); diff --git a/DataFormats/simulation/src/InteractionSampler.cxx b/DataFormats/simulation/src/InteractionSampler.cxx index bcd339ff2ecf0..473a920e4c85a 100644 --- a/DataFormats/simulation/src/InteractionSampler.cxx +++ b/DataFormats/simulation/src/InteractionSampler.cxx @@ -11,6 +11,8 @@ #include "SimulationDataFormat/InteractionSampler.h" #include +#include +#include using namespace o2::steer; @@ -38,6 +40,9 @@ void InteractionSampler::init() mMuBC = mIntRate / (nBCSet * o2::constants::lhc::LHCRevFreq); LOG(info) << "Deducing mu=" << mMuBC << " per BC from IR=" << mIntRate << " with " << nBCSet << " BCs"; } + if (!(mMuBC > 0.)) { + LOG(fatal) << "Interaction rate must be positive, got mu=" << mMuBC << " per BC"; + } mInteractingBCs.clear(); mInteractingBCs.reserve(nBCSet); @@ -70,11 +75,31 @@ int InteractionSampler::drawBCJump() const int InteractionSampler::drawNCollInBC() const { // Poisson distribution of number of collisions in the bunch excluding 0 - int n = 0; - while ((n = gRandom->Poisson(mMuBC)) == 0) { - ; + return drawZeroTruncatedPoisson(mMuBC); +} + +//_________________________________________________ +int InteractionSampler::drawZeroTruncatedPoisson(double mu) +{ + // inverse of the cumulative distribution of P(k) = mu^k exp(-mu) / k! / (1 - exp(-mu)), k >= 1; + // one uniform number per call; above mu = 30, P(0) < 1e-13 and the plain Poisson draw is used + if (mu > 30.) { + int n = 0; + while ((n = gRandom->Poisson(mu)) == 0) { + ; + } + return n; } - return n; + const double u = gRandom->Rndm() * -std::expm1(-mu); + double p = mu * std::exp(-mu); + double cumulative = p; + int k = 1; + while (u > cumulative && p > 1e-16 * cumulative) { // second condition stops on rounding at the tail + ++k; + p *= mu / k; + cumulative += p; + } + return k; } //_________________________________________________ @@ -103,7 +128,7 @@ void InteractionSampler::print() const const o2::InteractionTimeRecord& InteractionSampler::generateCollisionTime() { // generate single interaction record - if (mIntRate < 0) { + if (mIntRate < 0 || mMuBC < 0) { init(); } @@ -251,10 +276,7 @@ int NonUniformMuInteractionSampler::simulateInteractingBC() // now sample number of collisions in chosenBC, conditioned >=1: double mu_chosen = muFunc(mCurrBCIdx); // or does it need to be mCurrBCIdx - int ncoll = 0; - do { - ncoll = gRandom->Poisson(mu_chosen); - } while (ncoll == 0); + int ncoll = drawZeroTruncatedPoisson(mu_chosen); // assign random time withing a bunch for (int i = ncoll; i--;) { diff --git a/DataFormats/simulation/test/testInteractionSampler.cxx b/DataFormats/simulation/test/testInteractionSampler.cxx index 9c9bb7b8b9610..149a13199d6c4 100644 --- a/DataFormats/simulation/test/testInteractionSampler.cxx +++ b/DataFormats/simulation/test/testInteractionSampler.cxx @@ -187,6 +187,43 @@ BOOST_AUTO_TEST_CASE(UniformSamplerIsPoissonLargeMu) checkUniformSamplerIsPoisson(0.3, 24680, {0.5, 3., 7.}); } +// Zero-truncated Poisson draw must reproduce its distribution, mean and variance from very small to large mu +BOOST_AUTO_TEST_CASE(ZeroTruncatedPoissonDraw) +{ + gRandom->SetSeed(4321); + const int n = 1000000; + for (double mu : {2e-4, 2e-3, 0.1, 2., 6.5, 20., 29.9, 30.1, 100.}) { + std::map counts; + double sum = 0., sum2 = 0.; + for (int i = 0; i < n; ++i) { + const int k = o2::steer::InteractionSampler::drawZeroTruncatedPoisson(mu); + BOOST_REQUIRE(k >= 1); + counts[k]++; + sum += k; + sum2 += double(k) * k; + } + const double expMean = mu / -std::expm1(-mu); + const double expVar = expMean * (1. + mu - expMean); + const double mean = sum / n; + const double var = sum2 / n - mean * mean; + BOOST_TEST_MESSAGE("mu " << mu << " mean " << mean << " expected " << expMean << " variance " << var << " expected " << expVar); + BOOST_CHECK(std::abs(mean - expMean) < 5. * std::sqrt(expVar / n) + 1e-12); + double m4 = 0.; // fourth central moment, for the standard error of the variance + for (const auto& [k, c] : counts) { + m4 += c * std::pow(k - mean, 4) / n; + } + BOOST_CHECK(std::abs(var - expVar) < 5. * std::sqrt(std::max(m4 - var * var, 0.) / n) + 1e-9); + double p = mu * std::exp(-mu) / -std::expm1(-mu); + for (int k = 1; k <= 4; ++k) { + const double expected = n * p; + const double tolerance = 5. * std::sqrt(expected) + 1.; + BOOST_TEST_MESSAGE("mu " << mu << " k=" << k << " observed " << counts[k] << " expected " << expected); + BOOST_CHECK(std::abs(counts[k] - expected) < tolerance); + p *= mu / (k + 1); + } + } +} + // Non-uniform sampler with uniform scales must reproduce Poisson statistics BOOST_AUTO_TEST_CASE(NonUniformSamplerUniformScalesIsPoisson) {