Project
Loading...
Searching...
No Matches
GeneratorHybrid.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
13#include <chrono>
14#include <fairlogger/Logger.h>
15#include <algorithm>
16#include <tbb/concurrent_queue.h>
17#include <tbb/task_arena.h>
18#include <tbb/parallel_for.h>
20#include <filesystem>
21#include "TGrid.h"
22
23namespace o2
24{
25namespace eventgen
26{
27
28GeneratorHybrid& GeneratorHybrid::Instance(const std::string& inputgens)
29{
30 static GeneratorHybrid instance(inputgens);
31 return instance;
32}
33
34GeneratorHybrid::GeneratorHybrid(const std::string& inputgens)
35{
36 // This generator has trivial unit conversions
37 setTimeUnit(1.);
40 setEnergyUnit(1.);
41
42 // Pull file from alien for dynamic configuration if needed
43 bool isAlien = false;
44 if (inputgens.starts_with("alien://")) {
45 if (!gGrid) {
46 TGrid::Connect("alien://");
47 if (!gGrid) {
48 LOG(fatal) << "AliEn connection failed, check token.";
49 exit(1);
50 }
51 }
52 TString aliencp = Form("alien_cp %s file:./%s",
53 inputgens.c_str(), "hybridAlien.json");
54 if (gSystem->Exec(aliencp.Data()) != 0) {
55 LOG(fatal) << "Error: Issues in fetching file" << inputgens;
56 exit(1);
57 }
58 isAlien = true;
59 }
60
61 if (!parseJSON(isAlien ? "hybridAlien.json" : inputgens)) {
62 LOG(fatal) << "Failed to parse JSON configuration from input generators";
63 exit(1);
64 }
65 mRandomize = GeneratorHybridParam::Instance().randomize;
66 if (mConfigs.size() != mInputGens.size()) {
67 LOG(fatal) << "Number of configurations does not match the number of generators";
68 exit(1);
69 }
70 if (mConfigs.size() == 0) {
71 for (auto gen : mInputGens) {
72 mConfigs.push_back("");
73 }
74 }
75 int index = 0;
76 if (!(mRandomize || mGenerationMode == GenMode::kParallel)) {
77 if (mCocktailMode) {
78 if (mGroups.size() != mFractions.size()) {
79 LOG(fatal) << "Number of groups does not match the number of fractions";
80 return;
81 }
82 } else {
83 if (mFractions.size() != mInputGens.size()) {
84 LOG(fatal) << "Number of fractions does not match the number of generators";
85 return;
86 }
87 }
88 // Check if all elements of mFractions are 0
89 if (std::all_of(mFractions.begin(), mFractions.end(), [](int i) { return i == 0; })) {
90 LOG(fatal) << "All fractions provided are 0, no simulation will be performed";
91 return;
92 }
93 }
94 for (auto gen : mInputGens) {
95 // Search if the generator name is inside generatorNames (which is a vector of strings)
96 LOG(info) << "Checking if generator " << gen << " is in the list of available generators \n";
97 if (std::find(generatorNames.begin(), generatorNames.end(), gen) != generatorNames.end()) {
98 LOG(info) << "Found generator " << gen << " in the list of available generators \n";
99 if (gen.compare("boxgen") == 0) {
100 if (mConfigs[index].compare("") == 0) {
101 gens.push_back(std::make_shared<o2::eventgen::BoxGenerator>());
102 } else {
103 // Get the index of boxgen configuration
104 int confBoxIndex = std::stoi(mConfigs[index].substr(7));
105 gens.push_back(std::make_shared<o2::eventgen::BoxGenerator>(*mBoxGenConfigs[confBoxIndex]));
106 }
107 mGens.push_back(gen);
108 } else if (gen.compare(0, 7, "pythia8") == 0) {
109 // Check if mConfigs[index] contains pythia8_ and a number
110 if (mConfigs[index].compare("") == 0) {
111 auto pars = Pythia8GenConfig();
112 gens.push_back(std::make_shared<o2::eventgen::GeneratorPythia8>(pars));
113 } else {
114 // Get the index of pythia8 configuration
115 int confPythia8Index = std::stoi(mConfigs[index].substr(8));
116 gens.push_back(std::make_shared<o2::eventgen::GeneratorPythia8>(*mPythia8GenConfigs[confPythia8Index]));
117 }
118 mConfsPythia8.push_back(mConfigs[index]);
119 mGens.push_back(gen);
120 } else if (gen.compare("evtpool") == 0) {
121 int confEvtPoolIndex = std::stoi(mConfigs[index].substr(8));
122 gens.push_back(std::make_shared<o2::eventgen::GeneratorFromEventPool>(mEventPoolConfigs[confEvtPoolIndex]));
123 mGens.push_back(gen);
124 } else if (gen.compare("external") == 0) {
125 int confextIndex = std::stoi(mConfigs[index].substr(9));
126 // Hybrid configs can clone the same external generator config multiple times so
127 // an external macro that self-seeds from gRandom could sample the same seed.
128 // For this reason the shared RNG state is advanced as a precaution
129 // mirroring what GeneratorPythia8::seedGenerator() does for multiple Pythia8 instances.
130 if (std::count(mGens.begin(), mGens.end(), "external") > 0) {
131 gRandom->Rndm();
132 }
133 // we need analyse the ini file to update the config key param
134 if (mExternalGenConfigs[confextIndex]->iniFile.size() > 0) {
135 LOG(info) << "Setting up external gen using the given INI file";
136
137 // this means that we go via the ConfigurableParam system ---> in order not to interfere with other
138 // generators we use an approach with backup and restore of the system
139
140 // we write the current state to a file
141 // create a tmp file name
142 std::string tmp_config_file = "configkey_tmp_backup_" + std::to_string(getpid()) + std::string(".ini");
144
145 auto expandedFileName = o2::utils::expandShellVarsInFileName(mExternalGenConfigs[confextIndex]->iniFile);
147 // toDo: check that this INI file makes sense
148
150 LOG(info) << "Setting up external generator with following parameters";
151 LOG(info) << params;
152 auto extgen_filename = params.fileName;
153 auto extgen_func = params.funcName;
154 auto extgen = std::shared_ptr<o2::eventgen::Generator>(o2::conf::GetFromMacro<o2::eventgen::Generator*>(extgen_filename, extgen_func, "FairGenerator*", "extgen"));
155 if (!extgen) {
156 LOG(fatal) << "Failed to retrieve \'extgen\': problem with configuration ";
157 }
158 // restore old state
160 // delete tmp file
161 std::filesystem::remove(tmp_config_file);
162
163 gens.push_back(std::move(extgen));
164 mGens.push_back(gen);
165 } else {
166 LOG(info) << "Setting up external gen using the given fileName and funcName";
167 // we need to restore the config key param system to what is was before
168 auto& extgen_filename = mExternalGenConfigs[confextIndex]->fileName;
169 auto& extgen_func = mExternalGenConfigs[confextIndex]->funcName;
170 auto extGen = std::shared_ptr<o2::eventgen::Generator>(o2::conf::GetFromMacro<o2::eventgen::Generator*>(extgen_filename, extgen_func, "FairGenerator*", "extgen"));
171 if (!extGen) {
172 LOG(fatal) << "Failed to load external generator from " << extgen_filename << " with function " << extgen_func;
173 }
174 gens.push_back(std::move(extGen));
175 mGens.push_back(gen);
176 }
177 } else if (gen.compare("hepmc") == 0) {
178 int confHepMCIndex = std::stoi(mConfigs[index].substr(6));
179 gens.push_back(std::make_shared<o2::eventgen::GeneratorHepMC>());
180 auto& globalConfig = o2::conf::SimConfig::Instance();
181 dynamic_cast<o2::eventgen::GeneratorHepMC*>(gens.back().get())->setup(*mFileOrCmdGenConfigs[confHepMCIndex], *mHepMCGenConfigs[confHepMCIndex], globalConfig);
182 mGens.push_back(gen);
183 }
184 } else {
185 LOG(fatal) << "Generator " << gen << " not found in the list of available generators \n";
186 exit(1);
187 }
188 index++;
189 }
190}
191
192GeneratorHybrid::~GeneratorHybrid()
193{
194 LOG(info) << "Destructor of generator hybrid called";
195 // stop() is the designated shutdown hook (called via GeneratorService::stopGenerators),
196 // normally running end-of-stream, in which case this is a no-op. It is not reached on every exit path, e.g. when the
197 // driver quits before the event budget or the TTL is up, so it is repeated here.
198 stop();
199}
200
202{
203 mStopFlag = true;
204 // The worker lambdas reference mInputTaskQueue, mResultQueue and mTaskArena, which are
205 // destroyed together with this object, so they must not be left running.
206 // We wait for the thread to finish, which will happen once the worker lambdas notice mStopFlag.
207 if (mTBBTaskPoolRunner.joinable()) {
208 auto t0 = std::chrono::steady_clock::now();
209 mTBBTaskPoolRunner.join();
210 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count();
211 LOG(info) << "HybridGen: stop() joined TBB task pool after " << ms << " ms";
212 }
213 // Forward the hook to the sub-generators
214 for (auto& gen : gens) {
215 if (gen) {
216 gen->stop();
217 }
218 }
219}
220
222{
223 // protection against additional Init() which would assign over a joinable mTBBTaskPoolRunner, which calls std::terminate
224 if (mIsInitialized) {
225 return true;
226 }
227 // init all sub-gens
228 int count = 0;
229 for (auto& gen : mGens) {
230 if (gen == "pythia8pp") {
231 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_inel.cfg";
232 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
233 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
234 } else if (gen == "pythia8hf") {
235 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_hf.cfg";
236 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
237 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
238 } else if (gen == "pythia8hi") {
239 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_hi.cfg";
240 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
241 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
242 } else if (gen == "pythia8powheg") {
243 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_powheg.cfg";
244 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
245 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
246 }
247 gens[count]->Init(); // TODO: move this to multi-threaded
249 if (mTriggerModes[count] != o2::eventgen::Generator::kTriggerOFF) {
250 gens[count]->setTriggerMode(mTriggerModes[count]);
251 LOG(info) << "Setting Trigger mode of generator " << gen << " to: " << mTriggerModes[count];
252 o2::eventgen::Trigger trigger = nullptr;
253 o2::eventgen::DeepTrigger deeptrigger = nullptr;
254 for (int trg = 0; trg < mTriggerMacros[count].size(); trg++) {
255 if (mTriggerMacros[count][trg].empty() || mTriggerFuncs[count][trg].empty()) {
256 continue;
257 }
258 std::string expandedMacro = o2::utils::expandShellVarsInFileName(mTriggerMacros[count][trg]);
259 LOG(info) << "Setting trigger " << trg << " of generator " << gen << " with following parameters";
260 LOG(info) << "Macro filename: " << expandedMacro;
261 LOG(info) << "Function name: " << mTriggerFuncs[count][trg];
262 trigger = o2::conf::GetFromMacro<o2::eventgen::Trigger>(expandedMacro, mTriggerFuncs[count][trg], "o2::eventgen::Trigger", "trigger");
263 if (!trigger) {
264 LOG(info) << "Trying to retrieve a \'o2::eventgen::DeepTrigger\' type";
265 deeptrigger = o2::conf::GetFromMacro<o2::eventgen::DeepTrigger>(expandedMacro, mTriggerFuncs[count][trg], "o2::eventgen::DeepTrigger", "deeptrigger");
266 }
267 if (!trigger && !deeptrigger) {
268 LOG(warn) << "Failed to retrieve \'external trigger\': problem with configuration";
269 LOG(warn) << "Trigger " << trg << " of generator " << gen << " will not be included";
270 continue;
271 } else {
272 LOG(info) << "Trigger " << trg << " of generator " << gen << " successfully set";
273 }
274 if (trigger) {
275 gens[count]->addTrigger(trigger);
276 } else {
277 gens[count]->addDeepTrigger(deeptrigger);
278 }
279 }
280 }
281 count++;
282 }
283 // Label for groups: concatenation of the names of the generators in the group, separated by '+'.
284 // Currently used only if randomisation is enabled
285 auto groupLabel = [this](int k) {
286 std::string label;
287 for (auto subIndex : mGroups[k]) {
288 if (!label.empty()) {
289 label += "+";
290 }
291 label += (mConfigs[subIndex] == "" ? mGens[subIndex] : mConfigs[subIndex]);
292 }
293 return label;
294 };
295 if (mRandomize) {
296 if (std::all_of(mFractions.begin(), mFractions.end(), [](int i) { return i == 1; })) {
297 LOG(info) << "Full randomisation of generators order";
298 } else {
299 LOG(info) << "Randomisation based on fractions";
300 int allfracs = 0;
301 for (auto& f : mFractions) {
302 allfracs += f;
303 }
304 // Assign new rng fractions
305 float sum = 0;
306 float chance = 0;
307 for (int k = 0; k < mFractions.size(); k++) {
308 if (mFractions[k] == 0) {
309 // Generator will not be used if fraction is 0
310 mRngFractions.push_back(-1);
311 LOG(info) << "Generator " << groupLabel(k) << " will not be used";
312 } else {
313 chance = static_cast<float>(mFractions[k]) / allfracs;
314 sum += chance;
315 mRngFractions.push_back(sum);
316 LOG(info) << "Generator " << groupLabel(k) << " has a " << chance * 100 << "% chance of being used";
317 }
318 }
319 }
320 } else {
321 LOG(info) << "Generators will be used in sequence, following provided fractions";
322 }
323
324 mGenIsInitialized.resize(gens.size(), false);
325 if (mGenerationMode == GenMode::kParallel) {
326 // in parallel mode we just use one queue --> collaboration
327 mResultQueue.resize(1);
328 } else {
329 // in sequential mode we have one queue per generator
330 mResultQueue.resize(gens.size());
331 }
332 // Create a task arena with a specified number of threads
333 mTaskArena.initialize(GeneratorHybridParam::Instance().num_workers);
334
335 // the process task function actually calls event generation
336 // when it is done it notifies the outside world by pushing it's index into an appropriate queue
337 // This should be a lambda, which can be given at TaskPool creation time
338 auto process_generator_task = [this](std::vector<std::shared_ptr<o2::eventgen::Generator>> const& generatorvec, int task) {
339 LOG(debug) << "Starting eventgen for task " << task;
340 auto& generator = generatorvec[task];
341 if (!mStopFlag) {
342 // TODO: activate this once we are use Init is threadsafe
343 // if (!mGenIsInitialized[task]) {
344 // if(!generator->Init()) {
345 // LOG(error) << "failed to init generator " << task;
346 // }
347 // mGenIsInitialized[task] = true;
348 // }
349 }
350 bool isTriggered = false;
351 while (!isTriggered && !mStopFlag) {
352 generator->clearParticles();
353 generator->generateEvent();
354 generator->importParticles();
355 isTriggered = generator->triggerEvent();
356 }
357 LOG(debug) << "eventgen finished for task " << task;
358 if (!mStopFlag) {
359 if (mGenerationMode == GenMode::kParallel) {
360 mResultQueue[0].push(task);
361 } else {
362 mResultQueue[task].push(task);
363 }
364 }
365 };
366
367 // fundamental tbb thread-worker function
368 auto worker_function = [this, process_generator_task]() {
369 // we increase the reference count in the generator pointers
370 // by making a copy of the vector. In this way we ensure that the lifetime
371 // of the generators is no shorter than the lifetime of the thread for this worker function
372 auto generators_copy = gens;
373
374 while (!mStopFlag) {
375 int task;
376 if (mInputTaskQueue.try_pop(task)) {
377 process_generator_task(generators_copy, task); // Process the task
378 } else {
379 std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Wait if no task
380 }
381 }
382 };
383
384 // let the TBB task system run in it's own thread
385 mTBBTaskPoolRunner = std::thread([this, worker_function]() { mTaskArena.execute([&]() { tbb::parallel_for(0, mTaskArena.max_concurrency(), [&](int) { worker_function(); }); }); });
386 // NOTE: thread deliberately NOT detached. We never wait for it during the run, but the
387 // pool must be joined in the destructor before the queues and the arena are destroyed.
388
389 // let's also push initial generation tasks for each event generator
390 for (size_t genindex = 0; genindex < gens.size(); ++genindex) {
391 mInputTaskQueue.push(genindex);
392 mTasksStarted++;
393 }
394 mIsInitialized = true;
395 return Generator::Init();
396}
397
399{
400 if (!mIsInitialized) {
401 Init();
402 }
403 if (mGenerationMode == GenMode::kParallel) {
404 mIndex = -1; // this means any index is welcome
405 notifySubGenerator(0); // we shouldn't distinguish the sub-gen ids
406 } else {
407 // Order randomisation or sequence of generators
408 // following provided fractions, if not generators are used in proper sequence
409 // Order randomisation or sequence of generators
410 // following provided fractions. If not available generators will be used sequentially
411 if (mRandomize) {
412 if (mRngFractions.size() != 0) {
413 // Generate number between 0 and 1
414 float rnum = gRandom->Rndm();
415 // Find generator index
416 for (int k = 0; k < mRngFractions.size(); k++) {
417 if (rnum <= mRngFractions[k]) {
418 mIndex = k;
419 break;
420 }
421 }
422 } else {
423 mIndex = gRandom->Integer(mFractions.size());
424 }
425 } else {
426 while (mFractions[mCurrentFraction] == 0 || mseqCounter == mFractions[mCurrentFraction]) {
427 if (mFractions[mCurrentFraction] != 0) {
428 mseqCounter = 0;
429 }
430 mCurrentFraction = (mCurrentFraction + 1) % mFractions.size();
431 }
432 mIndex = mCurrentFraction;
433 }
434 notifySubGenerator(mIndex);
435 }
436 return true;
437}
438
440{
441 int genIndex = -1;
442 std::vector<int> subGenIndex = {};
443 if (mIndex == -1) {
444 // this means parallel mode ---> we have a common queue
445 mResultQueue[0].pop(genIndex);
446 } else {
447 // need to pop from a particular queue
448 if (!mCocktailMode) {
449 mResultQueue[mIndex].pop(genIndex);
450 } else {
451 // in cocktail mode we need to pop from the group queue
452 subGenIndex.resize(mGroups[mIndex].size());
453 for (size_t pos = 0; pos < mGroups[mIndex].size(); ++pos) {
454 int subIndex = mGroups[mIndex][pos];
455 LOG(info) << "Getting generator " << mGens[subIndex] << " from cocktail group " << mIndex;
456 mResultQueue[subIndex].pop(subGenIndex[pos]);
457 }
458 }
459 }
460
461 auto unit_transformer = [](auto& p, auto pos_unit, auto time_unit, auto en_unit, auto mom_unit) {
462 p.SetMomentum(p.Px() * mom_unit, p.Py() * mom_unit, p.Pz() * mom_unit, p.Energy() * en_unit);
463 p.SetProductionVertex(p.Vx() * pos_unit, p.Vy() * pos_unit, p.Vz() * pos_unit, p.T() * time_unit);
464 };
465
466 auto index_transformer = [](auto& p, int offset) {
467 for (int i = 0; i < 2; ++i) {
468 if (p.GetMother(i) != -1) {
469 const auto newindex = p.GetMother(i) + offset;
470 p.SetMother(i, newindex);
471 }
472 }
473 if (p.GetNDaughters() > 0) {
474 for (int i = 0; i < 2; ++i) {
475 const auto newindex = p.GetDaughter(i) + offset;
476 p.SetDaughter(i, newindex);
477 }
478 }
479 };
480
481 // Clear particles and event header
482 mParticles.clear();
483 // event header of underlying generator must be fully reset
484 // this is important when using event pools where the full header information is forwarded from the generator
485 // otherwise some events might have mixed header information from different generators
486 mMCEventHeader.Reset();
487 // Once the event budget is exhausted there is no further event to prepare, and re-queueing a
488 // sub-generator would start an event nobody consumes and that stop() then has to wait for
489 const bool queueNextEvent = getTotalNEvents() == 0 || mEventCounter + 1 < getTotalNEvents();
490 if (mCocktailMode) {
491 // in cocktail mode we need to merge the particles from the different generators
492 for (auto subIndex : subGenIndex) {
493 if (!mIsHyperloop) {
494 LOG(info) << "Importing particles for task " << subIndex;
495 }
496 auto subParticles = gens[subIndex]->getParticles();
497
498 auto time_unit = gens[subIndex]->getTimeUnit();
499 auto pos_unit = gens[subIndex]->getPositionUnit();
500 auto mom_unit = gens[subIndex]->getMomentumUnit();
501 auto energy_unit = gens[subIndex]->getEnergyUnit();
502
503 // The particles carry mother and daughter indices, which are relative
504 // to the sub-generator. We need to adjust these indices to reflect that particles
505 // are now embedded into a cocktail.
506 auto offset = mParticles.size();
507 for (auto& p : subParticles) {
508 // apply the mother-daugher index transformation
509 index_transformer(p, offset);
510 // apply unit transformation of sub-generator
511 unit_transformer(p, pos_unit, time_unit, energy_unit, mom_unit);
512 }
513
514 mParticles.insert(mParticles.end(), subParticles.begin(), subParticles.end());
515 // first generator of the cocktail is used as reference to update the event header information
516 if (mHeaderGeneratorIndex == -1) {
517 gens[subIndex]->updateHeader(&mMCEventHeader);
518 mHeaderGeneratorIndex = subIndex; // store index of generator updating the header
519 }
520 if (queueNextEvent) {
521 mInputTaskQueue.push(subIndex);
522 mTasksStarted++;
523 }
524 }
525 } else {
526 if (!mIsHyperloop) {
527 LOG(info) << "Importing particles for task " << genIndex;
528 }
529 // at this moment the mIndex-th generator is ready to be used
530 mParticles = gens[genIndex]->getParticles();
531
532 auto time_unit = gens[genIndex]->getTimeUnit();
533 auto pos_unit = gens[genIndex]->getPositionUnit();
534 auto mom_unit = gens[genIndex]->getMomentumUnit();
535 auto energy_unit = gens[genIndex]->getEnergyUnit();
536
537 // transform units to units of the hybrid generator
538 for (auto& p : mParticles) {
539 // apply unit transformation
540 unit_transformer(p, pos_unit, time_unit, energy_unit, mom_unit);
541 }
542
543 // fetch the event Header information from the underlying generator
544 gens[genIndex]->updateHeader(&mMCEventHeader);
545 mHeaderGeneratorIndex = genIndex; // store index of generator updating the header
546 if (queueNextEvent) {
547 mInputTaskQueue.push(genIndex);
548 mTasksStarted++;
549 }
550 }
551
552 mseqCounter++;
553 mEventCounter++;
554 if (mEventCounter == getTotalNEvents()) {
555 LOG(info) << "HybridGen: Stopping TBB task pool";
556 mStopFlag = true;
557 }
558
559 return true;
560}
561
563{
564 if (eventHeader) {
565 // Overwrite current vertex information to the underlying generator header,
566 // otherwise the info will be dropped when copying the FairMCEventHeader part of the header
567 mMCEventHeader.SetVertex(eventHeader->GetX(), eventHeader->GetY(), eventHeader->GetZ());
568 mHeaderGeneratorIndex = -1; // reset header generator index for next event
569 // Forward the base class fields from FairMCEventHeader
570 static_cast<FairMCEventHeader&>(*eventHeader) = static_cast<FairMCEventHeader&>(mMCEventHeader);
571 // Copy the key-value store info
572 eventHeader->copyInfoFrom(mMCEventHeader);
573
574 // put additional information about
575 eventHeader->putInfo<std::string>("forwarding-generator", "HybridGen");
576 }
577}
578
579template <typename T>
581{
582 rapidjson::StringBuffer buffer;
583 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
584 value.Accept(writer);
585 return buffer.GetString();
586}
587
589{
590 std::string name = gen["name"].GetString();
591 mInputGens.push_back(name);
592 if (gen.HasMember("config")) {
593 if (name == "boxgen") {
594 const auto& boxconf = gen["config"];
595 auto boxConfig = TBufferJSON::FromJSON<o2::eventgen::BoxGenConfig>(jsonValueToString(boxconf).c_str());
596 mBoxGenConfigs.push_back(std::move(boxConfig));
597 mConfigs.push_back("boxgen_" + std::to_string(mBoxGenConfigs.size() - 1));
598 } else if (name == "pythia8") {
599 const auto& pythia8conf = gen["config"];
600 auto pythia8Config = TBufferJSON::FromJSON<o2::eventgen::Pythia8GenConfig>(jsonValueToString(pythia8conf).c_str());
601 mPythia8GenConfigs.push_back(std::move(pythia8Config));
602 mConfigs.push_back("pythia8_" + std::to_string(mPythia8GenConfigs.size() - 1));
603 } else if (name == "evtpool") {
604 const auto& o2kineconf = gen["config"];
605 auto poolConfig = TBufferJSON::FromJSON<o2::eventgen::EventPoolGenConfig>(jsonValueToString(o2kineconf).c_str());
606 mEventPoolConfigs.push_back(*poolConfig);
607 mConfigs.push_back("evtpool_" + std::to_string(mEventPoolConfigs.size() - 1));
608 } else if (name == "external") {
609 const auto& extconf = gen["config"];
610 auto extConfig = TBufferJSON::FromJSON<o2::eventgen::ExternalGenConfig>(jsonValueToString(extconf).c_str());
611 mExternalGenConfigs.push_back(std::move(extConfig));
612 mConfigs.push_back("external_" + std::to_string(mExternalGenConfigs.size() - 1));
613 } else if (name == "hepmc") {
614 const auto& genconf = gen["config"];
615 const auto& cmdconf = genconf["configcmd"];
616 const auto& hepmcconf = genconf["confighepmc"];
617 auto cmdConfig = TBufferJSON::FromJSON<o2::eventgen::FileOrCmdGenConfig>(jsonValueToString(cmdconf).c_str());
618 auto hepmcConfig = TBufferJSON::FromJSON<o2::eventgen::HepMCGenConfig>(jsonValueToString(hepmcconf).c_str());
619 mFileOrCmdGenConfigs.push_back(std::move(cmdConfig));
620 mHepMCGenConfigs.push_back(std::move(hepmcConfig));
621 mConfigs.push_back("hepmc_" + std::to_string(mFileOrCmdGenConfigs.size() - 1));
622 } else {
623 mConfigs.push_back("");
624 }
625 } else {
626 if (name == "boxgen" || name == "pythia8" || name == "external" || name == "hepmc") {
627 LOG(fatal) << "No configuration provided for generator " << name;
628 return false;
629 } else {
630 mConfigs.push_back("");
631 }
632 }
633 if (gen.HasMember("triggers")) {
634 const auto& trigger = gen["triggers"];
635 auto trigger_specs = [this, &trigger]() {
636 mTriggerMacros.push_back({});
637 mTriggerFuncs.push_back({});
638 if (trigger.HasMember("specs")) {
639 for (auto& spec : trigger["specs"].GetArray()) {
640 if (spec.HasMember("macro")) {
641 const auto& macro = spec["macro"].GetString();
642 if (!(strcmp(macro, "") == 0)) {
643 mTriggerMacros.back().push_back(macro);
644 } else {
645 mTriggerMacros.back().push_back("");
646 }
647 } else {
648 mTriggerMacros.back().push_back("");
649 }
650 if (spec.HasMember("function")) {
651 const auto& function = spec["function"].GetString();
652 if (!(strcmp(function, "") == 0)) {
653 mTriggerFuncs.back().push_back(function);
654 } else {
655 mTriggerFuncs.back().push_back("");
656 }
657 } else {
658 mTriggerFuncs.back().push_back("");
659 }
660 }
661 } else {
662 mTriggerMacros.back().push_back("");
663 mTriggerFuncs.back().push_back("");
664 }
665 };
666 if (trigger.HasMember("mode")) {
667 const auto& trmode = trigger["mode"].GetString();
668 if (strcmp(trmode, "or") == 0) {
669 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOR);
670 trigger_specs();
671 } else if (strcmp(trmode, "and") == 0) {
672 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerAND);
673 trigger_specs();
674 } else if (strcmp(trmode, "off") == 0) {
675 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
676 mTriggerMacros.push_back({""});
677 mTriggerFuncs.push_back({""});
678 } else {
679 LOG(warn) << "Wrong trigger mode provided for generator " << name << ", keeping trigger OFF";
680 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
681 mTriggerMacros.push_back({""});
682 mTriggerFuncs.push_back({""});
683 }
684 } else {
685 LOG(warn) << "No trigger mode provided for generator " << name << ", turning trigger OFF";
686 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
687 mTriggerMacros.push_back({""});
688 mTriggerFuncs.push_back({""});
689 }
690 } else {
691 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
692 mTriggerMacros.push_back({""});
693 mTriggerFuncs.push_back({""});
694 }
695 return true;
696}
697
698Bool_t GeneratorHybrid::parseJSON(const std::string& path)
699{
700 auto expandedPath = o2::utils::expandShellVarsInFileName(path);
701 // Check if configuration file exists
702 if (gSystem->AccessPathName(expandedPath.c_str())) {
703 LOG(fatal) << "Configuration file " << expandedPath << " for hybrid generator does not exist";
704 return false;
705 }
706 // Parse JSON file to build map
707 std::ifstream fileStream(expandedPath, std::ios::in);
708 if (!fileStream.is_open()) {
709 LOG(error) << "Cannot open " << expandedPath;
710 return false;
711 }
712 rapidjson::IStreamWrapper isw(fileStream);
713 rapidjson::Document doc;
714 doc.ParseStream(isw);
715 if (doc.HasParseError()) {
716 LOG(error) << "Error parsing provided json file " << expandedPath;
717 LOG(error) << " - Error -> " << rapidjson::GetParseError_En(doc.GetParseError());
718 return false;
719 }
720
721 // check if there is a mode field
722 if (doc.HasMember("mode")) {
723 const auto& mode = doc["mode"].GetString();
724 if (strcmp(mode, "sequential") == 0) {
725 // events are generated in the order given by fractions or random weight
726 mGenerationMode = GenMode::kSeq;
727 }
728 if (strcmp(mode, "parallel") == 0) {
729 // events are generated fully in parallel and the order will be random
730 // this is mainly for event pool generation or mono-type generators
731 mGenerationMode = GenMode::kParallel;
732 LOG(info) << "Setting mode to parallel";
733 }
734 }
735
736 // Put the generator names in mInputGens
737 if (doc.HasMember("generators")) {
738 const auto& gens = doc["generators"];
739 for (const auto& gen : gens.GetArray()) {
740 mGroups.push_back({});
741 // Check if gen is an array (cocktail mode)
742 if (gen.HasMember("cocktail")) {
743 mCocktailMode = true;
744 for (const auto& subgen : gen["cocktail"].GetArray()) {
745 if (confSetter(subgen)) {
746 mGroups.back().push_back(mInputGens.size() - 1);
747 } else {
748 return false;
749 }
750 }
751 } else {
752 if (!confSetter(gen)) {
753 return false;
754 }
755 // Groups are created in case cocktail mode is activated, this way
756 // cocktails can be declared anywhere in the JSON file, without the need
757 // of grouping single generators. If no cocktail is defined
758 // groups will be ignored nonetheless.
759 mGroups.back().push_back(mInputGens.size() - 1);
760 }
761 }
762 }
763
764 // Get fractions and put them in mFractions
765 if (doc.HasMember("fractions")) {
766 const auto& fractions = doc["fractions"];
767 for (const auto& frac : fractions.GetArray()) {
768 if (!frac.IsInt()) {
769 LOG(fatal) << "Fractions must be integers. Wrong type found in JSON";
770 return false;
771 }
772 mFractions.push_back(frac.GetInt());
773 }
774 } else {
775 // Set fractions to unity for all generators in case they are not provided
776 const auto& gens = doc["generators"];
777 for (const auto& gen : gens.GetArray()) {
778 mFractions.push_back(1);
779 }
780 }
781 return true;
782}
783
784} // namespace eventgen
785} // namespace o2
786
default_random_engine gen(dev())
std::ostringstream debug
std::vector< double > sum
int32_t i
ClassImp(o2::eventgen::GeneratorHybrid)
char error[CURL_ERROR_SIZE]
uint16_t pos
Definition RawData.h:3
Double_t GetX() const
event identifier
void SetVertex(Double_t x, Double_t y, Double_t z)
Double_t GetY() const
vertex x [cm]
Double_t GetZ() const
vertex y [cm]
static void writeINI(std::string const &filename, std::string const &keyOnly="")
static void updateFromFile(std::string const &, std::string const &paramsList="", bool unchangedOnly=false)
static SimConfig & Instance()
Definition SimConfig.h:112
void copyInfoFrom(MCEventHeader const &other)
inits info fields from another Event header
void putInfo(std::string const &key, T const &value)
GeneratorHybrid(const GeneratorHybrid &)=delete
Bool_t parseJSON(const std::string &path)
std::string jsonValueToString(const T &value)
void updateHeader(o2::dataformats::MCEventHeader *eventHeader) override
static GeneratorHybrid & Instance(const std::string &inputgens="")
Bool_t confSetter(const auto &gen)
void setPositionUnit(double val)
Definition Generator.h:89
void setEnergyUnit(double val)
Definition Generator.h:87
void notifySubGenerator(int subGeneratorId)
Definition Generator.h:137
static unsigned int getTotalNEvents()
Definition Generator.h:102
void setTimeUnit(double val)
Definition Generator.h:91
void addSubGenerator(int subGeneratorId, std::string const &subGeneratorDescription)
std::vector< TParticle > mParticles
Definition Generator.h:161
void setMomentumUnit(double val)
Definition Generator.h:85
Bool_t Init() override
GLint GLsizei count
Definition glcorearb.h:399
GLuint buffer
Definition glcorearb.h:655
GLsizeiptr size
Definition glcorearb.h:659
GLuint const GLchar * name
Definition glcorearb.h:781
GLdouble f
Definition glcorearb.h:310
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLenum const GLfloat * params
Definition glcorearb.h:272
GLintptr offset
Definition glcorearb.h:660
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
GLsizei const GLchar *const * path
Definition glcorearb.h:3591
GLuint GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat t0
Definition glcorearb.h:5034
std::function< bool(void *, std::string)> DeepTrigger
Definition Trigger.h:26
std::function< bool(const std::vector< TParticle > &)> Trigger
Definition Trigger.h:25
std::string expandShellVarsInFileName(std::string const &input)
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
std::string to_string(gsl::span< T, Size > span)
Definition common.h:52
void empty(int)
void compare(std::string_view s1, std::string_view s2)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"