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