diff --git a/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h b/DataFormats/simulation/include/SimulationDataFormat/InteractionSampler.h index a68d972a991c4..95cd0a5ed5cb6 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 @@ -67,13 +66,15 @@ 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); - - 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 +91,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..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); @@ -47,38 +52,64 @@ void InteractionSampler::init() } } - auto mu = mMuBC; + mIntBCCache = 0; + mCurrBCIdx = 0; + mIR = mFirstIR; + while (mCurrBCIdx < mInteractingBCs.size() && mInteractingBCs[mCurrBCIdx] < mIR.bc) { + mCurrBCIdx++; + } + // set the "current BC" right in front of the 1st BC to generate. There will be a jump by at least 1 during generation + 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 - mBCJumpGenerator.initialize([mu]() { return (1. - std::log(1. - gRandom->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 - mNCollBCGenerator.initialize([mu]() { + 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; - }); - - 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; - }); + } + 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; +} - mIntBCCache = 0; - mCurrBCIdx = 0; - mIR = mFirstIR; - while (mCurrBCIdx < mInteractingBCs.size() && mInteractingBCs[mCurrBCIdx] < mIR.bc) { - mCurrBCIdx++; +//_________________________________________________ +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) { + ; } - // set the "current BC" right in front of the 1st BC to generate. There will be a jump by at least 1 during generation - mCurrBCIdx--; + return t; } //_________________________________________________ @@ -97,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(); } @@ -115,14 +146,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 +171,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; }); @@ -245,14 +276,11 @@ 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--;) { - 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..149a13199d6c4 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,140 @@ 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.}); +} + +// 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) {