Project
Loading...
Searching...
No Matches
CollisionContextTool.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
12#include <boost/program_options.hpp>
13#include <string>
14#include <iostream>
16#include <regex>
23#include <cmath>
24#include <TRandom.h>
25#include <numeric>
26#include <fairlogger/Logger.h>
31#include "SimConfig/SimConfig.h"
32#include <filesystem>
33#include <sstream>
34#include <vector>
35#include <numeric>
36
37//
38// Created by Sandro Wenzel on 13.07.21.
39//
40
41// A utility to create/engineer (later modify/display) collision contexts
42
43// options struct filled from command line
44struct Options {
45 std::vector<std::string> interactionRates;
46 std::string qedInteraction; // specification for QED contribution
47 std::string outfilename; //
48 int orbits; // number of orbits to generate (can be a multiple of orbitsPerTF --> determine fraction or multiple of timeframes)
49 long seed; //
50 bool printContext = false;
51 std::string bcpatternfile;
52 int tfid = 0; // tfid -> used to calculate start orbit for collisions
53 double orbitsEarly = 0.; // how many orbits from a prev timeframe should still be kept in the current timeframe
54 double firstFractionalOrbit; // capture orbit and bunch crossing via decimal number
55 uint32_t firstOrbit = 0; // first orbit in run (orbit offset)
56 uint32_t firstBC = 0; // first bunch crossing (relative to firstOrbit) of the first interaction;
57 int orbitsPerTF = 256; // number of orbits per timeframe --> used to calculate start orbit for collisions
59 bool noEmptyTF = false; // prevent empty timeframes; the first interaction will be shifted backwards to fall within the range given by Options.orbits
60 int maxCollsPerTF = -1; // the maximal number of hadronic collisions per TF (can be used to constrain number of collisions per timeframe to some maximal value)
61 std::string configKeyValues = ""; // string to init config key values
62 long timestamp = -1; // timestamp for CCDB queries
63 std::string individualTFextraction = ""; // triggers extraction of individuel timeframe components when non-null
64 // format is path prefix
65 std::string vertexModeString{"kNoVertex"}; // Vertex Mode; vertices will be assigned to collisions of mode != kNoVertex
67 std::string external_path = ""; // optional external path where we can directly take the collision contexts
68 // This is useful when someone else is creating the contexts (MC-data embedding) and we
69 // merely want to pass these through. If this is given, we simply take the timeframe ID, number of orbits
70 // and copy the right amount of timeframes into the destination folder (implies individualTFextraction)
71 std::string nontrivial_mu_distribution = ""; // path to fetch a non-uniform MC(BC) distribution for the interaction sampler
72 // can be: (a) ccdb, (b) a ROOT file with the histogram included
73};
74
76 NOLOCK,
77 EVERYN,
79};
80
81struct CcdbUrl {
82 std::string server; // may include http:// or https://
83 std::string port; // empty if none
84 std::string fullPath; // everything after server[:port]/
85};
86
87std::optional<CcdbUrl> parseCcdbRegex(const std::string& url)
88{
89 static const std::regex re(
90 R"(^(?:ccdb://)(https?://[^/:]+|[^/:]+)(?::(\d+))?/(.+)$)");
91 std::smatch m;
92 if (!std::regex_match(url, m, re)) {
93 return std::nullopt;
94 }
95
96 CcdbUrl out;
97 out.server = m[1].str(); // server (may include http:// or https://)
98 out.port = m[2].str(); // optional port
99 out.fullPath = m[3].str(); // remainder
100 return out;
101}
102
104 std::string name; // name (prefix for transport simulation); may also serve as unique identifier
106 std::pair<int, float> synconto; // if this interaction locks on another interaction; takes precedence over interactionRate
108 char syncmodeop = 0; // syncmode operation ("@" --> embedd; "r" --> replace)
109 int mcnumberasked = -1; // number of MC events asked (but can be left -1) in which case it will be determined from timeframelength
110 int mcnumberavail = -1; // number of MC events avail (but can be left -1); if avail < asked there will be reuse of events
111 bool randomizeorder = false; // whether order of events will be randomized
112};
113
114InteractionSpec parseInteractionSpec(std::string const& specifier, std::vector<InteractionSpec> const& existingPatterns, bool adjustEventCount)
115{
116 // An interaction specification is a command-separated string
117 // of the following form:
118 // SPEC=NAMESTRING,INTERACTIONSTRING[,MCNUMBERSTRING]
119 //
120 // where
121 //
122 // NAMESTRING : a simple named specifier for the interaction; matching to a simulation prefix used by o2-sim
123 //
124 // INTERACTIONSTRING: irate | @ID:[ed]FLOATVALUE
125 // - either: a simple number irate specifying the interaction rate in kHz
126 // - or: a string such as @0:e5, saying that this interaction should match/sync
127 // with collisions of the 0-th interaction, but inject only every 5 collisions.
128 // Alternatively @0:d10000 means to inject but leaving a timedistance of at least 10000ns between signals
129 // - or: a string r0:e5, saying that this interaction should sync with collisions of the 0-th interaction but
130 // **overwrite** every 5-th interaction with a collision from this interaction name
131 // MCNUMBERSTRING: NUMBER1:r?NUMBER2 can specify how many collisions NUMBER1 to produce, taking from a sample of NUMBER2 available collisions
132 // - this option is only supported on the first interaction which is supposed to be the background interaction
133 // - if the 'r' character is present we randomize the order of the MC events
134
135 // tokens are separated by comma
136 std::vector<std::string> tokens = o2::RangeTokenizer::tokenize<std::string>(specifier);
137
138 float rate = -1.;
139 std::pair<int, float> synconto(-1, 1);
140
141 // extract (kinematics prefix) name
142 std::string name = tokens[0];
143
144 // extract the MC number spec if given
145 int collisionsasked = -1;
146 int collisionsavail = -1;
147 bool randomizeorder = false;
148 if (tokens.size() > 2) {
149 auto mctoken = tokens[2];
150 std::regex re("([0-9]*):(r?)([0-9]*)$", std::regex_constants::extended);
151
152 std::cmatch m;
153 if (std::regex_match(mctoken.c_str(), m, re)) {
154 collisionsasked = std::atoi(m[1].str().c_str());
155 if (m[2].str().compare("r") == 0) {
156 randomizeorder = true;
157 }
158 collisionsavail = std::atoi(m[3].str().c_str());
159 } else {
160 LOG(error) << "Could not parse " << mctoken << " as MCNUMBERSTRING";
161 exit(1);
162 }
163 }
164
165 if (adjustEventCount) {
166 // if the number of collisionsavail has not been specified, we should
167 // try to extract it from the kinematics directly
169 if (collisionsavail > 0) {
170 collisionsavail = std::min((size_t)collisionsavail, (size_t)mcreader.getNEvents(0));
171 } else {
172 collisionsavail = mcreader.getNEvents(0);
173 }
174 }
175 LOG(info) << "Collisions avail for " << name << " " << collisionsavail;
176
177 // extract interaction rate ... or locking
178 auto& interactionToken = tokens[1];
179 if (interactionToken[0] == '@' || interactionToken[0] == 'r') {
180 try {
181 // locking onto some other interaction
182 std::regex re("[@r]([0-9]*):([ed])([0-9]*[.]?[0-9]?)$", std::regex_constants::extended);
183
184 std::cmatch m;
185 if (std::regex_match(interactionToken.c_str(), m, re)) {
186 auto crossindex = std::atoi(m[1].str().c_str());
187 auto mode = m[2].str();
188 auto modevalue = std::atof(m[3].str().c_str());
189
190 if (crossindex > existingPatterns.size()) {
191 LOG(error) << "Reference to non-existent interaction spec";
192 exit(1);
193 }
194 synconto = std::pair<int, float>(crossindex, modevalue);
195
196 InteractionLockMode lockMode;
197 if (mode.compare("e") == 0) {
199 }
200 if (mode.compare("d") == 0) {
202 }
203 return InteractionSpec{name, rate, synconto, lockMode, interactionToken[0], collisionsasked, collisionsavail, randomizeorder};
204 } else {
205 LOG(error) << "Could not parse " << interactionToken << " as INTERACTIONSTRING";
206 exit(1);
207 }
208 } catch (std::regex_error e) {
209 LOG(error) << "Exception during regular expression match " << e.what();
210 exit(1);
211 }
212 } else {
213 rate = std::atof(interactionToken.c_str());
214 return InteractionSpec{name, rate, synconto, InteractionLockMode::NOLOCK, 0, collisionsasked, collisionsavail, randomizeorder};
215 }
216}
217
218bool parseOptions(int argc, char* argv[], Options& optvalues)
219{
220 namespace bpo = boost::program_options;
221 bpo::options_description options(
222 "A utility to create and manipulate digitization contexts (MC collision structure within a timeframe).\n\n"
223 "Allowed options");
224
225 options.add_options()(
226 "interactions,i", bpo::value<std::vector<std::string>>(&optvalues.interactionRates)->multitoken(), "name,IRate|LockSpecifier")(
227 "QEDinteraction", bpo::value<std::string>(&optvalues.qedInteraction)->default_value(""), "Interaction specifier for QED contribution (name,IRATE,maxeventnumber)")(
228 "outfile,o", bpo::value<std::string>(&optvalues.outfilename)->default_value("collisioncontext.root"), "Outfile of collision context")(
229 "orbits", bpo::value<int>(&optvalues.orbits)->default_value(-1),
230 "Number of orbits to generate maximally (if given, can be used to determine the number of timeframes). "
231 "Otherwise, the context will be generated by using collision numbers from the interaction specification.")(
232 "seed", bpo::value<long>(&optvalues.seed)->default_value(0L), "Seed for random number generator (for time sampling etc). Default 0: Random")(
233 "show-context", "Print generated collision context to terminal.")(
234 "bcPatternFile", bpo::value<std::string>(&optvalues.bcpatternfile)->default_value(""), "Interacting BC pattern file (e.g. from CreateBCPattern.C); Use \"ccdb\" when fetching from CCDB.")(
235 "orbitsPerTF", bpo::value<int>(&optvalues.orbitsPerTF)->default_value(256), "Orbits per timeframes")(
236 "orbitsEarly", bpo::value<double>(&optvalues.orbitsEarly)->default_value(0.), "Number of orbits with extra collisions prefixed to each timeframe")(
237 "use-existing-kine", "Read existing kinematics to adjust event counts")(
238 "timeframeID", bpo::value<int>(&optvalues.tfid)->default_value(0), "Timeframe id of the first timeframe int this context. Allows to generate contexts for different start orbits")(
239 "first-orbit", bpo::value<double>(&optvalues.firstFractionalOrbit)->default_value(0), "First (fractional) orbit in the run (HBFUtils.firstOrbit + BC from decimal)")(
240 "maxCollsPerTF", bpo::value<int>(&optvalues.maxCollsPerTF)->default_value(-1), "Maximal number of MC collisions to put into one timeframe. By default no constraint.")(
241 "noEmptyTF", bpo::bool_switch(&optvalues.noEmptyTF), "Enforce to have at least one collision")(
242 "configKeyValues", bpo::value<std::string>(&optvalues.configKeyValues)->default_value(""), "Semicolon separated key=value strings (e.g.: 'TPC.gasDensity=1;...')")(
243 "with-vertices", bpo::value<std::string>(&optvalues.vertexModeString)->default_value("kNoVertex"), "Assign vertices to collisions. Argument is the vertex mode. Defaults to no vertexing applied")(
244 "timestamp", bpo::value<long>(&optvalues.timestamp)->default_value(-1L), "Timestamp for CCDB queries / anchoring")(
245 "extract-per-timeframe", bpo::value<std::string>(&optvalues.individualTFextraction)->default_value(""),
246 "Extract individual timeframe contexts. Format required: time_frame_prefix[:comma_separated_list_of_signals_to_offset]")(
247 "import-external", bpo::value<std::string>(&optvalues.external_path)->default_value(""), "Take collision contexts (per timeframe) from external files for instance for data-anchoring use-case. Needs timeframeID and number of orbits to be given as well.")(
248 "nontrivial-mu-distribution", bpo::value<std::string>(&optvalues.nontrivial_mu_distribution)->default_value(""), "Distribution for MU(BC)");
249
250 options.add_options()("help,h", "Produce help message.");
251
252 bpo::variables_map vm;
253 try {
254 bpo::store(bpo::command_line_parser(argc, argv).options(options).run(), vm);
255 bpo::notify(vm);
256
257 // help
258 if (vm.count("help")) {
259 std::cout << options << std::endl;
260 return false;
261 }
262 if (vm.count("show-context")) {
263 optvalues.printContext = true;
264 }
265 if (vm.count("use-existing-kine")) {
266 optvalues.useexistingkinematics = true;
267 }
268
270
271 // fix the first orbit and bunch crossing
272 // auto orbitbcpair = parseOrbitAndBC(optvalues.firstIRString);
273 optvalues.firstOrbit = (uint32_t)optvalues.firstFractionalOrbit;
274 optvalues.firstBC = (uint32_t)((optvalues.firstFractionalOrbit - 1. * optvalues.firstOrbit) * o2::constants::lhc::LHCMaxBunches);
275 LOG(info) << "First orbit " << optvalues.firstOrbit;
276 LOG(info) << "First BC " << optvalues.firstBC;
277
278 } catch (const bpo::error& e) {
279 std::cerr << e.what() << "\n\n";
280 std::cerr << "Error parsing options; Available options:\n";
281 std::cerr << options << std::endl;
282 return false;
283 }
284 return true;
285}
286
287bool copy_collision_context(const std::string& external_path, int this_tf_id, int target_tf_id)
288{
289 namespace fs = std::filesystem;
290 try {
291 fs::path filename;
292 if (fs::exists(external_path) && fs::is_regular_file(external_path)) {
293 std::cout << "external_path is an existing file: " << external_path << "\n";
294 // use it directly
295 filename = fs::path(external_path);
296 } else {
297 // Construct source file path
298 filename = fs::path(external_path) / ("collission_context_" + std::to_string(this_tf_id) + ".root");
299 }
300
301 LOG(info) << "Checking existence of file: " << filename;
302
303 if (fs::exists(filename)) {
304 // Build destination path
305 std::string path_prefix = "tf"; // Can be made configurable
306 std::stringstream destination_path_stream;
307 destination_path_stream << path_prefix << (target_tf_id) << "/collisioncontext.root";
308 fs::path destination_path = destination_path_stream.str();
309
310 // Ensure parent directory exists
311 fs::path destination_dir = destination_path.parent_path();
312 if (!fs::exists(destination_dir)) {
313 fs::create_directories(destination_dir);
314 LOG(info) << "Created directory: " << destination_dir;
315 }
316
317 // Copy file
318 fs::copy_file(filename, destination_path, fs::copy_options::overwrite_existing);
319 LOG(info) << "Copied file to: " << destination_path;
320 return true;
321 } else {
322 LOG(warning) << "Source file does not exist: " << filename;
323 return false;
324 }
325 } catch (const fs::filesystem_error& e) {
326 LOG(error) << "Filesystem error: " << e.what();
327 return false;
328 } catch (const std::exception& e) {
329 LOG(error) << "Unexpected error: " << e.what();
330 return false;
331 }
332 return true;
333}
334
335int main(int argc, char* argv[])
336{
337 Options options;
338 if (!parseOptions(argc, argv, options)) {
339 exit(1);
340 }
341
342 // init params
344
345 // See if this is external mode, which simplifies things
346 if (options.external_path.size() > 0) {
347 // in this mode, we don't actually have to do much work.
348 // all we do is to
349 // - determine how many timeframes are asked
350 // - check if the right files are present in the external path (someone else needs to create/put them there)
351 // - check if the given contexts are consistent with options given (orbitsPerTF, ...)
352 // - copy the files into the MC destination folder (this implies timeframeextraction mode)
353 // - return
354
355 if (options.orbits < 0) {
356 LOG(error) << "External mode; orbits need to be given";
357 return 1;
358 }
359
360 if (options.orbitsPerTF == 0) {
361 LOG(error) << "External mode; need to have orbitsPerTF";
362 return 1;
363 }
364
365 if (options.individualTFextraction.size() == 0) {
366 LOG(error) << "External mode: This requires --extract-per-timeframe";
367 return 1;
368 }
369
370 // calculate number of timeframes
371 auto num_timeframes = options.orbits / options.orbitsPerTF;
372 LOG(info) << "External mode for " << num_timeframes << " consecutive timeframes; starting from " << options.tfid;
373
374 // loop over all timeframe ids - check if file is present - (check consistency) - copy to final destination
375 for (int i = 0; i < num_timeframes; ++i) {
376 auto this_tf_id = options.tfid + i;
377 if (!copy_collision_context(options.external_path, this_tf_id, i + 1)) {
378 return 1;
379 }
380 }
381 return 0;
382 }
383
384 // init random generator
385 gRandom->SetSeed(options.seed);
386
387 std::vector<InteractionSpec> ispecs;
388 // building the interaction spec
389 for (auto& i : options.interactionRates) {
390 // this is created as output from
391 ispecs.push_back(parseInteractionSpec(i, ispecs, options.useexistingkinematics));
392 }
393
394 std::vector<std::pair<o2::InteractionTimeRecord, std::vector<o2::steer::EventPart>>> collisions;
395 std::vector<o2::BunchFilling> bunchFillings; // vector of bunch filling objects; generated by interaction samplers
396
397 // now we generate the collision structure (interaction type by interaction type)
398 bool usetimeframelength = options.orbits > 0;
399
400 auto setBCFillingHelper = [&options](auto& sampler, auto& bcPatternString) {
401 if (bcPatternString == "ccdb") {
402 LOG(info) << "Fetch bcPattern information from CCDB";
403 // fetch the GRP Object
405 ccdb.setCaching(false);
406 ccdb.setLocalObjectValidityChecking(true);
407 auto grpLHC = ccdb.getForTimeStamp<o2::parameters::GRPLHCIFData>("GLO/Config/GRPLHCIF", options.timestamp);
408 LOG(info) << "Fetched injection scheme " << grpLHC->getInjectionScheme() << " from CCDB";
409 sampler.setBunchFilling(grpLHC->getBunchFilling());
410 } else {
411 sampler.setBunchFilling(bcPatternString);
412 }
413 };
414
415 // this is the starting orbit from which on we construct interactions (it is possibly shifted by one tf to the left
416 // in order to generate eventual "earlyOrbits"
417 auto orbitstart = options.firstOrbit + options.tfid * options.orbitsPerTF;
418 auto orbits_total = options.orbits;
419 if (options.orbitsEarly > 0.) {
420 orbitstart -= options.orbitsPerTF;
421 orbits_total += options.orbitsPerTF;
422 }
423
424 for (int id = 0; id < ispecs.size(); ++id) {
425 auto mode = ispecs[id].syncmode;
427 auto sampler = std::make_unique<o2::steer::InteractionSampler>();
428 std::unique_ptr<TH1F> mu_hist;
429
430 // we check if there is a realistic bunch crossing distribution available
431 const auto& mu_distr_source = options.nontrivial_mu_distribution;
432 if (mu_distr_source.size() > 0) {
433 if (mu_distr_source.find("ccdb") == 0) {
434 auto ccdb_info_wrapper = parseCcdbRegex(mu_distr_source);
435 if (!ccdb_info_wrapper.has_value()) {
436 LOG(error) << "Could not parse CCDB path for mu(bc) distribution";
437 } else {
438 auto& ccdb_info = ccdb_info_wrapper.value();
439
440 // for now construct a specific CCDBManager for this query
441 o2::ccdb::CCDBManagerInstance ccdb_inst(ccdb_info.server + std::string(":") + ccdb_info.port);
442 ccdb_inst.setFatalWhenNull(false);
443 // this is a private instance, so it does not inherit the time-machine
444 // constraint that BasicCCDBManager picks up from the environment;
445 // carry it over explicitly (a 0 here means "unconstrained" anyway)
446 ccdb_inst.setCreatedNotAfter(o2::ccdb::BasicCCDBManager::instance().getCreatedNotAfter());
447 auto local_hist = ccdb_inst.getForTimeStamp<TH1F>(ccdb_info.fullPath, options.timestamp);
448 if (local_hist) {
449 // case in which CCDB object contains directly a ROOT histogram
450 mu_hist.reset((TH1F*)local_hist->Clone("h2")); // we need to clone since ownership of local_hist is with TFile
451 } else if (auto events_per_bc = ccdb_inst.getForTimeStamp<o2::ft0::EventsPerBc>(ccdb_info.fullPath, options.timestamp)) {
452 // case in which CCDB object is from FT0 EventsPerBC calib (will be default)
453 mu_hist = events_per_bc->toTH1F();
454 } else {
455 LOG(warn) << "No mu(bc) distribution found on CCDB. Using uniform one";
456 }
457 }
458 } else {
459 // we interpret the file as a ROOT file and open it to extract the wanted histogram
460 auto mudistr_file = TFile::Open(mu_distr_source.c_str(), "OPEN");
461 if (mudistr_file && !mudistr_file->IsZombie()) {
462 auto local_hist = mudistr_file->Get<TH1F>("hBcTVX");
463 mu_hist.reset((TH1F*)local_hist->Clone("h2")); // we need to clone since ownership of local_hist is with TFile
464 mudistr_file->Close();
465 }
466 }
467 if (mu_hist) {
468 LOG(info) << "Found an external mu distribution with mean BC value " << mu_hist->GetMean();
469
470 // do some checks
471
472 // reset to correct interaction Sampler type
474 }
475 }
476
477 // for debug purposes: allows to instantiate trivial sampler
478 if (const char* env = getenv("ALICEO2_ENFORCE_TRIVIAL_BC_SAMPLER")) {
479 std::string spec(env);
480 std::regex re(R"((\d+):(\d+))");
481 std::smatch match;
482 int every_n = 1, mult = 1;
483 if (std::regex_match(spec, match, re)) {
484 every_n = std::stoi(match[1]);
485 mult = std::stoi(match[2]);
486 } else {
487 LOG(error) << "ALICEO2_ENFORCE_TRIVIAL_BC_SAMPLER format invalid, expected NUMBER_1:NUMBER_2";
488 exit(1);
489 }
490 sampler.reset(new o2::steer::FixedSkipBC_InteractionSampler(every_n, mult));
491 }
492
493 sampler->setInteractionRate(ispecs[id].interactionRate);
494 if (!options.bcpatternfile.empty()) {
495 setBCFillingHelper(*sampler, options.bcpatternfile);
496 }
497 sampler->init();
498 if (auto sampler_cast = dynamic_cast<o2::steer::NonUniformMuInteractionSampler*>(sampler.get())) {
499 if (mu_hist) {
500 sampler_cast->setBCIntensityScales(*mu_hist);
501 }
502 }
503
505 // this loop makes sure that the first collision is within the range of orbits asked (if noEmptyTF is enabled)
506 do {
507 sampler->setFirstIR(o2::InteractionRecord(options.firstBC, orbitstart));
508 sampler->init();
509 record = sampler->generateCollisionTime();
510 } while (options.noEmptyTF && usetimeframelength && record.orbit >= orbitstart + orbits_total);
511 int count = 0;
512 do {
513 if (usetimeframelength && record.orbit >= orbitstart + orbits_total) {
514 break;
515 }
516 std::vector<o2::steer::EventPart> parts;
517 parts.emplace_back(id, count);
518
519 std::pair<o2::InteractionTimeRecord, std::vector<o2::steer::EventPart>> insertvalue(record, parts);
520 auto iter = std::lower_bound(collisions.begin(), collisions.end(), insertvalue, [](std::pair<o2::InteractionTimeRecord, std::vector<o2::steer::EventPart>> const& a, std::pair<o2::InteractionTimeRecord, std::vector<o2::steer::EventPart>> const& b) { return a.first < b.first; });
521 collisions.insert(iter, insertvalue);
522 record = sampler->generateCollisionTime();
523 count++;
524 } while ((ispecs[id].mcnumberasked > 0 && count < ispecs[id].mcnumberasked)); // TODO: this loop should probably be replaced by a condition with usetimeframelength and number of orbits
525
526 // we support randomization etc on non-injected/embedded interactions
527 // and we can apply them here
528 auto random_shuffle = [](auto first, auto last) {
529 auto n = last - first;
530 for (auto i = n - 1; i > 0; --i) {
531 using std::swap;
532 swap(first[i], first[(int)(gRandom->Rndm() * n)]);
533 }
534 };
535 std::vector<int> eventindices(count);
536 std::iota(eventindices.begin(), eventindices.end(), 0);
537 // apply randomization of order if any
538 if (ispecs[id].randomizeorder) {
539 random_shuffle(eventindices.begin(), eventindices.end());
540 }
541 if (ispecs[id].mcnumberavail > 0) {
542 // apply cutting to number of available entries
543 for (auto& e : eventindices) {
544 e = e % ispecs[id].mcnumberavail;
545 }
546 }
547 // make these transformations final:
548 for (auto& col : collisions) {
549 for (auto& part : col.second) {
550 if (part.sourceID == id) {
551 part.entryID = eventindices[part.entryID];
552 }
553 }
554 }
555
556 // keep bunch filling information produced by these samplers
557 bunchFillings.push_back(sampler->getBunchFilling());
558
559 } else {
560 // we are in some lock/sync mode and modify existing collisions
561 int lastcol = -1;
562 double lastcoltime = -1.;
563 auto distanceval = ispecs[id].synconto.second;
564 auto lockonto = ispecs[id].synconto.first;
565 int eventcount = 0;
566
567 for (int colid = 0; colid < collisions.size(); ++colid) {
568 auto& col = collisions[colid];
569 auto coltime = col.first.getTimeNS();
570
571 bool rightinteraction = false;
572 // we are locking only on collisions which have the referenced interaction present
573 // --> there must be an EventPart with the right sourceID
574 for (auto& eventPart : col.second) {
575 if (eventPart.sourceID == lockonto) {
576 rightinteraction = true;
577 break;
578 }
579 }
580 if (!rightinteraction) {
581 continue;
582 }
583
584 bool inject = false;
585 // we always start with first one
586 if (lastcol == -1) {
587 inject = true;
588 }
589 if (mode == InteractionLockMode::EVERYN && (colid - lastcol) >= distanceval) {
590 inject = true;
591 }
592 if (mode == InteractionLockMode::MINTIMEDISTANCE && (coltime - lastcoltime) >= distanceval) {
593 inject = true;
594 }
595
596 if (inject) {
597 if (ispecs[id].syncmodeop == 'r') {
598 LOG(debug) << "Replacing/overwriting another event ";
599 // Syncing is replacing; which means we need to take out the original
600 // event that we locked onto.
601 // We take out this event part immediately (and complain if there is a problem).
602 int index = 0;
603 auto iter = std::find_if(col.second.begin(), col.second.end(), [lockonto](auto val) { return lockonto == val.sourceID; });
604 if (iter != col.second.end()) {
605 col.second.erase(iter);
606 } else {
607 LOG(error) << "Expected to replace another event part but did not find one for source " << lockonto << " and collision " << colid;
608 }
609 }
610
611 if (ispecs[id].mcnumberavail >= 0) {
612 col.second.emplace_back(id, eventcount % ispecs[id].mcnumberavail);
613 } else {
614 col.second.emplace_back(id, eventcount);
615 }
616 eventcount++;
617 lastcol = colid;
618 lastcoltime = coltime;
619 }
620 }
621 }
622 }
623
624 // create DigitizationContext
626 // we can fill this container
627 auto& parts = digicontext.getEventParts();
628 // we can fill this container
629 auto& records = digicontext.getEventRecords();
630 // copy over information
631 size_t maxParts = 0;
632 for (auto& p : collisions) {
633 records.push_back(p.first);
634 parts.push_back(p.second);
635 maxParts = std::max(p.second.size(), maxParts);
636 }
637 digicontext.setNCollisions(collisions.size());
638 digicontext.setMaxNumberParts(maxParts);
639 // merge bunch filling info
640 for (int i = 1; i < bunchFillings.size(); ++i) {
641 bunchFillings[0].mergeWith(bunchFillings[i]);
642 }
643 digicontext.setBunchFilling(bunchFillings[0]);
644 std::vector<std::string> prefixes;
645 // Signal interaction rate
646 float sgnIRate = -1.;
647 for (auto& p : ispecs) {
648 prefixes.push_back(p.name);
649 // Set the interaction rate from the first pattern with a valid value.
650 // This handles both simple signal-only productions (where "sgn" has the rate)
651 // and embedding productions (where "bkg" has the rate and "sgn" syncs to it)
652 if (sgnIRate < 0 && p.interactionRate > 0) {
653 LOG(debug) << "Setting signal interaction rate to " << p.interactionRate << " Hz in the digitization context.";
654 sgnIRate = p.interactionRate;
655 digicontext.setDigitizerInteractionRate(p.interactionRate);
656 }
657 }
658 digicontext.setSimPrefixes(prefixes);
659
660 // <---- at this moment we have a dense collision context (not representing the final output we want)
661 LOG(info) << "<<------ DENSE CONTEXT ---------";
662 if (options.printContext) {
663 digicontext.printCollisionSummary();
664 }
665 LOG(info) << "-------- DENSE CONTEXT ------->>";
666
667 auto timeframeindices = digicontext.calcTimeframeIndices(orbitstart, options.orbitsPerTF, options.orbitsEarly);
668 LOG(info) << "Fixed " << timeframeindices.size() << " timeframes ";
669 for (auto p : timeframeindices) {
670 LOG(info) << std::get<0>(p) << " " << std::get<1>(p) << " " << std::get<2>(p);
671 }
672
673 // apply max collision per timeframe filters + reindexing of event id (linearisation and compactification)
674 digicontext.applyMaxCollisionFilter(timeframeindices, orbitstart, options.orbitsPerTF, options.maxCollsPerTF, options.orbitsEarly);
675
676 LOG(info) << "Timeframe indices after collision filter";
677 LOG(info) << "Fixed " << timeframeindices.size() << " timeframes ";
678 for (auto p : timeframeindices) {
679 LOG(info) << std::get<0>(p) << " " << std::get<1>(p) << " " << std::get<2>(p);
680 }
681
682 // <---- at this moment we have a dense collision context (not representing the final output we want)
683 LOG(info) << "<<------ FILTERED CONTEXT ---------";
684 if (options.printContext) {
685 digicontext.printCollisionSummary();
686 }
687 LOG(info) << "-------- FILTERED CONTEXT ------->>";
688
689 auto numTimeFrames = timeframeindices.size(); // digicontext.finalizeTimeframeStructure(orbitstart, options.orbitsPerTF, options.orbitsEarly);
690
692 switch (options.vertexMode) {
694 // fetch mean vertex from CCDB
696 if (meanv) {
697 LOG(info) << "Applying vertexing using CCDB mean vertex " << *meanv;
698 digicontext.sampleInteractionVertices(*meanv);
699 } else {
700 LOG(fatal) << "No vertex available";
701 }
702 break;
703 }
704
706 // init this vertex from CCDB or InteractionDiamond parameter
708 o2::dataformats::MeanVertexObject meanv(dparam.position[0], dparam.position[1], dparam.position[2], dparam.width[0], dparam.width[1], dparam.width[2], dparam.slopeX, dparam.slopeY);
709 LOG(info) << "Applying vertexing using DiamondParam mean vertex " << meanv;
710 digicontext.sampleInteractionVertices(meanv);
711 break;
712 }
713 default: {
714 LOG(error) << "Unknown vertex mode ... Not generating vertices";
715 }
716 }
717 }
718
719 // we fill QED contributions to the context
720 if (options.qedInteraction.size() > 0) {
721 // TODO: use bcFilling information
722 auto qedSpec = parseInteractionSpec(options.qedInteraction, ispecs, options.useexistingkinematics);
723 std::cout << "### IRATE " << qedSpec.interactionRate << "\n";
724 digicontext.fillQED(qedSpec.name, qedSpec.mcnumberasked, qedSpec.interactionRate);
725 }
726
727 if (options.printContext) {
728 digicontext.printCollisionSummary();
729 }
730 digicontext.saveToFile(options.outfilename);
731
732 // extract individual timeframes
733 if (options.individualTFextraction.size() > 0) {
734 // we are asked to extract individual timeframe components
735
736 LOG(info) << "Extracting individual timeframe collision contexts";
737 // extract prefix path to store these collision contexts
738 // Function to check the pattern and extract tokens from b
739 auto check_and_extract_tokens = [](const std::string& input, std::vector<std::string>& tokens) {
740 // the regular expression pattern for expected input format
741 const std::regex pattern(R"(^([a-zA-Z0-9]+)(:([a-zA-Z0-9]+(,[a-zA-Z0-9]+)*))?$)");
742 std::smatch matches;
743
744 // Check if the input matches the pattern
745 if (std::regex_match(input, matches, pattern)) {
746 // Clear any existing tokens in the vector
747 tokens.clear();
748
749 // matches[1] contains the part before the colon which we save first
750 tokens.push_back(matches[1].str());
751 // matches[2] contains the comma-separated list
752 std::string b = matches[2].str();
753 std::regex token_pattern(R"([a-zA-Z0-9]+)");
754 auto tokens_begin = std::sregex_iterator(b.begin(), b.end(), token_pattern);
755 auto tokens_end = std::sregex_iterator();
756
757 // Iterate over the tokens and add them to the vector
758 for (std::sregex_iterator i = tokens_begin; i != tokens_end; ++i) {
759 tokens.push_back((*i).str());
760 }
761 return true;
762 }
763 LOG(error) << "Argument for --extract-per-timeframe does not match specification";
764 return false;
765 };
766
767 std::vector<std::string> tokens;
768 if (check_and_extract_tokens(options.individualTFextraction, tokens)) {
769 auto path_prefix = tokens[0];
770 std::vector<int> sources_to_offset{};
771
772 LOG(info) << "PREFIX is " << path_prefix;
773
774 for (int i = 1; i < tokens.size(); ++i) {
775 LOG(info) << "Offsetting " << tokens[i];
776 sources_to_offset.push_back(digicontext.findSimPrefix(tokens[i]));
777 }
778
779 auto first_timeframe = options.orbitsEarly > 0. ? 1 : 0;
780 // now we are ready to loop over all timeframes
781 int tf_output_counter = 1;
782 for (int tf_id = first_timeframe; tf_id < numTimeFrames; ++tf_id) {
783 auto copy = digicontext.extractSingleTimeframe(tf_id, timeframeindices, sources_to_offset);
784
785 // each individual case gets QED interactions injected
786 // This should probably be done inside the extraction itself
787 if (digicontext.isQEDProvided()) {
788 auto qedSpec = parseInteractionSpec(options.qedInteraction, ispecs, options.useexistingkinematics);
789 copy.fillQED(qedSpec.name, qedSpec.mcnumberasked, qedSpec.interactionRate);
790 }
791
792 std::stringstream str;
793 str << path_prefix << tf_output_counter++ << "/collisioncontext.root";
794 copy.saveToFile(str.str());
795 LOG(info) << "---- CollisionContext for timeframe " << tf_id << " -----";
796 copy.printCollisionSummary();
797 }
798 }
799 }
800
801 return 0;
802}
std::vector< o2::soa::IndexRecord > records
std::string url
bool copy_collision_context(const std::string &external_path, int this_tf_id, int target_tf_id)
bool parseOptions(int argc, char *argv[], Options &optvalues)
std::optional< CcdbUrl > parseCcdbRegex(const std::string &url)
InteractionSpec parseInteractionSpec(std::string const &specifier, std::vector< InteractionSpec > const &existingPatterns, bool adjustEventCount)
std::ostringstream debug
int32_t i
container for the LHC InterFace data
Helper function to tokenize sequences and ranges of integral numbers.
uint32_t eventcount
Definition RawData.h:1
uint32_t col
Definition RawData.h:4
static BasicCCDBManager & instance()
void setCreatedNotAfter(long v)
set the object upper validity limit
T * getForTimeStamp(std::string const &path, long timestamp, std::map< std::string, std::string > *headers=nullptr)
retrieve an object of type T from CCDB as stored under path and timestamp. Optional to get the header...
void setFatalWhenNull(bool b)
set the fatal property (when false; nullptr object responses will not abort)
static void updateFromString(std::string const &)
static bool parseVertexModeString(std::string const &vertexstring, o2::conf::VertexMode &mode)
const std::string & getInjectionScheme() const
DigitizationContext extractSingleTimeframe(int timeframeid, std::vector< std::tuple< int, int, int > > const &timeframeindices, std::vector< int > const &sources_to_offset)
void fillQED(std::string_view QEDprefix, int max_events, double qedrate)
add QED contributions to context, giving prefix; maximal event number and qed interaction rate
void printCollisionSummary(bool withQED=false, int truncateOutputTo=-1) const
int findSimPrefix(std::string const &prefix) const
void applyMaxCollisionFilter(std::vector< std::tuple< int, int, int > > &timeframeindices, long startOrbit, long orbitsPerTF, int maxColl, double orbitsEarly=0.)
void setSimPrefixes(std::vector< std::string > const &p)
std::vector< o2::InteractionTimeRecord > & getEventRecords(bool withQED=false)
void sampleInteractionVertices(o2::dataformats::MeanVertexObject const &v)
std::vector< std::vector< o2::steer::EventPart > > & getEventParts(bool withQED=false)
void saveToFile(std::string_view filename) const
void setBunchFilling(o2::BunchFilling const &bf)
std::vector< std::tuple< int, int, int > > calcTimeframeIndices(long startOrbit, long orbitsPerTF, double orbitsEarly=0.) const
get timeframe structure --> index markers where timeframe starts/ends/is_influenced_by
void setDigitizerInteractionRate(float intRate)
size_t getNEvents(int source) const
Get number of events.
bool match(const std::vector< std::string > &queries, const char *pattern)
Definition dcs-ccdb.cxx:229
GLdouble n
Definition glcorearb.h:1982
const GLfloat * m
Definition glcorearb.h:4066
GLenum mode
Definition glcorearb.h:266
GLint GLsizei count
Definition glcorearb.h:399
GLuint GLenum * rate
Definition glcorearb.h:5735
GLuint sampler
Definition glcorearb.h:1630
GLuint index
Definition glcorearb.h:781
GLuint const GLchar * name
Definition glcorearb.h:781
GLint first
Definition glcorearb.h:399
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLuint GLfloat * val
Definition glcorearb.h:1582
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLuint id
Definition glcorearb.h:650
constexpr int LHCMaxBunches
std::string to_string(gsl::span< T, Size > span)
Definition common.h:52
std::string filename()
std::string port
std::string server
std::string fullPath
InteractionLockMode syncmode
std::pair< int, float > synconto
std::string nontrivial_mu_distribution
std::string vertexModeString
std::string configKeyValues
Definition GRPTool.cxx:66
o2::conf::VertexMode vertexMode
std::string individualTFextraction
std::string external_path
std::string bcpatternfile
std::vector< std::string > interactionRates
uint64_t timestamp
Definition GRPTool.cxx:67
std::string outfilename
double firstFractionalOrbit
int orbitsPerTF
Definition GRPTool.cxx:51
std::string qedInteraction
uint32_t orbit
LHC orbit.
void compare(std::string_view s1, std::string_view s2)
#define main
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::array< uint16_t, 5 > pattern
const std::string str