28 std::cout <<
"Summary of DigitizationContext --\n";
29 std::cout <<
"Maximal parts per collision " << mMaxPartNumber <<
"\n";
30 std::cout <<
"Collision parts taken from simulations specified by prefix:\n";
31 for (
int p = 0; p < mSimPrefixes.size(); ++p) {
32 std::cout <<
"Part " << p <<
" : " << mSimPrefixes[p] <<
"\n";
34 std::cout <<
"QED information included " <<
isQEDProvided() <<
"\n";
36 std::cout <<
"Number of Collisions " << mEventRecords.size() <<
"\n";
37 std::cout <<
"Number of QED events " << mEventRecordsWithQED.size() - mEventRecords.size() <<
"\n";
39 for (
int i = 0;
i < mEventRecordsWithQED.size(); ++
i) {
40 if (truncateOutputTo >= 0 &&
i > truncateOutputTo) {
41 std::cout <<
"--- Output truncated to " << truncateOutputTo <<
" ---\n";
44 std::cout <<
"Record " <<
i <<
" TIME " << mEventRecordsWithQED[
i];
45 for (
auto&
e : mEventPartsWithQED[
i]) {
46 std::cout <<
" (" <<
e.sourceID <<
" , " <<
e.entryID <<
")";
51 std::cout <<
"Number of Collisions " << mEventRecords.size() <<
"\n";
52 if (mEventPartsWithQED.size() > 0) {
53 auto num_qed_events = mEventPartsWithQED.size() - mEventRecords.size();
54 if (num_qed_events > 0) {
55 std::cout <<
"Number of QED events (but not shown) " << num_qed_events <<
"\n";
58 auto firstQEDcoll_iter = std::find_if(mEventPartsWithQED.begin(), mEventPartsWithQED.end(),
59 [](
const std::vector<EventPart>&
vec) {
60 return std::find_if(vec.begin(), vec.end(), [](EventPart const& p) { return p.sourceID == 99; }) !=
vec.end();
63 auto lastColl_iter = std::find_if(mEventPartsWithQED.rbegin(), mEventPartsWithQED.rend(),
64 [](
const std::vector<EventPart>&
vec) {
65 return std::find_if(vec.begin(), vec.end(), [](EventPart const& p) { return p.sourceID == 99; }) !=
vec.end();
68 auto firstindex = std::distance(mEventPartsWithQED.begin(), firstQEDcoll_iter);
69 auto lastindex = std::distance(mEventPartsWithQED.begin(), lastColl_iter.base()) - 1;
70 std::cout <<
"QED from: " << mEventRecordsWithQED[firstindex] <<
" ---> " << mEventRecordsWithQED[lastindex] <<
"\n";
73 for (
int i = 0;
i < mEventRecords.size(); ++
i) {
74 if (truncateOutputTo >= 0 &&
i > truncateOutputTo) {
75 std::cout <<
"--- Output truncated to " << truncateOutputTo <<
" ---\n";
78 std::cout <<
"Collision " <<
i <<
" TIME " << mEventRecords[
i];
79 for (
auto&
e : mEventParts[
i]) {
80 std::cout <<
" (" <<
e.sourceID <<
" , " <<
e.entryID <<
")";
82 if (
i < mInteractionVertices.size()) {
83 std::cout <<
" sampled vertex : " << mInteractionVertices[
i];
92 mSimPrefixes = prefixes;
97 if (!(simchains.size() == 0)) {
105 LOG(info) <<
"Not hit file present for " << detid.
getName() <<
" (exiting SimChain setup)";
110 simchains.emplace_back(
new TChain(
"o2sim"));
115 simchains.emplace_back(
new TChain(
"o2sim"));
121 if (mEventRecordsWithQED.size() > 0) {
122 if (mSimPrefixes.size() >= QEDSOURCEID) {
123 LOG(fatal) <<
"Too many signal chains; crashes with QED source ID";
127 simchains.resize(QEDSOURCEID + 1,
nullptr);
128 simchains[QEDSOURCEID] =
new TChain(
"o2sim");
140 if (!(simkinematicschains.size() == 0)) {
145 simkinematicschains.emplace_back(
new TChain(
"o2sim"));
150 simkinematicschains.emplace_back(
new TChain(
"o2sim"));
156 if (mEventRecordsWithQED.size() > 0) {
157 if (mSimPrefixes.size() >= QEDSOURCEID) {
158 LOG(fatal) <<
"Too many signal chains; crashes with QED source ID";
162 simkinematicschains.resize(QEDSOURCEID + 1,
nullptr);
163 simkinematicschains[QEDSOURCEID] =
new TChain(
"o2sim");
172 if (mMaxPartNumber == 1) {
176 auto checkVertexPair = [](math_utils::Point3D<double>
const&
p1, math_utils::Point3D<double>
const&
p2) ->
bool {
177 return (
p2 -
p1).Mag2() < 1E-6;
180 std::vector<TChain*> kinematicschain;
181 std::vector<TBranch*> headerbranches;
182 std::vector<o2::dataformats::MCEventHeader*> headers;
183 std::vector<math_utils::Point3D<double>> vertices;
185 bool consistent =
true;
186 if (kinematicschain.size() > 0) {
187 headerbranches.resize(kinematicschain.size(),
nullptr);
188 headers.resize(kinematicschain.size(),
nullptr);
194 for (
auto& part : collision) {
195 const auto source = part.sourceID;
196 const auto entry = part.entryID;
198 if (!headerbranches[
source]) {
199 headerbranches[
source] =
chain->GetBranch(
"MCEventHeader.");
208 bool thiscollision =
true;
209 const auto&
p1 = vertices[0];
210 for (
int j = 1;
j < vertices.size(); ++
j) {
211 const auto&
p2 = vertices[
j];
212 bool thischeck = checkVertexPair(
p1,
p2);
213 thiscollision &= thischeck;
215 if (verbose && !thiscollision) {
216 std::stringstream text;
217 text <<
"Found inconsistent vertices for digit collision ";
218 text << collisionID <<
" : ";
219 for (
auto& p : vertices) {
224 consistent &= thiscollision;
243 auto ensure_path_exists = [](std::string_view
filename) {
246 std::filesystem::path file_path(
filename);
247 std::filesystem::path dir_path = file_path.parent_path();
250 if (dir_path.empty()) {
256 if (!std::filesystem::exists(dir_path)) {
257 if (std::filesystem::create_directories(dir_path)) {
261 std::cerr <<
"Failed to create directories: " << dir_path.string() << std::endl;
266 }
catch (
const std::filesystem::filesystem_error& ex) {
267 std::cerr <<
"Filesystem error: " << ex.what() << std::endl;
269 }
catch (
const std::exception& ex) {
270 std::cerr <<
"General error: " << ex.what() << std::endl;
275 if (!ensure_path_exists(
filename)) {
276 LOG(
error) <<
"Filename contains path component which could not be created";
282 auto cl = TClass::GetClass(
typeid(*
this));
283 file.WriteObjectAny(
this, cl,
"DigitizationContext");
299 file.GetObject(
"DigitizationContext", incontext);
305 if (mEventRecords.size() <= 1) {
316 auto first = mEventRecords.front();
317 auto last = mEventRecords.back();
319 last.bc = o2::constants::lhc::LHCMaxBunches;
320 LOG(info) <<
"QED RATE " << qedrate;
323 qedInteractionSampler.
init();
324 qedInteractionSampler.
print();
325 std::vector<o2::InteractionTimeRecord> qedinteractionrecords;
327 LOG(info) <<
"GENERATING COL TIMES";
330 qedinteractionrecords.push_back(
t);
332 LOG(info) <<
"DONE GENERATING COL TIMES";
333 fillQED(QEDprefix, qedinteractionrecords, max_events,
false);
336void DigitizationContext::fillQED(std::string_view QEDprefix, std::vector<o2::InteractionTimeRecord>
const& irecord,
int max_events,
bool fromKinematics)
338 mQEDSimPrefix = QEDprefix;
340 std::vector<std::vector<o2::steer::EventPart>> qedEventParts;
342 int numberQEDevents = max_events;
343 if (fromKinematics) {
347 TFile
f(qedKinematicsName.c_str(),
"OPEN");
348 auto t = (TTree*)
f.Get(
"o2sim");
350 LOG(
error) <<
"No QED kinematics found";
351 throw std::runtime_error(
"No QED kinematics found");
353 numberQEDevents =
t->GetEntries();
357 for (
auto& tmp : irecord) {
358 std::vector<EventPart> qedpart;
359 qedpart.emplace_back(QEDSOURCEID, eventID++);
360 qedEventParts.push_back(qedpart);
361 if (eventID == numberQEDevents) {
369 auto combinedrecords = mEventRecords;
370 combinedrecords.insert(combinedrecords.end(), irecord.begin(), irecord.end());
371 auto combinedparts = mEventParts;
372 combinedparts.insert(combinedparts.end(), qedEventParts.begin(), qedEventParts.end());
375 std::vector<size_t> idx(combinedrecords.size());
376 std::iota(idx.begin(), idx.end(), 0);
378 std::stable_sort(idx.begin(), idx.end(),
379 [&combinedrecords](
size_t i1,
size_t i2) { return combinedrecords[i1] < combinedrecords[i2]; });
381 mEventRecordsWithQED.clear();
382 mEventPartsWithQED.clear();
383 for (
int i = 0;
i < idx.size(); ++
i) {
384 mEventRecordsWithQED.push_back(combinedrecords[idx[
i]]);
385 mEventPartsWithQED.push_back(combinedparts[idx[
i]]);
397std::vector<std::pair<int, int>> getTimeFrameBoundaries(std::vector<o2::InteractionTimeRecord>
const& irecords,
long startOrbit,
long orbitsPerTF,
long nTimeframes = -1)
399 std::vector<std::pair<int, int>>
result;
401 auto pad_and_return = [&
result, nTimeframes](
int index) {
402 if (nTimeframes > 0) {
403 while ((
long)
result.size() < nTimeframes) {
406 result.resize(nTimeframes);
412 if (irecords.size() == 0) {
413 return pad_and_return(0);
416 if (irecords.back().orbit < startOrbit) {
417 LOG(
error) <<
"start orbit larger than last collision entry";
418 return pad_and_return((
int)irecords.size());
423 while (
left < irecords.size() && irecords[
left].orbit < startOrbit) {
429 long timeframe_count = 1;
430 while (
right < irecords.size()) {
435 while (irecords[
right].
orbit >= startOrbit + timeframe_count * orbitsPerTF) {
444 return pad_and_return((
int)irecords.size());
448std::vector<std::tuple<int, int, int>> getTimeFrameBoundaries(std::vector<o2::InteractionTimeRecord>
const& irecords,
452 long nTimeframes = -1)
455 auto true_indices = getTimeFrameBoundaries(irecords, startOrbit, orbitsPerTF, nTimeframes);
457 std::vector<std::tuple<int, int, int>> indices_with_early{};
458 for (
int ti = 0; ti < true_indices.size(); ++ti) {
460 auto& tf_range = true_indices[ti];
463 indices_with_early.push_back(std::make_tuple(tf_range.first, tf_range.second, -1));
467 if (orbitsEarly > 0. && ti > 0 && tf_range.first <= tf_range.second) {
468 auto& prev_tf_range = true_indices[ti - 1];
472 int earlyOrbitIndex = -1;
475 auto orbit_timeframe_start = startOrbit + ti * orbitsPerTF;
477 auto orbit_timeframe_early_fractional = 1. * orbit_timeframe_start - orbitsEarly;
478 auto orbit_timeframe_early_integral =
static_cast<long>(std::floor(orbit_timeframe_early_fractional));
480 auto bc_early = (
uint32_t)((orbit_timeframe_early_fractional - orbit_timeframe_early_integral) * o2::constants::lhc::LHCMaxBunches);
488 auto differenceInBCNS_max = timeframe_start_record.differenceInBCNS(timeframe_early_record);
490 for (
int j = prev_tf_range.second;
j >= prev_tf_range.first; --
j) {
492 auto timediff_NS = timeframe_start_record.differenceInBCNS(irecords[
j]);
493 if (timediff_NS < differenceInBCNS_max) {
499 std::get<2>(indices_with_early.back()) = earlyOrbitIndex;
502 return indices_with_early;
512 std::vector<std::vector<o2::steer::EventPart>> newparts;
513 std::vector<o2::InteractionTimeRecord> newrecords;
515 std::unordered_map<int, int> currMaxId;
516 std::unordered_map<int, std::unordered_map<int, int>> reIndexMap;
519 maxColl = mEventRecords.size();
523 int first_timeframe = orbitsEarly > 0. ? 1 : 0;
526 std::unordered_map<size_t, size_t> indices_old_to_new;
529 for (
int tf_id = first_timeframe; tf_id < timeframeindices.size(); ++tf_id) {
530 auto& tf_indices = timeframeindices[tf_id];
532 auto firstindex = std::get<0>(tf_indices);
533 auto lastindex = std::get<1>(tf_indices);
534 auto previndex = std::get<2>(tf_indices);
536 LOG(info) <<
"timeframe indices " << previndex <<
" : " << firstindex <<
" : " << lastindex;
539 const size_t nrecords_before = newrecords.size();
541 for (
int index = previndex >= 0 ? previndex : firstindex;
index <= lastindex; ++
index) {
542 if (collCount >= maxColl) {
548 if (indices_old_to_new.find(
index) != indices_old_to_new.end()) {
553 bool keep =
index < firstindex || collCount < maxColl;
559 if (
index >= firstindex) {
567 indices_old_to_new[
index] = newrecords.size();
568 newrecords.push_back(mEventRecords[
index]);
569 newparts.push_back(mEventParts[
index]);
572 for (
auto& part : newparts.back()) {
573 auto source = part.sourceID;
574 auto entry = part.entryID;
576 if (reIndexMap.find(
source) != reIndexMap.end() && reIndexMap[
source].find(
entry) != reIndexMap[
source].end()) {
580 if (currMaxId.find(
source) == currMaxId.end()) {
583 part.entryID = currMaxId[
source];
592 if (newrecords.size() == nrecords_before) {
595 std::get<0>(tf_indices) = (int)newrecords.size();
596 std::get<1>(tf_indices) = (int)newrecords.size() - 1;
597 std::get<2>(tf_indices) = -1;
600 if (indices_old_to_new.find(firstindex) != indices_old_to_new.end()) {
601 std::get<0>(tf_indices) = indices_old_to_new[firstindex];
603 if (indices_old_to_new.find(lastindex) != indices_old_to_new.end()) {
604 std::get<1>(tf_indices) = indices_old_to_new[lastindex];
606 std::get<1>(tf_indices) = newrecords.size() - 1;
608 if (indices_old_to_new.find(previndex) != indices_old_to_new.end()) {
609 std::get<2>(tf_indices) = indices_old_to_new[previndex];
613 mEventRecords = newrecords;
614 mEventParts = newparts;
619 auto timeframeindices = getTimeFrameBoundaries(mEventRecords, startOrbit, orbitsPerTF, orbitsEarly, nTimeframes);
620 return timeframeindices;
627 std::unordered_map<int, int>
result;
629 for (
int collindex = 0; collindex < parts.size(); ++collindex) {
630 for (
auto& eventpart : parts[collindex]) {
631 if (eventpart.sourceID ==
source) {
632 result[eventpart.entryID] = collindex;
641 auto iter = std::find(mSimPrefixes.begin(), mSimPrefixes.end(), prefix);
642 if (iter != mSimPrefixes.end()) {
643 return std::distance(mSimPrefixes.begin(), iter);
651 template <
class T1,
class T2>
652 std::size_t operator()(
const std::pair<T1, T2>& pair)
const
654 return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
661 if (external_vertices.size() != mEventRecords.size()) {
662 LOG(
error) <<
"Size mismatch with event record";
665 mInteractionVertices.clear();
666 std::copy(external_vertices.begin(), external_vertices.end(), std::back_inserter(mInteractionVertices));
673 std::unordered_map<std::pair<int, int>, int, pair_hash> vertex_cache;
675 mInteractionVertices.clear();
678 std::unordered_set<int> vset;
679 for (
auto& coll : mEventParts) {
684 for (
auto& part : coll) {
685 auto source = part.sourceID;
686 auto event = part.entryID;
687 auto cached_iter = vertex_cache.find(std::pair<int, int>(
source,
event));
689 if (cached_iter != vertex_cache.end()) {
690 vset.emplace(cached_iter->second);
695 if (vset.size() > 1) {
696 LOG(fatal) <<
"Impossible conflict during interaction vertex sampling";
700 if (vset.size() == 1) {
702 cacheindex = *(vset.begin());
703 mInteractionVertices.push_back(mInteractionVertices[cacheindex]);
706 mInteractionVertices.emplace_back(meanv.
sample());
707 cacheindex = mInteractionVertices.size() - 1;
710 for (
auto& part : coll) {
711 auto source = part.sourceID;
712 auto event = part.entryID;
713 vertex_cache[std::pair<int, int>(
source,
event)] = cacheindex;
721 if (timeframeindices.size() == 0) {
722 LOG(
error) <<
"Timeframe index structure empty; Returning empty object.";
725 r.mSimPrefixes = mSimPrefixes;
727 r.mBCFilling = mBCFilling;
728 r.mDigitizerInteractionRate = mDigitizerInteractionRate;
730 auto tf_ranges = timeframeindices.at(timeframeid);
732 auto startindex = std::get<0>(tf_ranges);
733 auto endindex = std::get<1>(tf_ranges) + 1;
734 auto earlyindex = std::get<2>(tf_ranges);
736 if (earlyindex >= 0) {
737 startindex = earlyindex;
739 if (endindex < startindex) {
742 endindex = startindex;
744 std::copy(mEventRecords.begin() + startindex, mEventRecords.begin() + endindex, std::back_inserter(
r.mEventRecords));
745 std::copy(mEventParts.begin() + startindex, mEventParts.begin() + endindex, std::back_inserter(
r.mEventParts));
746 if (mInteractionVertices.size() >= endindex) {
747 std::copy(mInteractionVertices.begin() + startindex, mInteractionVertices.begin() + endindex, std::back_inserter(
r.mInteractionVertices));
753 auto perform_offsetting = [&
r](
int source_id) {
754 auto indices_for_source =
r.getCollisionIndicesForSource(source_id);
755 int minvalue = std::numeric_limits<int>::max();
756 for (
auto& p : indices_for_source) {
757 if (p.first < minvalue) {
762 for (
auto& p : indices_for_source) {
763 auto index_into_mEventParts = p.second;
764 for (
auto& part :
r.mEventParts[index_into_mEventParts]) {
765 if (part.sourceID == source_id) {
766 part.entryID -= minvalue;
771 for (
auto source_id : sources_to_offset) {
772 perform_offsetting(source_id);
775 }
catch (std::exception) {
776 LOG(warn) <<
"No such timeframe id in collision context. Returing empty object";
779 r.setNCollisions(
r.mEventRecords.size());
Definition of the Names Generator class.
std::vector< std::string > header
configStandalone Light OpenGL display display_light Apply smoothing to points Enable Z buffer Highlight links Highlight seeds Highlight sector tracks Highlight final tracks Show individual Show related Highlight grid Show only individual collision Color clusters belonging to track objects Set line Enable drawing TPC data Enable drawing TOF data Enable drawing magnetic field Set field line step count Invert colors configStandalone Heavy OpenGL display display_heavy Show tracks with ITS contribution Show tracks with TOF contribution Enable propagation of loopers Show clusters at nominal x of pad row for early transformed data Split CE tracks when they cross the central Mark clusters Mark adjacent clusters Hide rejected tracks Apply filter on tracks to be displayed Separate increase X h configStandalone Camera window renderer OpenGL display display_camera Orient the camera such that the y axis is always upwards Full Screen MultiSample Anti Downsampling Anti Enable Vertical Sync Target frame or if the backend cannot limit to the refresh Use OpenGL indirect draws to reduce number of draw calls Display h configStandalone Vulkan display display_vulkan Have uniform buffers in host accessible device memory h configStandalone Internal display display_internal Number of updates the Qt GUI may send ahead of the last one the display has before it waits for the display Opacity of the console background Number of console lines the history is shortened to this when it reaches twice the size Time in seconds an info message fades out after setInfoTime h OpenGL display display Font size Do not use Freetype for font Renderer for event Frontend to use for event ROOT macros used as track filter Console script file
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
constexpr int p1()
constexpr to accelerate the coordinates changing
char error[CURL_ERROR_SIZE]
static std::string getHitsFileName(DId d, const std::string_view prefix=STANDARDSIMPREFIX)
static std::string getMCKinematicsFileName(const std::string_view prefix=STANDARDSIMPREFIX)
static std::string getCollisionContextFileName(const std::string_view prefix="")
Static class with identifiers, bitmasks and names for ALICE detectors.
static constexpr const char * getName(ID id)
names of defined detectors
static GRPObject * loadFrom(const std::string &grpFileName="")
DigitizationContext extractSingleTimeframe(int timeframeid, std::vector< std::tuple< int, int, int > > const &timeframeindices, std::vector< int > const &sources_to_offset)
bool checkVertexCompatibility(bool verbose=false) const
Check collision parts for vertex consistency.
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
bool initSimChains(o2::detectors::DetID detid, std::vector< TChain * > &simchains) const
std::unordered_map< int, int > getCollisionIndicesForSource(int source) const
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.)
int setInteractionVertices(std::vector< math_utils::Point3D< float > > const &vertices)
void setSimPrefixes(std::vector< std::string > const &p)
std::vector< std::tuple< int, int, int > > calcTimeframeIndices(long startOrbit, long orbitsPerTF, double orbitsEarly=0., long nTimeframes=-1) const
bool initSimKinematicsChains(std::vector< TChain * > &simkinematicschains) const
o2::parameters::GRPObject const & getGRP() const
returns the GRP object associated to this context
bool isQEDProvided() const
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
static DigitizationContext * loadFromFile(std::string_view filename="")
void setFirstIR(const o2::InteractionRecord &ir)
const o2::InteractionTimeRecord & generateCollisionTime()
void setBunchFilling(const BunchFilling &bc)
void setInteractionRate(float rateHz)
GLsizei GLsizei GLchar * source
std::vector< o2::ctf::BufferType > vec
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"