From 5b91a2f97047942dbab895c375fcb2b3b2f43336 Mon Sep 17 00:00:00 2001 From: Marco Giacalone Date: Wed, 18 Nov 2026 14:37:57 +0100 Subject: [PATCH 1/3] Implement external helper generator for Monopoles --- .../external/generator/GeneratorMonopoles.C | 1730 +++++++++++++++++ .../generator/monopoles_schwinger_PbPb.json | 20 + .../generator/monopoles_showcase.json | 33 + .../external/generator/monopoles_single.json | 21 + .../BSM/ini/GeneratorMonopolesSchwinger.ini | 22 + .../ini/tests/GeneratorMonopolesSchwinger.C | 77 + 6 files changed, 1903 insertions(+) create mode 100644 MC/config/BSM/external/generator/GeneratorMonopoles.C create mode 100644 MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json create mode 100644 MC/config/BSM/external/generator/monopoles_showcase.json create mode 100644 MC/config/BSM/external/generator/monopoles_single.json create mode 100644 MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini create mode 100644 MC/config/BSM/ini/tests/GeneratorMonopolesSchwinger.C diff --git a/MC/config/BSM/external/generator/GeneratorMonopoles.C b/MC/config/BSM/external/generator/GeneratorMonopoles.C new file mode 100644 index 000000000..bfbb6c0ad --- /dev/null +++ b/MC/config/BSM/external/generator/GeneratorMonopoles.C @@ -0,0 +1,1730 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GeneratorMonopoles.C +/// \brief Configurable external generator for BSM magnetic monopoles +/// \author M. Giacalone - November 2026 +/// co-authored with Claude Opus 5.5 +/// +/// A JSON-driven external O2 generator for magnetic monopoles. Every kinematic +/// quantity can be set to a fixed value, to a weighted list of values, or drawn +/// from a range with a choice of distributions (see MonoValue below). +/// +/// Production modes ("mode" in the JSON): +/// "schwinger" : monopole / antimonopole pair, back-to-back in the pair rest +/// frame, as produced by the Schwinger mechanism in the field of +/// an ultraperipheral heavy-ion collision. The defaults +/// reproduce the PbPb HepMC samples +/// (PbPb_MMs_massGeV_g_N*.hepmc): isotropic emission and +/// a Maxwell-Juettner momentum spectrum +/// dN/dp propto p^2 exp(-sqrt(p^2+m^2)/T), T = 18.37 GeV +/// which was obtained by an unbinned maximum-likelihood fit to +/// those files (chi2/ndf ~ 1.0 for m = 100 and 200 GeV, g = 1 +/// and 3; the spectrum does not depend on the magnetic charge). +/// "single" : independent single monopoles, charge sign fixed or random. +/// +/// New modes only need a new entry in the EMode enum, in parseMode() and in +/// generateEvent(); everything else (sampling, consistency checks, bookkeeping) +/// is shared. +/// +/// IMPORTANT - transport consistency +/// The transported monopole mass and magnetic charge are *transport* settings, +/// G4.monopoleMass and G4.monopoleMagneticCharge, and they live in a different +/// process than the generator, so this generator cannot set them. It instead +/// reads them back and refuses to run with an inconsistent configuration (see +/// the "transport" JSON block). Use MonopolesTransportKeys() in this same macro +/// to derive the matching --configKeyValues string from the very same JSON file. +/// +/// Usage +/// The easiest way is the ini file, which sets the generator and the transport +/// settings at once: +/// o2-sim -g external -n 10 \ +/// --configFile $O2DPG_MC_CONFIG_ROOT/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini +/// or on the command line, where every key has to be given explicitly: +/// o2-sim -g external -n 10 \ +/// --configKeyValues "GeneratorExternal.fileName=GeneratorMonopoles.C+;GeneratorExternal.funcName=GeneratorMonopoles(\"cfg.json\");G4.monopole=1;G4.monopoleMass=100;G4.monopoleMagneticCharge=1" +/// +/// The trailing "+" on fileName is mandatory: the macro is compiled with ACLiC +/// because cling cannot interpret it (it autoparses FairRoot's dictionary +/// payload, which does not compile). +/// +/// Where ACLiC puts the build products (GeneratorMonopoles_C.so, .d, _rdict.pcm): +/// * next to the macro, when that directory is writable - a local checkout; +/// * in a temporary directory as soon as it is not, which is the case for an +/// installation on CVMFS. The target is $TMPDIR when it is set and exists, +/// and /tmp otherwise, with the user name appended (/tmp//...), so a +/// Grid job never tries to write into the installation and does not need +/// $TMPDIR to be set at all. +/// This macro needs an O2 that carries the monopole integration: +/// SimulationDataFormat/MonopoleParticles.h, the G4.monopole / G4.monopoleMass / +/// G4.monopoleMagneticCharge keys of o2::conf::G4Params and the two-argument +/// O2DatabasePDG::addALICEParticles(). It does not compile against an older O2, +/// by design - there is no fallback that could silently produce monopoles the +/// transport does not know. +/// +/// The JSON keys are documented where they are read, in readConfig() below, and +/// the three configurations next to this file are working examples: +/// monopoles_schwinger_PbPb.json the reference PbPb Schwinger production +/// monopoles_single.json single monopoles, flat in pT and eta +/// monopoles_showcase.json every knob in one file, for reference + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "SimConfig/G4Params.h" +#include "Generators/Generator.h" +#include "SimulationDataFormat/MCEventHeader.h" +#include "SimulationDataFormat/MCUtils.h" + +#include "Generators/PrimaryGeneratorParam.h" +#include "CommonUtils/FileSystemUtils.h" +#include "SimulationDataFormat/MonopoleParticles.h" +#include "SimulationDataFormat/O2DatabasePDG.h" + +namespace o2::eventgen +{ + +/// PDG codes and default mass of the monopole species, from O2 itself +/// (SimulationDataFormat/MonopoleParticles.h), so that this generator, the PDG +/// table and the transport cannot drift apart. +constexpr int kMonopolePdgSymm = o2::sim::MonopolePdgSymm; ///< equal electric and magnetic charge +constexpr int kMonopolePdgAsymm = o2::sim::MonopolePdgAsymm; ///< opposite electric and magnetic charge +constexpr double kMonopoleMassDefaultGeV = o2::sim::MonopoleMassDefaultGeV; + +/// Temperature of the Maxwell-Juettner spectrum fitted to the reference PbPb +/// Schwinger HepMC samples, in GeV. +constexpr double kSchwingerTemperatureGeV = 18.37; + +/// The transport keys this generator has to agree with. +constexpr const char* kG4MassKey = "G4.monopoleMass"; +constexpr const char* kG4ChargeKey = "G4.monopoleMagneticCharge"; + +/// true when a transport key was given explicitly (command line, ini file or +/// CCDB), false when it still carries the value compiled into O2. Without this +/// a key that was never set looks exactly like one set to its default, and the +/// generator would silently adopt a value nobody asked for. ConfigurableParam +/// throws for a key it does not know, which counts as "not set". +inline bool transportKeyWasSet(const char* key) +{ + try { + return o2::conf::ConfigurableParam::getProvenance(key) != o2::conf::ConfigurableParam::kCODE; + } catch (const std::exception&) { + return false; + } +} + +/// The monopole transport settings, as the transport process will see them. +inline bool g4MonopolePhysicsEnabled() { return o2::conf::G4Params::Instance().monopole; } +inline double g4MonopoleMass() { return o2::conf::G4Params::Instance().monopoleMass; } +inline double g4MonopoleMagneticCharge() { return o2::conf::G4Params::Instance().monopoleMagneticCharge; } + +//============================================================================== +// MonoValue: one configurable quantity +//============================================================================== + +/// A single configurable number. It is read from JSON either as a bare number +/// (fixed value) or as an object selecting one of the supported distributions: +/// +/// 100 fixed +/// {"value": 100} fixed +/// {"values": [50,100,200], "weights": [1,1,2]} weighted discrete choice +/// {"dist":"uniform", "min":a, "max":b} +/// {"dist":"loguniform", "min":a, "max":b} flat in ln(x), a > 0 +/// {"dist":"gaus", "mean":m, "sigma":s [,"min":a,"max":b]} +/// {"dist":"exp", "tau":t [,"min":a,"max":b]} propto exp(-x/t) +/// {"dist":"powerlaw", "exponent":n, "min":a,"max":b} propto x^n +/// {"dist":"poisson", "mean":m [,"min":a,"max":b]} +/// {"dist":"thermal", "temperature":T [,"mass":m,"min":a,"max":b]} +/// propto x^2 exp(-sqrt(x^2+m^2)/T) +/// mass defaults to the monopole mass +/// {"dist":"formula", "formula":"x*x*exp(-x/10)", "min":a,"max":b} +/// +/// Any spec accepts +/// "sampleOnce": true draw once at Init() and reuse the value for the whole run +/// (the default for mass and magnetic charge, which the +/// transport cannot change event by event) +/// "integer": true round the drawn value to the nearest integer +/// +/// Continuous shapes that have no closed-form inverse ("powerlaw", "thermal", +/// "formula", truncated "gaus"/"exp") are drawn from a tabulated inverse CDF +/// built once at Init() with kCdfBins bins, so the sampling cost and accuracy do +/// not depend on the shape. +class MonoValue +{ + public: + enum EKind { kUnset, + kFixed, + kList, + kUniform, + kLogUniform, + kGaus, + kExp, + kPowerLaw, + kPoisson, + kThermal, + kFormula }; + + static constexpr int kCdfBins = 20000; + + MonoValue() = default; + explicit MonoValue(double fixed) : mKind(kFixed), mValue(fixed) {} + + bool isSet() const { return mKind != kUnset; } + /// true when the JSON gave a plain number, as opposed to a shape to draw from + bool isFixedSpec() const { return mKind == kFixed; } + double min() const { return mMin; } + double max() const { return mMax; } + /// true if the value cannot change from one call to the next + bool isConstant() const { return mKind == kFixed || mSampleOnce; } + const std::string& name() const { return mName; } + + /// Parse a JSON node. Throws std::runtime_error on any malformed input. + void parse(const rapidjson::Value& node, const std::string& name) + { + mName = name; + if (node.IsNull()) { + throw std::runtime_error(name + ": null is not a valid value specification"); + } + if (node.IsNumber()) { + mKind = kFixed; + mValue = node.GetDouble(); + return; + } + if (!node.IsObject()) { + throw std::runtime_error(name + ": expected a number or an object, got a " + jsonTypeName(node)); + } + + mSampleOnce = getBool(node, "sampleOnce", mSampleOnce); + mInteger = getBool(node, "integer", mInteger); + + const bool hasValue = node.HasMember("value"); + const bool hasValues = node.HasMember("values"); + const bool hasDist = node.HasMember("dist"); + if (hasValue + hasValues + hasDist != 1) { + throw std::runtime_error(name + ": exactly one of \"value\", \"values\" or \"dist\" must be given"); + } + + if (hasValue) { + mKind = kFixed; + mValue = getNumber(node, "value"); + return; + } + + if (hasValues) { + mKind = kList; + const auto& arr = node["values"]; + if (!arr.IsArray() || arr.Empty()) { + throw std::runtime_error(name + ".values: expected a non-empty array of numbers"); + } + for (const auto& v : arr.GetArray()) { + if (!v.IsNumber()) { + throw std::runtime_error(name + ".values: all entries must be numbers"); + } + mList.push_back(v.GetDouble()); + } + if (node.HasMember("weights")) { + const auto& w = node["weights"]; + if (!w.IsArray() || w.Size() != arr.Size()) { + throw std::runtime_error(name + ".weights: expected an array with as many entries as \"values\""); + } + for (const auto& v : w.GetArray()) { + if (!v.IsNumber() || v.GetDouble() < 0.) { + throw std::runtime_error(name + ".weights: all entries must be non-negative numbers"); + } + mWeights.push_back(v.GetDouble()); + } + } else { + mWeights.assign(mList.size(), 1.); + } + // cumulative weights, normalised + double sum = std::accumulate(mWeights.begin(), mWeights.end(), 0.); + if (!(sum > 0.)) { + throw std::runtime_error(name + ".weights: the sum of the weights must be positive"); + } + mCumWeights.resize(mWeights.size()); + double run = 0.; + for (size_t i = 0; i < mWeights.size(); ++i) { + run += mWeights[i] / sum; + mCumWeights[i] = run; + } + mCumWeights.back() = 1.; + return; + } + + // dist + if (!node["dist"].IsString()) { + throw std::runtime_error(name + ".dist: expected a string"); + } + const std::string dist = node["dist"].GetString(); + mMin = getNumber(node, "min", -std::numeric_limits::infinity()); + mMax = getNumber(node, "max", std::numeric_limits::infinity()); + if (!(mMax > mMin)) { + throw std::runtime_error(name + ": \"max\" must be larger than \"min\""); + } + + if (dist == "uniform") { + mKind = kUniform; + requireFinite(name, "min", mMin); + requireFinite(name, "max", mMax); + } else if (dist == "loguniform") { + mKind = kLogUniform; + requireFinite(name, "min", mMin); + requireFinite(name, "max", mMax); + if (!(mMin > 0.)) { + throw std::runtime_error(name + ": \"loguniform\" needs min > 0"); + } + } else if (dist == "gaus" || dist == "gauss" || dist == "normal") { + mKind = kGaus; + mPar1 = getNumber(node, "mean"); + mPar2 = getNumber(node, "sigma"); + if (!(mPar2 > 0.)) { + throw std::runtime_error(name + ": \"sigma\" must be positive"); + } + } else if (dist == "exp" || dist == "exponential") { + mKind = kExp; + mPar1 = getNumber(node, "tau"); + if (!(mPar1 > 0.)) { + throw std::runtime_error(name + ": \"tau\" must be positive"); + } + if (!std::isfinite(mMin)) { + mMin = 0.; + } + } else if (dist == "powerlaw") { + mKind = kPowerLaw; + mPar1 = getNumber(node, "exponent"); + requireFinite(name, "min", mMin); + requireFinite(name, "max", mMax); + if (mMin < 0. || (mPar1 < 0. && !(mMin > 0.))) { + throw std::runtime_error(name + ": \"powerlaw\" needs min >= 0, and min > 0 for a negative exponent"); + } + } else if (dist == "poisson") { + mKind = kPoisson; + mPar1 = getNumber(node, "mean"); + if (mPar1 < 0.) { + throw std::runtime_error(name + ": \"mean\" must be non-negative"); + } + mInteger = true; + } else if (dist == "thermal") { + mKind = kThermal; + mPar1 = getNumber(node, "temperature", kSchwingerTemperatureGeV); + if (!(mPar1 > 0.)) { + throw std::runtime_error(name + ": \"temperature\" must be positive"); + } + mPar2 = getNumber(node, "mass", -1.); // < 0 => take the monopole mass + if (!std::isfinite(mMin) || mMin < 0.) { + mMin = 0.; + } + } else if (dist == "formula") { + mKind = kFormula; + if (!node.HasMember("formula") || !node["formula"].IsString()) { + throw std::runtime_error(name + ": \"formula\" (a TFormula string in x) is required"); + } + mFormula = node["formula"].GetString(); + requireFinite(name, "min", mMin); + requireFinite(name, "max", mMax); + } else { + throw std::runtime_error(name + ": unknown \"dist\" \"" + dist + + "\". Known: uniform, loguniform, gaus, exp, powerlaw, poisson, thermal, formula"); + } + } + + /// Build the tabulated inverse CDF where needed and draw the sampleOnce value. + /// @param defaultMass mass used by a "thermal" spec that does not give its own + void init(double defaultMass) + { + switch (mKind) { + case kThermal: { + const double mass = mPar2 >= 0. ? mPar2 : defaultMass; + const double T = mPar1; + if (!std::isfinite(mMax)) { + // the spectrum peaks near sqrt(2 m T); go far enough out that the + // truncated tail is below 1e-14 of the peak + mMax = autoRange([mass, T](double p) { return p * p * std::exp(-(std::sqrt(p * p + mass * mass) - mass) / T); }, + std::max(1., std::sqrt(2. * mass * T)), mMin); + } + // exp() of the subtracted mass keeps the pdf in a sane numerical range + buildCdf([mass, T](double p) { return p * p * std::exp(-(std::sqrt(p * p + mass * mass) - mass) / T); }); + break; + } + case kPowerLaw: { + const double n = mPar1; + buildCdf([n](double x) { return x <= 0. ? 0. : std::pow(x, n); }); + break; + } + case kFormula: { + mTF1 = std::make_unique((std::string("monoval_") + mName).c_str(), mFormula.c_str(), mMin, mMax); + if (!mTF1->IsValid()) { + throw std::runtime_error(mName + ": could not compile formula \"" + mFormula + "\""); + } + TF1* f = mTF1.get(); + buildCdf([f](double x) { return std::max(0., f->Eval(x)); }); + break; + } + case kGaus: + if (std::isfinite(mMin) || std::isfinite(mMax)) { + // truncated Gaussian: tabulate so that the truncation is exact and + // does not need rejection + const double mean = mPar1, sigma = mPar2; + if (!std::isfinite(mMin)) { + mMin = mean - 8. * sigma; + } + if (!std::isfinite(mMax)) { + mMax = mean + 8. * sigma; + } + buildCdf([mean, sigma](double x) { + const double z = (x - mean) / sigma; + return std::exp(-0.5 * z * z); + }); + } + break; + case kExp: + if (std::isfinite(mMax)) { + const double tau = mPar1, lo = mMin; + buildCdf([tau, lo](double x) { return std::exp(-(x - lo) / tau); }); + } + break; + default: + break; + } + + if (mSampleOnce) { + // keep mKind, so that the spec is still available to allows() + mFrozenValue = draw(); + mFrozen = true; + } + } + + /// Draw a value, or return the fixed / drawn-once one. + double sample() const + { + if (mKind == kFixed) { + return applyInteger(mValue); + } + if (mFrozen) { + return applyInteger(mFrozenValue); + } + return applyInteger(draw()); + } + + /// Would this spec ever produce @p v? Used to check an externally imposed + /// value (G4.monopoleMass) against the configuration. + bool allows(double v) const + { + const double tol = 1e-6 * std::max(1., std::abs(v)); + switch (mKind) { + case kUnset: + return false; + case kFixed: + return std::abs(v - mValue) <= tol; + case kList: + return std::any_of(mList.begin(), mList.end(), + [v, tol](double x) { return std::abs(v - x) <= tol; }); + default: + return v >= mMin - tol && v <= mMax + tol; + } + } + + /// Human readable summary for the Init() printout. + std::string describe() const + { + std::ostringstream os; + switch (mKind) { + case kUnset: + os << ""; + break; + case kFixed: + os << mValue << " (fixed)"; + break; + case kList: { + os << "one of {"; + for (size_t i = 0; i < mList.size(); ++i) { + os << (i ? ", " : "") << mList[i] << ":w=" << mWeights[i]; + } + os << "}"; + break; + } + case kUniform: + os << "uniform in [" << mMin << ", " << mMax << "]"; + break; + case kLogUniform: + os << "log-uniform in [" << mMin << ", " << mMax << "]"; + break; + case kGaus: + os << "gaus(mean=" << mPar1 << ", sigma=" << mPar2 << ")"; + break; + case kExp: + os << "exp(tau=" << mPar1 << ")"; + break; + case kPowerLaw: + os << "x^" << mPar1 << " in [" << mMin << ", " << mMax << "]"; + break; + case kPoisson: + os << "poisson(mean=" << mPar1 << ")"; + break; + case kThermal: + os << "p^2 exp(-E/T), T=" << mPar1 << " GeV, m=" << (mPar2 >= 0. ? mPar2 : -1.) + << " GeV (<0: monopole mass)"; + break; + case kFormula: + os << "\"" << mFormula << "\""; + break; + } + if (mKind != kFixed && mKind != kList && std::isfinite(mMin) && std::isfinite(mMax) && + mKind != kUniform && mKind != kLogUniform && mKind != kPowerLaw) { + os << " restricted to [" << mMin << ", " << mMax << "]"; + } + if (mInteger) { + os << " [integer]"; + } + if (mFrozen) { + os << " -> drawn once at startup: " << mFrozenValue; + } + return os.str(); + } + + private: + double applyInteger(double v) const { return mInteger ? std::round(v) : v; } + + double draw() const + { + switch (mKind) { + case kFixed: + return mValue; + case kList: { + const double u = gRandom->Rndm(); + auto it = std::lower_bound(mCumWeights.begin(), mCumWeights.end(), u); + size_t i = static_cast(it - mCumWeights.begin()); + return mList[std::min(i, mList.size() - 1)]; + } + case kUniform: + // an integer uniform has to be flat over the integers in [min, max]: + // rounding Uniform(min, max) would give the two ends half the weight + return mInteger ? std::floor(gRandom->Uniform(mMin, mMax + 1.)) + : gRandom->Uniform(mMin, mMax); + case kLogUniform: + return std::exp(gRandom->Uniform(std::log(mMin), std::log(mMax))); + case kGaus: + if (!mCdf.empty()) { + return sampleCdf(); + } + return gRandom->Gaus(mPar1, mPar2); + case kExp: + if (!mCdf.empty()) { + return sampleCdf(); + } + return mMin + gRandom->Exp(mPar1); + case kPoisson: { + // "min"/"max" act as an acceptance window + constexpr int kMaxTries = 100000; + double v = gRandom->Poisson(mPar1); + for (int trial = 0; (v < mMin || v > mMax) && trial < kMaxTries; ++trial) { + v = gRandom->Poisson(mPar1); + } + if (v < mMin || v > mMax) { + // returning an out-of-window value silently would change the + // configured physics without any trace in the log + const double clamped = std::min(std::max(v, mMin), mMax); + LOG(error) << mName << ": no Poisson(" << mPar1 << ") draw fell into the configured " + << "window [" << mMin << ", " << mMax << "] in " << kMaxTries + << " tries, using " << clamped << " instead; the window and the mean are " + << "probably incompatible"; + return clamped; + } + return v; + } + case kPowerLaw: + case kThermal: + case kFormula: + return sampleCdf(); + default: + throw std::runtime_error(mName + ": sampling an unset value"); + } + } + + /// Inverse-CDF sampling with linear interpolation inside the bin. + double sampleCdf() const + { + const double u = gRandom->Rndm(); + auto it = std::lower_bound(mCdf.begin(), mCdf.end(), u); + if (it == mCdf.begin()) { + // inside the first bin: interpolate from the left edge + const double f = mCdf[0] > 0. ? u / mCdf[0] : 0.5; + return mCdfMin + f * mCdfStep; + } + const size_t i = static_cast(it - mCdf.begin()); + if (i >= mCdf.size()) { + return mCdfMin + mCdf.size() * mCdfStep; + } + const double c0 = mCdf[i - 1], c1 = mCdf[i]; + const double f = (c1 > c0) ? (u - c0) / (c1 - c0) : 0.5; + return mCdfMin + (static_cast(i) + f) * mCdfStep; + } + + /// Tabulate the normalised cumulative of @p pdf over [mMin, mMax]. + void buildCdf(const std::function& pdf) + { + mCdfMin = mMin; + mCdfStep = (mMax - mMin) / kCdfBins; + mCdf.assign(kCdfBins, 0.); + double run = 0.; + for (int i = 0; i < kCdfBins; ++i) { + // trapezoidal weight of the bin + const double a = pdf(mMin + i * mCdfStep); + const double b = pdf(mMin + (i + 1) * mCdfStep); + run += 0.5 * (std::max(0., a) + std::max(0., b)); + mCdf[i] = run; + } + if (!(run > 0.)) { + throw std::runtime_error(mName + ": the distribution integrates to zero over [" + + std::to_string(mMin) + ", " + std::to_string(mMax) + "]"); + } + for (auto& c : mCdf) { + c /= run; + } + mCdf.back() = 1.; + } + + /// Walk outwards from @p peak until the pdf has dropped by 1e-14, to pick a + /// sensible upper edge for an open-ended spectrum. + static double autoRange(const std::function& pdf, double peak, double lo) + { + const double fpeak = std::max(pdf(peak), 1e-300); + double x = std::max(peak, lo + 1.); + for (int i = 0; i < 4000; ++i) { + if (pdf(x) / fpeak < 1e-14) { + return x; + } + x *= 1.05; + } + return x; + } + + static void requireFinite(const std::string& name, const char* what, double v) + { + if (!std::isfinite(v)) { + throw std::runtime_error(name + ": \"" + what + "\" is required for this distribution"); + } + } + + static const char* jsonTypeName(const rapidjson::Value& v) + { + static const char* names[] = {"null", "false", "true", "object", "array", "string", "number"}; + return names[v.GetType()]; + } + + static double getNumber(const rapidjson::Value& node, const char* key) + { + if (!node.HasMember(key) || !node[key].IsNumber()) { + throw std::runtime_error(std::string("\"") + key + "\" is required and must be a number"); + } + return node[key].GetDouble(); + } + static double getNumber(const rapidjson::Value& node, const char* key, double def) + { + if (!node.HasMember(key)) { + return def; + } + if (!node[key].IsNumber()) { + throw std::runtime_error(std::string("\"") + key + "\" must be a number"); + } + return node[key].GetDouble(); + } + static bool getBool(const rapidjson::Value& node, const char* key, bool def) + { + if (!node.HasMember(key)) { + return def; + } + if (!node[key].IsBool()) { + throw std::runtime_error(std::string("\"") + key + "\" must be true or false"); + } + return node[key].GetBool(); + } + + EKind mKind = kUnset; + std::string mName; + double mValue = 0.; + double mPar1 = 0., mPar2 = 0.; + double mMin = -std::numeric_limits::infinity(); + double mMax = std::numeric_limits::infinity(); + bool mSampleOnce = false; + bool mInteger = false; + bool mFrozen = false; + double mFrozenValue = 0.; + std::string mFormula; + std::vector mList, mWeights, mCumWeights; + std::vector mCdf; + double mCdfMin = 0., mCdfStep = 0.; + std::unique_ptr mTF1; +}; + +//============================================================================== +// GeneratorMonopoles +//============================================================================== + +/// One generated monopole, in GeV / GeV/c / cm / s. At namespace scope so that +/// rootcling can build a dictionary for the vector holding them. +struct MonoObject { + int pdg; + double px, py, pz, e; + double vx, vy, vz, vt; +}; + +class GeneratorMonopolesImpl : public Generator +{ + public: + enum EMode { kSchwinger, + kSingle }; + /// every mode the generator knows; extend together with EMode and modeName() + static constexpr EMode kAllModes[] = {kSchwinger, kSingle}; + enum EChargeSign { kRandomSign, + kPositive, + kNegative }; + enum EOnMismatch { kFatal, + kWarn, + kIgnore }; + + GeneratorMonopolesImpl() : Generator("GeneratorMonopoles", "ALICEo2 configurable monopole generator") + { + // we fill GeV, GeV/c, cm and s directly + setMomentumUnit(1.); + setEnergyUnit(1.); + setPositionUnit(1.); + setTimeUnit(1.); + } + ~GeneratorMonopolesImpl() override = default; + + /// The path may contain shell variables: O2 hands the argument of funcName to + /// the macro verbatim, and the O2DPG ini files write the path as + /// ${O2DPG_MC_CONFIG_ROOT}/..., so it is the macro that has to expand it, with + /// the same helper the other O2 generators use. + void setConfigFile(const std::string& f) { mConfigFile = o2::utils::expandShellVarsInFileName(f); } + + /// Parses the configuration and prints the transport settings that go with it, + /// both as a --configKeyValues string and as an ini snippet, without touching + /// or even reading the transport. This is what makes a separate key-deriving + /// script unnecessary: see MonopolesTransportKeys() at the end of this file. + int printTransportKeys() + { + try { + readConfig(); + mCheckTransport = false; // only report: never read or adopt the transport values + finaliseConfig(); + } catch (const std::exception& e) { + LOG(error) << "GeneratorMonopoles: " << e.what(); + return 1; + } + + std::ostringstream keys; + keys << "G4.monopole=1" + << ";G4.monopoleMass=" << mLastMass + << ";G4.monopoleMagneticCharge=" << mLastCharge; + if (mGeneratorId >= 0) { + keys << ";PrimaryGenerator.id=" << mGeneratorId; + } + + std::cout << "\n# transport settings matching " + << (mConfigFile.empty() ? std::string("the built-in defaults") : mConfigFile) << "\n" + << "\n# as --configKeyValues (append to the generator keys)\n" + << keys.str() << "\n" + << "\n# as an ini file section\n" + << "[G4]\n" + << "monopole = true\n" + << "monopoleMass = " << mLastMass << "\n" + << "monopoleMagneticCharge = " << mLastCharge << "\n"; + if (mGeneratorId >= 0) { + std::cout << "\n[PrimaryGenerator]\n" + << "id = " << mGeneratorId << "\n"; + } + if (!mMass.isFixedSpec() || !mCharge.isFixedSpec()) { + std::cout << "\n# note: mass [" << mMass.describe() << "] and magnetic charge [" + << mCharge.describe() << "] are not fixed values. The numbers above are the ones\n" + << "# drawn by this call; any other value the specification allows works too, the\n" + << "# generator adopts G4.monopoleMass / G4.monopoleMagneticCharge at startup.\n"; + } + std::cout << std::endl; + return 0; + } + + //---------------------------------------------------------------------------- + Bool_t Init() override + { + if (!Generator::Init()) { + return kFALSE; + } + return setup(); + } + + /// Read the configuration and get everything ready. Idempotent, and called + /// from generateEvent() as well as from Init(): some O2 execution paths never + /// call Init() on the primary generators (o2-sim --noGeant, for one), so the + /// generator must not depend on it having run. + Bool_t setup() + { + if (mSetupDone) { + return mSetupOk; + } + mSetupDone = true; + mSetupOk = kFALSE; + try { + readConfig(); + finaliseConfig(); + } catch (const std::exception& e) { + LOG(fatal) << "GeneratorMonopoles: " << e.what(); + return kFALSE; + } + registerMonopolesInPdgDatabase(mLastMass); + checkGeneratorId(); + // O2's sub-generator bookkeeping: the description map goes into the event + // header and ends up in the AO2D MC collisions (o2::mcgenid), so the + // production mode can be selected at analysis level. + for (EMode mode : kAllModes) { + addSubGenerator(static_cast(mode), std::string("monopoles: ") + modeName(mode)); + } + if (mVerbose > 0) { + printConfig(); + } + mSetupOk = checkTransport(); + return mSetupOk; + } + + //---------------------------------------------------------------------------- + Bool_t generateEvent() override + { + if (!setup()) { + return kFALSE; + } + notifySubGenerator(static_cast(mMode)); + mObjects.clear(); + const int n = std::max(0, static_cast(std::lround(mNObjects.sample()))); + for (int i = 0; i < n; ++i) { + switch (mMode) { + case kSchwinger: + if (!makeSchwingerPair()) { + return kFALSE; + } + break; + case kSingle: + if (!makeSingle()) { + return kFALSE; + } + break; + } + } + if (mVerbose > 1) { + LOG(info) << "GeneratorMonopoles: generated " << mObjects.size() << " monopole(s)"; + } + return kTRUE; + } + + //---------------------------------------------------------------------------- + Bool_t importParticles() override + { + // ReadEvent() already clears it; done here too so that importParticles() + // is also safe to call on its own + mParticles.clear(); + for (const auto& o : mObjects) { + TParticle p(o.pdg, 1, -1, -1, -1, -1, + o.px, o.py, o.pz, o.e, + o.vx, o.vy, o.vz, o.vt); + // HepMC status 1 (final state), generator status 0, to be transported + o2::mcutils::MCGenHelper::encodeParticleStatusAndTracking(p, 1, 0, true); + mParticles.push_back(p); + } + mNGenerated += mObjects.size(); + ++mNEvents; + return kTRUE; + } + + //---------------------------------------------------------------------------- + void updateHeader(o2::dataformats::MCEventHeader* header) override + { + using Key = o2::dataformats::MCInfoKeys; + header->putInfo(Key::generator, "monopoles"); + header->putInfo(Key::processName, modeName(mMode)); + header->putInfo(Key::processCode, static_cast(mMode)); + header->putInfo(Key::weight, 1.f); + header->putInfo("monopole_mass", static_cast(mLastMass)); + header->putInfo("monopole_magnetic_charge", static_cast(mLastCharge)); + header->putInfo("monopole_pdg", mPdg); + header->putInfo("monopole_multiplicity", static_cast(mObjects.size())); + } + + void stop() override + { + if (mNEvents > 0) { + LOG(info) << "GeneratorMonopoles: " << mNGenerated << " monopoles in " << mNEvents + << " events (" << static_cast(mNGenerated) / mNEvents << " per event), " + << "mass " << mLastMass << " GeV" + << valueOrigin(mMass, mLastMass, g4MonopoleMass(), kG4MassKey) + << ", magnetic charge " << mLastCharge << " g_D" + << valueOrigin(mCharge, mLastCharge, g4MonopoleMagneticCharge(), kG4ChargeKey); + } + } + + /// Where the value used for the run comes from, for the summary line: nothing + /// for a plain number in the JSON, the transport key when it was adopted from + /// it, and the specification otherwise (the per-event values are in the event + /// header, as monopole_mass and monopole_magnetic_charge). + static std::string valueOrigin(const MonoValue& spec, double used, double g4value, const char* key) + { + if (spec.isFixedSpec()) { + return ""; + } + if (g4value > 0. && std::abs(g4value - used) <= 1e-6 * std::max(1., std::abs(g4value))) { + return std::string(" (from ") + key + ")"; + } + return " (last of " + spec.describe() + ")"; + } + + private: + //-------------------------------------------------------------------------- + // configuration + //-------------------------------------------------------------------------- + void readConfig() + { + if (mConfigFile.empty()) { + LOG(info) << "GeneratorMonopoles: no JSON file given, using the built-in Schwinger defaults"; + return; + } + std::ifstream in(mConfigFile); + if (!in.is_open()) { + throw std::runtime_error("cannot open configuration file \"" + mConfigFile + "\""); + } + rapidjson::IStreamWrapper isw(in); + rapidjson::Document doc; + doc.ParseStream(isw); + if (doc.HasParseError()) { + throw std::runtime_error("parse error in \"" + mConfigFile + "\" at offset " + + std::to_string(doc.GetErrorOffset()) + ": " + + rapidjson::GetParseError_En(doc.GetParseError())); + } + if (!doc.IsObject()) { + throw std::runtime_error("\"" + mConfigFile + "\": the top level must be a JSON object"); + } + checkKeys(doc, "", {"mode", "verbose", "generatorId", "nPairs", "nParticles", "particle", + "kinematics", "vertex", "pairRecoil", "transport", "comment"}); + + if (doc.HasMember("mode")) { + if (!doc["mode"].IsString()) { + throw std::runtime_error("\"mode\" must be a string"); + } + mMode = parseMode(doc["mode"].GetString()); + } + if (doc.HasMember("verbose")) { + if (!doc["verbose"].IsInt()) { + throw std::runtime_error("\"verbose\" must be an integer"); + } + mVerbose = doc["verbose"].GetInt(); + } + if (doc.HasMember("generatorId")) { + if (!doc["generatorId"].IsInt() || doc["generatorId"].GetInt() < 0 || doc["generatorId"].GetInt() > 127) { + throw std::runtime_error("\"generatorId\" must be an integer in [0, 127] (7 bits in the " + "AO2D MC generator id encoding)"); + } + mGeneratorId = doc["generatorId"].GetInt(); + } + + // multiplicity: nPairs for schwinger, nParticles for single + const char* nKey = (mMode == kSchwinger) ? "nPairs" : "nParticles"; + const char* otherKey = (mMode == kSchwinger) ? "nParticles" : "nPairs"; + if (doc.HasMember(otherKey)) { + throw std::runtime_error(std::string("\"") + otherKey + "\" does not apply to mode \"" + + modeName(mMode) + "\"; use \"" + nKey + "\""); + } + if (doc.HasMember(nKey)) { + mNObjects.parse(doc[nKey], nKey); + } + + if (doc.HasMember("particle")) { + const auto& pn = doc["particle"]; + if (!pn.IsObject()) { + throw std::runtime_error("\"particle\" must be an object"); + } + checkKeys(pn, "particle", {"pdg", "species", "mass", "magneticCharge", "chargeSign"}); + if (pn.HasMember("pdg") && pn.HasMember("species")) { + throw std::runtime_error("particle: give either \"pdg\" or \"species\", not both"); + } + if (pn.HasMember("pdg")) { + if (!pn["pdg"].IsInt()) { + throw std::runtime_error("particle.pdg must be an integer"); + } + mPdg = std::abs(pn["pdg"].GetInt()); + if (mPdg != kMonopolePdgSymm && mPdg != kMonopolePdgAsymm) { + throw std::runtime_error("particle.pdg must be " + std::to_string(kMonopolePdgSymm) + + " (symmetric) or " + std::to_string(kMonopolePdgAsymm) + " (asymmetric)"); + } + } + if (pn.HasMember("species")) { + if (!pn["species"].IsString()) { + throw std::runtime_error("particle.species must be a string"); + } + const std::string s = pn["species"].GetString(); + if (s == "symm" || s == "symmetric") { + mPdg = kMonopolePdgSymm; + } else if (s == "asymm" || s == "asymmetric") { + mPdg = kMonopolePdgAsymm; + } else { + throw std::runtime_error("particle.species: unknown \"" + s + "\" (known: symm, asymm)"); + } + } + if (pn.HasMember("mass")) { + mMass.parse(pn["mass"], "particle.mass"); + } + if (pn.HasMember("magneticCharge")) { + mCharge.parse(pn["magneticCharge"], "particle.magneticCharge"); + } + if (pn.HasMember("chargeSign")) { + if (mMode != kSingle) { + throw std::runtime_error("particle.chargeSign only applies to mode \"single\"; a Schwinger " + "pair always contains one monopole and one antimonopole"); + } + if (!pn["chargeSign"].IsString()) { + throw std::runtime_error("particle.chargeSign must be a string"); + } + const std::string s = pn["chargeSign"].GetString(); + if (s == "random") { + mChargeSign = kRandomSign; + } else if (s == "positive" || s == "plus" || s == "monopole") { + mChargeSign = kPositive; + } else if (s == "negative" || s == "minus" || s == "antimonopole") { + mChargeSign = kNegative; + } else { + throw std::runtime_error("particle.chargeSign: unknown \"" + s + + "\" (known: random, positive, negative)"); + } + } + } + + if (doc.HasMember("kinematics")) { + const auto& kn = doc["kinematics"]; + if (!kn.IsObject()) { + throw std::runtime_error("\"kinematics\" must be an object"); + } + checkKeys(kn, "kinematics", {"p", "pt", "ekin", "etot", "eta", "y", "theta", "costheta", "phi"}); + for (const char* k : {"p", "pt", "ekin", "etot"}) { + if (kn.HasMember(k)) { + mMagnitude.parse(kn[k], std::string("kinematics.") + k); + mMagVar = k; + } + } + for (const char* k : {"eta", "y", "theta", "costheta"}) { + if (kn.HasMember(k)) { + if (!mAngleVar.empty()) { + throw std::runtime_error("kinematics: \"" + mAngleVar + "\" and \"" + k + + "\" are alternatives, give only one"); + } + mAngle.parse(kn[k], std::string("kinematics.") + k); + mAngleVar = k; + } + } + if (kn.HasMember("phi")) { + mPhi.parse(kn["phi"], "kinematics.phi"); + } + // how many of p/pt/ekin/etot were given + int nMag = 0; + for (const char* k : {"p", "pt", "ekin", "etot"}) { + nMag += kn.HasMember(k) ? 1 : 0; + } + if (nMag > 1) { + throw std::runtime_error("kinematics: \"p\", \"pt\", \"ekin\" and \"etot\" are alternatives, " + "give only one"); + } + } + + if (doc.HasMember("vertex")) { + const auto& vn = doc["vertex"]; + if (!vn.IsObject()) { + throw std::runtime_error("\"vertex\" must be an object"); + } + checkKeys(vn, "vertex", {"x", "y", "z", "t", "perObject"}); + if (vn.HasMember("x")) { + mVx.parse(vn["x"], "vertex.x"); + } + if (vn.HasMember("y")) { + mVy.parse(vn["y"], "vertex.y"); + } + if (vn.HasMember("z")) { + mVz.parse(vn["z"], "vertex.z"); + } + if (vn.HasMember("t")) { + mVt.parse(vn["t"], "vertex.t"); + } + if (vn.HasMember("perObject")) { + if (!vn["perObject"].IsBool()) { + throw std::runtime_error("vertex.perObject must be true or false"); + } + mVertexPerObject = vn["perObject"].GetBool(); + } + } + + if (doc.HasMember("pairRecoil")) { + if (mMode != kSchwinger) { + throw std::runtime_error("\"pairRecoil\" only applies to mode \"schwinger\""); + } + const auto& rn = doc["pairRecoil"]; + if (!rn.IsObject()) { + throw std::runtime_error("\"pairRecoil\" must be an object"); + } + checkKeys(rn, "pairRecoil", {"pt", "pz", "phi"}); + if (rn.HasMember("pt")) { + mRecoilPt.parse(rn["pt"], "pairRecoil.pt"); + } + if (rn.HasMember("pz")) { + mRecoilPz.parse(rn["pz"], "pairRecoil.pz"); + } + if (rn.HasMember("phi")) { + mRecoilPhi.parse(rn["phi"], "pairRecoil.phi"); + } + } + + if (doc.HasMember("transport")) { + const auto& tn = doc["transport"]; + if (!tn.IsObject()) { + throw std::runtime_error("\"transport\" must be an object"); + } + checkKeys(tn, "transport", {"check", "onMismatch", "massFromG4", "tolerance"}); + if (tn.HasMember("check")) { + if (!tn["check"].IsBool()) { + throw std::runtime_error("transport.check must be true or false"); + } + mCheckTransport = tn["check"].GetBool(); + } + if (tn.HasMember("massFromG4")) { + if (!tn["massFromG4"].IsBool()) { + throw std::runtime_error("transport.massFromG4 must be true or false"); + } + mMassFromG4 = tn["massFromG4"].GetBool(); + } + if (tn.HasMember("tolerance")) { + if (!tn["tolerance"].IsNumber()) { + throw std::runtime_error("transport.tolerance must be a number"); + } + mTolerance = tn["tolerance"].GetDouble(); + } + if (tn.HasMember("onMismatch")) { + if (!tn["onMismatch"].IsString()) { + throw std::runtime_error("transport.onMismatch must be a string"); + } + const std::string s = tn["onMismatch"].GetString(); + if (s == "fatal") { + mOnMismatch = kFatal; + } else if (s == "warn") { + mOnMismatch = kWarn; + } else if (s == "ignore") { + mOnMismatch = kIgnore; + } else { + throw std::runtime_error("transport.onMismatch: unknown \"" + s + + "\" (known: fatal, warn, ignore)"); + } + } + } + } + + /// Apply the defaults that depend on the mode and build the samplers. + void finaliseConfig() + { + // mass: explicit, from the transport, or the O2 default + if (!mMass.isSet() || mMassFromG4) { + const double g4mass = g4MonopoleMass(); + if (transportKeyWasSet(kG4MassKey) && g4mass > 0.) { + mMass = MonoValue(g4mass); + LOG(info) << "GeneratorMonopoles: taking the monopole mass from G4.monopoleMass = " << g4mass << " GeV"; + } else if (mMassFromG4) { + throw std::runtime_error("transport.massFromG4 is set but G4.monopoleMass was not given " + "(it still holds the O2 default of " + std::to_string(g4mass) + ")"); + } else { + mMass = MonoValue(kMonopoleMassDefaultGeV); + LOG(info) << "GeneratorMonopoles: no mass configured and G4.monopoleMass not given, " + << "using the O2 default of " << kMonopoleMassDefaultGeV << " GeV"; + } + } + if (!mCharge.isSet()) { + mCharge = MonoValue(g4MonopoleMagneticCharge()); + } + if (!mNObjects.isSet()) { + mNObjects = MonoValue(1.); + } + mNObjects.init(0.); + + // mass and magnetic charge have to stay constant: the transport knows a + // single value for the whole run + mMass.init(0.); + mCharge.init(0.); + if (!mMass.isConstant()) { + throw std::runtime_error("particle.mass varies event by event, which the transport cannot " + "follow (it uses the single value G4.monopoleMass). Add " + "\"sampleOnce\": true to draw one mass per run, or give a fixed value"); + } + if (!mCharge.isConstant()) { + throw std::runtime_error("particle.magneticCharge varies event by event, which the transport " + "cannot follow (it uses the single value G4.monopoleMagneticCharge). " + "Add \"sampleOnce\": true, or give a fixed value"); + } + mLastMass = mMass.sample(); + mLastCharge = mCharge.sample(); + + // When the configuration leaves the mass (or the charge) open and the + // transport has an explicit value, adopt the transport value instead of an + // independently drawn one: the two processes cannot negotiate, so taking + // the single value the transport will use is the only way to stay + // consistent by construction. A mass scan then just varies + // G4.monopoleMass over one JSON file. transport.check == false means "do + // not look at the transport at all", so it switches this off as well. + if (mCheckTransport) { + adoptFromTransport("mass", kG4MassKey, mMass, g4MonopoleMass(), mLastMass); + adoptFromTransport("magneticCharge", kG4ChargeKey, mCharge, g4MonopoleMagneticCharge(), mLastCharge); + } + + if (!(mLastMass > 0.)) { + throw std::runtime_error("the monopole mass must be positive, got " + std::to_string(mLastMass)); + } + + // kinematics defaults + if (!mMagnitude.isSet()) { + if (mMode == kSchwinger) { + // the Maxwell-Juettner spectrum of the reference PbPb HepMC samples + rapidjson::Document d; + d.Parse("{\"dist\":\"thermal\",\"temperature\":18.37}"); + mMagnitude.parse(d, "kinematics.p"); + mMagVar = "p"; + } else { + throw std::runtime_error("mode \"single\" needs one of kinematics.p, .pt, .ekin or .etot"); + } + } + if (mAngleVar.empty()) { + // isotropic + rapidjson::Document d; + d.Parse("{\"dist\":\"uniform\",\"min\":-1.0,\"max\":1.0}"); + mAngle.parse(d, "kinematics.costheta"); + mAngleVar = "costheta"; + } + if (!mPhi.isSet()) { + rapidjson::Document d; + d.Parse("{\"dist\":\"uniform\",\"min\":0.0,\"max\":6.283185307179586}"); + mPhi.parse(d, "kinematics.phi"); + } + + mMagnitude.init(mLastMass); + mAngle.init(mLastMass); + mPhi.init(mLastMass); + for (auto* v : {&mVx, &mVy, &mVz, &mVt, &mRecoilPt, &mRecoilPz, &mRecoilPhi}) { + if (v->isSet()) { + v->init(mLastMass); + } + } + if (mRecoilPt.isSet() && !mRecoilPhi.isSet()) { + rapidjson::Document d; + d.Parse("{\"dist\":\"uniform\",\"min\":0.0,\"max\":6.283185307179586}"); + mRecoilPhi.parse(d, "pairRecoil.phi"); + mRecoilPhi.init(mLastMass); + } + + // a pt-based magnitude with eta is fine, but pt with costheta/theta needs + // sin(theta) != 0 + if (mMagVar == "pt" && (mAngleVar == "costheta" || mAngleVar == "theta")) { + LOG(warning) << "GeneratorMonopoles: kinematics.pt combined with " << mAngleVar + << " diverges for theta -> 0; directions with |sin(theta)| < 1e-6 are redrawn"; + } + } + + void printConfig() const + { + LOG(info) << "=== GeneratorMonopoles configuration ==="; + LOG(info) << " config file : " << (mConfigFile.empty() ? std::string("") : mConfigFile); + LOG(info) << " mode : " << modeName(mMode); + LOG(info) << " species / |pdg| : " << (mPdg == kMonopolePdgSymm ? "symm" : "asymm") << " / " << mPdg; + LOG(info) << " mass : " << mLastMass << " GeV [" << mMass.describe() << "]"; + LOG(info) << " magnetic charge : " << mLastCharge << " g_D [" << mCharge.describe() << "]"; + LOG(info) << " " << (mMode == kSchwinger ? "pairs/event " : "monopoles/event ") << " : " + << mNObjects.describe(); + if (mMode == kSingle) { + LOG(info) << " charge sign : " + << (mChargeSign == kRandomSign ? "random" : (mChargeSign == kPositive ? "positive" : "negative")); + } + LOG(info) << " magnitude (" << mMagVar << ") : " << mMagnitude.describe(); + LOG(info) << " direction (" << mAngleVar << ") : " << mAngle.describe(); + LOG(info) << " phi : " << mPhi.describe(); + if (mVx.isSet() || mVy.isSet() || mVz.isSet() || mVt.isSet()) { + LOG(info) << " vertex offset [cm] : x=" << (mVx.isSet() ? mVx.describe() : "0") + << " y=" << (mVy.isSet() ? mVy.describe() : "0") + << " z=" << (mVz.isSet() ? mVz.describe() : "0") + << " t[s]=" << (mVt.isSet() ? mVt.describe() : "0") + << (mVertexPerObject ? " (drawn per monopole)" + : (mMode == kSchwinger ? " (drawn per pair)" : " (drawn per monopole)")); + } + if (mRecoilPt.isSet() || mRecoilPz.isSet()) { + LOG(info) << " pair recoil : pt=" << (mRecoilPt.isSet() ? mRecoilPt.describe() : "0") + << " pz=" << (mRecoilPz.isSet() ? mRecoilPz.describe() : "0"); + } + LOG(info) << "========================================"; + } + + //-------------------------------------------------------------------------- + // transport consistency + //-------------------------------------------------------------------------- + /// If @p spec is not a plain fixed number and the transport was given an + /// explicit value, replace @p current with it after checking the configuration + /// allows it. A key that was never set is left alone: adopting the value + /// compiled into O2 would quietly override the configured specification, and + /// a specification that excludes that default would fail on a key the user + /// never touched. + void adoptFromTransport(const char* what, const char* key, const MonoValue& spec, + double g4value, double& current) + { + if (spec.isFixedSpec() || !(g4value > 0.)) { + return; + } + if (!transportKeyWasSet(key)) { + LOG(info) << "GeneratorMonopoles: particle." << what << " is a range or a list and " << key + << " was not given, so the drawn value " << current << " is used; set " << key + << " to the same value for the transport"; + return; + } + if (!spec.allows(g4value)) { + const std::string problem = std::string(key) + " = " + std::to_string(g4value) + + " is not a value particle." + what + " can produce (" + + spec.describe() + ")"; + if (mOnMismatch == kFatal) { + throw std::runtime_error(problem); + } + // with onMismatch warn/ignore the generator keeps its own value; checkTransport() + // then reports the resulting disagreement with the same severity + if (mOnMismatch == kWarn) { + LOG(warning) << "GeneratorMonopoles: " << problem << ", keeping the drawn value " << current; + } else { + LOG(info) << "GeneratorMonopoles (ignored): " << problem << ", keeping the drawn value " + << current; + } + return; + } + if (std::abs(g4value - current) > 1e-6 * std::max(1., std::abs(g4value))) { + LOG(info) << "GeneratorMonopoles: particle." << what << " is configured as a range or a list, " + << "taking the transport value " << g4value << " instead of the drawn " << current + << " so that the generator and the transport agree"; + } + current = g4value; + } + + /// The generator id is stamped into the event header by o2::eventgen::PrimaryGenerator + /// from the PrimaryGenerator.id configurable parameter, and it ends up, together with + /// the sub-generator id, in the AO2D MC collisions (o2::mcgenid). The generator cannot + /// set it - it belongs to the primary generator - so, exactly as for the transport + /// settings, it is only checked here; MonopolesTransportKeys() prints the matching + /// PrimaryGenerator.id from the "generatorId" key of this very JSON file. + void checkGeneratorId() const + { + if (mGeneratorId < 0) { + return; + } + const int fromParams = o2::eventgen::PrimaryGeneratorParam::Instance().id; + if (fromParams != mGeneratorId) { + LOG(warning) << "GeneratorMonopoles: the configuration asks for generatorId " << mGeneratorId + << " but PrimaryGenerator.id is " << fromParams + << "; add PrimaryGenerator.id=" << mGeneratorId + << " to the configuration keys (MonopolesTransportKeys() prints it)"; + } else if (mVerbose > 0) { + LOG(info) << "GeneratorMonopoles: generator id " << mGeneratorId + << " will be stamped into the event header"; + } + } + + /// Make sure TDatabasePDG knows the monopoles with the mass this run uses. + /// Everything that derives a mass from the PDG table - the MCTrack getters, + /// kinematics dumps, analysis code - then agrees with the + /// generator. TDatabasePDG keeps the first registration of a code, so if + /// something already added the monopoles with another mass we can only report + /// it. + void registerMonopolesInPdgDatabase(double mass) const + { + auto* db = TDatabasePDG::Instance(); + // o2-sim registers them in GeneratorFactory before this generator is even + // built, so normally there is nothing to do here; calling the O2 helper + // again would only make TDatabasePDG warn about every particle it already + // knows. The call is kept for hosts that build the generator themselves. + if (db->GetParticle(kMonopolePdgSymm) == nullptr) { + o2::O2DatabasePDG::addALICEParticles(db, mass); + LOG(info) << "GeneratorMonopoles: registered the ALICE particles via " + << "O2DatabasePDG::addALICEParticles() with monopole mass " << mass << " GeV"; + } else if (const auto* registered = db->GetParticle(kMonopolePdgSymm); + std::abs(registered->Mass() - mass) > 1e-6 * std::max(1., mass)) { + // TDatabasePDG keeps the first registration of a code, so this can only be reported + LOG(warning) << "GeneratorMonopoles: the monopoles are already in TDatabasePDG with mass " + << registered->Mass() << " GeV instead of " << mass << " GeV, so a mass read " + << "from the PDG table (e.g. MCTrack::GetMass()) will not match the generator. " + << "The generated 4-momenta are not affected"; + } + } + + Bool_t checkTransport() + { + if (!mCheckTransport) { + return kTRUE; + } + std::vector problems; + + if (!g4MonopolePhysicsEnabled()) { + problems.push_back("G4.monopole is off: the monopoles will not be defined to the transport " + "engine. Add G4.monopole=1 to --configKeyValues (and use the Geant4 engine)"); + } + const double g4mass = g4MonopoleMass(); + if (std::abs(g4mass - mLastMass) > mTolerance * std::max(1., std::abs(mLastMass))) { + problems.push_back("generator mass " + std::to_string(mLastMass) + " GeV != G4.monopoleMass " + + std::to_string(g4mass) + " GeV"); + } + const double g4charge = g4MonopoleMagneticCharge(); + if (std::abs(g4charge - mLastCharge) > mTolerance * std::max(1., std::abs(mLastCharge))) { + problems.push_back("generator magnetic charge " + std::to_string(mLastCharge) + + " g_D != G4.monopoleMagneticCharge " + std::to_string(g4charge) + " g_D"); + } + + if (problems.empty()) { + LOG(info) << "GeneratorMonopoles: transport settings are consistent with the generator " + << "(G4.monopole=1, mass=" << mLastMass << " GeV, g=" << mLastCharge << " g_D)"; + return kTRUE; + } + + const std::string hint = "the matching settings for this configuration are: G4.monopole=1;G4.monopoleMass=" + + std::to_string(mLastMass) + ";G4.monopoleMagneticCharge=" + std::to_string(mLastCharge); + for (const auto& p : problems) { + if (mOnMismatch == kFatal) { + LOG(error) << "GeneratorMonopoles: " << p; + } else if (mOnMismatch == kWarn) { + LOG(warning) << "GeneratorMonopoles: " << p; + } else { + LOG(info) << "GeneratorMonopoles (ignored): " << p; + } + } + if (mOnMismatch == kFatal) { + LOG(fatal) << "GeneratorMonopoles: inconsistent transport configuration; " << hint + << ". Set transport.onMismatch to \"warn\" to continue anyway"; + return kFALSE; + } + LOG(warning) << "GeneratorMonopoles: " << hint; + return kTRUE; + } + + //-------------------------------------------------------------------------- + // kinematics + //-------------------------------------------------------------------------- + /// Draw one 3-momentum from the configured magnitude and direction specs. + /// Returns false only if no valid combination was found after many tries. + bool drawMomentum(double mass, double& px, double& py, double& pz) const + { + constexpr int kMaxTries = 10000; + for (int trial = 0; trial < kMaxTries; ++trial) { + const double phi = mPhi.sample(); + const double a = mAngle.sample(); + + // magnitude variable -> |p| (except for the pt/y combination, handled below) + double mag = mMagnitude.sample(); + double p = 0.; + if (mMagVar == "p") { + p = mag; + } else if (mMagVar == "etot") { + if (mag < mass) { + continue; + } + p = std::sqrt(std::max(0., mag * mag - mass * mass)); + } else if (mMagVar == "ekin") { + if (mag < 0.) { + continue; + } + const double e = mag + mass; + p = std::sqrt(std::max(0., e * e - mass * mass)); + } + + if (mAngleVar == "y") { + const double y = a; + const double sh = std::sinh(y), ch = std::cosh(y); + double pt = 0.; + if (mMagVar == "pt") { + pt = mag; + } else { + // p^2 = pt^2 cosh^2(y) + m^2 sinh^2(y) => pt^2 = (p^2 - m^2 sinh^2 y)/cosh^2 y + const double num = p * p - mass * mass * sh * sh; + if (num < 0.) { + continue; // this |p| cannot reach this rapidity + } + pt = std::sqrt(num) / ch; + } + if (pt < 0.) { + continue; + } + pz = std::sqrt(pt * pt + mass * mass) * sh; + px = pt * std::cos(phi); + py = pt * std::sin(phi); + return true; + } + + // costheta / theta / eta -> cos(theta) + double ct = 0.; + if (mAngleVar == "costheta") { + ct = a; + } else if (mAngleVar == "theta") { + ct = std::cos(a); + } else { // eta + ct = std::tanh(a); + } + if (ct < -1. || ct > 1.) { + continue; + } + const double st = std::sqrt(std::max(0., 1. - ct * ct)); + + if (mMagVar == "pt") { + if (st < 1e-6) { + continue; // pt is degenerate along the beam axis + } + p = mag / st; + } + if (p < 0.) { + continue; + } + px = p * st * std::cos(phi); + py = p * st * std::sin(phi); + pz = p * ct; + return true; + } + LOG(error) << "GeneratorMonopoles: could not find a momentum consistent with the configured " + << "magnitude (" << mMagVar << ") and direction (" << mAngleVar + << ") after " << kMaxTries << " tries; the two ranges are probably incompatible"; + return false; + } + + void drawVertex(double& x, double& y, double& z, double& t) const + { + x = mVx.isSet() ? mVx.sample() : 0.; + y = mVy.isSet() ? mVy.sample() : 0.; + z = mVz.isSet() ? mVz.sample() : 0.; + t = mVt.isSet() ? mVt.sample() : 0.; + } + + bool makeSchwingerPair() + { + const double m = mLastMass; + double px = 0., py = 0., pz = 0.; + if (!drawMomentum(m, px, py, pz)) { + return false; + } + // optional net momentum of the pair; zero by default, which is the + // back-to-back topology of the reference HepMC samples + double rx = 0., ry = 0., rz = 0.; + if (mRecoilPt.isSet()) { + const double pt = mRecoilPt.sample(); + const double phi = mRecoilPhi.sample(); + rx = pt * std::cos(phi); + ry = pt * std::sin(phi); + } + if (mRecoilPz.isSet()) { + rz = mRecoilPz.sample(); + } + + double vx, vy, vz, vt; + drawVertex(vx, vy, vz, vt); + + const double e = std::sqrt(px * px + py * py + pz * pz + m * m); + TLorentzVector plus(px, py, pz, e); + TLorentzVector minus(-px, -py, -pz, e); + if (rx != 0. || ry != 0. || rz != 0.) { + // The net momentum is given to the pair as a Lorentz boost of the + // back-to-back configuration (TLorentzVector::Boost), so the pair keeps + // its invariant mass and the two monopoles stay back-to-back in the pair + // rest frame. Adding half of the recoil to each momentum instead would + // silently change the pair mass. + const double mPair = plus.E() + minus.E(); // pair rest frame: p_tot = 0 + const double eTot = std::sqrt(mPair * mPair + rx * rx + ry * ry + rz * rz); + const TVector3 beta(rx / eTot, ry / eTot, rz / eTot); + plus.Boost(beta); + minus.Boost(beta); + } + + auto push = [&](int pdg, const TLorentzVector& q) { + if (mVertexPerObject) { + drawVertex(vx, vy, vz, vt); + } + mObjects.push_back({pdg, q.Px(), q.Py(), q.Pz(), q.E(), vx, vy, vz, vt}); + }; + push(+mPdg, plus); + push(-mPdg, minus); + return true; + } + + bool makeSingle() + { + const double m = mLastMass; + double px = 0., py = 0., pz = 0.; + if (!drawMomentum(m, px, py, pz)) { + return false; + } + int sign = +1; + if (mChargeSign == kRandomSign) { + sign = gRandom->Rndm() < 0.5 ? -1 : +1; + } else if (mChargeSign == kNegative) { + sign = -1; + } + double vx, vy, vz, vt; + drawVertex(vx, vy, vz, vt); + const double e = std::sqrt(px * px + py * py + pz * pz + m * m); + mObjects.push_back({sign * mPdg, px, py, pz, e, vx, vy, vz, vt}); + return true; + } + + //-------------------------------------------------------------------------- + static EMode parseMode(const std::string& s) + { + if (s == "schwinger" || s == "pair") { + return kSchwinger; + } + if (s == "single") { + return kSingle; + } + throw std::runtime_error("unknown \"mode\" \"" + s + "\" (known: schwinger, single)"); + } + static const char* modeName(EMode m) + { + switch (m) { + case kSchwinger: + return "schwinger"; + case kSingle: + return "single"; + } + return "unknown"; + } + + /// Reject unknown keys, so that a typo is an error instead of a silently + /// ignored setting. + static void checkKeys(const rapidjson::Value& node, const std::string& prefix, + const std::vector& allowed) + { + for (auto it = node.MemberBegin(); it != node.MemberEnd(); ++it) { + const std::string k = it->name.GetString(); + if (std::find(allowed.begin(), allowed.end(), k) == allowed.end()) { + std::ostringstream os; + os << "unknown key \"" << (prefix.empty() ? k : prefix + "." + k) << "\". Known keys here:"; + for (const auto& a : allowed) { + os << " " << a; + } + throw std::runtime_error(os.str()); + } + } + } + + //-------------------------------------------------------------------------- + std::string mConfigFile; + int mVerbose = 1; + int mGeneratorId = -1; ///< wanted PrimaryGenerator.id, -1 = not requested + EMode mMode = kSchwinger; + int mPdg = kMonopolePdgSymm; + EChargeSign mChargeSign = kRandomSign; + + MonoValue mNObjects, mMass, mCharge; + MonoValue mMagnitude, mAngle, mPhi; + MonoValue mVx, mVy, mVz, mVt; + MonoValue mRecoilPt, mRecoilPz, mRecoilPhi; + std::string mMagVar = "p"; + std::string mAngleVar; + bool mVertexPerObject = false; + + bool mSetupDone = false; + Bool_t mSetupOk = kFALSE; + + bool mCheckTransport = true; + bool mMassFromG4 = false; + EOnMismatch mOnMismatch = kFatal; + double mTolerance = 1e-4; + + double mLastMass = 0., mLastCharge = 0.; + std::vector mObjects; + unsigned long mNGenerated = 0; + unsigned long mNEvents = 0; + + ClassDefOverride(GeneratorMonopolesImpl, 1); +}; + +} // namespace o2::eventgen + +/// Loader for GeneratorExternal.funcName: +/// +/// GeneratorExternal.funcName=GeneratorMonopoles("myconfig.json") +/// +/// With no argument the configuration file is taken from the environment +/// variable MONOPOLES_CONFIG. That route exists because O2DPG strips the inner +/// double quotes out of a -confKey string, which would turn the argument into +/// an unquoted path and break the macro; in a workflow, export MONOPOLES_CONFIG +/// and leave GeneratorExternal.funcName at GeneratorMonopoles() - or leave it +/// empty altogether, since O2 then derives the function name from the file name. +/// With neither, the built-in Schwinger defaults are used. +FairGenerator* GeneratorMonopoles(std::string configFile = "") +{ + if (configFile.empty()) { + if (const char* fromEnv = std::getenv("MONOPOLES_CONFIG"); fromEnv != nullptr && *fromEnv) { + configFile = fromEnv; + LOG(info) << "GeneratorMonopoles: taking the configuration from $MONOPOLES_CONFIG = " << configFile; + } + } + auto* gen = new o2::eventgen::GeneratorMonopolesImpl(); + gen->setConfigFile(configFile); + return gen; +} + +//============================================================================== +// Tools, in this same macro so that the generator needs nothing but ROOT and O2 +//============================================================================== + +/// The configuration file an entry point should use: the argument, else +/// $MONOPOLES_CONFIG, else none (the built-in defaults). +inline std::string monopolesConfigFile(std::string configFile) +{ + if (configFile.empty()) { + if (const char* fromEnv = std::getenv("MONOPOLES_CONFIG"); fromEnv != nullptr && *fromEnv) { + configFile = fromEnv; + } + } + return configFile; +} + +/// Prints the transport settings (G4.monopole*, PrimaryGenerator.id) that match a +/// configuration file, as a --configKeyValues string and as an ini section: +/// +/// root -l -b -q 'GeneratorMonopoles.C+' -e 'MonopolesTransportKeys("cfg.json")' +/// +/// The generator cannot set them itself: they are read in the transport process, +/// before the generator of that process even exists, so they have to be on the +/// command line or in the ini file. Returns 0 on success. +int MonopolesTransportKeys(std::string configFile = "") +{ + auto gen = std::make_unique(); + gen->setConfigFile(monopolesConfigFile(std::move(configFile))); + return gen->printTransportKeys(); +} diff --git a/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json b/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json new file mode 100644 index 000000000..d99a53dab --- /dev/null +++ b/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json @@ -0,0 +1,20 @@ +{ + "comment": "Schwinger monopole-antimonopole pair production in PbPb, reproducing PbPb_MMs_mass100GeV_g1_N1000000.hepmc. Matching transport keys: G4.monopole=1;G4.monopoleMass=100;G4.monopoleMagneticCharge=1", + "mode": "schwinger", + "verbose": 1, + "nPairs": 1, + "particle": { + "species": "symm", + "mass": 100.0, + "magneticCharge": 1.0 + }, + "kinematics": { + "p": { "dist": "thermal", "temperature": 18.37 }, + "costheta": { "dist": "uniform", "min": -1.0, "max": 1.0 }, + "phi": { "dist": "uniform", "min": 0.0, "max": 6.283185307179586 } + }, + "transport": { + "check": true, + "onMismatch": "fatal" + } +} diff --git a/MC/config/BSM/external/generator/monopoles_showcase.json b/MC/config/BSM/external/generator/monopoles_showcase.json new file mode 100644 index 000000000..efc44033d --- /dev/null +++ b/MC/config/BSM/external/generator/monopoles_showcase.json @@ -0,0 +1,33 @@ +{ + "comment": "Every configurable parameter in one file. The mass is drawn once per run from a weighted list (the transport knows a single mass, so sampleOnce is mandatory for anything but a fixed value); a seed-dependent drawn-once value cannot be known before the run, so prefer a fixed mass for production and derive the transport keys with MonopolesTransportKeys(). The energy range has to be compatible with every mass the list can give: etot >= mass*cosh(y) must have a solution, otherwise the generator stops.", + "mode": "schwinger", + "verbose": 1, + "generatorId": 7, + "nPairs": { "dist": "poisson", "mean": 1.5, "min": 1 }, + "particle": { + "species": "asymm", + "mass": { "values": [100.0, 200.0, 500.0], "weights": [2, 1, 1], "sampleOnce": true }, + "magneticCharge": { "value": 3.0 } + }, + "kinematics": { + "etot": { "dist": "formula", "formula": "x*x*exp(-x/200.)", "min": 500.0, "max": 4000.0 }, + "y": { "dist": "gaus", "mean": 0.0, "sigma": 1.5, "min": -4.0, "max": 4.0 }, + "phi": { "dist": "uniform", "min": 0.0, "max": 6.283185307179586 } + }, + "vertex": { + "x": { "dist": "gaus", "mean": 0.0, "sigma": 0.01 }, + "y": { "dist": "gaus", "mean": 0.0, "sigma": 0.01 }, + "z": { "dist": "uniform", "min": -5.0, "max": 5.0 }, + "t": 0.0, + "perObject": false + }, + "pairRecoil": { + "pt": { "dist": "exp", "tau": 0.5, "max": 5.0 }, + "pz": { "dist": "gaus", "mean": 0.0, "sigma": 1.0 } + }, + "transport": { + "check": true, + "onMismatch": "warn", + "tolerance": 1e-4 + } +} diff --git a/MC/config/BSM/external/generator/monopoles_single.json b/MC/config/BSM/external/generator/monopoles_single.json new file mode 100644 index 000000000..20673d073 --- /dev/null +++ b/MC/config/BSM/external/generator/monopoles_single.json @@ -0,0 +1,21 @@ +{ + "comment": "Single monopoles, flat in pT and eta: the configuration to use for acceptance and tracking studies. Matching transport keys: G4.monopole=1;G4.monopoleMass=50;G4.monopoleMagneticCharge=1", + "mode": "single", + "verbose": 1, + "nParticles": { "dist": "uniform", "min": 1, "max": 4, "integer": true }, + "particle": { + "species": "symm", + "mass": 50.0, + "magneticCharge": 1.0, + "chargeSign": "random" + }, + "kinematics": { + "pt": { "dist": "uniform", "min": 1.0, "max": 100.0 }, + "eta": { "dist": "uniform", "min": -0.9, "max": 0.9 }, + "phi": { "dist": "uniform", "min": 0.0, "max": 6.283185307179586 } + }, + "transport": { + "check": true, + "onMismatch": "fatal" + } +} diff --git a/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini b/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini new file mode 100644 index 000000000..3c71c9b97 --- /dev/null +++ b/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini @@ -0,0 +1,22 @@ +# Schwinger production of BSM magnetic-monopole pairs, reproducing the PbPb reference samples: +# m = 100 GeV, g = 1 g_D, one pair per event, isotropic +# Three things to note in this configuration: +# * the trailing "+" on fileName is mandatory. The macro is compiled with ACLiC because cling +# cannot interpret it. The build products go next to the macro when that directory is +# writable, and into $TMPDIR, or /tmp/ when $TMPDIR is not set, as soon as it is not +# - the CVMFS case - so a Grid job never writes into the installation. +# * it needs an O2 with the monopole integration (SimulationDataFormat/MonopoleParticles.h +# and the G4.monopole* keys); it does not compile against an older one. +# * the mass and the magnetic charge are *transport* settings: they are read in the transport +# process, before its own generator even exists, so the generator cannot set them and they +# have to be given here, in the [G4] section. The generator reads them back and refuses to +# start if they disagree with the JSON. +#NEV_TEST> 20 +[GeneratorExternal] +fileName = ${O2DPG_MC_CONFIG_ROOT}/MC/config/BSM/external/generator/GeneratorMonopoles.C+ +funcName = GeneratorMonopoles("${O2DPG_MC_CONFIG_ROOT}/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json") + +[G4] +monopole = true +monopoleMass = 100 +monopoleMagneticCharge = 1 diff --git a/MC/config/BSM/ini/tests/GeneratorMonopolesSchwinger.C b/MC/config/BSM/ini/tests/GeneratorMonopolesSchwinger.C new file mode 100644 index 000000000..636ce1aa8 --- /dev/null +++ b/MC/config/BSM/ini/tests/GeneratorMonopolesSchwinger.C @@ -0,0 +1,77 @@ +#include "SimulationDataFormat/MonopoleParticles.h" + +int External() +{ + // the species codes come from O2 itself, so this test cannot drift from the simulation + const int pdgMonopole = o2::sim::MonopolePdgSymm; + const double momentumTolerance = 1e-6; // relative, on the momentum sum of the pairs + + // Note on the mass: it is deliberately not checked here. MCTrack stores only the momentum, + // and MCTrack::GetEnergy() rebuilds the energy as sqrt(m^2 + p^2) with m taken from the PDG + // table of *this* process, so any mass derived from the tracks is the table value and not + // what the generator used - the check would always pass. The mass is enforced on the + // generator side instead: GeneratorMonopoles refuses to start when its configured mass + // disagrees with G4.monopoleMass, which the ini file sets. + + std::string path{"o2sim_Kine.root"}; + TFile file(path.c_str(), "READ"); + if (file.IsZombie()) { + std::cerr << "Cannot open ROOT file " << path << "\n"; + return 1; + } + auto tree = (TTree*)file.Get("o2sim"); + if (!tree) { + std::cerr << "Cannot find tree 'o2sim' in file " << path << "\n"; + return 1; + } + std::vector* tracks{}; + tree->SetBranchAddress("MCTrack", &tracks); + + const auto nEvents = tree->GetEntries(); + if (nEvents == 0) { + std::cerr << "No events found\n"; + return 1; + } + + for (Long64_t i = 0; i < nEvents; ++i) { + tree->GetEntry(i); + int nMonopoles = 0; + int nAntiMonopoles = 0; + double sumPx = 0., sumPy = 0., sumPz = 0., sumP = 0.; + for (const auto& track : *tracks) { + const auto pdg = track.GetPdgCode(); + if (!o2::sim::isMonopole(pdg) || std::abs(pdg) != pdgMonopole) { + std::cerr << "Found unexpected PDG code " << pdg << " in event " << i << "\n"; + return 1; + } + (pdg > 0 ? nMonopoles : nAntiMonopoles)++; + const double px = track.Px(), py = track.Py(), pz = track.Pz(); + const double p2 = px * px + py * py + pz * pz; + sumPx += px; + sumPy += py; + sumPz += pz; + sumP += std::sqrt(p2); + } + if (nMonopoles < 1 || nAntiMonopoles < 1) { + std::cerr << "Event " << i << " has no monopole pair: " << nMonopoles << " monopole(s) and " + << nAntiMonopoles << " antimonopole(s)\n"; + return 1; + } + if (nMonopoles != nAntiMonopoles) { + std::cerr << "Event " << i << " is not made of pairs: " << nMonopoles << " monopole(s) and " + << nAntiMonopoles << " antimonopole(s)\n"; + return 1; + } + // the Schwinger configuration has no pair recoil, so each pair, and hence the event, has + // vanishing total momentum + const double imbalance = std::sqrt(sumPx * sumPx + sumPy * sumPy + sumPz * sumPz); + if (sumP <= 0. || imbalance > momentumTolerance * sumP) { + std::cerr << "Monopoles in event " << i << " are not back-to-back: momentum imbalance " + << imbalance << " GeV/c for a total momentum of " << sumP << " GeV/c\n"; + return 1; + } + } + + file.Close(); + return 0; +} From 406595f7c6a4b6fd202365e37d186e388c12817a Mon Sep 17 00:00:00 2001 From: Marco Giacalone Date: Wed, 25 Nov 2026 09:25:40 +0100 Subject: [PATCH 2/3] Integrate code review Now unknown keys inside value specifications are rejected too. The momentum draws that are kinematically impossible for the configured magnitude and direction (e.g. etot < m*cosh(y)) are now counted and get redrawn. Warn when more than 1% are rejected, because the generated distributions are then narrower than the configured ones. MonopolesTransportKeys() no longer reads any transport setting. In plain ROOT it used to abort in ConfigurableParamHelper when the JSON left the mass open. A mass or charge left to the transport now prints the O2 default, with a note saying which key to set and why (not configured, or transport.massFromG4). monopoles_showcase.json: use onMismatch "fatal", as the file serves as a template, and choose kinematics with no rejected draws (etot in [2000, 8000], |y| <= 2, so etot >= 500*cosh(2) for every mass in the list). --- .../external/generator/GeneratorMonopoles.C | 160 ++++++++++++++---- .../generator/monopoles_showcase.json | 8 +- 2 files changed, 135 insertions(+), 33 deletions(-) diff --git a/MC/config/BSM/external/generator/GeneratorMonopoles.C b/MC/config/BSM/external/generator/GeneratorMonopoles.C index bfbb6c0ad..c1c7d5abf 100644 --- a/MC/config/BSM/external/generator/GeneratorMonopoles.C +++ b/MC/config/BSM/external/generator/GeneratorMonopoles.C @@ -82,6 +82,7 @@ #include #include #include +#include #include #include #include @@ -122,6 +123,25 @@ namespace o2::eventgen constexpr int kMonopolePdgSymm = o2::sim::MonopolePdgSymm; ///< equal electric and magnetic charge constexpr int kMonopolePdgAsymm = o2::sim::MonopolePdgAsymm; ///< opposite electric and magnetic charge constexpr double kMonopoleMassDefaultGeV = o2::sim::MonopoleMassDefaultGeV; +/// Default of G4.monopoleMagneticCharge in o2::conf::G4Params, for which O2 has no named constant. +constexpr double kMonopoleMagneticChargeDefault = 1.; + +/// Reject unknown keys, so that a typo is an error instead of a silently ignored setting. +inline void checkKeys(const rapidjson::Value& node, const std::string& prefix, + const std::vector& allowed) +{ + for (auto it = node.MemberBegin(); it != node.MemberEnd(); ++it) { + const std::string k = it->name.GetString(); + if (std::find(allowed.begin(), allowed.end(), k) == allowed.end()) { + std::ostringstream os; + os << "unknown key \"" << (prefix.empty() ? k : prefix + "." + k) << "\". Known keys here:"; + for (const auto& a : allowed) { + os << " " << a; + } + throw std::runtime_error(os.str()); + } + } +} /// Temperature of the Maxwell-Juettner spectrum fitted to the reference PbPb /// Schwinger HepMC samples, in GeV. @@ -237,12 +257,14 @@ class MonoValue } if (hasValue) { + checkKeys(node, name, {"value", "sampleOnce", "integer"}); mKind = kFixed; mValue = getNumber(node, "value"); return; } if (hasValues) { + checkKeys(node, name, {"values", "weights", "sampleOnce", "integer"}); mKind = kList; const auto& arr = node["values"]; if (!arr.IsArray() || arr.Empty()) { @@ -288,6 +310,25 @@ class MonoValue throw std::runtime_error(name + ".dist: expected a string"); } const std::string dist = node["dist"].GetString(); + // the keys each distribution reads, on top of dist/min/max/sampleOnce/integer: + // a misspelt optional parameter would otherwise silently keep its default + static const std::map> kDistKeys = { + {"uniform", {}}, + {"loguniform", {}}, + {"gaus", {"mean", "sigma"}}, + {"gauss", {"mean", "sigma"}}, + {"normal", {"mean", "sigma"}}, + {"exp", {"tau"}}, + {"exponential", {"tau"}}, + {"powerlaw", {"exponent"}}, + {"poisson", {"mean"}}, + {"thermal", {"temperature", "mass"}}, + {"formula", {"formula"}}}; + if (const auto known = kDistKeys.find(dist); known != kDistKeys.end()) { + std::vector allowed{"dist", "min", "max", "sampleOnce", "integer"}; + allowed.insert(allowed.end(), known->second.begin(), known->second.end()); + checkKeys(node, name, allowed); + } mMin = getNumber(node, "min", -std::numeric_limits::infinity()); mMax = getNumber(node, "max", std::numeric_limits::infinity()); if (!(mMax > mMin)) { @@ -723,7 +764,8 @@ class GeneratorMonopolesImpl : public Generator setPositionUnit(1.); setTimeUnit(1.); } - ~GeneratorMonopolesImpl() override = default; + + ~GeneratorMonopolesImpl() override { finalMomentumReport(); } /// The path may contain shell variables: O2 hands the argument of funcName to /// the macro verbatim, and the O2DPG ini files write the path as @@ -739,7 +781,7 @@ class GeneratorMonopolesImpl : public Generator { try { readConfig(); - mCheckTransport = false; // only report: never read or adopt the transport values + mReportOnly = true; // only report: never read or adopt the transport values finaliseConfig(); } catch (const std::exception& e) { LOG(error) << "GeneratorMonopoles: " << e.what(); @@ -767,16 +809,30 @@ class GeneratorMonopolesImpl : public Generator std::cout << "\n[PrimaryGenerator]\n" << "id = " << mGeneratorId << "\n"; } - if (!mMass.isFixedSpec() || !mCharge.isFixedSpec()) { - std::cout << "\n# note: mass [" << mMass.describe() << "] and magnetic charge [" - << mCharge.describe() << "] are not fixed values. The numbers above are the ones\n" - << "# drawn by this call; any other value the specification allows works too, the\n" - << "# generator adopts G4.monopoleMass / G4.monopoleMagneticCharge at startup.\n"; - } + printOpenValueNote("mass", kG4MassKey, mMass, mMassFromTransport, + mMassFromG4 ? "transport.massFromG4 is set" : "it is not set in the configuration"); + printOpenValueNote("magnetic charge", kG4ChargeKey, mCharge, mChargeFromTransport, + "it is not set in the configuration"); std::cout << std::endl; return 0; } + /// Explains a transport value printed by printTransportKeys() that the JSON + /// does not fix, for the mass and the charge separately. @param reason why the + /// generator takes the value from the transport key, when fromTransport is set + static void printOpenValueNote(const char* what, const char* key, const MonoValue& spec, + bool fromTransport, const char* reason) + { + if (fromTransport) { + std::cout << "\n# note: the generator takes the " << what << " from " << key << " (" << reason << ").\n" + << "# The value above is the O2 default; set " << key << " to the " << what << " you want.\n"; + } else if (!spec.isFixedSpec()) { + std::cout << "\n# note: the " << what << " [" << spec.describe() << "] is not a fixed value. The\n" + << "# number above is the one drawn by this call; any other value the specification\n" + << "# allows works too, the generator adopts " << key << " at startup.\n"; + } + } + //---------------------------------------------------------------------------- Bool_t Init() override { @@ -891,6 +947,7 @@ class GeneratorMonopolesImpl : public Generator << ", magnetic charge " << mLastCharge << " g_D" << valueOrigin(mCharge, mLastCharge, g4MonopoleMagneticCharge(), kG4ChargeKey); } + finalMomentumReport(); } /// Where the value used for the run comes from, for the summary line: nothing @@ -1156,7 +1213,12 @@ class GeneratorMonopolesImpl : public Generator void finaliseConfig() { // mass: explicit, from the transport, or the O2 default - if (!mMass.isSet() || mMassFromG4) { + if ((!mMass.isSet() || mMassFromG4) && mReportOnly) { + // report mode reads no transport setting: outside o2-sim even asking for + // the provenance of a G4 key aborts in ConfigurableParamHelper + mMass = MonoValue(kMonopoleMassDefaultGeV); + mMassFromTransport = true; + } else if (!mMass.isSet() || mMassFromG4) { const double g4mass = g4MonopoleMass(); if (transportKeyWasSet(kG4MassKey) && g4mass > 0.) { mMass = MonoValue(g4mass); @@ -1170,7 +1232,10 @@ class GeneratorMonopolesImpl : public Generator << "using the O2 default of " << kMonopoleMassDefaultGeV << " GeV"; } } - if (!mCharge.isSet()) { + if (!mCharge.isSet() && mReportOnly) { + mCharge = MonoValue(kMonopoleMagneticChargeDefault); + mChargeFromTransport = true; + } else if (!mCharge.isSet()) { mCharge = MonoValue(g4MonopoleMagneticCharge()); } if (!mNObjects.isSet()) { @@ -1202,7 +1267,7 @@ class GeneratorMonopolesImpl : public Generator // consistent by construction. A mass scan then just varies // G4.monopoleMass over one JSON file. transport.check == false means "do // not look at the transport at all", so it switches this off as well. - if (mCheckTransport) { + if (mCheckTransport && !mReportOnly) { adoptFromTransport("mass", kG4MassKey, mMass, g4MonopoleMass(), mLastMass); adoptFromTransport("magneticCharge", kG4ChargeKey, mCharge, g4MonopoleMagneticCharge(), mLastCharge); } @@ -1444,6 +1509,7 @@ class GeneratorMonopolesImpl : public Generator { constexpr int kMaxTries = 10000; for (int trial = 0; trial < kMaxTries; ++trial) { + countMomentumDraw(trial > 0); const double phi = mPhi.sample(); const double a = mAngle.sample(); @@ -1522,6 +1588,52 @@ class GeneratorMonopolesImpl : public Generator return false; } + /// Every draw drawMomentum() throws away reshapes the configured distributions, + /// so the rejections are counted and reported instead of passing silently + /// At 100, 1000, 10000... draws, and once more at the end of the run (stop() + /// or the destructor) so that short runs are covered too, a warning gives the + /// fraction rejected so far when it is above kMaxRejectedFraction. + void countMomentumDraw(bool previousRejected) const + { + ++mMomentumDraws; + if (previousRejected) { + ++mMomentumRejected; + } + if (mMomentumDraws < mNextRejectionReport) { + return; + } + mNextRejectionReport *= 10; + reportMomentumRejections("the first "); + } + + void finalMomentumReport() + { + if (!mFinalMomentumReportDone) { + mFinalMomentumReportDone = true; + reportMomentumRejections("all "); + } + } + + void reportMomentumRejections(const char* which) const + { + static constexpr double kMaxRejectedFraction = 0.01; + if (mMomentumRejected == 0) { + return; + } + const double fraction = double(mMomentumRejected) / double(mMomentumDraws); + std::ostringstream msg; + msg << "GeneratorMonopoles: " << mMomentumRejected << " of " << which << mMomentumDraws + << " momentum draws (" << 100. * fraction << "%) were kinematically impossible for " + << "the configured magnitude (" << mMagVar << ") and direction (" << mAngleVar + << ") and were redrawn"; + if (fraction > kMaxRejectedFraction) { + LOG(warning) << msg.str() << ", so the generated distributions are narrower than the " + << "configured ones. Make the two ranges compatible (e.g. etot >= mass*cosh(y))"; + } else { + LOG(info) << msg.str(); + } + } + void drawVertex(double& x, double& y, double& z, double& t) const { x = mVx.isSet() ? mVx.sample() : 0.; @@ -1622,24 +1734,6 @@ class GeneratorMonopolesImpl : public Generator return "unknown"; } - /// Reject unknown keys, so that a typo is an error instead of a silently - /// ignored setting. - static void checkKeys(const rapidjson::Value& node, const std::string& prefix, - const std::vector& allowed) - { - for (auto it = node.MemberBegin(); it != node.MemberEnd(); ++it) { - const std::string k = it->name.GetString(); - if (std::find(allowed.begin(), allowed.end(), k) == allowed.end()) { - std::ostringstream os; - os << "unknown key \"" << (prefix.empty() ? k : prefix + "." + k) << "\". Known keys here:"; - for (const auto& a : allowed) { - os << " " << a; - } - throw std::runtime_error(os.str()); - } - } - } - //-------------------------------------------------------------------------- std::string mConfigFile; int mVerbose = 1; @@ -1660,6 +1754,14 @@ class GeneratorMonopolesImpl : public Generator Bool_t mSetupOk = kFALSE; bool mCheckTransport = true; + bool mReportOnly = false; ///< MonopolesTransportKeys(): parse and print, never touch the transport + bool mMassFromTransport = false; ///< report mode: the JSON leaves the mass to G4.monopoleMass + bool mChargeFromTransport = false; ///< report mode: the JSON leaves the charge to G4.monopoleMagneticCharge + // momentum draws rejected by drawMomentum(), see countMomentumDraw() + mutable long mMomentumDraws = 0; + mutable long mMomentumRejected = 0; + mutable long mNextRejectionReport = 100; + bool mFinalMomentumReportDone = false; bool mMassFromG4 = false; EOnMismatch mOnMismatch = kFatal; double mTolerance = 1e-4; diff --git a/MC/config/BSM/external/generator/monopoles_showcase.json b/MC/config/BSM/external/generator/monopoles_showcase.json index efc44033d..ebe0bd9aa 100644 --- a/MC/config/BSM/external/generator/monopoles_showcase.json +++ b/MC/config/BSM/external/generator/monopoles_showcase.json @@ -1,5 +1,5 @@ { - "comment": "Every configurable parameter in one file. The mass is drawn once per run from a weighted list (the transport knows a single mass, so sampleOnce is mandatory for anything but a fixed value); a seed-dependent drawn-once value cannot be known before the run, so prefer a fixed mass for production and derive the transport keys with MonopolesTransportKeys(). The energy range has to be compatible with every mass the list can give: etot >= mass*cosh(y) must have a solution, otherwise the generator stops.", + "comment": "Every configurable parameter in one file. The mass is drawn once per run from a weighted list (the transport knows a single mass, so sampleOnce is mandatory for anything but a fixed value); a seed-dependent drawn-once value cannot be known before the run, so prefer a fixed mass for production and derive the transport keys with MonopolesTransportKeys(). The energy and rapidity ranges have to be compatible with every mass the list can give: here etot >= 2000 >= 500*cosh(2), so no draw is ever rejected. A draw with etot < mass*cosh(y) is redrawn, which reshapes the configured distributions, so the generator warns when more than 1% are rejected and stops when no valid draw can be found.", "mode": "schwinger", "verbose": 1, "generatorId": 7, @@ -10,8 +10,8 @@ "magneticCharge": { "value": 3.0 } }, "kinematics": { - "etot": { "dist": "formula", "formula": "x*x*exp(-x/200.)", "min": 500.0, "max": 4000.0 }, - "y": { "dist": "gaus", "mean": 0.0, "sigma": 1.5, "min": -4.0, "max": 4.0 }, + "etot": { "dist": "formula", "formula": "x*x*exp(-x/1000.)", "min": 2000.0, "max": 8000.0 }, + "y": { "dist": "gaus", "mean": 0.0, "sigma": 1.0, "min": -2.0, "max": 2.0 }, "phi": { "dist": "uniform", "min": 0.0, "max": 6.283185307179586 } }, "vertex": { @@ -27,7 +27,7 @@ }, "transport": { "check": true, - "onMismatch": "warn", + "onMismatch": "fatal", "tolerance": 1e-4 } } From a47c1bd0cd1afb12c2d13ec83a773cd49222b2b9 Mon Sep 17 00:00:00 2001 From: Marco Giacalone Date: Wed, 25 Nov 2026 14:07:29 +0100 Subject: [PATCH 3/3] Temperature from sqrt(s_NN) and field kick as in the authors' notebook Bring the Schwinger kinematics in line with the notebook the authors use to produce their monopole samples: Maxwell-Juettner temperature is now calculated based on the center of mass energy of the heavy ion collision, and the field kick is integrated, however the direction is drawn per event instead of being constant for the entire run as done in the original simulation --- .../external/generator/GeneratorMonopoles.C | 133 ++++++++++++++---- .../generator/monopoles_schwinger_PbPb.json | 5 +- .../BSM/ini/GeneratorMonopolesSchwinger.ini | 4 +- 3 files changed, 111 insertions(+), 31 deletions(-) diff --git a/MC/config/BSM/external/generator/GeneratorMonopoles.C b/MC/config/BSM/external/generator/GeneratorMonopoles.C index c1c7d5abf..f4543f15b 100644 --- a/MC/config/BSM/external/generator/GeneratorMonopoles.C +++ b/MC/config/BSM/external/generator/GeneratorMonopoles.C @@ -21,14 +21,18 @@ /// Production modes ("mode" in the JSON): /// "schwinger" : monopole / antimonopole pair, back-to-back in the pair rest /// frame, as produced by the Schwinger mechanism in the field of -/// an ultraperipheral heavy-ion collision. The defaults -/// reproduce the PbPb HepMC samples -/// (PbPb_MMs_massGeV_g_N*.hepmc): isotropic emission and -/// a Maxwell-Juettner momentum spectrum -/// dN/dp propto p^2 exp(-sqrt(p^2+m^2)/T), T = 18.37 GeV -/// which was obtained by an unbinned maximum-likelihood fit to -/// those files (chi2/ndf ~ 1.0 for m = 100 and 200 GeV, g = 1 -/// and 3; the spectrum does not depend on the magnetic charge). +/// an ultraperipheral heavy-ion collision. By default the +/// emission is isotropic with a Maxwell-Juettner momentum spectrum +/// dN/dp propto p^2 exp(-sqrt(p^2+m^2)/T), T = omega/4, +/// where omega = c_w gamma / R_Pb is the characteristic frequency +/// of the field pulse and gamma = sqrt(s_NN) / (2 m_p) (see +/// schwingerTemperature()). sqrt(s_NN) is the "sqrtsNN" JSON key, +/// by default the Run 3 PbPb energy of 5.36 TeV (T = 19.58 GeV); +/// 5.02 TeV gives T = 18.34 GeV, which matches Run 2 PbPb configuration +/// On top of that the field kicks the pair: the monopole gets a +/// transverse momentum +g k and the antimonopole -g k, along a +/// direction drawn per event, with k = g_0 B / omega per unit +/// Dirac charge, calculated from sqrtsNN (fieldKickPerCharge()). /// "single" : independent single monopoles, charge sign fixed or random. /// /// New modes only need a new entry in the EMode enum, in parseMode() and in @@ -143,9 +147,42 @@ inline void checkKeys(const rapidjson::Value& node, const std::string& prefix, } } -/// Temperature of the Maxwell-Juettner spectrum fitted to the reference PbPb -/// Schwinger HepMC samples, in GeV. -constexpr double kSchwingerTemperatureGeV = 18.37; +/// Default nucleon-nucleon centre-of-mass energy: Run 3 PbPb, in GeV. +constexpr double kSqrtsNNDefaultGeV = 5360.; + +/// Temperature of the Maxwell-Juettner spectrum of Schwinger pairs produced in +/// the field of an ultraperipheral PbPb collision at @p sqrtsNN (GeV): +/// T = omega / 4, omega = c_w gamma / R_Pb, gamma = sqrt(s_NN) / (2 m_p) +/// with c_w = 0.92 and R_Pb = 33.5484 GeV^-1, the values of the notebook the +/// reference samples were produced with (Gould, Ho, Rajantie, PRD 104, 015033). +/// 5.02 TeV gives 18.34 GeV, 5.36 TeV gives 19.58 GeV. +inline double schwingerTemperature(double sqrtsNN) +{ + constexpr double kProtonMassGeV = 0.9382720813; + constexpr double kFieldPulseCw = 0.92; + constexpr double kPbRadiusInvGeV = 33.5484; + const double gamma = sqrtsNN / (2. * kProtonMassGeV); + const double omega = kFieldPulseCw * gamma / kPbRadiusInvGeV; + return omega / 4.; +} + +/// Transverse momentum (GeV) the field of an ultraperipheral PbPb collision at +/// @p sqrtsNN (GeV) gives a monopole per unit Dirac charge: k = g_0 B / omega, +/// with g_0 = 2 pi / e the Dirac charge in natural units and the peak field B +/// and pulse frequency omega of the authors' notebook, B = 8.1 GeV^2 and +/// omega = 80 GeV at the Run 3 energy of 5.36 TeV. Both grow linearly with the +/// Lorentz factor, so both are scaled with sqrt(s_NN); their ratio, and with it +/// k, is then the same at every energy. The value used is printed at startup. +inline double fieldKickPerCharge(double sqrtsNN) +{ + constexpr double kAlpha = 1. / 137.035999139; + constexpr double kSqrtsNNRun3GeV = 5360.; + constexpr double kPeakFieldRun3GeV2 = 8.1; + constexpr double kPulseFrequencyRun3GeV = 80.; + const double g0 = 2. * M_PI / std::sqrt(4. * M_PI * kAlpha); + const double scale = sqrtsNN / kSqrtsNNRun3GeV; + return g0 * (kPeakFieldRun3GeV2 * scale) / (kPulseFrequencyRun3GeV * scale); +} /// The transport keys this generator has to agree with. constexpr const char* kG4MassKey = "G4.monopoleMass"; @@ -186,9 +223,10 @@ inline double g4MonopoleMagneticCharge() { return o2::conf::G4Params::Instance() /// {"dist":"exp", "tau":t [,"min":a,"max":b]} propto exp(-x/t) /// {"dist":"powerlaw", "exponent":n, "min":a,"max":b} propto x^n /// {"dist":"poisson", "mean":m [,"min":a,"max":b]} -/// {"dist":"thermal", "temperature":T [,"mass":m,"min":a,"max":b]} +/// {"dist":"thermal" [,"temperature":T,"mass":m,"min":a,"max":b]} /// propto x^2 exp(-sqrt(x^2+m^2)/T) -/// mass defaults to the monopole mass +/// mass defaults to the monopole mass, +/// T to schwingerTemperature(sqrtsNN) /// {"dist":"formula", "formula":"x*x*exp(-x/10)", "min":a,"max":b} /// /// Any spec accepts @@ -379,8 +417,8 @@ class MonoValue mInteger = true; } else if (dist == "thermal") { mKind = kThermal; - mPar1 = getNumber(node, "temperature", kSchwingerTemperatureGeV); - if (!(mPar1 > 0.)) { + mPar1 = getNumber(node, "temperature", -1.); // < 0 => from sqrtsNN, see init() + if (node.HasMember("temperature") && !(mPar1 > 0.)) { throw std::runtime_error(name + ": \"temperature\" must be positive"); } mPar2 = getNumber(node, "mass", -1.); // < 0 => take the monopole mass @@ -403,10 +441,15 @@ class MonoValue /// Build the tabulated inverse CDF where needed and draw the sampleOnce value. /// @param defaultMass mass used by a "thermal" spec that does not give its own - void init(double defaultMass) + /// @param defaultTemperature temperature used by a "thermal" spec that does not + /// give its own (the one of the configured sqrtsNN) + void init(double defaultMass, double defaultTemperature) { switch (mKind) { case kThermal: { + if (mPar1 < 0.) { + mPar1 = defaultTemperature; + } const double mass = mPar2 >= 0. ? mPar2 : defaultMass; const double T = mPar1; if (!std::isfinite(mMax)) { @@ -990,7 +1033,7 @@ class GeneratorMonopolesImpl : public Generator if (!doc.IsObject()) { throw std::runtime_error("\"" + mConfigFile + "\": the top level must be a JSON object"); } - checkKeys(doc, "", {"mode", "verbose", "generatorId", "nPairs", "nParticles", "particle", + checkKeys(doc, "", {"mode", "verbose", "generatorId", "sqrtsNN", "fieldKick", "nPairs", "nParticles", "particle", "kinematics", "vertex", "pairRecoil", "transport", "comment"}); if (doc.HasMember("mode")) { @@ -999,6 +1042,25 @@ class GeneratorMonopolesImpl : public Generator } mMode = parseMode(doc["mode"].GetString()); } + // "sqrtsNN": nucleon-nucleon centre-of-mass energy in GeV, sets the + // temperature of every "thermal" spec that does not give its own + if (doc.HasMember("sqrtsNN")) { + if (!doc["sqrtsNN"].IsNumber() || !(doc["sqrtsNN"].GetDouble() > 0.)) { + throw std::runtime_error("\"sqrtsNN\" must be a positive number (GeV)"); + } + mSqrtsNN = doc["sqrtsNN"].GetDouble(); + } + mThermalTemperature = schwingerTemperature(mSqrtsNN); + // "fieldKick": transverse momentum per unit Dirac charge (GeV) the field + // gives a Schwinger pair, instead of the one calculated from sqrtsNN; 0 + // switches it off + mFieldKickPerCharge = fieldKickPerCharge(mSqrtsNN); + if (doc.HasMember("fieldKick")) { + if (!doc["fieldKick"].IsNumber() || doc["fieldKick"].GetDouble() < 0.) { + throw std::runtime_error("\"fieldKick\" must be a non-negative number (GeV per Dirac charge)"); + } + mFieldKickPerCharge = doc["fieldKick"].GetDouble(); + } if (doc.HasMember("verbose")) { if (!doc["verbose"].IsInt()) { throw std::runtime_error("\"verbose\" must be an integer"); @@ -1241,12 +1303,12 @@ class GeneratorMonopolesImpl : public Generator if (!mNObjects.isSet()) { mNObjects = MonoValue(1.); } - mNObjects.init(0.); + mNObjects.init(0., mThermalTemperature); // mass and magnetic charge have to stay constant: the transport knows a // single value for the whole run - mMass.init(0.); - mCharge.init(0.); + mMass.init(0., mThermalTemperature); + mCharge.init(0., mThermalTemperature); if (!mMass.isConstant()) { throw std::runtime_error("particle.mass varies event by event, which the transport cannot " "follow (it uses the single value G4.monopoleMass). Add " @@ -1279,9 +1341,9 @@ class GeneratorMonopolesImpl : public Generator // kinematics defaults if (!mMagnitude.isSet()) { if (mMode == kSchwinger) { - // the Maxwell-Juettner spectrum of the reference PbPb HepMC samples + // the Maxwell-Juettner spectrum at the temperature of the configured sqrtsNN rapidjson::Document d; - d.Parse("{\"dist\":\"thermal\",\"temperature\":18.37}"); + d.Parse("{\"dist\":\"thermal\"}"); mMagnitude.parse(d, "kinematics.p"); mMagVar = "p"; } else { @@ -1301,19 +1363,19 @@ class GeneratorMonopolesImpl : public Generator mPhi.parse(d, "kinematics.phi"); } - mMagnitude.init(mLastMass); - mAngle.init(mLastMass); - mPhi.init(mLastMass); + mMagnitude.init(mLastMass, mThermalTemperature); + mAngle.init(mLastMass, mThermalTemperature); + mPhi.init(mLastMass, mThermalTemperature); for (auto* v : {&mVx, &mVy, &mVz, &mVt, &mRecoilPt, &mRecoilPz, &mRecoilPhi}) { if (v->isSet()) { - v->init(mLastMass); + v->init(mLastMass, mThermalTemperature); } } if (mRecoilPt.isSet() && !mRecoilPhi.isSet()) { rapidjson::Document d; d.Parse("{\"dist\":\"uniform\",\"min\":0.0,\"max\":6.283185307179586}"); mRecoilPhi.parse(d, "pairRecoil.phi"); - mRecoilPhi.init(mLastMass); + mRecoilPhi.init(mLastMass, mThermalTemperature); } // a pt-based magnitude with eta is fine, but pt with costheta/theta needs @@ -1329,6 +1391,11 @@ class GeneratorMonopolesImpl : public Generator LOG(info) << "=== GeneratorMonopoles configuration ==="; LOG(info) << " config file : " << (mConfigFile.empty() ? std::string("") : mConfigFile); LOG(info) << " mode : " << modeName(mMode); + LOG(info) << " sqrt(s_NN) : " << mSqrtsNN << " GeV (default thermal T = " << mThermalTemperature << " GeV)"; + if (mMode == kSchwinger) { + LOG(info) << " field kick : " << mFieldKickPerCharge << " GeV per g_D, " + << mFieldKickPerCharge * std::abs(mLastCharge) << " GeV per monopole, random transverse direction"; + } LOG(info) << " species / |pdg| : " << (mPdg == kMonopolePdgSymm ? "symm" : "asymm") << " / " << mPdg; LOG(info) << " mass : " << mLastMass << " GeV [" << mMass.describe() << "]"; LOG(info) << " magnetic charge : " << mLastCharge << " g_D [" << mCharge.describe() << "]"; @@ -1649,6 +1716,15 @@ class GeneratorMonopolesImpl : public Generator if (!drawMomentum(m, px, py, pz)) { return false; } + // The field of the passing nuclei kicks the monopole along the field and + // the antimonopole the other way. The field direction follows the event + // plane, so it is drawn per event, transverse to the beam. + const double kick = mFieldKickPerCharge * std::abs(mLastCharge); + if (kick > 0.) { + const double phiKick = gRandom->Uniform(0., 2. * M_PI); + px += kick * std::cos(phiKick); + py += kick * std::sin(phiKick); + } // optional net momentum of the pair; zero by default, which is the // back-to-back topology of the reference HepMC samples double rx = 0., ry = 0., rz = 0.; @@ -1737,6 +1813,9 @@ class GeneratorMonopolesImpl : public Generator //-------------------------------------------------------------------------- std::string mConfigFile; int mVerbose = 1; + double mSqrtsNN = kSqrtsNNDefaultGeV; ///< GeV + double mThermalTemperature = schwingerTemperature(kSqrtsNNDefaultGeV); ///< GeV, from mSqrtsNN + double mFieldKickPerCharge = fieldKickPerCharge(kSqrtsNNDefaultGeV); ///< GeV per g_D int mGeneratorId = -1; ///< wanted PrimaryGenerator.id, -1 = not requested EMode mMode = kSchwinger; int mPdg = kMonopolePdgSymm; diff --git a/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json b/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json index d99a53dab..e743f56e4 100644 --- a/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json +++ b/MC/config/BSM/external/generator/monopoles_schwinger_PbPb.json @@ -1,6 +1,7 @@ { - "comment": "Schwinger monopole-antimonopole pair production in PbPb, reproducing PbPb_MMs_mass100GeV_g1_N1000000.hepmc. Matching transport keys: G4.monopole=1;G4.monopoleMass=100;G4.monopoleMagneticCharge=1", + "comment": "Schwinger monopole-antimonopole pair production in Run 3 PbPb. Adding \"temperature\": T to kinematics.p overrides the automatic calculation of the variable based on sqrtsNN. The field kicks the monopole by +g*k and the antimonopole by -g*k, transverse to the beam in a direction drawn per event, with k = g_0 B / omega per Dirac charge calculated from sqrtsNN; a top-level \"fieldKick\" (GeV per Dirac charge, 0 = off) overrides the calculation. Matching transport keys: G4.monopole=1;G4.monopoleMass=100;G4.monopoleMagneticCharge=1", "mode": "schwinger", + "sqrtsNN": 5360.0, "verbose": 1, "nPairs": 1, "particle": { @@ -9,7 +10,7 @@ "magneticCharge": 1.0 }, "kinematics": { - "p": { "dist": "thermal", "temperature": 18.37 }, + "p": { "dist": "thermal" }, "costheta": { "dist": "uniform", "min": -1.0, "max": 1.0 }, "phi": { "dist": "uniform", "min": 0.0, "max": 6.283185307179586 } }, diff --git a/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini b/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini index 3c71c9b97..87beaa341 100644 --- a/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini +++ b/MC/config/BSM/ini/GeneratorMonopolesSchwinger.ini @@ -1,5 +1,5 @@ -# Schwinger production of BSM magnetic-monopole pairs, reproducing the PbPb reference samples: -# m = 100 GeV, g = 1 g_D, one pair per event, isotropic +# Schwinger production of BSM magnetic-monopole pairs in Run 3 PbPb (sqrtsNN = 5.36 TeV): +# m = 100 GeV, g = 1 g_D, one pair per event, isotropic, temperature calculated from sqrtsNN # Three things to note in this configuration: # * the trailing "+" on fileName is mandatory. The macro is compiled with ACLiC because cling # cannot interpret it. The build products go next to the macro when that directory is