22#include <fairlogger/Logger.h>
24#include "TClonesArray.h"
32#ifdef GENERATORS_WITH_TPCLOOPERS
36#ifdef GENERATORS_WITH_PYTHIA8
47unsigned int Generator::gTotalNEvents = 0;
51 static const bool isHY = std::getenv(
"IS_HYPERLOOP") && std::atoi(std::getenv(
"IS_HYPERLOOP"));
63#ifdef GENERATORS_WITH_TPCLOOPERS
66 if (!loopersParam.loopersVeto) {
67 bool transport = (simConfig.getMCEngine() !=
"O2TrivialMCEngine");
69 bool tpcActive = (std::find(simConfig.getReadoutDetectors().begin(), simConfig.getReadoutDetectors().end(),
"TPC") != simConfig.getReadoutDetectors().end());
71 if (initTPCLoopersGen()) {
72 mAddTPCLoopers = kTRUE;
75 LOG(info) <<
"TPC not active in readout detectors: loopers fast generator disabled.";
79 LOG(info) <<
"Loopers fast generator turned OFF with veto flag.";
92#ifdef GENERATORS_WITH_TPCLOOPERS
95 if (!loopersParam.loopersVeto) {
96 bool transport = (simConfig.getMCEngine() !=
"O2TrivialMCEngine");
98 bool tpcActive = (std::find(simConfig.getReadoutDetectors().begin(), simConfig.getReadoutDetectors().end(),
"TPC") != simConfig.getReadoutDetectors().end());
100 if (initTPCLoopersGen()) {
101 mAddTPCLoopers = kTRUE;
104 LOG(info) <<
"TPC not active in readout detectors: loopers fast generator disabled.";
108 LOG(info) <<
"Loopers fast generator turned OFF with veto flag.";
118#ifdef GENERATORS_WITH_TPCLOOPERS
119 if (mTPCLoopersGen) {
120 delete mTPCLoopersGen;
121 mTPCLoopersGen =
nullptr;
124#ifdef GENERATORS_WITH_PYTHIA8
125 if (mEventDecayerReport) {
126 LOG(info) <<
"EventDecayer summary of generator " << GetName();
127 mEventDecayerReport->
print();
129 delete mEventDecayer;
130 delete mEventDecayerReport;
135#ifdef GENERATORS_WITH_TPCLOOPERS
136bool Generator::initTPCLoopersGen()
140 auto expandPathName = [](
const std::string&
path) {
141 TString expandedPath =
path;
142 gSystem->ExpandPathName(expandedPath);
143 return std::string(expandedPath.Data());
145 std::string model_pairs = expandPathName(loopersParam.model_pairs);
146 std::string model_compton = expandPathName(loopersParam.model_compton);
147 std::string nclxrate = expandPathName(loopersParam.nclxrate);
148 const std::string scaler_pair = expandPathName(loopersParam.scaler_pair);
149 const std::string scaler_compton = expandPathName(loopersParam.scaler_compton);
150 const std::string poisson = expandPathName(loopersParam.poisson);
151 const std::string gauss = expandPathName(loopersParam.gauss);
152 const auto& flat_gas = loopersParam.flat_gas;
153 const auto& colsys = loopersParam.colsys;
155 if (colsys !=
"PbPb" && colsys !=
"pp") {
156 LOG(warning) <<
"Automatic background loopers configuration supports only 'pp' and 'PbPb' systems.";
157 LOG(warning) <<
"Fast loopers generator will remain OFF.";
160 bool isContext = std::filesystem::exists(
"collisioncontext.root");
162 LOG(warning) <<
"Warning: No collisioncontext.root file found!";
163 LOG(warning) <<
"Loopers will be kept OFF.";
170 if (!o2::eventgen::GenTPCLoopers::ownsContextCollisions()) {
171 LOG(info) <<
"All collisions of this simulation are owned by another source of the collision context, which generates their loopers.";
172 LOG(info) <<
"Fast loopers generator will remain OFF.";
175 std::array<float, 2> multiplier = {loopersParam.multiplier[0], loopersParam.multiplier[1]};
176 unsigned int nLoopersPairs = loopersParam.fixedNLoopers[0];
177 unsigned int nLoopersCompton = loopersParam.fixedNLoopers[1];
178 const std::array<std::string, 3> models = {model_pairs, model_compton, nclxrate};
179 const std::array<std::string, 3> local_names = {
"WGANpair.onnx",
"WGANcompton.onnx",
"nclxrate.root"};
180 const std::array<bool, 3> isAlien = {models[0].starts_with(
"alien://"), models[1].starts_with(
"alien://"), models[2].starts_with(
"alien://")};
181 const std::array<bool, 3> isCCDB = {models[0].starts_with(
"ccdb://"), models[1].starts_with(
"ccdb://"), models[2].starts_with(
"ccdb://")};
182 if (std::any_of(isAlien.begin(), isAlien.end(), [](
bool v) { return v; })) {
184 TGrid::Connect(
"alien://");
186 LOG(fatal) <<
"AliEn connection failed, check token.";
190 for (
size_t i = 0;
i < models.size(); ++
i) {
191 if (isAlien[
i] && !TFile::Cp(models[
i].c_str(), local_names[
i].c_str())) {
192 LOG(fatal) <<
"Error: Model file " << models[
i] <<
" does not exist!";
197 if (std::any_of(isCCDB.begin(), isCCDB.end(), [](
bool v) { return v; })) {
199 ccdb.setURL(
"http://alice-ccdb.cern.ch");
201 auto& ccdb_api = ccdb.getCCDBAccessor();
202 for (
size_t i = 0;
i < models.size(); ++
i) {
204 auto model_path = models[
i].substr(7);
206 auto extension = model_path.find(
".onnx");
207 if (extension != std::string::npos) {
208 auto last_slash = model_path.find_last_of(
'/');
209 model_path = model_path.substr(0, last_slash);
211 std::map<std::string, std::string>
filter;
213 LOG(fatal) <<
"Error: issues in retrieving " << model_path <<
" from CCDB!";
219 model_pairs = isAlien[0] || isCCDB[0] ? local_names[0] : model_pairs;
220 model_compton = isAlien[1] || isCCDB[1] ? local_names[1] : model_compton;
221 nclxrate = isAlien[2] || isCCDB[2] ? local_names[2] : nclxrate;
224 mTPCLoopersGen =
new o2::eventgen::GenTPCLoopers(model_pairs, model_compton, poisson, gauss, scaler_pair, scaler_compton);
225 mTPCLoopersGen->setGeomProtection(loopersParam.geomProtection);
226 const auto& intrate = loopersParam.intrate;
230 mTPCLoopersGen->SetRate(nclxrate, (colsys ==
"PbPb") ?
true :
false, intrate);
231 mTPCLoopersGen->SetAdjust(loopersParam.adjust_flatgas);
236 mTPCLoopersGen->SetNLoopers(nLoopersPairs, nLoopersCompton);
237 mTPCLoopersGen->SetMultiplier(multiplier);
239 LOG(info) <<
"TPC Loopers generator initialized successfully";
240 }
catch (
const std::exception&
e) {
241 LOG(
error) <<
"Failed to initialize TPC Loopers generator: " <<
e.what();
242 delete mTPCLoopersGen;
243 mTPCLoopersGen =
nullptr;
266#ifdef GENERATORS_WITH_TPCLOOPERS
267 if (mAddTPCLoopers) {
268 if (!mTPCLoopersGen) {
269 LOG(
error) <<
"Loopers generator not initialized";
274 if (!mTPCLoopersGen->generateEvent()) {
275 LOG(
error) <<
"Failed to generate loopers event";
278 const auto nCandidates = mTPCLoopersGen->getNLoopers();
279 if (nCandidates == 0) {
280 LOG(warning) <<
"No loopers generated for this event";
283 const auto& looperParticles = mTPCLoopersGen->importParticles();
284 const auto skippedLoopers = mTPCLoopersGen->getNSkipped();
285 if (looperParticles.empty()) {
286 if (skippedLoopers == nCandidates) {
288 LOG(
debug) <<
"All " << skippedLoopers <<
" candidate loopers were outside the TPC active volume; none added for this event";
291 LOG(
error) <<
"Failed to import loopers particles";
297 LOG(
debug) <<
"Added " << looperParticles.size() <<
" looper particles";
298 if (skippedLoopers > 0) {
299 LOG(
debug) <<
"Geometrical protection skipped " << skippedLoopers <<
" loopers outside the TPC active volume";
321 mSubGeneratorId = -1;
325 LOG(
error) <<
"ReadEvent failed in generateEvent";
331 LOG(
error) <<
"ReadEvent failed in importParticles";
337 LOG(
error) <<
"ReadEvent failed in finalizeEvent";
341 if (mSubGeneratorsIdToDesc.empty() && mSubGeneratorId > -1) {
342 LOG(fatal) <<
"ReadEvent failed because no SubGenerator description given";
345 if (!mSubGeneratorsIdToDesc.empty() && mSubGeneratorId < 0) {
346 LOG(fatal) <<
"ReadEvent failed because SubGenerator description given but sub-generator not set";
361 LOG(fatal) <<
"MC event header is not a 'o2::dataformats::MCEventHeader' object";
366 if (!decayParticles(o2header)) {
367 LOG(
error) <<
"ReadEvent failed in decayParticles";
373 LOG(
error) <<
"ReadEvent failed in addTracks";
379 updateSubGeneratorInformation(o2header);
390#ifdef GENERATORS_WITH_PYTHIA8
394 if (!mEventDecayer) {
395 mEventDecayer =
new EventDecayer();
396 if (!mEventDecayer->
init()) {
397 LOG(fatal) <<
"Could not initialise the EventDecayer of generator " << GetName();
400 mEventDecayerReport =
new EventDecayerReport();
406 header->putInfo<
int>(
"eventDecayerSeed", mEventDecayer->
seed());
421 LOG(fatal) <<
"PrimaryGenerator is not a o2::eventgen::PrimaryGenerator";
427 o2primGen->
AddTrack(particle.GetPdgCode(),
434 particle.GetMother(0),
435 particle.GetMother(1),
436 particle.GetDaughter(0),
437 particle.GetDaughter(1),
441 particle.GetWeight(),
442 (TMCProcess)particle.GetUniqueID(),
443 particle.GetStatusCode());
515 if (subGeneratorId < 0) {
516 LOG(fatal) <<
"Sub-generator IDs must be >= 0, instead, passed value is " << subGeneratorId;
518 mSubGeneratorsIdToDesc.insert({subGeneratorId, subGeneratorDescription});
525 if (mSubGeneratorId < 0) {
std::vector< std::string > header
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions false
ClassImp(o2::eventgen::Generator)
char error[CURL_ERROR_SIZE]
FairMCEventHeader * GetEvent()
static BasicCCDBManager & instance()
static const GenTPCLoopersParam & Instance()
static SimConfig & Instance()
void setUnits(double positionUnit, double timeUnit, double momentumUnit=1., double energyUnit=1.)
Sets the caller's units in cm, s, GeV/c and GeV, as the unit setters of Generator (default cm,...
EventDecayerReport decay(std::vector< TParticle > &particles)
std::string configSummary() const
virtual void updateHeader(o2::dataformats::MCEventHeader *eventHeader)
std::string mInterfaceName
Bool_t ReadEvent(FairPrimaryGenerator *primGen) final
static std::atomic< int > InstanceCounter
std::vector< Trigger > mTriggers
std::function< void(std::vector< TParticle > const &p, int eventCount)> mTriggerOkHook
virtual Bool_t generateEvent()=0
std::vector< DeepTrigger > mDeepTriggers
std::function< void(std::vector< TParticle > const &p, int eventCount)> mTriggerFalseHook
void addSubGenerator(int subGeneratorId, std::string const &subGeneratorDescription)
ETriggerMode_t mTriggerMode
static bool isHyperloop()
Bool_t addTracks(FairPrimaryGenerator *primGen)
std::vector< TParticle > mParticles
virtual Bool_t importParticles()=0
void AddTrack(Int_t pdgid, Double_t px, Double_t py, Double_t pz, Double_t vx, Double_t vy, Double_t vz, Int_t mother1=-1, Int_t mother2=-1, Int_t daughter1=-1, Int_t daughter2=-1, Bool_t wanttracking=true, Double_t e=-9e9, Double_t tof=0., Double_t weight=0., TMCProcess proc=kPPrimary, Int_t generatorStatus=0)
static constexpr Property SUBGENERATORID
static constexpr Property SUBGENERATORDESCRIPTIONMAP
GLuint const GLchar * name
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
GLsizei const GLchar *const * path
long getCurrentTimestamp()
returns the timestamp in long corresponding to "now"
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
void merge(EventDecayerReport const &other)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"