Project
Loading...
Searching...
No Matches
Detector.h
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
14
15#ifndef ALICEO2_BASE_DETECTOR_H_
16#define ALICEO2_BASE_DETECTOR_H_
17
18#include <map>
19#include <tbb/concurrent_unordered_map.h>
20#include <vector>
21#include <initializer_list>
22#include <memory>
23
24#include "FairDetector.h" // for FairDetector
25#include "FairRootManager.h"
27#include "Rtypes.h" // for Float_t, Int_t, Double_t, Detector::Class, etc
28#include <cxxabi.h>
29#include <typeinfo>
30#include <type_traits>
31#include <string>
34#include <sys/shm.h>
35#include <atomic>
36#include <type_traits>
37#include <unistd.h>
38#include <cassert>
39#include <list>
40#include <mutex>
41#include <thread>
42
43#include <fairmq/FwdDecls.h>
44
45namespace o2::base
46{
47
50class Detector : public FairDetector
51{
52
53 public:
54 Detector(const char* name, Bool_t Active);
55
57 Detector();
58
60 ~Detector() override;
61
62 // Module composition
63 void Material(Int_t imat, const char* name, Float_t a, Float_t z, Float_t dens, Float_t radl, Float_t absl,
64 Float_t* buf = nullptr, Int_t nwbuf = 0);
65
66 void Mixture(Int_t imat, const char* name, Float_t* a, Float_t* z, Float_t dens, Int_t nlmat,
67 Float_t* wmat);
68
69 void Medium(Int_t numed, const char* name, Int_t nmat, Int_t isvol, Int_t ifield, Float_t fieldm,
70 Float_t tmaxfd, Float_t stemax, Float_t deemax, Float_t epsil, Float_t stmin, Float_t* ubuf = nullptr,
71 Int_t nbuf = 0);
72
74 void SpecialCuts(Int_t numed, const std::initializer_list<std::pair<ECut, Float_t>>& parIDValMap);
76 void SpecialCut(Int_t numed, ECut parID, Float_t val);
77
78 void SpecialProcesses(Int_t numed, const std::initializer_list<std::pair<EProc, int>>& parIDValMap);
80 void SpecialProcess(Int_t numed, EProc parID, int val);
81
90 void Matrix(Int_t& nmat, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3,
91 Double_t phi3) const;
92
93 static void setDensityFactor(Float_t density)
94 {
95 mDensityFactor = density;
96 }
97
99 {
100 return mDensityFactor;
101 }
102
105 void SetSpecialPhysicsCuts() override;
106
108 virtual void addAlignableVolumes() const;
109
111 virtual void fillParallelWorld() const;
112
114 virtual void defineWrapperVolume(Int_t id, Double_t rmin, Double_t rmax, Double_t zspan);
115
117 virtual void setNumberOfWrapperVolumes(Int_t n);
118
119 virtual void defineLayer(Int_t nlay, Double_t phi0, Double_t r, Int_t nladd, Int_t nmod,
120 Double_t lthick = 0., Double_t dthick = 0., UInt_t detType = 0, Int_t buildFlag = 0);
121
122 virtual void defineLayerTurbo(Int_t nlay, Double_t phi0, Double_t r, Int_t nladd, Int_t nmod,
123 Double_t width, Double_t tilt, Double_t lthick = 0., Double_t dthick = 0.,
124 UInt_t detType = 0, Int_t buildFlag = 0);
125
126 // returns global material ID given a "local" material ID for this detector
127 // returns -1 in case local ID not found
128 int getMaterialID(int imat) const
129 {
131 return mgr.getMaterialID(GetName(), imat);
132 }
133
134 // returns global medium ID given a "local" medium ID for this detector
135 // returns -1 in case local ID not found
136 int getMediumID(int imed) const
137 {
139 return mgr.getMediumID(GetName(), imed);
140 }
141
142 // fill the medium index mapping into a standard vector
143 // the vector gets sized properly and will be overridden
144 void getMediumIDMappingAsVector(std::vector<int>& mapping)
145 {
147 mgr.getMediumIDMappingAsVector(GetName(), mapping);
148 }
149
150 // return the name augmented by extension
151 std::string addNameTo(const char* ext) const
152 {
153 std::string s(GetName());
154 return s + ext;
155 }
156
157 // returning the name of the branch (corresponding to probe)
158 // returns zero length string when probe not defined
159 virtual std::string getHitBranchNames(int probe) const = 0;
160
161 // interface to update track indices of data objects
162 // usually called by the Stack, at the end of an event, which might have changed
163 // the track indices due to filtering
164 // FIXME: make private friend of stack?
165 virtual void updateHitTrackIndices(std::map<int, int> const&) = 0;
166
167 // the index a hit's track ended up at after the stack filtered the event;
168 // a pruned track has no entry in the mapping and gets the invalid index -1
169 static int updatedTrackIndex(std::map<int, int> const& indexmapping, int trackID)
170 {
171 const auto iter = indexmapping.find(trackID);
172 return iter != indexmapping.end() ? iter->second : -1;
173 }
174
175 // the index a hit or a track reference gets when the sub-events of one event
176 // are concatenated; an index already flagged invalid carries no track to
177 // shift and stays invalid
178 static int offsetTrackIndex(int trackID, int nprimaries, int primaryOffset, int secondaryOffset)
179 {
180 if (trackID < 0) {
181 return trackID;
182 }
183 return trackID + (trackID < nprimaries ? primaryOffset : secondaryOffset);
184 }
185
186 // interfaces to attach properly encoded hit information to a FairMQ message
187 // and to decode it
188 virtual void attachHits(fair::mq::Channel&, fair::mq::Parts&) = 0;
189 virtual void fillHitBranch(TTree& tr, fair::mq::Parts& parts, int& index) = 0;
190 virtual void collectHits(int eventID, fair::mq::Parts& parts, int& index, bool shm) = 0;
191 virtual void mergeHitEntriesAndFlush(int eventID,
192 TTree& target,
193 std::vector<int> const& trackoffsets,
194 std::vector<int> const& nprimaries,
195 std::vector<int> const& subevtsOrdered) = 0;
196
197 // interface needed to merge together hit entries in TBranches (as used by hit merger process)
198 // trackoffsets: a map giving the corresponding trackoffset to be applied to the trackID property when
199 // merging
200 virtual void mergeHitEntries(TTree& origin, TTree& target, std::vector<int> const& trackoffsets, std::vector<int> const& nprimaries, std::vector<int> const& subevtsOrdered) = 0;
201
202 // hook which is called automatically to custom initialize the O2 detectors
203 // all initialization not able to do in constructors should be done here
204 // (typically the case for geometry related stuff, etc)
205 virtual void InitializeO2Detector() = 0;
206
207 // the original FairModule/Detector virtual Initialize function
208 // calls individual customized initializations and makes sure that the mother Initialize
209 // is called as well. Marked final for this reason!
210 void Initialize() final
211 {
213 // make sure the basic initialization is also done
215 }
216
217 // a second initialization method for stuff that should be initialized late
218 // (in our case after forking off from the main simulation setup
219 // ... for things that should be setup in each simulation worker separately)
220 virtual void initializeLate() = 0;
221
223 virtual bool isMTSafe() const { return false; }
224
227 int registerSensitiveVolumeAndGetVolID(std::string const& name);
228
231 int registerSensitiveVolumeAndGetVolID(TGeoVolume const* vol);
232
233 // The GetCollection interface is made final and deprecated since
234 // we no longer support TClonesArrays
235 [[deprecated("Use getHits API on concrete detectors!")]] TClonesArray* GetCollection(int iColl) const final;
236
237 // static and reusable service function to set tracking parameters in relation to field
238 // returns global integration mode (inhomogenety) for the field and the max field value
239 // which is required for media creation
240 static void initFieldTrackingParams(int& mode, float& maxfield);
241
243 static void setDetId2HitBitIndex(std::vector<int> const& v) { Detector::sDetId2HitBitIndex = v; }
244 static std::vector<int> const& getDetId2HitBitIndex() { return Detector::sDetId2HitBitIndex; }
245
246 protected:
247 Detector(const Detector& origin);
248
249 Detector& operator=(const Detector&);
250
251 private:
256 std::map<int, int> mMapMaterial;
257
259 std::map<int, int> mMapMedium;
260
261 static Float_t mDensityFactor;
262 // systematic studies)
263 static std::vector<int> sDetId2HitBitIndex;
264
265 ClassDefOverride(Detector, 1); // Base class for ALICE Modules
266};
267
269inline std::string demangle(const char* name)
270{
271 int status = -4; // some arbitrary value to eliminate compiler warnings
272 std::unique_ptr<char, void (*)(void*)> res{abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free};
273 return (status == 0) ? res.get() : name;
274}
275
276// a flag in shared memory telling whether the hit merger still reads a hit buffer
277using ShmBusyFlag = std::atomic<bool>;
278
279void attachShmMessage(void* hitsptr, fair::mq::Channel& channel, fair::mq::Parts& parts, ShmBusyFlag* busy_ptr);
280void* decodeShmCore(fair::mq::Parts& dataparts, int index, ShmBusyFlag*& busy);
281
282template <typename T>
283T decodeShmMessage(fair::mq::Parts& dataparts, int index, ShmBusyFlag*& busy)
284{
285 return reinterpret_cast<T>(decodeShmCore(dataparts, index, busy));
286}
287
288// this goes into the source
289void attachMessageBufferToParts(fair::mq::Parts& parts, fair::mq::Channel& channel, void* data, TClass* cl);
290
291template <typename Container>
292void attachTMessage(Container const& hits, fair::mq::Channel& channel, fair::mq::Parts& parts)
293{
294 attachMessageBufferToParts(parts, channel, (void*)&hits, TClass::GetClass(typeid(hits)));
295}
296
297void* decodeTMessageCore(fair::mq::Parts& dataparts, int index);
298template <typename T>
299T decodeTMessage(fair::mq::Parts& dataparts, int index)
300{
301 return static_cast<T>(decodeTMessageCore(dataparts, index));
302}
303
304// header message preceding the hits of one detector
306 int detID;
307 bool shm; // whether the hits follow as shared-memory references or as TMessages
308};
309
310void attachHitsHeaderMessage(HitsHeader const& header, fair::mq::Channel& channel, fair::mq::Parts& parts);
311
312template <typename T>
313TBranch* getOrMakeBranch(TTree& tree, const char* brname, T* ptr)
314{
315 if (auto br = tree.GetBranch(brname)) {
316 br->SetAddress(static_cast<void*>(&ptr));
317 return br;
318 }
319 // otherwise make it
320 return tree.Branch(brname, ptr);
321}
322
323// a trait to determine if we should use shared mem or serialize using TMessage
324template <typename Det>
325struct UseShm {
326 static constexpr bool value = false;
327};
328
329// an implementation helper template which automatically implements
330// common functionality for deriving classes via the CRT pattern
331// (example: it implements the updateHitTrackIndices function and avoids
332// code duplication, while at the same time avoiding virtual function calls)
333template <typename Det>
335{
336 public:
337 // offer same constructors as base
338 using Detector::Detector;
339
341 DetImpl(const DetImpl& rhs) : Detector(rhs) {}
342 DetImpl& operator=(const DetImpl&) = delete;
343
344 // default implementation for getHitBranchNames
345 std::string getHitBranchNames(int probe) const override
346 {
347 if (probe == 0) {
348 return addNameTo("Hit");
349 }
350 return std::string(); // empty string as undefined
351 }
352
353 // generic implementation for the updateHitTrackIndices interface
354 // assumes Detectors have a GetHits(int) function that return some iterable
355 // hits which are o2::BaseHits
356 void updateHitTrackIndices(std::map<int, int> const& indexmapping) override
357 {
358 int probe = 0; // some Detectors have multiple hit vectors and we are probing
359 // them via a probe integer until we get a nullptr
360 while (auto hits = static_cast<Det*>(this)->Det::getHits(probe++)) {
361 for (auto& hit : *hits) {
362 hit.SetTrackID(updatedTrackIndex(indexmapping, hit.GetTrackID()));
363 }
364 }
365 }
366
367 void attachHits(fair::mq::Channel& channel, fair::mq::Parts& parts) override
368 {
369 int probe = 0;
370 // check if there is anything to be attached
371 // at least the first hit index should return non nullptr
372 if (static_cast<Det*>(this)->Det::getHits(0) == nullptr) {
373 return;
374 }
375
376 // decide the transport once, so that the header and all hit messages agree
378 attachHitsHeaderMessage({GetDetId(), shm}, channel, parts); // the DetId s are universal as they come from o2::detector::DetID
379
380 while (auto hits = static_cast<Det*>(this)->Det::getHits(probe++)) {
381 if (!shm) {
382 attachTMessage(*hits, channel, parts);
383 } else {
384 // this is the shared mem variant
385 // we will just send the sharedmem ID and the offset inside
386 *mShmBusy[mCurrentBuffer] = true;
387 attachShmMessage((void*)hits, channel, parts, mShmBusy[mCurrentBuffer]);
388 }
389 }
390 }
391
392 // this merges several entries from the TBranch brname from the origin TTree
393 // into a single entry in a target TTree / same branch
394 // (assuming T is typically a vector; merging is simply done by appending)
395 // make this function a (static helper)
396 template <typename T>
397 void mergeAndAdjustHits(std::string const& brname, TTree& origin, TTree& target,
398 std::vector<int> const& trackoffsets, std::vector<int> const& nprimaries, std::vector<int> const& subevtsOrdered)
399 {
400 auto originbr = origin.GetBranch(brname.c_str());
401 if (originbr) {
402 auto targetdata = new T;
403 T* incomingdata = nullptr;
404 originbr->SetAddress(&incomingdata);
405
406 T* filladdress = nullptr;
407 if (origin.GetEntries() == 1) {
408 originbr->GetEntry(0);
409 filladdress = incomingdata;
410 } else {
411 Int_t entries = origin.GetEntries();
412 Int_t nprimTot = 0;
413 for (auto entry = 0; entry < entries; entry++) {
414 nprimTot += nprimaries[entry];
415 }
416 // offset for pimary track index
417 Int_t idelta0 = 0;
418 // offset for secondary track index
419 Int_t idelta1 = nprimTot;
420 for (int entry = entries - 1; entry >= 0; --entry) {
421 // proceed in the order of subevent Ids
422 Int_t index = subevtsOrdered[entry];
423 // numbe of primaries for this event
424 Int_t nprim = nprimaries[index];
425 idelta1 -= nprim;
426 filladdress = targetdata;
427 originbr->GetEntry(index);
428 if (incomingdata) {
429 // fix the trackIDs for this data
430 for (auto& hit : *incomingdata) {
431 hit.SetTrackID(offsetTrackIndex(hit.GetTrackID(), nprim, idelta0, idelta1));
432 }
433 // this could be further generalized by using a policy for T
434 std::copy(incomingdata->begin(), incomingdata->end(), std::back_inserter(*targetdata));
435 delete incomingdata;
436 incomingdata = nullptr;
437 }
438 // adjust offsets for next subevent
439 idelta0 += nprim;
440 idelta1 += trackoffsets[index];
441 } // subevent loop
442 }
443 // fill target for this event
444 auto targetbr = o2::base::getOrMakeBranch(target, brname.c_str(), &filladdress);
445 targetbr->SetAddress(&filladdress);
446 targetbr->Fill();
447 targetbr->ResetAddress();
448 targetdata->clear();
449 if (incomingdata) {
450 delete incomingdata;
451 incomingdata = nullptr;
452 }
453 delete targetdata;
454 }
455 }
456
457 // this merges several entries from temporary hit buffer into
458 // into a single entry in a target TTree / same branch
459 // (assuming T is typically a vector; merging is simply done by appending)
460 template <typename T, typename L>
461 void mergeAndAdjustHits(std::string const& brname, L& hitbuffervector, TTree& target,
462 std::vector<int> const& trackoffsets, std::vector<int> const& nprimaries,
463 std::vector<int> const& subevtsOrdered)
464 {
465 auto entries = hitbuffervector.size();
466
467 T targetdata; // used to collect data inside a single container
468 T* filladdress = nullptr; // pointer used for final ROOT IO
469 if (entries == 1) {
470 filladdress = hitbuffervector[0].get();
471 // nothing to do; we can directly do IO from the existing buffer
472 } else {
473 // here we need to do merging and index adjustment
474 int nprimTot = 0;
475 size_t nhits = 0;
476 for (auto entry = 0; entry < entries; entry++) {
477 nprimTot += nprimaries[entry];
478 nhits += hitbuffervector[entry] ? hitbuffervector[entry]->size() : 0;
479 }
480 targetdata.reserve(nhits);
481 // offset for pimary track index
482 int idelta0 = 0;
483 // offset for secondary track index
484 int idelta1 = nprimTot;
485 filladdress = &targetdata;
486 for (int entry = entries - 1; entry >= 0; --entry) {
487 // proceed in the order of subevent Ids
488 int index = subevtsOrdered[entry];
489 // number of primaries for this event
490 int nprim = nprimaries[index];
491 idelta1 -= nprim;
492
493 // fetch correct data item
494 auto incomingdata = hitbuffervector[index].get();
495 if (incomingdata) {
496 // fix the trackIDs for this data
497 for (auto& hit : *incomingdata) {
498 hit.SetTrackID(offsetTrackIndex(hit.GetTrackID(), nprim, idelta0, idelta1));
499 }
500 // move rather than copy, since hits may own memory themselves (e.g. TPC HitGroup)
501 targetdata.insert(targetdata.end(), std::make_move_iterator(incomingdata->begin()), std::make_move_iterator(incomingdata->end()));
502 }
503 // adjust offsets for next subevent
504 idelta0 += nprim;
505 idelta1 += trackoffsets[index];
506 } // subevent loop
507 }
508 // fill target for this event
509 auto targetbr = o2::base::getOrMakeBranch(target, brname.c_str(), &filladdress);
510 targetbr->SetAddress(&filladdress);
511 targetbr->Fill();
512 targetbr->ResetAddress();
513 hitbuffervector = L(); // swap with empty vector to release mem
514 }
515
516 void mergeHitEntries(TTree& origin, TTree& target, std::vector<int> const& trackoffsets, std::vector<int> const& nprimaries, std::vector<int> const& subevtsOrdered) final
517 {
518 // loop over hit containers / different branches
519 // adjust trackID in hits on the go
520 int probe = 0;
521 using Hit_t = decltype(static_cast<Det*>(this)->Det::getHits(probe));
522 std::string name = static_cast<Det*>(this)->getHitBranchNames(probe++);
523 while (name.size() > 0) {
524 mergeAndAdjustHits<typename std::remove_pointer<Hit_t>::type>(name, origin, target, trackoffsets, nprimaries, subevtsOrdered);
525 // next name
526 name = static_cast<Det*>(this)->getHitBranchNames(probe++);
527 }
528 }
529
530 // the hit containers buffered in the hit merger, per event and per hit branch
532 {
533 using Hit_t = typename std::remove_pointer<decltype(static_cast<Det*>(this)->Det::getHits(0))>::type;
534 using Collector_t = tbb::concurrent_unordered_map<int, std::vector<std::vector<std::unique_ptr<Hit_t>>>>;
535 if (!mHitCollector) {
536 mHitCollector = std::make_shared<Collector_t>();
537 }
538 return *static_cast<Collector_t*>(mHitCollector.get());
539 }
540
541 void mergeHitEntriesAndFlush(int eventID, TTree& target, std::vector<int> const& trackoffsets, std::vector<int> const& nprimaries, std::vector<int> const& subevtsOrdered) final
542 {
543 // loop over hit containers / different branches
544 // adjust trackID in hits on the go
545 int probe = 0;
546 using Hit_t = typename std::remove_pointer<decltype(static_cast<Det*>(this)->Det::getHits(0))>::type;
547 // remove buffered event from the hit store
548 auto& collector = hitCollector();
549 auto iter = collector.find(eventID);
550 if (iter == collector.end()) {
551 LOG(error) << "No buffered hits available for event " << eventID;
552 return;
553 }
554
555 std::string name = static_cast<Det*>(this)->getHitBranchNames(probe);
556 while (name.size() > 0) {
557 auto& vectorofHitBuffers = (*iter).second[probe];
558 // flushing and buffer removal is done inside here:
559 mergeAndAdjustHits<Hit_t>(name, vectorofHitBuffers, target, trackoffsets, nprimaries, subevtsOrdered);
560 // next name
561 probe++;
562 name = static_cast<Det*>(this)->getHitBranchNames(probe);
563 }
564 }
565
566 public:
570 void collectHits(int eventID, fair::mq::Parts& parts, int& index, bool shm) override
571 {
572 using Hit_t = typename std::remove_pointer<decltype(static_cast<Det*>(this)->Det::getHits(0))>::type;
573 auto& hitcollector = hitCollector();
574
575 int probe = 0;
576 ShmBusyFlag* busy = nullptr;
577 using HitPtr_t = decltype(static_cast<Det*>(this)->Det::getHits(probe));
578 std::string name = static_cast<Det*>(this)->getHitBranchNames(probe);
579
580 // stores one hit container of this event and probe in the collector
581 auto store = [eventID, &hitcollector](std::unique_ptr<Hit_t> hits, int probe) {
582 auto& hitvector = hitcollector[eventID]; // tbb insertion is thread-safe
583 if (probe >= hitvector.size()) {
584 hitvector.resize(probe + 1);
585 }
586 hitvector[probe].emplace_back(std::move(hits));
587 };
588
589 while (name.size() > 0) {
590 if (!shm) {
591 // a decoded TMessage is ours, so we adopt it
592 if (auto hitsptr = decodeTMessage<HitPtr_t>(parts, index++)) {
593 store(std::unique_ptr<Hit_t>(hitsptr), probe);
594 }
595 } else {
596 // hits in shared memory belong to the worker, so we copy them
597 auto hitsptr = decodeShmMessage<HitPtr_t>(parts, index++, busy);
598 store(std::make_unique<Hit_t>(*hitsptr), probe);
599 }
600 // next name
601 probe++;
602 name = static_cast<Det*>(this)->getHitBranchNames(probe);
603 }
604 // there is only one busy flag per detector so we need to clear it only
605 // at the end (after all branches have been treated)
606 if (busy) {
607 *busy = false;
608 }
609 }
610
611 void fillHitBranch(TTree& tr, fair::mq::Parts& parts, int& index) override
612 {
613 int probe = 0;
614 ShmBusyFlag* busy = nullptr;
615 using Hit_t = decltype(static_cast<Det*>(this)->Det::getHits(probe));
616 std::string name = static_cast<Det*>(this)->getHitBranchNames(probe++);
617 while (name.size() > 0) {
619
620 // for each branch name we extract/decode hits from the message parts ...
621 auto hitsptr = decodeTMessage<Hit_t>(parts, index++);
622 if (hitsptr) {
623 // ... and fill the tree branch
624 auto br = getOrMakeBranch(tr, name.c_str(), hitsptr);
625 br->SetAddress(static_cast<void*>(&hitsptr));
626 br->Fill();
627 br->ResetAddress();
628 delete hitsptr;
629 }
630 } else {
631 // for each branch name we extract/decode hits from the message parts ...
632 auto hitsptr = decodeShmMessage<Hit_t>(parts, index++, busy);
633 // ... and fill the tree branch
634 auto br = getOrMakeBranch(tr, name.c_str(), hitsptr);
635 br->SetAddress(static_cast<void*>(&hitsptr));
636 br->Fill();
637 br->ResetAddress();
638 }
639 // next name
640 name = static_cast<Det*>(this)->getHitBranchNames(probe++);
641 }
642 // there is only one busy flag per detector so we need to clear it only
643 // at the end (after all branches have been treated)
644 if (busy) {
645 *busy = false;
646 }
647 }
648
649 // implementing CloneModule (for G4-MT mode) automatically for each deriving
650 // Detector class "Det"; calls copy constructor of Det
651 FairModule* CloneModule() const final
652 {
653 return new Det(static_cast<const Det&>(*this));
654 }
655
657 {
658 using Hit_t = decltype(static_cast<Det*>(this)->Det::getHits(0));
659 if (UseShm<Det>::value) {
660 for (int buffer = 0; buffer < NHITBUFFERS; ++buffer) {
661 for (auto ptr : mCachedPtr[buffer]) {
662 o2::utils::freeSimVector(static_cast<Hit_t>(ptr));
663 }
664 }
665 }
666 }
667
668 // default implementation for setting hits
669 // always returns false indicating that there is no other
670 // component to assign to apart from i == 0
671 template <typename Hit_t>
672 bool setHits(int i, std::vector<Hit_t>* ptr)
673 {
674 if (i == 0) {
675 static_cast<Det*>(this)->Det::mHits = ptr;
676 }
677 return false;
678 }
679
680 // creating a number of hit buffers (in shared mem) -- to which
681 // detectors can write in round-robin fashion
683 {
684 using VectorHit_t = decltype(static_cast<Det*>(this)->Det::getHits(0));
685 using Hit_t = typename std::remove_pointer<VectorHit_t>::type::value_type;
686 for (int buffer = 0; buffer < NHITBUFFERS; ++buffer) {
687 int probe = 0;
688 bool more{false};
689 do {
690 auto ptr = o2::utils::createSimVector<Hit_t>();
691 more = static_cast<Det*>(this)->Det::setHits(probe, ptr);
692 mCachedPtr[buffer].emplace_back(ptr);
693 probe++;
694 } while (more);
695 }
696 }
697
698 void initializeLate() final
699 {
700 if (!mInitialized) {
701 if (UseShm<Det>::value) {
702 static_cast<Det*>(this)->Det::createHitBuffers();
703 for (int b = 0; b < NHITBUFFERS; ++b) {
704 auto& instance = o2::utils::ShmManager::Instance();
705 mShmBusy[b] = instance.hasSegment() ? new (instance.getmemblock(sizeof(ShmBusyFlag))) ShmBusyFlag(false) : new ShmBusyFlag(false);
706 }
707 }
708 mInitialized = true;
709 mCurrentBuffer = 0;
710 }
711 }
712
713 void BeginEvent() final
714 {
715 if (UseShm<Det>::value) {
717 while (mShmBusy[mCurrentBuffer] != nullptr && *mShmBusy[mCurrentBuffer]) {
718 // this should ideally never happen
719 LOG(info) << " BUSY WAITING SIZE ";
720 sleep(1);
721 }
722
723 using Hit_t = decltype(static_cast<Det*>(this)->Det::getHits(0));
724
725 // now we have to clear the hits before writing again
726 int probe = 0;
727 for (auto bareptr : mCachedPtr[mCurrentBuffer]) {
728 auto hits = static_cast<Hit_t>(bareptr);
729 // assign ..
730 static_cast<Det*>(this)->Det::setHits(probe, hits);
731 hits->clear();
732 probe++;
733 }
734 }
735 }
736
737 ~DetImpl() override
738 {
739 for (int i = 0; i < NHITBUFFERS; ++i) {
740 if (mShmBusy[i]) {
741 auto& instance = o2::utils::ShmManager::Instance();
742 if (instance.hasSegment()) {
743 instance.freememblock(mShmBusy[i]);
744 } else {
745 delete mShmBusy[i];
746 }
747 }
748 }
750 }
751
752 protected:
753 static constexpr int NHITBUFFERS = 3; // number of buffers for hits in order to allow async processing
754 // in the hit merger without blocking nor copying the data
755 // (like done in typical data aquisition systems)
757 std::vector<void*> mCachedPtr[NHITBUFFERS];
758 int mCurrentBuffer = 0; // holding the current buffer information
759 int mInitialized = false;
760
761 std::shared_ptr<void> mHitCollector;
762
764};
765} // namespace o2::base
766
767#endif
header::DataOrigin origin
std::vector< long > entries
int32_t i
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 s
char error[CURL_ERROR_SIZE]
uint32_t res
Definition RawData.h:0
TBranch * ptr
virtual void Initialize()
Int_t GetDetId()
void freeHitBuffers()
Definition Detector.h:656
~DetImpl() override
Definition Detector.h:737
void updateHitTrackIndices(std::map< int, int > const &indexmapping) override
Definition Detector.h:356
std::shared_ptr< void > mHitCollector
Definition Detector.h:761
void mergeHitEntriesAndFlush(int eventID, TTree &target, std::vector< int > const &trackoffsets, std::vector< int > const &nprimaries, std::vector< int > const &subevtsOrdered) final
Definition Detector.h:541
std::vector< void * > mCachedPtr[NHITBUFFERS]
pointer to flag in shared mem indicating of IO busy
Definition Detector.h:757
auto & hitCollector()
Definition Detector.h:531
std::string getHitBranchNames(int probe) const override
Definition Detector.h:345
DetImpl(const DetImpl &rhs)
copy for a worker thread of multithreaded Geant4; the copy creates its own hit buffers in initializeL...
Definition Detector.h:341
void collectHits(int eventID, fair::mq::Parts &parts, int &index, bool shm) override
Definition Detector.h:570
static constexpr int NHITBUFFERS
Definition Detector.h:753
void fillHitBranch(TTree &tr, fair::mq::Parts &parts, int &index) override
Definition Detector.h:611
void createHitBuffers()
Definition Detector.h:682
void BeginEvent() final
Definition Detector.h:713
void attachHits(fair::mq::Channel &channel, fair::mq::Parts &parts) override
Definition Detector.h:367
void mergeAndAdjustHits(std::string const &brname, TTree &origin, TTree &target, std::vector< int > const &trackoffsets, std::vector< int > const &nprimaries, std::vector< int > const &subevtsOrdered)
Definition Detector.h:397
void mergeAndAdjustHits(std::string const &brname, L &hitbuffervector, TTree &target, std::vector< int > const &trackoffsets, std::vector< int > const &nprimaries, std::vector< int > const &subevtsOrdered)
Definition Detector.h:461
bool setHits(int i, std::vector< Hit_t > *ptr)
Definition Detector.h:672
ShmBusyFlag * mShmBusy[NHITBUFFERS]
Definition Detector.h:756
FairModule * CloneModule() const final
Definition Detector.h:651
void initializeLate() final
Definition Detector.h:698
void mergeHitEntries(TTree &origin, TTree &target, std::vector< int > const &trackoffsets, std::vector< int > const &nprimaries, std::vector< int > const &subevtsOrdered) final
Definition Detector.h:516
ClassDefOverride(DetImpl, 0)
type-erased hit buffers of this instance in the hit merger (see hitCollector())
DetImpl & operator=(const DetImpl &)=delete
virtual std::string getHitBranchNames(int probe) const =0
void SpecialProcess(Int_t numed, EProc parID, int val)
Set process by name and value.
Definition Detector.cxx:98
int registerSensitiveVolumeAndGetVolID(std::string const &name)
Definition Detector.cxx:190
~Detector() override
Default Destructor.
Definition Detector.cxx:93
static std::vector< int > const & getDetId2HitBitIndex()
Definition Detector.h:244
virtual void initializeLate()=0
Detector & operator=(const Detector &)
Definition Detector.cxx:46
virtual void defineLayerTurbo(Int_t nlay, Double_t phi0, Double_t r, Int_t nladd, Int_t nmod, Double_t width, Double_t tilt, Double_t lthick=0., Double_t dthick=0., UInt_t detType=0, Int_t buildFlag=0)
Definition Detector.cxx:117
TClonesArray * GetCollection(int iColl) const final
Definition Detector.cxx:162
virtual void attachHits(fair::mq::Channel &, fair::mq::Parts &)=0
virtual void fillParallelWorld() const
fill parallel geometry with sensitive volumes of detector
Definition Detector.cxx:174
void Initialize() final
Definition Detector.h:210
int getMaterialID(int imat) const
Definition Detector.h:128
void getMediumIDMappingAsVector(std::vector< int > &mapping)
Definition Detector.h:144
static void setDensityFactor(Float_t density)
Definition Detector.h:93
static int updatedTrackIndex(std::map< int, int > const &indexmapping, int trackID)
Definition Detector.h:169
virtual bool isMTSafe() const
whether this detector may run in multithreaded Geant4, with one clone per worker thread
Definition Detector.h:223
void SpecialCuts(Int_t numed, const std::initializer_list< std::pair< ECut, Float_t > > &parIDValMap)
Custom processes and transport cuts.
Definition Detector.cxx:80
void SpecialCut(Int_t numed, ECut parID, Float_t val)
Set cut by name and value.
Definition Detector.cxx:86
void SpecialProcesses(Int_t numed, const std::initializer_list< std::pair< EProc, int > > &parIDValMap)
Definition Detector.cxx:92
void Matrix(Int_t &nmat, Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t theta3, Double_t phi3) const
Definition Detector.cxx:104
Detector()
Default Constructor.
Definition Detector.cxx:36
virtual void setNumberOfWrapperVolumes(Int_t n)
Books arrays for wrapper volumes.
Definition Detector.cxx:111
virtual void updateHitTrackIndices(std::map< int, int > const &)=0
virtual void mergeHitEntries(TTree &origin, TTree &target, std::vector< int > const &trackoffsets, std::vector< int > const &nprimaries, std::vector< int > const &subevtsOrdered)=0
virtual void collectHits(int eventID, fair::mq::Parts &parts, int &index, bool shm)=0
void Mixture(Int_t imat, const char *name, Float_t *a, Float_t *z, Float_t dens, Int_t nlmat, Float_t *wmat)
Definition Detector.cxx:66
virtual void addAlignableVolumes() const
declare alignable volumes of detector
Definition Detector.cxx:169
void Medium(Int_t numed, const char *name, Int_t nmat, Int_t isvol, Int_t ifield, Float_t fieldm, Float_t tmaxfd, Float_t stemax, Float_t deemax, Float_t epsil, Float_t stmin, Float_t *ubuf=nullptr, Int_t nbuf=0)
Definition Detector.cxx:72
void SetSpecialPhysicsCuts() override
Definition Detector.cxx:122
static Float_t getDensityFactor()
Definition Detector.h:98
int getMediumID(int imed) const
Definition Detector.h:136
virtual void fillHitBranch(TTree &tr, fair::mq::Parts &parts, int &index)=0
static void setDetId2HitBitIndex(std::vector< int > const &v)
set the DetID to HitBitIndex mapping. Succeeds if not already set.
Definition Detector.h:243
static void initFieldTrackingParams(int &mode, float &maxfield)
Definition Detector.cxx:143
virtual void defineWrapperVolume(Int_t id, Double_t rmin, Double_t rmax, Double_t zspan)
Sets per wrapper volume parameters.
Definition Detector.cxx:110
virtual void defineLayer(Int_t nlay, Double_t phi0, Double_t r, Int_t nladd, Int_t nmod, Double_t lthick=0., Double_t dthick=0., UInt_t detType=0, Int_t buildFlag=0)
virtual void mergeHitEntriesAndFlush(int eventID, TTree &target, std::vector< int > const &trackoffsets, std::vector< int > const &nprimaries, std::vector< int > const &subevtsOrdered)=0
static int offsetTrackIndex(int trackID, int nprimaries, int primaryOffset, int secondaryOffset)
Definition Detector.h:178
void Material(Int_t imat, const char *name, Float_t a, Float_t z, Float_t dens, Float_t radl, Float_t absl, Float_t *buf=nullptr, Int_t nwbuf=0)
Definition Detector.cxx:59
std::string addNameTo(const char *ext) const
Definition Detector.h:151
virtual void InitializeO2Detector()=0
Definition Detector.cxx:104
static MaterialManager & Instance()
static ShmManager & Instance()
Definition ShmManager.h:62
bool isOperational() const
Definition ShmManager.h:99
GLdouble n
Definition glcorearb.h:1982
GLuint buffer
Definition glcorearb.h:655
GLuint entry
Definition glcorearb.h:5735
const GLdouble * v
Definition glcorearb.h:832
GLuint index
Definition glcorearb.h:781
GLuint const GLchar * name
Definition glcorearb.h:781
GLint GLsizei width
Definition glcorearb.h:270
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLenum target
Definition glcorearb.h:1641
GLint GLint GLsizei GLint GLenum GLenum type
Definition glcorearb.h:275
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint GLfloat * val
Definition glcorearb.h:1582
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLenum GLuint GLenum GLsizei const GLchar * buf
Definition glcorearb.h:2514
GLdouble GLdouble GLdouble z
Definition glcorearb.h:843
ECut
cuts available
void * decodeShmCore(fair::mq::Parts &dataparts, int index, ShmBusyFlag *&busy)
Definition Detector.cxx:240
EProc
processes available
void attachShmMessage(void *hitsptr, fair::mq::Channel &channel, fair::mq::Parts &parts, ShmBusyFlag *busy_ptr)
Definition Detector.cxx:223
void * decodeTMessageCore(fair::mq::Parts &dataparts, int index)
Definition Detector.cxx:255
std::atomic< bool > ShmBusyFlag
Definition Detector.h:277
TBranch * getOrMakeBranch(TTree &tree, const char *brname, T *ptr)
Definition Detector.h:313
void attachMessageBufferToParts(fair::mq::Parts &parts, fair::mq::Channel &channel, void *data, TClass *cl)
Definition Detector.cxx:207
void attachTMessage(Container const &hits, fair::mq::Channel &channel, fair::mq::Parts &parts)
Definition Detector.h:292
void attachHitsHeaderMessage(HitsHeader const &header, fair::mq::Channel &channel, fair::mq::Parts &parts)
Definition Detector.cxx:218
std::string demangle(const char *name)
utility function to demangle cxx type names
Definition Detector.h:269
T decodeShmMessage(fair::mq::Parts &dataparts, int index, ShmBusyFlag *&busy)
Definition Detector.h:283
T decodeTMessage(fair::mq::Parts &dataparts, int index)
Definition Detector.h:299
void freeSimVector(std::vector< T > *ptr)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::unique_ptr< TTree > tree((TTree *) flIn.Get(std::string(o2::base::NameConf::CTFTREENAME).c_str()))