Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Generators/include/Generators/GeneratorHybrid.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ class GeneratorHybrid : public Generator
// Cocktail mode
bool mCocktailMode = false;
std::vector<std::vector<int>> mGroups;
// Sub-generator ID reported by each entry of the generators list
std::vector<int> mGroupSubGenIds;

// Trigger configuration
std::vector<ETriggerMode_t> mTriggerModes; // trigger mode for each generator
Expand Down
176 changes: 144 additions & 32 deletions Generators/src/GeneratorHybrid.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <chrono>
#include <fairlogger/Logger.h>
#include <algorithm>
#include <unordered_map>
#include <tbb/concurrent_queue.h>
#include <tbb/task_arena.h>
#include <tbb/parallel_for.h>
Expand Down Expand Up @@ -73,18 +74,12 @@ GeneratorHybrid::GeneratorHybrid(const std::string& inputgens)
}
}
int index = 0;
// Parallel mode ignores the fractions.
if (mGenerationMode != GenMode::kParallel && mGroups.size() != mFractions.size()) {
LOG(fatal) << "Number of fractions does not match the number of entries in the generators list";
return;
}
if (!(mRandomize || mGenerationMode == GenMode::kParallel)) {
if (mCocktailMode) {
if (mGroups.size() != mFractions.size()) {
LOG(fatal) << "Number of groups does not match the number of fractions";
return;
}
} else {
if (mFractions.size() != mInputGens.size()) {
LOG(fatal) << "Number of fractions does not match the number of generators";
return;
}
}
// Check if all elements of mFractions are 0
if (std::all_of(mFractions.begin(), mFractions.end(), [](int i) { return i == 0; })) {
LOG(fatal) << "All fractions provided are 0, no simulation will be performed";
Expand Down Expand Up @@ -245,7 +240,6 @@ Bool_t GeneratorHybrid::Init()
dynamic_cast<o2::eventgen::GeneratorPythia8*>(gens[count].get())->setConfig(config);
}
gens[count]->Init(); // TODO: move this to multi-threaded
addSubGenerator(count, gen);
if (mTriggerModes[count] != o2::eventgen::Generator::kTriggerOFF) {
gens[count]->setTriggerMode(mTriggerModes[count]);
LOG(info) << "Setting Trigger mode of generator " << gen << " to: " << mTriggerModes[count];
Expand Down Expand Up @@ -286,6 +280,23 @@ Bool_t GeneratorHybrid::Init()
}
count++;
}
// A sub-generator ID identifies an entry of the generators list rather than a single generator:
// an entry can be served by several generators (a cocktail) or share one with another entry (a
// 'ref'). Descriptions are therefore registered per entry, under the ID that entry reports, so
// that every ID written to the event header has one. Entries sharing an ID (a 'ref' and the
// entry it points to) are served by the same generators, and addSubGenerator keeps the first.
for (size_t entry = 0; entry < mGroups.size(); ++entry) {
std::string description;
for (const auto generator : mGroups[entry]) {
if (!description.empty()) {
description += "+";
}
description += mGens[generator];
}
LOG(debug) << "Sub-generator " << mGroupSubGenIds[entry] << " (entry " << entry << "): " << description;
addSubGenerator(mGroupSubGenIds[entry], description);
}

// Label for groups: concatenation of the names of the generators in the group, separated by '+'.
// Currently used only if randomisation is enabled
auto groupLabel = [this](int k) {
Expand Down Expand Up @@ -445,32 +456,23 @@ bool GeneratorHybrid::generateEvent()
}
mIndex = mCurrentFraction;
}
notifySubGenerator(mIndex);
notifySubGenerator(mGroupSubGenIds[mIndex]);
}
return true;
}

bool GeneratorHybrid::importParticles()
{
int genIndex = -1;
std::vector<int> subGenIndex = {};
if (mIndex == -1) {
// this means parallel mode ---> we have a common queue
mResultQueue[0].pop(genIndex);
} else {
// need to pop from a particular queue
if (!mCocktailMode) {
mResultQueue[mIndex].pop(genIndex);
} else {
// in cocktail mode we need to pop from the group queue
subGenIndex.resize(mGroups[mIndex].size());
for (size_t pos = 0; pos < mGroups[mIndex].size(); ++pos) {
int subIndex = mGroups[mIndex][pos];
LOG(info) << "Getting generator " << mGens[subIndex] << " from cocktail group " << mIndex;
mResultQueue[subIndex].pop(subGenIndex[pos]);
}
}
} else if (!mCocktailMode) {
// need to pop from the queue of the generator serving this entry of the list
mResultQueue[mGroups[mIndex].front()].pop(genIndex);
}
// in cocktail mode the events of the group members are popped one by one while they are
// imported, so that one generator shared by two members of the same group can serve both

auto unit_transformer = [](auto& p, auto pos_unit, auto time_unit, auto en_unit, auto mom_unit) {
p.SetMomentum(p.Px() * mom_unit, p.Py() * mom_unit, p.Pz() * mom_unit, p.Energy() * en_unit);
Expand Down Expand Up @@ -503,8 +505,14 @@ bool GeneratorHybrid::importParticles()
const bool queueNextEvent = getTotalNEvents() == 0 || mEventCounter + 1 < getTotalNEvents();
if (mCocktailMode) {
// in cocktail mode we need to merge the particles from the different generators
for (auto subIndex : subGenIndex) {
const auto& group = mGroups[mIndex];
for (size_t pos = 0; pos < group.size(); ++pos) {
const auto member = group[pos];
int subIndex = -1;
// wait for the event of this generator; the queue index is the generator index
mResultQueue[member].pop(subIndex);
if (!mIsHyperloop) {
LOG(info) << "Getting generator " << mGens[subIndex] << " from cocktail group " << mIndex;
LOG(info) << "Importing particles for task " << subIndex;
}
auto subParticles = gens[subIndex]->getParticles();
Expand All @@ -531,7 +539,12 @@ bool GeneratorHybrid::importParticles()
gens[subIndex]->updateHeader(&mMCEventHeader);
mHeaderGeneratorIndex = subIndex; // store index of generator updating the header
}
if (queueNextEvent) {
// One generator can serve several members of the same group on the reference/label mechanism,
// and each of them consumes one event of it. The remaining members would then wait forever for an event nobody
// prepares, so such a generator is queued again even when the event budget is over.
// The event is consumed before this loop ends, hence nothing is left running.
const bool neededAgainInThisGroup = std::find(group.begin() + pos + 1, group.end(), member) != group.end();
if (queueNextEvent || neededAgainInThisGroup) {
mInputTaskQueue.push(subIndex);
mTasksStarted++;
}
Expand Down Expand Up @@ -749,19 +762,105 @@ Bool_t GeneratorHybrid::parseJSON(const std::string& path)

// Put the generator names in mInputGens
if (doc.HasMember("generators")) {
// A generator, or a whole cocktail, can be given a name with 'label' and reused by any later
// entry with {"ref": "<label>"}. A referring entry does not configure a new generator: it is
// served by the very same one and it reports its sub-generator ID.
struct LabelledEntry {
std::vector<int> generators; // the generators declared under the label
int subGenId; // ID reported by the labelled entry; -1 if the label is on a
// cocktail member, which has no ID of its own (see below)
};
std::unordered_map<std::string, LabelledEntry> labelled;
// declares the label of an entry, if it has one
auto declareLabel = [&labelled](const auto& gen, const std::vector<int>& generators, int subGenId) {
if (!gen.HasMember("label")) {
return true;
}
if (!gen["label"].IsString() || gen["label"].GetStringLength() == 0) {
LOG(fatal) << "The 'label' of a generator entry must be a non-empty string";
return false;
}
std::string label = gen["label"].GetString();
if (!labelled.emplace(label, LabelledEntry{generators, subGenId}).second) {
LOG(fatal) << "Label '" << label << "' is declared by more than one generator entry";
return false;
}
LOG(debug) << "Generator entry labelled '" << label << "' can be reused with {\"ref\": \"" << label << "\"}";
return true;
};
// resolves the 'ref' of an entry to the label it points to
auto resolveRef = [&labelled](const auto& gen) -> const LabelledEntry* {
for (const auto& member : {"name", "config", "triggers", "cocktail", "label"}) {
if (gen.HasMember(member)) {
LOG(fatal) << "A 'ref' generator entry must not define '" << member
<< "': it reuses the referenced generator exactly as it is declared";
return nullptr;
}
}
if (!gen["ref"].IsString()) {
LOG(fatal) << "The 'ref' of a generator entry must be a string";
return nullptr;
}
const auto target = labelled.find(gen["ref"].GetString());
if (target == labelled.end()) {
LOG(fatal) << "Generator entry refers to '" << gen["ref"].GetString()
<< "', which is not the label of any entry declared before it";
return nullptr;
}
return &target->second;
};
const auto& gens = doc["generators"];
for (const auto& gen : gens.GetArray()) {
mGroups.push_back({});
// Check if gen is an array (cocktail mode)
if (gen.HasMember("cocktail")) {
// by default an entry reports its own position in the generators list as sub-generator ID
mGroupSubGenIds.push_back(mGroups.size() - 1);
if (gen.HasMember("ref")) {
const auto* target = resolveRef(gen);
if (!target) {
return false;
}
// the entry is served by the generators of the entry it points to.
// It reports its sub-generator ID as well, unless the label is on a cocktail
// member (-1), which has no ID to pass on and leaves this entry with its own
mGroups.back() = target->generators;
if (target->subGenId >= 0) {
mGroupSubGenIds.back() = target->subGenId;
}
LOG(debug) << "Generator entry " << mGroups.size() - 1 << " reuses the generator(s) labelled '"
<< gen["ref"].GetString() << "'";
if (mGenerationMode == GenMode::kParallel) {
LOG(warn) << "In parallel mode the generators collaborate on a single stream of events and the "
<< "entries of the generators list are not used one by one: a 'ref' entry has no effect";
}
} else if (gen.HasMember("cocktail")) {
// Check if gen is an array (cocktail mode)
mCocktailMode = true;
for (const auto& subgen : gen["cocktail"].GetArray()) {
if (confSetter(subgen)) {
if (subgen.HasMember("ref")) {
const auto* target = resolveRef(subgen);
if (!target) {
return false;
}
if (target->generators.size() != 1) {
LOG(fatal) << "A cocktail member refers to '" << subgen["ref"].GetString()
<< "', which is a cocktail itself: cocktails cannot be nested";
return false;
}
mGroups.back().push_back(target->generators.front());
} else if (confSetter(subgen)) {
mGroups.back().push_back(mInputGens.size() - 1);
// Sub-generator IDs are assigned per entry of the 'generators' list, and a cocktail
// member is not an entry of its own.
if (!declareLabel(subgen, {mGroups.back().back()}, -1)) {
return false;
}
} else {
return false;
}
}
if (!declareLabel(gen, mGroups.back(), mGroupSubGenIds.back())) {
return false;
}
} else {
if (!confSetter(gen)) {
return false;
Expand All @@ -771,6 +870,9 @@ Bool_t GeneratorHybrid::parseJSON(const std::string& path)
// of grouping single generators. If no cocktail is defined
// groups will be ignored nonetheless.
mGroups.back().push_back(mInputGens.size() - 1);
if (!declareLabel(gen, mGroups.back(), mGroupSubGenIds.back())) {
return false;
}
}
}
}
Expand All @@ -781,6 +883,16 @@ Bool_t GeneratorHybrid::parseJSON(const std::string& path)
return false;
}

// Without cocktails every entry is served by exactly one generator, and a 'ref' entry makes the
// position of an entry in the list differ from the index of that generator. Reporting the index
// keeps the IDs of such a configuration the same as those of the equivalent one without any
// 'ref', instead of leaving gaps where the referring entries are.
if (!mCocktailMode) {
for (size_t entry = 0; entry < mGroups.size(); ++entry) {
mGroupSubGenIds[entry] = mGroups[entry].front();
}
}

// Get fractions and put them in mFractions
if (doc.HasMember("fractions")) {
const auto& fractions = doc["fractions"];
Expand Down
115 changes: 115 additions & 0 deletions run/SimExamples/Hybrid_reuse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<!-- doxy
\page refrunSimExamplesHybridreuse Example Hybrid_reuse
/doxy -->

This example shows how to reuse one generator in several entries of the hybrid generator
configuration, with `label` and `ref`.

A generator, or a whole cocktail, can be given a name with `"label"` and Any **later** entry of the
`generators` list can then be written as `{"ref": "<label>"}`. This configures no new generator and
is served by the same one. This matters when the same generator appears several times in a
configuration, because each copy would otherwise be built, initialised and kept in memory again.
Nothing changes for configurations that use neither `label` nor `ref`.

Important rules to follow:
- a `ref` must point to a label declared by an **earlier** entry, so the configuration can be read
from top to bottom;
- a `ref` entry carries nothing else: no `name`, `config`, `triggers`, `cocktail` or `label` of its
own, since it reuses the referenced generator exactly as it is declared, triggers included;
- `fractions` i still the same &rarr; one value per entry of the `generators` list, `ref` entries
included;
- a cocktail cannot be nested: a cocktail member referring to a whole cocktail is rejected (done on purpose to avoid recursion loops)

# The configuration in this example

`hybridreuse.json` declares 8 entries served by 3 generators (one Pythia8, one boxgen of
&Lambda;<sub>c</sub>, one boxgen of D<sup>0</sup>):

| entry | configuration | generators used | sub-generator ID |
| --- | --- | --- | --- |
| 0 | Pythia8, `"label": "mb"` | Pythia8 | 0 |
| 1 | cocktail `[{"ref": "mb"}, boxgen &Lambda;<sub>c</sub> `"label": "lc"`]`, `"label": "mb_lc"` | Pythia8 + boxgen &Lambda;<sub>c</sub> | 1 |
| 2 | `{"ref": "mb"}` | Pythia8 | 0 |
| 3 | `{"ref": "mb_lc"}` | Pythia8 + boxgen &Lambda;<sub>c</sub> | 1 |
| 4 | `{"ref": "lc"}` | boxgen &Lambda;<sub>c</sub> | 4 |
| 5 | cocktail `[{"ref": "mb"}, boxgen D`<sup>0</sup>` "label": "d0"]` | Pythia8 + boxgen D<sup>0</sup> | 5 |
| 6 | cocktail `[{"ref": "d0"}, {"ref": "mb"}]` | boxgen D<sup>0</sup> + Pythia8 | 6 |
| 7 | cocktail `[{"ref": "mb"}, {"ref": "mb"}]` | Pythia8, twice | 7 |

It therefore covers every way of reusing a generator:

- **a plain generator reused** (entry 2 reuses entry 0);
- **a generator reused inside a cocktail** (entry 1 mixes the Pythia8 of entry 0 with a boxgen);
- **a whole cocktail reused** (entry 3 reuses entry 1);
- **one member of a cocktail reused on its own** (entry 4 runs only the &Lambda;<sub>c</sub> boxgen
declared inside entry 1);
- **the same two generators mixed in the opposite order** (entries 5 and 6);
- **one generator serving two members of the same cocktail** (entry 7 merges two Pythia8 events).

# Sub-generator IDs

The ID written to the event header identifies an **entry** of the list, and an entry referring to
another reports that entry's ID. Running 8 events with equal fractions gives one event per entry:

```
SEQUENCE 0 1 0 1 4 5 6 7
NPART 96 195 338 55 2 204 39 383
```

- entries 0 and 2 both report **0**, and entries 1 and 3 both report **1**: a `ref` is a copy of
the entry it points to, so the events of the two are counted together.
- entry 4 reports **4**, not 1. A cocktail *member* is not an entry of the list and has no ID of
its own, so an entry referring to one keeps its own: its events contain only the
&Lambda;<sub>c</sub> boxgen, and reporting 1 would label them as if they also contained the
Pythia8 event of the cocktail.
- IDs 2 and 3 never appear. That is expected: the entries in those positions are `ref`s and report
the ID of their target instead.

The particle counts show the entries really are doing different things: 96 for a bare Pythia8
event, 195 = 193 + 2 for the Pythia8 + &Lambda;<sub>c</sub> cocktail, 2 for the
&Lambda;<sub>c</sub> boxgen alone, and 383 = 129 + 254 for the cocktail that merges two *different*
Pythia8 events out of one generator.

## Does the order inside a cocktail change the ID?

No. The ID is the position of the entry in the list, so it does not depend on the order of the
members: entries 5 and 6 contain the same two generators in opposite order and report 5 and 6
because they are two different entries, not because of the order. Reversing the members of one
cocktail would leave its ID unchanged.

What the order does change:

- **which generator provides the event header.** The first member of a cocktail is the one used to
update the header, so the entry whose header information should be kept belongs first.
- **the order of the particles** in the event, and therefore the mother/daughter offsets.
- **the description** registered next to the ID, which lists the generators in order:

```
Sub-generator 5 (entry 5): pythia8+boxgen
Sub-generator 6 (entry 6): boxgen+pythia8
```

These lines are printed at `debug` severity, together with one per entry:

```
Sub-generator 0 (entry 0): pythia8
Sub-generator 0 (entry 2): pythia8
Sub-generator 1 (entry 1): pythia8+boxgen
Sub-generator 1 (entry 3): pythia8+boxgen
Sub-generator 4 (entry 4): boxgen
Sub-generator 7 (entry 7): pythia8+pythia8
```

# Files description

- **runo2sim.sh** &rarr; runs the example with `o2-sim`
- **hybridreuse.json** &rarr; the hybrid generator configuration using `label` and `ref`

The basic hybrid generator mechanisms are shown in the Hybrid, Hybrid_cocktail, Hybrid_parallel
and Hybrid_trigger example folders.

# Note on parallel mode

`"mode": "parallel"` lets the generators collaborate on a single stream of events, so the entries
of the list are not used one by one and a `ref` entry has no effect there. Cocktails cannot be used
in parallel mode at all.
Loading