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 <fairlogger/Logger.h>
14#include <algorithm>
15#include <tbb/concurrent_queue.h>
16#include <tbb/task_arena.h>
17#include <tbb/parallel_for.h>
19#include <filesystem>
20
21namespace o2
22{
23namespace eventgen
24{
25
26GeneratorHybrid& GeneratorHybrid::Instance(const std::string& inputgens)
27{
28 static GeneratorHybrid instance(inputgens);
29 return instance;
30}
31
32GeneratorHybrid::GeneratorHybrid(const std::string& inputgens)
33{
34 // This generator has trivial unit conversions
35 setTimeUnit(1.);
38 setEnergyUnit(1.);
39
40 if (!parseJSON(inputgens)) {
41 LOG(fatal) << "Failed to parse JSON configuration from input generators";
42 exit(1);
43 }
44 mRandomize = GeneratorHybridParam::Instance().randomize;
45 if (mConfigs.size() != mInputGens.size()) {
46 LOG(fatal) << "Number of configurations does not match the number of generators";
47 exit(1);
48 }
49 if (mConfigs.size() == 0) {
50 for (auto gen : mInputGens) {
51 mConfigs.push_back("");
52 }
53 }
54 int index = 0;
55 if (!(mRandomize || mGenerationMode == GenMode::kParallel)) {
56 if (mCocktailMode) {
57 if (mGroups.size() != mFractions.size()) {
58 LOG(fatal) << "Number of groups does not match the number of fractions";
59 return;
60 }
61 } else {
62 if (mFractions.size() != mInputGens.size()) {
63 LOG(fatal) << "Number of fractions does not match the number of generators";
64 return;
65 }
66 }
67 // Check if all elements of mFractions are 0
68 if (std::all_of(mFractions.begin(), mFractions.end(), [](int i) { return i == 0; })) {
69 LOG(fatal) << "All fractions provided are 0, no simulation will be performed";
70 return;
71 }
72 }
73 for (auto gen : mInputGens) {
74 // Search if the generator name is inside generatorNames (which is a vector of strings)
75 LOG(info) << "Checking if generator " << gen << " is in the list of available generators \n";
76 if (std::find(generatorNames.begin(), generatorNames.end(), gen) != generatorNames.end()) {
77 LOG(info) << "Found generator " << gen << " in the list of available generators \n";
78 if (gen.compare("boxgen") == 0) {
79 if (mConfigs[index].compare("") == 0) {
80 gens.push_back(std::make_shared<o2::eventgen::BoxGenerator>());
81 } else {
82 // Get the index of boxgen configuration
83 int confBoxIndex = std::stoi(mConfigs[index].substr(7));
84 gens.push_back(std::make_shared<o2::eventgen::BoxGenerator>(*mBoxGenConfigs[confBoxIndex]));
85 }
86 mGens.push_back(gen);
87 } else if (gen.compare(0, 7, "pythia8") == 0) {
88 // Check if mConfigs[index] contains pythia8_ and a number
89 if (mConfigs[index].compare("") == 0) {
90 auto pars = Pythia8GenConfig();
91 gens.push_back(std::make_shared<o2::eventgen::GeneratorPythia8>(pars));
92 } else {
93 // Get the index of pythia8 configuration
94 int confPythia8Index = std::stoi(mConfigs[index].substr(8));
95 gens.push_back(std::make_shared<o2::eventgen::GeneratorPythia8>(*mPythia8GenConfigs[confPythia8Index]));
96 }
97 mConfsPythia8.push_back(mConfigs[index]);
98 mGens.push_back(gen);
99 } else if (gen.compare("extkinO2") == 0) {
100 int confO2KineIndex = std::stoi(mConfigs[index].substr(9));
101 gens.push_back(std::make_shared<o2::eventgen::GeneratorFromO2Kine>(*mO2KineGenConfigs[confO2KineIndex]));
102 mGens.push_back(gen);
103 } else if (gen.compare("evtpool") == 0) {
104 int confEvtPoolIndex = std::stoi(mConfigs[index].substr(8));
105 gens.push_back(std::make_shared<o2::eventgen::GeneratorFromEventPool>(mEventPoolConfigs[confEvtPoolIndex]));
106 mGens.push_back(gen);
107 } else if (gen.compare("external") == 0) {
108 int confextIndex = std::stoi(mConfigs[index].substr(9));
109 // we need analyse the ini file to update the config key param
110 if (mExternalGenConfigs[confextIndex]->iniFile.size() > 0) {
111 LOG(info) << "Setting up external gen using the given INI file";
112
113 // this means that we go via the ConfigurableParam system ---> in order not to interfere with other
114 // generators we use an approach with backup and restore of the system
115
116 // we write the current state to a file
117 // create a tmp file name
118 std::string tmp_config_file = "configkey_tmp_backup_" + std::to_string(getpid()) + std::string(".ini");
120
121 auto expandedFileName = o2::utils::expandShellVarsInFileName(mExternalGenConfigs[confextIndex]->iniFile);
123 // toDo: check that this INI file makes sense
124
126 LOG(info) << "Setting up external generator with following parameters";
127 LOG(info) << params;
128 auto extgen_filename = params.fileName;
129 auto extgen_func = params.funcName;
130 auto extgen = std::shared_ptr<o2::eventgen::Generator>(o2::conf::GetFromMacro<o2::eventgen::Generator*>(extgen_filename, extgen_func, "FairGenerator*", "extgen"));
131 if (!extgen) {
132 LOG(fatal) << "Failed to retrieve \'extgen\': problem with configuration ";
133 }
134 // restore old state
136 // delete tmp file
137 std::filesystem::remove(tmp_config_file);
138
139 gens.push_back(std::move(extgen));
140 mGens.push_back(gen);
141 } else {
142 LOG(info) << "Setting up external gen using the given fileName and funcName";
143 // we need to restore the config key param system to what is was before
144 auto& extgen_filename = mExternalGenConfigs[confextIndex]->fileName;
145 auto& extgen_func = mExternalGenConfigs[confextIndex]->funcName;
146 auto extGen = std::shared_ptr<o2::eventgen::Generator>(o2::conf::GetFromMacro<o2::eventgen::Generator*>(extgen_filename, extgen_func, "FairGenerator*", "extgen"));
147 if (!extGen) {
148 LOG(fatal) << "Failed to load external generator from " << extgen_filename << " with function " << extgen_func;
149 }
150 gens.push_back(std::move(extGen));
151 mGens.push_back(gen);
152 }
153 } else if (gen.compare("hepmc") == 0) {
154 int confHepMCIndex = std::stoi(mConfigs[index].substr(6));
155 gens.push_back(std::make_shared<o2::eventgen::GeneratorHepMC>());
156 auto& globalConfig = o2::conf::SimConfig::Instance();
157 dynamic_cast<o2::eventgen::GeneratorHepMC*>(gens.back().get())->setup(*mFileOrCmdGenConfigs[confHepMCIndex], *mHepMCGenConfigs[confHepMCIndex], globalConfig);
158 mGens.push_back(gen);
159 }
160 } else {
161 LOG(fatal) << "Generator " << gen << " not found in the list of available generators \n";
162 exit(1);
163 }
164 index++;
165 }
166}
167
168GeneratorHybrid::~GeneratorHybrid()
169{
170 LOG(info) << "Destructor of generator hybrid called";
171 mStopFlag = true;
172}
173
175{
176 // init all sub-gens
177 int count = 0;
178 for (auto& gen : mGens) {
179 if (gen == "pythia8pp") {
180 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_inel.cfg";
181 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
182 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
183 } else if (gen == "pythia8hf") {
184 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_hf.cfg";
185 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
186 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
187 } else if (gen == "pythia8hi") {
188 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_hi.cfg";
189 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
190 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
191 } else if (gen == "pythia8powheg") {
192 auto config = std::string(std::getenv("O2_ROOT")) + "/share/Generators/egconfig/pythia8_powheg.cfg";
193 LOG(info) << "Setting \'Pythia8\' base configuration: " << config << std::endl;
194 dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
195 }
196 gens[count]->Init(); // TODO: move this to multi-threaded
198 if (mTriggerModes[count] != o2::eventgen::Generator::kTriggerOFF) {
199 gens[count]->setTriggerMode(mTriggerModes[count]);
200 LOG(info) << "Setting Trigger mode of generator " << gen << " to: " << mTriggerModes[count];
201 o2::eventgen::Trigger trigger = nullptr;
202 o2::eventgen::DeepTrigger deeptrigger = nullptr;
203 for (int trg = 0; trg < mTriggerMacros[count].size(); trg++) {
204 if (mTriggerMacros[count][trg].empty() || mTriggerFuncs[count][trg].empty()) {
205 continue;
206 }
207 std::string expandedMacro = o2::utils::expandShellVarsInFileName(mTriggerMacros[count][trg]);
208 LOG(info) << "Setting trigger " << trg << " of generator " << gen << " with following parameters";
209 LOG(info) << "Macro filename: " << expandedMacro;
210 LOG(info) << "Function name: " << mTriggerFuncs[count][trg];
211 trigger = o2::conf::GetFromMacro<o2::eventgen::Trigger>(expandedMacro, mTriggerFuncs[count][trg], "o2::eventgen::Trigger", "trigger");
212 if (!trigger) {
213 LOG(info) << "Trying to retrieve a \'o2::eventgen::DeepTrigger\' type";
214 deeptrigger = o2::conf::GetFromMacro<o2::eventgen::DeepTrigger>(expandedMacro, mTriggerFuncs[count][trg], "o2::eventgen::DeepTrigger", "deeptrigger");
215 }
216 if (!trigger && !deeptrigger) {
217 LOG(warn) << "Failed to retrieve \'external trigger\': problem with configuration";
218 LOG(warn) << "Trigger " << trg << " of generator " << gen << " will not be included";
219 continue;
220 } else {
221 LOG(info) << "Trigger " << trg << " of generator " << gen << " successfully set";
222 }
223 if (trigger) {
224 gens[count]->addTrigger(trigger);
225 } else {
226 gens[count]->addDeepTrigger(deeptrigger);
227 }
228 }
229 }
230 count++;
231 }
232 if (mRandomize) {
233 if (std::all_of(mFractions.begin(), mFractions.end(), [](int i) { return i == 1; })) {
234 LOG(info) << "Full randomisation of generators order";
235 } else {
236 LOG(info) << "Randomisation based on fractions";
237 int allfracs = 0;
238 for (auto& f : mFractions) {
239 allfracs += f;
240 }
241 // Assign new rng fractions
242 float sum = 0;
243 float chance = 0;
244 for (int k = 0; k < mFractions.size(); k++) {
245 if (mFractions[k] == 0) {
246 // Generator will not be used if fraction is 0
247 mRngFractions.push_back(-1);
248 LOG(info) << "Generator " << mGens[k] << " will not be used";
249 } else {
250 chance = static_cast<float>(mFractions[k]) / allfracs;
251 sum += chance;
252 mRngFractions.push_back(sum);
253 LOG(info) << "Generator " << (mConfigs[k] == "" ? mGens[k] : mConfigs[k]) << " has a " << chance * 100 << "% chance of being used";
254 }
255 }
256 }
257 } else {
258 LOG(info) << "Generators will be used in sequence, following provided fractions";
259 }
260
261 mGenIsInitialized.resize(gens.size(), false);
262 if (mGenerationMode == GenMode::kParallel) {
263 // in parallel mode we just use one queue --> collaboration
264 mResultQueue.resize(1);
265 } else {
266 // in sequential mode we have one queue per generator
267 mResultQueue.resize(gens.size());
268 }
269 // Create a task arena with a specified number of threads
270 mTaskArena.initialize(GeneratorHybridParam::Instance().num_workers);
271
272 // the process task function actually calls event generation
273 // when it is done it notifies the outside world by pushing it's index into an appropriate queue
274 // This should be a lambda, which can be given at TaskPool creation time
275 auto process_generator_task = [this](std::vector<std::shared_ptr<o2::eventgen::Generator>> const& generatorvec, int task) {
276 LOG(debug) << "Starting eventgen for task " << task;
277 auto& generator = generatorvec[task];
278 if (!mStopFlag) {
279 // TODO: activate this once we are use Init is threadsafe
280 // if (!mGenIsInitialized[task]) {
281 // if(!generator->Init()) {
282 // LOG(error) << "failed to init generator " << task;
283 // }
284 // mGenIsInitialized[task] = true;
285 // }
286 }
287 bool isTriggered = false;
288 while (!isTriggered) {
289 generator->clearParticles();
290 generator->generateEvent();
291 generator->importParticles();
292 isTriggered = generator->triggerEvent();
293 }
294 LOG(debug) << "eventgen finished for task " << task;
295 if (!mStopFlag) {
296 if (mGenerationMode == GenMode::kParallel) {
297 mResultQueue[0].push(task);
298 } else {
299 mResultQueue[task].push(task);
300 }
301 }
302 };
303
304 // fundamental tbb thread-worker function
305 auto worker_function = [this, process_generator_task]() {
306 // we increase the reference count in the generator pointers
307 // by making a copy of the vector. In this way we ensure that the lifetime
308 // of the generators is no shorter than the lifetime of the thread for this worker function
309 auto generators_copy = gens;
310
311 while (!mStopFlag) {
312 int task;
313 if (mInputTaskQueue.try_pop(task)) {
314 process_generator_task(generators_copy, task); // Process the task
315 } else {
316 std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Wait if no task
317 }
318 }
319 };
320
321 // let the TBB task system run in it's own thread
322 mTBBTaskPoolRunner = std::thread([this, worker_function]() { mTaskArena.execute([&]() { tbb::parallel_for(0, mTaskArena.max_concurrency(), [&](int) { worker_function(); }); }); });
323 mTBBTaskPoolRunner.detach(); // detaching because we don't like to wait on the thread to finish
324 // some of the generators might still be generating when we are done
325
326 // let's also push initial generation tasks for each event generator
327 for (size_t genindex = 0; genindex < gens.size(); ++genindex) {
328 mInputTaskQueue.push(genindex);
329 mTasksStarted++;
330 }
331 mIsInitialized = true;
332 return Generator::Init();
333}
334
336{
337 if (!mIsInitialized) {
338 Init();
339 }
340 if (mGenerationMode == GenMode::kParallel) {
341 mIndex = -1; // this means any index is welcome
342 notifySubGenerator(0); // we shouldn't distinguish the sub-gen ids
343 } else {
344 // Order randomisation or sequence of generators
345 // following provided fractions, if not generators are used in proper sequence
346 // Order randomisation or sequence of generators
347 // following provided fractions. If not available generators will be used sequentially
348 if (mRandomize) {
349 if (mRngFractions.size() != 0) {
350 // Generate number between 0 and 1
351 float rnum = gRandom->Rndm();
352 // Find generator index
353 for (int k = 0; k < mRngFractions.size(); k++) {
354 if (rnum <= mRngFractions[k]) {
355 mIndex = k;
356 break;
357 }
358 }
359 } else {
360 mIndex = gRandom->Integer(mFractions.size());
361 }
362 } else {
363 while (mFractions[mCurrentFraction] == 0 || mseqCounter == mFractions[mCurrentFraction]) {
364 if (mFractions[mCurrentFraction] != 0) {
365 mseqCounter = 0;
366 }
367 mCurrentFraction = (mCurrentFraction + 1) % mFractions.size();
368 }
369 mIndex = mCurrentFraction;
370 }
371 notifySubGenerator(mIndex);
372 }
373 return true;
374}
375
377{
378 int genIndex = -1;
379 std::vector<int> subGenIndex = {};
380 if (mIndex == -1) {
381 // this means parallel mode ---> we have a common queue
382 mResultQueue[0].pop(genIndex);
383 } else {
384 // need to pop from a particular queue
385 if (!mCocktailMode) {
386 mResultQueue[mIndex].pop(genIndex);
387 } else {
388 // in cocktail mode we need to pop from the group queue
389 subGenIndex.resize(mGroups[mIndex].size());
390 for (size_t pos = 0; pos < mGroups[mIndex].size(); ++pos) {
391 int subIndex = mGroups[mIndex][pos];
392 LOG(info) << "Getting generator " << mGens[subIndex] << " from cocktail group " << mIndex;
393 mResultQueue[subIndex].pop(subGenIndex[pos]);
394 }
395 }
396 }
397
398 auto unit_transformer = [](auto& p, auto pos_unit, auto time_unit, auto en_unit, auto mom_unit) {
399 p.SetMomentum(p.Px() * mom_unit, p.Py() * mom_unit, p.Pz() * mom_unit, p.Energy() * en_unit);
400 p.SetProductionVertex(p.Vx() * pos_unit, p.Vy() * pos_unit, p.Vz() * pos_unit, p.T() * time_unit);
401 };
402
403 auto index_transformer = [](auto& p, int offset) {
404 for (int i = 0; i < 2; ++i) {
405 if (p.GetMother(i) != -1) {
406 const auto newindex = p.GetMother(i) + offset;
407 p.SetMother(i, newindex);
408 }
409 }
410 if (p.GetNDaughters() > 0) {
411 for (int i = 0; i < 2; ++i) {
412 const auto newindex = p.GetDaughter(i) + offset;
413 p.SetDaughter(i, newindex);
414 }
415 }
416 };
417
418 // Clear particles and event header
419 mParticles.clear();
420 mMCEventHeader.clearInfo();
421 if (mCocktailMode) {
422 // in cocktail mode we need to merge the particles from the different generators
423 for (auto subIndex : subGenIndex) {
424 LOG(info) << "Importing particles for task " << subIndex;
425 auto subParticles = gens[subIndex]->getParticles();
426
427 auto time_unit = gens[subIndex]->getTimeUnit();
428 auto pos_unit = gens[subIndex]->getPositionUnit();
429 auto mom_unit = gens[subIndex]->getMomentumUnit();
430 auto energy_unit = gens[subIndex]->getEnergyUnit();
431
432 // The particles carry mother and daughter indices, which are relative
433 // to the sub-generator. We need to adjust these indices to reflect that particles
434 // are now embedded into a cocktail.
435 auto offset = mParticles.size();
436 for (auto& p : subParticles) {
437 // apply the mother-daugher index transformation
438 index_transformer(p, offset);
439 // apply unit transformation of sub-generator
440 unit_transformer(p, pos_unit, time_unit, energy_unit, mom_unit);
441 }
442
443 mParticles.insert(mParticles.end(), subParticles.begin(), subParticles.end());
444 // fetch the event Header information from the underlying generator
445 gens[subIndex]->updateHeader(&mMCEventHeader);
446 mInputTaskQueue.push(subIndex);
447 mTasksStarted++;
448 }
449 } else {
450 LOG(info) << "Importing particles for task " << genIndex;
451 // at this moment the mIndex-th generator is ready to be used
452 mParticles = gens[genIndex]->getParticles();
453
454 auto time_unit = gens[genIndex]->getTimeUnit();
455 auto pos_unit = gens[genIndex]->getPositionUnit();
456 auto mom_unit = gens[genIndex]->getMomentumUnit();
457 auto energy_unit = gens[genIndex]->getEnergyUnit();
458
459 // transform units to units of the hybrid generator
460 for (auto& p : mParticles) {
461 // apply unit transformation
462 unit_transformer(p, pos_unit, time_unit, energy_unit, mom_unit);
463 }
464
465 // fetch the event Header information from the underlying generator
466 gens[genIndex]->updateHeader(&mMCEventHeader);
467 mInputTaskQueue.push(genIndex);
468 mTasksStarted++;
469 }
470
471 mseqCounter++;
472 mEventCounter++;
473 if (mEventCounter == getTotalNEvents()) {
474 LOG(info) << "HybridGen: Stopping TBB task pool";
475 mStopFlag = true;
476 }
477
478 return true;
479}
480
482{
483 if (eventHeader) {
484 // we forward the original header information if any
485 eventHeader->copyInfoFrom(mMCEventHeader);
486
487 // put additional information about
488 eventHeader->putInfo<std::string>("forwarding-generator", "HybridGen");
489 }
490}
491
492template <typename T>
494{
495 rapidjson::StringBuffer buffer;
496 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
497 value.Accept(writer);
498 return buffer.GetString();
499}
500
502{
503 std::string name = gen["name"].GetString();
504 mInputGens.push_back(name);
505 if (gen.HasMember("config")) {
506 if (name == "boxgen") {
507 const auto& boxconf = gen["config"];
508 auto boxConfig = TBufferJSON::FromJSON<o2::eventgen::BoxGenConfig>(jsonValueToString(boxconf).c_str());
509 mBoxGenConfigs.push_back(std::move(boxConfig));
510 mConfigs.push_back("boxgen_" + std::to_string(mBoxGenConfigs.size() - 1));
511 } else if (name == "pythia8") {
512 const auto& pythia8conf = gen["config"];
513 auto pythia8Config = TBufferJSON::FromJSON<o2::eventgen::Pythia8GenConfig>(jsonValueToString(pythia8conf).c_str());
514 mPythia8GenConfigs.push_back(std::move(pythia8Config));
515 mConfigs.push_back("pythia8_" + std::to_string(mPythia8GenConfigs.size() - 1));
516 } else if (name == "extkinO2") {
517 const auto& o2kineconf = gen["config"];
518 auto o2kineConfig = TBufferJSON::FromJSON<o2::eventgen::O2KineGenConfig>(jsonValueToString(o2kineconf).c_str());
519 mO2KineGenConfigs.push_back(std::move(o2kineConfig));
520 mConfigs.push_back("extkinO2_" + std::to_string(mO2KineGenConfigs.size() - 1));
521 } else if (name == "evtpool") {
522 const auto& o2kineconf = gen["config"];
523 auto poolConfig = TBufferJSON::FromJSON<o2::eventgen::EventPoolGenConfig>(jsonValueToString(o2kineconf).c_str());
524 mEventPoolConfigs.push_back(*poolConfig);
525 mConfigs.push_back("evtpool_" + std::to_string(mEventPoolConfigs.size() - 1));
526 } else if (name == "external") {
527 const auto& extconf = gen["config"];
528 auto extConfig = TBufferJSON::FromJSON<o2::eventgen::ExternalGenConfig>(jsonValueToString(extconf).c_str());
529 mExternalGenConfigs.push_back(std::move(extConfig));
530 mConfigs.push_back("external_" + std::to_string(mExternalGenConfigs.size() - 1));
531 } else if (name == "hepmc") {
532 const auto& genconf = gen["config"];
533 const auto& cmdconf = genconf["configcmd"];
534 const auto& hepmcconf = genconf["confighepmc"];
535 auto cmdConfig = TBufferJSON::FromJSON<o2::eventgen::FileOrCmdGenConfig>(jsonValueToString(cmdconf).c_str());
536 auto hepmcConfig = TBufferJSON::FromJSON<o2::eventgen::HepMCGenConfig>(jsonValueToString(hepmcconf).c_str());
537 mFileOrCmdGenConfigs.push_back(std::move(cmdConfig));
538 mHepMCGenConfigs.push_back(std::move(hepmcConfig));
539 mConfigs.push_back("hepmc_" + std::to_string(mFileOrCmdGenConfigs.size() - 1));
540 } else {
541 mConfigs.push_back("");
542 }
543 } else {
544 if (name == "boxgen" || name == "pythia8" || name == "extkinO2" || name == "external" || name == "hepmc") {
545 LOG(fatal) << "No configuration provided for generator " << name;
546 return false;
547 } else {
548 mConfigs.push_back("");
549 }
550 }
551 if (gen.HasMember("triggers")) {
552 const auto& trigger = gen["triggers"];
553 auto trigger_specs = [this, &trigger]() {
554 mTriggerMacros.push_back({});
555 mTriggerFuncs.push_back({});
556 if (trigger.HasMember("specs")) {
557 for (auto& spec : trigger["specs"].GetArray()) {
558 if (spec.HasMember("macro")) {
559 const auto& macro = spec["macro"].GetString();
560 if (!(strcmp(macro, "") == 0)) {
561 mTriggerMacros.back().push_back(macro);
562 } else {
563 mTriggerMacros.back().push_back("");
564 }
565 } else {
566 mTriggerMacros.back().push_back("");
567 }
568 if (spec.HasMember("function")) {
569 const auto& function = spec["function"].GetString();
570 if (!(strcmp(function, "") == 0)) {
571 mTriggerFuncs.back().push_back(function);
572 } else {
573 mTriggerFuncs.back().push_back("");
574 }
575 } else {
576 mTriggerFuncs.back().push_back("");
577 }
578 }
579 } else {
580 mTriggerMacros.back().push_back("");
581 mTriggerFuncs.back().push_back("");
582 }
583 };
584 if (trigger.HasMember("mode")) {
585 const auto& trmode = trigger["mode"].GetString();
586 if (strcmp(trmode, "or") == 0) {
587 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOR);
588 trigger_specs();
589 } else if (strcmp(trmode, "and") == 0) {
590 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerAND);
591 trigger_specs();
592 } else if (strcmp(trmode, "off") == 0) {
593 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
594 mTriggerMacros.push_back({""});
595 mTriggerFuncs.push_back({""});
596 } else {
597 LOG(warn) << "Wrong trigger mode provided for generator " << name << ", keeping trigger OFF";
598 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
599 mTriggerMacros.push_back({""});
600 mTriggerFuncs.push_back({""});
601 }
602 } else {
603 LOG(warn) << "No trigger mode provided for generator " << name << ", turning trigger OFF";
604 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
605 mTriggerMacros.push_back({""});
606 mTriggerFuncs.push_back({""});
607 }
608 } else {
609 mTriggerModes.push_back(o2::eventgen::Generator::kTriggerOFF);
610 mTriggerMacros.push_back({""});
611 mTriggerFuncs.push_back({""});
612 }
613 return true;
614}
615
616Bool_t GeneratorHybrid::parseJSON(const std::string& path)
617{
618 // Parse JSON file to build map
619 std::ifstream fileStream(path, std::ios::in);
620 if (!fileStream.is_open()) {
621 LOG(error) << "Cannot open " << path;
622 return false;
623 }
624 rapidjson::IStreamWrapper isw(fileStream);
625 rapidjson::Document doc;
626 doc.ParseStream(isw);
627 if (doc.HasParseError()) {
628 LOG(error) << "Error parsing provided json file " << path;
629 LOG(error) << " - Error -> " << rapidjson::GetParseError_En(doc.GetParseError());
630 return false;
631 }
632
633 // check if there is a mode field
634 if (doc.HasMember("mode")) {
635 const auto& mode = doc["mode"].GetString();
636 if (strcmp(mode, "sequential") == 0) {
637 // events are generated in the order given by fractions or random weight
638 mGenerationMode = GenMode::kSeq;
639 }
640 if (strcmp(mode, "parallel") == 0) {
641 // events are generated fully in parallel and the order will be random
642 // this is mainly for event pool generation or mono-type generators
643 mGenerationMode = GenMode::kParallel;
644 LOG(info) << "Setting mode to parallel";
645 }
646 }
647
648 // Put the generator names in mInputGens
649 if (doc.HasMember("generators")) {
650 const auto& gens = doc["generators"];
651 for (const auto& gen : gens.GetArray()) {
652 mGroups.push_back({});
653 // Check if gen is an array (cocktail mode)
654 if (gen.HasMember("cocktail")) {
655 mCocktailMode = true;
656 for (const auto& subgen : gen["cocktail"].GetArray()) {
657 if (confSetter(subgen)) {
658 mGroups.back().push_back(mInputGens.size() - 1);
659 } else {
660 return false;
661 }
662 }
663 } else {
664 if (!confSetter(gen)) {
665 return false;
666 }
667 // Groups are created in case cocktail mode is activated, this way
668 // cocktails can be declared anywhere in the JSON file, without the need
669 // of grouping single generators. If no cocktail is defined
670 // groups will be ignored nonetheless.
671 mGroups.back().push_back(mInputGens.size() - 1);
672 }
673 }
674 }
675
676 // Get fractions and put them in mFractions
677 if (doc.HasMember("fractions")) {
678 const auto& fractions = doc["fractions"];
679 for (const auto& frac : fractions.GetArray()) {
680 mFractions.push_back(frac.GetInt());
681 }
682 } else {
683 // Set fractions to unity for all generators in case they are not provided
684 const auto& gens = doc["generators"];
685 for (const auto& gen : gens.GetArray()) {
686 mFractions.push_back(1);
687 }
688 }
689 return true;
690}
691
692} // namespace eventgen
693} // namespace o2
694
default_random_engine gen(dev())
int32_t i
ClassImp(o2::eventgen::GeneratorHybrid)
uint16_t pos
Definition RawData.h:3
std::ostringstream debug
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:111
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:84
void setEnergyUnit(double val)
Definition Generator.h:82
void notifySubGenerator(int subGeneratorId)
Definition Generator.h:120
static unsigned int getTotalNEvents()
Definition Generator.h:97
void setTimeUnit(double val)
Definition Generator.h:86
void addSubGenerator(int subGeneratorId, std::string const &subGeneratorDescription)
std::vector< TParticle > mParticles
Definition Generator.h:144
void setMomentumUnit(double val)
Definition Generator.h:80
Bool_t Init() override
Definition Generator.cxx:57
float sum(float s, o2::dcs::DataPointValue v)
Definition dcs-ccdb.cxx:39
GLenum mode
Definition glcorearb.h:266
GLint GLsizei count
Definition glcorearb.h:399
GLuint buffer
Definition glcorearb.h:655
GLsizeiptr size
Definition glcorearb.h:659
GLuint index
Definition glcorearb.h:781
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
GLsizei const GLchar *const * path
Definition glcorearb.h:3591
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"