ATLAS Offline Software
Loading...
Searching...
No Matches
RootNtupleEventSelector.cxx
Go to the documentation of this file.
1
2
3/*
4 Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
5*/
6
7// RootNtupleEventSelector.cxx
8// Implementation file for class RootNtupleEventSelector
9// Author: S.Binet<binet@cern.ch>
11
12// STL includes
13#include <sstream>
14#include <string>
15#include <vector>
16#include <stdint.h>
17#include <unordered_map>
18#include <unordered_set>
19
20// ROOT includes
21#include "TROOT.h"
23#include "TClass.h"
24#include "TClassEdit.h"
25#include "TFile.h"
26#include "TKey.h"
27#include "TLeaf.h"
28
29// Framework includes
30//#include "GaudiKernel/GenericAddress.h"
31#include "GaudiKernel/FileIncident.h"
32#include "GaudiKernel/IIoComponentMgr.h"
33#include "GaudiKernel/ISvcLocator.h"
34#include "GaudiKernel/ITHistSvc.h"
35#include "GaudiKernel/MsgStream.h"
36#include "GaudiKernel/StatusCode.h"
37#include "GaudiKernel/System.h"
40
41// StoreGate includes
42
43#include "SGTools/BuiltinsClids.h" // to make sure we have their clids
44#include "SGTools/StlMapClids.h" // to make sure we have their clids
45#include "SGTools/StlVectorClids.h" // to make sure we have their clids
48
49#include "TObject.h"
50#include "TTree.h"
51CLASS_DEF( TObject, 74939790 , 1 )
52#include "AthenaRootComps/TransferTree.h"
53
54// EventInfo includes
55#include "EventInfo/EventInfo.h"
56#include "EventInfo/EventType.h"
57#include "EventInfo/EventID.h"
60
61
62// Package includes
64#include "RootBranchAddress.h"
65#include "RootGlobalsRestore.h"
66
67#include "boost/tokenizer.hpp"
68
69namespace {
70 std::string
71 root_typename(const std::string& root_type_name)
72 {
73 static const std::unordered_map<std::string,std::string> s = {
74 {"Int_t", System::typeinfoName(typeid(Int_t))},
75 {"UInt_t", System::typeinfoName(typeid(UInt_t))},
76
77 {"Long_t", System::typeinfoName(typeid(Long_t))},
78 {"ULong_t", System::typeinfoName(typeid(ULong_t))},
79
80 {"Long64_t", System::typeinfoName(typeid(Long64_t))},
81 {"ULong64_t", System::typeinfoName(typeid(ULong64_t))},
82
83 {"Float_t", System::typeinfoName(typeid(Float_t))},
84 {"Float16_t", System::typeinfoName(typeid(Float16_t))},
85 {"Double_t", System::typeinfoName(typeid(Double_t))},
86 {"Double32_t", System::typeinfoName(typeid(Double32_t))},
87
88 {"Bool_t", System::typeinfoName(typeid(Bool_t))},
89 {"Char_t", System::typeinfoName(typeid(Char_t))},
90 {"UChar_t", System::typeinfoName(typeid(UChar_t))},
91
92 {"Short_t", System::typeinfoName(typeid(Short_t))},
93 {"UShort_t", System::typeinfoName(typeid(UShort_t))}
94 };
95
96 return s.at(root_type_name);
97 }
98
99#if 0
100 std::vector<std::string>
101 get_active_leaves(TTree *tuple)
102 {
103 std::vector<std::string> active;
104 TObjArray *leaves = tuple->GetListOfLeaves();
105 if (leaves) {
106 // loop over leaves
107 for (Int_t i = 0; i < leaves->GetEntries(); ++i) {
108 TLeaf *leaf = (TLeaf *)leaves->At(i);
109 TBranch *branch = leaf->GetBranch();
110 if (branch) {
111 const char *brname = branch->GetName();
112 if (tuple->GetBranchStatus(brname)) {
113 active.push_back(std::string(brname));
114 }
115 }
116 }
117 }
118 return active;
119 }
120#endif
121
122}
123
124namespace Athena {
125
130 public ::IEvtSelector::Context
131{
132public:
134 typedef std::vector<std::string> FileNames_t;
135
136private:
139
142
145
147 std::string m_fid;
148
149public:
150
158
161
162 // access to the container of files
163 const FileNames_t& files() const
164 { return m_evtsel->m_inputCollectionsName.value(); }
165
167 virtual void* identifier() const
168 { return (void*)(m_evtsel); }
169
171 std::size_t fileIndex() const
172 { return m_collIdx; }
173
175 void setFileIndex(std::size_t idx)
176 { m_collIdx = idx; }
177
178 std::size_t tupleIndex() const
179 { return m_tupleIdx; }
180
181 void setTupleIndex(std::size_t idx)
182 { m_tupleIdx = idx; }
183
185 int64_t entry() const { return m_evtsel->m_curEvt; }
186
188 void setFID(const std::string& fid) { m_fid = fid; }
189
191 const std::string& fid() const { return m_fid; }
192
194 TTree* tree() const { return m_evtsel->m_tuple; }
195
197 void setTree(TTree* tree) {
198 // make sure we clean-up and close the file holding
199 // the previous tree, if any.
200 // dont close if it is the same tree though!
201 TTree *cur = m_evtsel->m_tuple;
202 if (cur && tree != cur) {
203 TFile *old_file = cur->GetCurrentFile();
204 if (old_file) {
205 old_file->Close();
206 }
207 }
208
209 m_evtsel->m_tuple = tree;
210 }
211};
212
214
216// Public methods:
218
219// Constructors
221
223 ISvcLocator* svcLoc ) :
224 extends ( name, svcLoc ),
225 m_dataStore( "StoreGateSvc/StoreGateSvc", name ),
226 m_imetaStore( "StoreGateSvc/InputMetaDataStore", name ),
227 m_ometaStore( "StoreGateSvc/MetaDataStore", name ),
228 m_clidsvc ( "ClassIDSvc", name ),
229 m_dictsvc ( "AthDictLoaderSvc", name ),
230 m_incsvc ( "IncidentSvc", name ),
231 m_nbrEvts ( 0 ),
232 m_curEvt ( 0 ),
233 m_collEvts ( ),
234 m_tuple (NULL),
235 m_needReload (true),
236 m_fireBIF (true)
237{
238 declareProperty( "DataStore",
240 "Store where to publish data");
241
242 declareProperty( "InputMetaStore",
244 "Store where to publish (input) metadata");
245
246 declareProperty( "MetaStore",
248 "Store where to publish (output) metadata");
249
250 declareProperty( "InputCollections",
252 "List of input (ROOT) file names" );
253 m_inputCollectionsName.declareUpdateHandler
255
256 declareProperty( "TupleName",
257 m_tupleName = "CollectionTree",
258 "Name of the TTree to load/read from input file(s). "
259 "May be a semicolon-separated string to read multiple TTrees.");
260
261 declareProperty( "SkipEvents",
262 m_skipEvts = 0,
263 "Number of events to skip at the beginning" );
264
265 declareProperty( "ActiveBranches",
267 "List of branch names to activate" );
268}
269
270// Destructor
274
276{
277 ATH_MSG_INFO ("Enter RootNtupleEventSelector initialization...");
278
279 // retrieve clidsvc
280 if ( !m_clidsvc.retrieve().isSuccess() ) {
282 ("Could not retrieve [" << m_clidsvc.typeAndName() << "]");
283 return StatusCode::FAILURE;
284 }
285
286 // retrieve dictsvc
287 if ( !m_dictsvc.retrieve().isSuccess() ) {
289 ("Could not retrieve [" << m_dictsvc.typeAndName() << "]");
290 return StatusCode::FAILURE;
291 }
292
293 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
294 boost::char_separator<char> sep (" ;");
295 tokenizer tokens (m_tupleName.value(), sep);
296 m_tupleNames.assign (tokens.begin(), tokens.end());
297
298 if ( m_tupleNames.empty() ) {
300 ("You have to give a TTree name to read from the ROOT files !");
301 return StatusCode::FAILURE;
302 }
303
304 CHECK( m_incsvc.retrieve() );
305 m_incsvc->addListener(this,IncidentType::BeginEvent,99); //used to trigger BeginInputFile on start of first event of file - 99 priority so AFTER storegatesvc done
306
307
309 const std::size_t nbrInputFiles = m_inputCollectionsName.value().size();
310 if ( nbrInputFiles < 1 ) {
312 ("You need to give at least 1 input file !!" << endmsg
313 << "(Got [" << nbrInputFiles << "] file instead !)");
314 return StatusCode::FAILURE;
315 } else {
317 ("Selector configured to read [" << nbrInputFiles << "] file(s)..."
318 << endmsg
319 << " TTree [" << m_tupleName.value() << "]");
320 }
321
322 {
323 // register this service for 'I/O' events
324 ServiceHandle<IIoComponentMgr> iomgr("IoComponentMgr", name());
325 if (!iomgr.retrieve().isSuccess()) {
326 ATH_MSG_FATAL("Could not retrieve IoComponentMgr !");
327 return StatusCode::FAILURE;
328 }
329 if (!iomgr->io_register(this).isSuccess()) {
330 ATH_MSG_FATAL("Could not register myself with the IoComponentMgr !");
331 return StatusCode::FAILURE;
332 }
333 // register input file's names with the I/O manager
334 const std::vector<std::string>& incol = m_inputCollectionsName.value();
335 bool allGood = true;
336 for (std::size_t icol = 0, imax = incol.size(); icol < imax; icol++) {
337 if (!iomgr->io_register(this,
338 IIoComponentMgr::IoMode::READ,
339 incol[icol]).isSuccess()) {
340 ATH_MSG_FATAL("could not register [" << incol[icol] << "] for output !");
341 allGood = false;
342 } else {
343 ATH_MSG_VERBOSE("io_register[" << this->name() << "](" << incol[icol] << ") [ok]");
344 }
345 }
346 if (!allGood) {
347 return StatusCode::FAILURE;
348 }
349 }
350
351 if (!do_init_io().isSuccess()) {
352 return StatusCode::FAILURE;
353 }
354
355 // retrieve event store
356 // this needs to happen *after* having initialized the i/o
357 // as our branches (which need a valid m_ntuple pointer)
358 // may be asked to be registered as we are a ProxyProvider.
359 // retrieving the event store will poke the ProxyProviderSvc...
360 /*
361 if ( !m_dataStore.retrieve().isSuccess() ) {
362 ATH_MSG_ERROR
363 ("Could not retrieve [" << m_dataStore.typeAndName() << "] !!");
364 return StatusCode::FAILURE;
365 }
366
367 // ditto for (input) meta data store
368 if (!m_imetaStore.retrieve().isSuccess()) {
369 ATH_MSG_ERROR
370 ("Could not retrieve [" << m_imetaStore.typeAndName() << "] !!");
371 return StatusCode::FAILURE;
372 }
373
374 // ditto for (output) meta data store
375 if (!m_ometaStore.retrieve().isSuccess()) {
376 ATH_MSG_ERROR
377 ("Could not retrieve [" << m_ometaStore.typeAndName() << "] !!");
378 return StatusCode::FAILURE;
379 }
380 */
381
382 //ensure the Athena::NtupleCnvSvc is in the EventPersistencySvc
383 ServiceHandle<IProperty> epSvc("EventPersistencySvc",name());
384 std::vector<std::string> propVal;
385 CHECK( Gaudi::Parsers::parse( propVal , epSvc->getProperty("CnvServices").toString() ) );
386 bool foundSvc(false);
387 for(const std::string& s : propVal) {
388 if(s=="Athena::xAODCnvSvc") { foundSvc=true; break; }
389 }
390 if(!foundSvc) {
391 propVal.push_back("Athena::NtupleCnvSvc");
392 CHECK( epSvc->setProperty("CnvServices", Gaudi::Utils::toString( propVal ) ));
393 }
394
395 //we should also add ourself as a proxy provider
396 ServiceHandle<IProxyProviderSvc> ppSvc("ProxyProviderSvc",name());
397 CHECK( ppSvc.retrieve() );
398 ppSvc->addProvider( this );
399
400
401
402 return StatusCode::SUCCESS;
403}
404
406{
407 ATH_MSG_INFO ("Finalize...");
408 // FIXME: this should be tweaked/updated if/when a selection function
409 // or filtering predicate is applied (one day?)
410 ATH_MSG_INFO ("Total events read: " << (m_nbrEvts - m_skipEvts));
411
412 // Explicitly delete all the files we created.
413 // If we leave it up to root, then xrootd can get cleaned up before
414 // the root destructors run, leading to a crash.
415 for (TFile* f : m_files)
416 delete f;
417 m_files.clear();
418
419 return StatusCode::SUCCESS;
420}
421
423// Const methods:
425
427{
428 const FileNames_t& fnames = rctx->files();
429 std::size_t fidx = rctx->fileIndex();
430 m_incsvc->fireIncident(FileIncident(name(), "EndInputFile", fnames[fidx]));
431
432 // prepare for next file, if any...
433 // std::cout << "=========================================================="
434 // << std::endl;
435 // std::cerr << "::switch to next file...\n";
436
437 // iterate over proxies and
438 // mark as garbage and drop the RootBranchAddress (as a side effect of
439 // ::setAddress(NULL).
440 // this way, the next time we hit ::createRootBranchAddress or ::updateAddress
441 // all internal states are kosher.
442 for (const SG::DataProxy* cdp : m_dataStore->proxies()) {
443 if (dynamic_cast<Athena::RootBranchAddress*> (cdp->address()) != nullptr) {
444 if (SG::DataProxy* dp = m_dataStore->proxy_exact (cdp->sgkey())) {
445 dp->setAddress (nullptr);
446 }
447 }
448 }
449
450 const bool forceRemove = false;
451 CHECK( m_dataStore->clearStore(forceRemove) ); //must clear the storegate so that any tampering user did in EndInputFile incident is cleared
452 m_needReload = true;m_fireBIF=true;
453
454 return StatusCode::SUCCESS;
455}
456
457StatusCode
458RootNtupleEventSelector::next( IEvtSelector::Context& ctx ) const
459{
460 // std::cout << "::next(fidx=" << ctx->fileIndex() << ", eidx=" << m_curEvt << ")"
461 // << std::endl;
462 ATH_MSG_DEBUG ("next() : iEvt " << m_curEvt);
463
464 // get evt context
465 RootNtupleEventContext* rctx = dynamic_cast<RootNtupleEventContext*>(&ctx);
466 if ( 0 == rctx ) {
467 ATH_MSG_ERROR ("Could not dyn-cast to RootNtupleEventContext !!");
468 throw "RootNtupleEventSelector: Unable to get RootNtupleEventContext";
469 }
470
471 TTree *tree = rctx->tree();
472 if (!tree) {
473 const FileNames_t& fnames = rctx->files();
474 std::size_t fidx = rctx->fileIndex();
475 rctx->setTree(NULL);
476 //rctx->setEntry(-1);
477
478 while (!tree && rctx->tupleIndex() < m_tupleNames.size()) {
479 if (fidx < rctx->files().size()) {
480 const std::string& fname = fnames[fidx];
481 tree = fetchNtuple(fname, m_tupleNames[rctx->tupleIndex()]);
482 if (!tree) {
483 throw "RootNtupleEventSelector: Unable to get tree";
484 }
485 rctx->setTree(tree);
486
487 }
488 else {
489 // end of collections; go to next tuple.
490 rctx->setTupleIndex (rctx->tupleIndex()+1);
491 rctx->setFileIndex (0);
492 fidx = 0;
493 }
494 }
495
496 if (!tree) {
497 return StatusCode::FAILURE;
498 }
499 }
500 int64_t global_entry = rctx->entry();
501 size_t collIdx = rctx->fileIndex();
502 size_t tupleIdx = rctx->tupleIndex();
503 int64_t entry = global_entry;
504 if (m_collEvts[tupleIdx][collIdx].min_entries < 0) {
505 // need to trigger collmetadata...
506 long coll_idx, tuple_idx;
507 const_cast<RootNtupleEventSelector*>(this)->find_coll_idx(entry,
508 coll_idx,
509 tuple_idx);
510 }
511 // rctx::entry is the *global* entry number.
512 // we need the local one...
513 entry = global_entry - m_collEvts[tupleIdx][collIdx].min_entries;
514
515 Long64_t nentries = tree->GetEntriesFast();
516 // std::cout << "::entry=" << global_entry
517 // << ", nentries=" << nentries
518 // << ", local=" << entry
519 // << " (min=" << m_collEvts[collIdx].min_entries
520 // << ", max=" << m_collEvts[collIdx].max_entries << ")"
521 // << " (tree=" << tree << ")"
522 // << std::endl;
523 if ( nentries > entry ) {
524
525 // load data from tuple
526 //std::cout << "--load-data--" << " " << tree->GetReadEntry() << std::endl;
527 if (tree->LoadTree(entry) < 0) {
529 ("Problem loading tree for event [" << m_curEvt << "] !!");
530 throw "RootNtupleEventSelector: Problem loading input tree";
531 } else {
532 ATH_MSG_DEBUG("==> loaded-tree(" << m_curEvt << ")");
533 }
534
535 ++m_nbrEvts;
536 m_curEvt = global_entry + 1;
537
538 // std::cout << "--event-info--" << std::endl;
539 // event info
540 EventType* evtType = new EventType;
541 const std::size_t runNbr = 0;
542 EventInfo* evtInfo = new EventInfo(new EventID(runNbr, m_curEvt-1, 0), evtType);
543 if ( !m_dataStore->record( evtInfo, "TTreeEventInfo" ).isSuccess() ) {
544 ATH_MSG_ERROR ("Could not record TTreeEventInfo !");
545 delete evtInfo; evtInfo = 0;
546 return StatusCode::FAILURE;
547 }
548
549 {
550 auto ei = std::make_unique<xAOD::EventInfo>();
551 auto ei_store = std::make_unique<xAOD::EventAuxInfo>();
552 ei->setStore (ei_store.get());
553 ei->setRunNumber (runNbr);
554 ei->setEventNumber (global_entry);
555
556 static const SG::AuxElement::Accessor<std::string> tupleName ("tupleName");
557 static const SG::AuxElement::Accessor<std::string> collName ("collectionName");
558 tupleName(*ei) = m_tupleNames[tupleIdx];
559 collName(*ei) = m_inputCollectionsName[collIdx];
560
561 CHECK( m_dataStore->record (std::move(ei), "EventInfo") );
562 CHECK( m_dataStore->record (std::move(ei_store), "EventInfoAux.") );
563 }
564
565 // now the data has been loaded into the store, we can
566 // notify clients and fire the BeginInputFile incident
567 //MOVED TO handle method
568 /*if (m_fireBIF) {
569 m_fireBIF = false;
570 const FileNames_t& fnames = rctx->files();
571 std::size_t fidx = rctx->fileIndex();
572 const std::string& fname = fnames[fidx];
573 // notify other clients
574 // std::cout << "::switchED to next file..." << std::endl;
575 m_incsvc->fireIncident(FileIncident(name(), "BeginInputFile", fname));
576 // std::cerr << ":: new file: [" << fname << "]\n";
577 }*/
578 return StatusCode::SUCCESS;
579
580 } else {
581 // file is depleted
582 CHECK( endInputFile (rctx) );
583 rctx->setFileIndex (rctx->fileIndex() + 1);
584 rctx->setTree(NULL);
585 return next(*rctx);
586 }
587
588 // NOT REACHED
589 // std::cout << "***end of collections***" << std::endl;
590 // end of collections
591 //return StatusCode::FAILURE;
592}
593
594StatusCode RootNtupleEventSelector::next( Context& ctx, int jump ) const
595{
596 ATH_MSG_DEBUG ("next(" << jump << ") : iEvt " << m_curEvt);
597
598 if (self()->seek(ctx, m_curEvt + jump).isSuccess()) {
599 return StatusCode::FAILURE;
600 }
601 return next(ctx);
602}
603
604StatusCode
605RootNtupleEventSelector::previous( IEvtSelector::Context& ctx ) const
606{
607 return next( ctx, -1 );
608}
609
610StatusCode
611RootNtupleEventSelector::previous( Context& ctx, int jump ) const
612{
613 return next( ctx, -jump );
614}
615
616StatusCode
617RootNtupleEventSelector::last( Context& /*ctxt*/ ) const
618{
619 ATH_MSG_ERROR ("............. Last Event Not Implemented .............");
620 return StatusCode::FAILURE;
621}
622
623
624StatusCode
625RootNtupleEventSelector::rewind( Context& ctxt ) const
626{
627 return self()->seek(ctxt, 0);
628}
629
630StatusCode
632{
634 refCtx = ctx;
635 return StatusCode::SUCCESS;
636}
637
638StatusCode
639RootNtupleEventSelector::createAddress( const Context& /*refCtx*/,
640 IOpaqueAddress*& /*addr*/ ) const
641{
642 //std::cerr << "::TTES::createAddress()...\n";
643 return StatusCode::SUCCESS;
644}
645
646StatusCode
648{
649 RootNtupleEventContext *ctx = dynamic_cast<RootNtupleEventContext*>(refCtxt);
650 if ( ctx ) {
651 delete ctx; ctx = 0;
652 return StatusCode::SUCCESS;
653 }
654
655 return StatusCode::FAILURE;
656}
657
658StatusCode
659RootNtupleEventSelector::resetCriteria( const std::string&, Context& ) const
660{
661 ATH_MSG_ERROR ("............. resetCriteria Not Implemented .............");
662 return StatusCode::FAILURE;
663}
664
666// Non-const methods:
668
673StatusCode
674RootNtupleEventSelector::seek (Context& ctx, int evtnum) const
675{
676 RootNtupleEventContext* rctx = dynamic_cast<RootNtupleEventContext*>(&ctx);
677 if (!rctx) {
678 return StatusCode::FAILURE;
679 }
680
681 // std::cout << "::seek - evtnum=" << evtnum
682 // << " curevt=" << m_curEvt
683 // << " curcol=" << rctx->fileIndex()
684 // << std::endl;
685 long coll_idx, tuple_idx;
686 find_coll_idx(evtnum, coll_idx, tuple_idx);
687 // std::cout << "::seek - evtnum=" << evtnum
688 // << " curevt=" << m_curEvt
689 // << " curcol=" << rctx->fileIndex()
690 // << " colidx=" << coll_idx
691 // << std::endl;
692 if ((coll_idx == -1 || tuple_idx == -1) && evtnum < m_curEvt) {
693 coll_idx = rctx->fileIndex();
694 tuple_idx = rctx->tupleIndex();
695 }
696
697 if (coll_idx == -1 || tuple_idx == -1) {
698 ATH_MSG_INFO("seek: reached end of input.");
699 return StatusCode::RECOVERABLE;
700 }
701
702 if (coll_idx != static_cast<int>(rctx->fileIndex()) ||
703 tuple_idx != static_cast<int>(rctx->tupleIndex()))
704 {
705 // tell everyone we switched files...
706 m_tuple = NULL;
707 CHECK( endInputFile (rctx) );
708 }
709
710 rctx->setFileIndex (coll_idx);
711 rctx->setTupleIndex (tuple_idx);
712 m_curEvt = evtnum;
713
714 return StatusCode::SUCCESS;
715}
716
721int
722RootNtupleEventSelector::curEvent (const Context& /*refCtxt*/) const
723{
724 return m_curEvt;
725}
726
729StatusCode
731{
732 ATH_MSG_INFO("I/O reinitialization...");
733
734 ServiceHandle<IIoComponentMgr> iomgr("IoComponentMgr", name());
735 if (!iomgr.retrieve().isSuccess()) {
736 ATH_MSG_FATAL("Could not retrieve IoComponentMgr !");
737 return StatusCode::FAILURE;
738 }
739 if (!iomgr->io_hasitem(this)) {
740 ATH_MSG_FATAL("IoComponentMgr does not know about myself !");
741 return StatusCode::FAILURE;
742 }
743 std::vector<std::string> inputCollections = m_inputCollectionsName.value();
744
745 for (std::size_t
746 i = 0,
747 imax = m_inputCollectionsName.value().size();
748 i < imax;
749 ++i) {
750 std::string &fname = inputCollections[i];
751 // std::cout << "--retrieve new name for [" << fname << "]...\n";
752 if (!iomgr->io_contains(this, fname)) {
753 ATH_MSG_ERROR("IoComponentMgr does not know about [" << fname << "] !");
754 return StatusCode::FAILURE;
755 }
756 if (!iomgr->io_retrieve(this, fname).isSuccess()) {
757 ATH_MSG_FATAL("Could not retrieve new value for [" << fname << "] !");
758 return StatusCode::FAILURE;
759 }
760 // std::cout << "--> [" << fname << "]\n" << std::flush;
761 }
762 // all good... copy over.
763 m_inputCollectionsName = inputCollections;
764
765 // remove our EventInfo if any...
766 // {
767 // const bool force_remove = true;
768 // if (!m_dataStore->clearStore(force_remove).isSuccess()) {
769 // ATH_MSG_ERROR("could not clear event store!");
770 // return StatusCode::FAILURE;
771 // } else {
772 // ATH_MSG_INFO("sgdump: \n" << m_dataStore->dump());
773 // }
774 // }
775
776 // std::cout << "--> do_init_io...\n" << std::flush;
777 if (!do_init_io().isSuccess()) {
778 return StatusCode::FAILURE;
779 }
780
781 ATH_MSG_INFO("I/O reinitialization... [done]");
782 return StatusCode::SUCCESS;
783}
784
785
789StatusCode
791 tadList& /*tads*/)
792{
793 // std::cerr << "TTES::preLoadAddresses(" << int(storeID)
794 // << "," << tads.size()
795 // << ")...\n";
796 return StatusCode::SUCCESS;
797}
798
800StatusCode
802{
803 if (m_needReload) {
804 return createRootBranchAddresses(storeID, tads);
805 }
806
807 return StatusCode::SUCCESS;
808}
809
811StatusCode
813 const EventContext& /*ctx*/)
814{
815 if (tad) {
816 if (m_dataStore->proxy_exact (tad->sgkey())) {
817 return StatusCode::SUCCESS;
818 }
819 return StatusCode::FAILURE;
820 }
821 // do nothing.
822 return StatusCode::SUCCESS;
823}
824
825
827// Protected methods:
829
831void
832RootNtupleEventSelector::setupInputCollection( Gaudi::Details::PropertyBase& /*inputCollectionsName*/ )
833{
834 // nothing ?
835 return;
836}
837
838StatusCode
840 tadList &tads)
841{
842 if (storeID != StoreID::EVENT_STORE) {
843 ATH_MSG_INFO("-- not the event-store --");
844 return(StatusCode::SUCCESS);
845 }
846
847 if (0 == m_tuple) {
848 ATH_MSG_ERROR("null pointer to n-tuple !");
849 return StatusCode::FAILURE;
850 }
851
852 TObjArray *leaves = m_tuple->GetListOfLeaves();
853 if (!leaves) {
854 ATH_MSG_INFO("no leaves!!");
855 return StatusCode::SUCCESS;
856 }
857
858 // loop over leaves
859 for (Int_t i = 0; i < leaves->GetEntries(); ++i) {
860 TLeaf *leaf = (TLeaf *)leaves->At(i);
861 TBranch *branch = leaf->GetBranch();
862 if (branch) {
863
864 CLID id = 0;
865 const void* value_ptr = m_tuple;
866 const std::string type_name = leaf->GetTypeName();
867 const std::string br_name = branch->GetName();
868 const std::string sg_key = br_name;//m_tupleName.value()+"/"+br_name;
869 TClass *cls = TClass::GetClass(type_name.c_str());
870 const std::type_info *ti = 0;
871
872 if (cls) {
873 ti = cls->GetTypeInfo();
874 // first, try to load a dict for that class...
875 if (ti) {
876 m_dictsvc->load_type(*ti);
877 }
878 if (!ti) {
879 ATH_MSG_WARNING("could not find a type-info for [" <<
880 type_name << "]");
881 continue;
882 }
883 std::string ti_typename = System::typeinfoName(*ti);
884 if (!m_clidsvc->getIDOfTypeInfoName(ti_typename, id)
885 .isSuccess()) {
886 // try another one...
887 {
888 // Protect against data race inside TClassEdit.
889 // https://github.com/root-project/root/issues/10353
890 // Should be fixed in root 6.26.02.
891 R__WRITE_LOCKGUARD(ROOT::gCoreMutex);
892 ti_typename = TClassEdit::ShortType(ti_typename.c_str(),
893 TClassEdit::kDropAllDefault);
894 }
895 if (!m_clidsvc->getIDOfTypeInfoName(ti_typename, id)
896 .isSuccess()) {
897 ATH_MSG_DEBUG("** could not find a CLID from type-info ["
898 << System::typeinfoName(*ti) << "]");
899 ATH_MSG_DEBUG("** could not find a CLID from type-info-alias ["
900 << ti_typename << "]");
901 continue;
902 }
903 }
904 } else {
905 // probably a built-in type...
906 if (!m_clidsvc->getIDOfTypeName(::root_typename(type_name), id)
907 .isSuccess()) {
908 ATH_MSG_DEBUG("** could not find a CLID for type-name ["
909 << type_name << "]");
910 continue;
911 }
912 }
913 if (id == 0) {
914 ATH_MSG_DEBUG("** could not find a CLID for type-name ["
915 << type_name << "]");
916 continue;
917 }
919 (ROOT_StorageType, id,
920 m_tuple->GetName(),
921 br_name,
922 (unsigned long)(value_ptr),
923 (unsigned long)(m_curEvt-1));
924
925 // recycle old rootaddress, if any.
926 SG::DataProxy* proxy = m_dataStore->proxy (id, sg_key);
927 if (proxy) {
928 proxy->setAddress (addr);
929 }
930 else {
931 auto taddr = new SG::TransientAddress(id, sg_key, addr, false);
932 taddr->setProvider(this, storeID);
933 // only add the *new* TransientAddress to the input list as the *old* ones
934 // are already tracked by the datastore (via the sticky proxies)
935 tads.push_back(taddr);
936 }
937 }
938 }
939 m_needReload = false;
940 // remember that we need to fire a BeginInputFile incident.
941 // we can't fire it just now as some client may need the tree and its
942 // content loaded in the evtstore when their ::handle method is
943 // called.
944 // so we do it later.
945 //MOVED TO handle method - which is fired on BeginEvent after StoreGateSvc
946 //m_fireBIF = true;
947
948 return StatusCode::SUCCESS;
949}
950
951StatusCode
953 TTree *tree,
954 const std::string& prefix) const
955{
956 if (0 == store) {
957 ATH_MSG_ERROR("null pointer to store !");
958 return StatusCode::FAILURE;
959 }
960
961 if (0 == tree) {
962 ATH_MSG_ERROR("null pointer to n-tuple !");
963 return StatusCode::FAILURE;
964 }
965
966 // Record tree in Storegate for later writing
967 TransferTree* temp = new TransferTree(tree);
968 if (store->record(temp,prefix).isFailure()) ATH_MSG_ERROR("Unable to record metadata tree " << tree->GetName());
969
970 const std::string tree_name = tree->GetName();
971 TObjArray *branches = tree->GetListOfBranches();
972 if (!branches) {
973 ATH_MSG_INFO("no branches!!");
974 return StatusCode::SUCCESS;
975 }
976
977 // loop over branches
978 for (Int_t i = 0; i < branches->GetEntries(); ++i) {
979 TBranch *branch = (TBranch *)branches->At(i);
980 if (branch) {
981
982 CLID id = 0;
983 const void* value_ptr = tree;
984 const std::string type_name = branch->GetClassName();
985 const std::string br_name = branch->GetName();
986 const std::string sg_key = prefix.empty()
987 ? br_name
988 : prefix + "/" + br_name;
989 TClass *cls = NULL;
990 if (!type_name.empty()) {
991 cls = TClass::GetClass(type_name.c_str());
992 }
993 const std::type_info *ti = 0;
994
995 if (cls) {
996 ti = cls->GetTypeInfo();
997 // first, try to load a dict for that class...
998 if (ti) {
999 m_dictsvc->load_type(*ti);
1000 }
1001 if (!ti) {
1002 ATH_MSG_WARNING("could not find a type-info for [" <<
1003 type_name << "]");
1004 continue;
1005 }
1006 std::string ti_typename = System::typeinfoName(*ti);
1007 if (!m_clidsvc->getIDOfTypeInfoName(ti_typename, id)
1008 .isSuccess()) {
1009 // try another one...
1010 {
1011 // Protect against data race inside TClassEdit.
1012 // https://github.com/root-project/root/issues/10353
1013 // Should be fixed in root 6.26.02.
1014 R__WRITE_LOCKGUARD(ROOT::gCoreMutex);
1015 ti_typename = TClassEdit::ShortType(ti_typename.c_str(),
1016 TClassEdit::kDropAllDefault);
1017 }
1018 if (!m_clidsvc->getIDOfTypeInfoName(ti_typename, id)
1019 .isSuccess()) {
1020 ATH_MSG_INFO("** could not find a CLID from type-info ["
1021 << System::typeinfoName(*ti) << "]");
1022 ATH_MSG_INFO("** could not find a CLID from type-info-alias ["
1023 << ti_typename << "]");
1024 continue;
1025 }
1026 }
1027 } else {
1028 // probably a built-in type...
1029 TObjArray *leaves = branch->GetListOfLeaves();
1030 if (leaves &&
1031 leaves->GetEntries() == 1) {
1032 const std::string type_name = ((TLeaf*)leaves->At(0))->GetTypeName();
1033 if (!m_clidsvc->getIDOfTypeName(::root_typename(type_name), id)
1034 .isSuccess()) {
1035 ATH_MSG_INFO("** could not find a CLID for type-name ["
1036 << type_name << "]");
1037 continue;
1038 }
1039 }
1040 }
1041 if (id == 0) {
1042 ATH_MSG_INFO("** could not find a CLID for type-name ["
1043 << type_name << "]");
1044 continue;
1045 }
1048 (ROOT_StorageType, id,
1049 tree_name,
1050 br_name,
1051 (unsigned long)(value_ptr),
1052 (unsigned long)(0)));
1053 if (!store->recordAddress(sg_key, std::move(addr), true).isSuccess()) {
1054 ATH_MSG_ERROR("could not record address at [" << sg_key << "] in store ["
1055 << store->name() << "]");
1056 }
1057 // SG::TransientAddress* taddr = new SG::TransientAddress
1058 // (id, sg_key, addr);
1059 // taddr->setProvider(this);
1060 // taddr->clearAddress(true);
1061 // tads.push_back(taddr);
1062 }
1063 }
1064 return StatusCode::SUCCESS;
1065}
1066
1067TTree*
1069 const std::string& tupleName) const
1070{
1071 // std::cout << "::fetchNtuple(" << fname << ")..." << std::endl;
1072 TTree* tree = NULL;
1074 // std::cout << "::TFile::Open()..." << std::endl;
1075 TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(fname.c_str());
1076 TFile* fnew = nullptr;
1077 if (!f) {
1078 f = TFile::Open(fname.c_str(), "READ");
1079 fnew = f;
1080 if (f) {
1081 f->SetName(fname.c_str());
1082 }
1083 }
1084 if (!f || f->IsZombie()) {
1085 ATH_MSG_ERROR("could not open next file in input collection ["
1086 << fname << "]");
1087 if (f) {
1088 f->Close();
1089 }
1090 return tree;
1091 }
1092 // std::cout << "::TFile::GetTree(" << m_tupleName << ")..." << std::endl;
1093 tree = (TTree*)f->Get(tupleName.c_str());
1094 if (!tree) {
1095 ATH_MSG_ERROR("could not retrieve tree [" << tupleName << "]"
1096 << " from file [" << fname << "]");
1097 f->Close();
1098 return tree;
1099 }
1100
1101 if (fnew)
1102 m_files.push_back(fnew);
1103
1104 // std::cout << "::TTree::SetBranchStatus()..." << std::endl;
1105 // disable all branches
1106 tree->SetBranchStatus("*", 0);
1107
1108 if (!m_imetaStore->clearStore().isSuccess()) {
1109 ATH_MSG_INFO("could not clear store [" << m_imetaStore.typeAndName() << "]");
1110 return tree;
1111 }
1112
1113 addMetadataFromDirectoryName(tupleName+"Meta", f);
1114 addMetadataFromDirectoryName("Lumi", f, "Lumi");
1115 return tree;
1116}
1117
1118void RootNtupleEventSelector::addMetadataFromDirectoryName(const std::string &metadirname, TFile *fileObj, const std::string &prefix) const
1119{
1120 TDirectoryFile *metadir = (TDirectoryFile*)fileObj->Get(metadirname.c_str());
1121 if (!metadir) return;
1122 addMetadataFromDirectory(metadir, prefix);
1123}
1124
1125void RootNtupleEventSelector::addMetadataFromDirectory(TDirectoryFile *metadir, const std::string &prefix) const
1126{
1127 std::unordered_set<std::string> meta_keys;
1128 const TList *keys = metadir->GetListOfKeys();
1129 for (Int_t i=0; i < keys->GetSize(); ++i) {
1130 TKey* key = dynamic_cast<TKey*>(keys->At(i));
1131 if (!key) {
1132 continue;
1133 }
1134
1135 const std::string meta_key = key->GetName();
1136 if (!meta_keys.emplace(key->GetName()).second) {
1137 // key was already in the set:
1138 // meta_key is another cycle from a previous key entry.
1139 // *ASSUME* the highest cycle is the one we are interested in
1140 // *AND* that it was the previous one...
1141 continue;
1142 }
1143
1144 std::string fullPrefix(prefix);
1145 if (prefix != "") fullPrefix += "/";
1146 const std::string path = fullPrefix + key->GetName();
1147
1148 TString fullKeyName(TString::Format("%s;%hi", key->GetName(), key->GetCycle()));
1149 TObject *objRef = metadir->Get(fullKeyName);
1150
1151 TTree *metatree = dynamic_cast<TTree*>(objRef);
1152 if (metatree) {
1153 addMetadata(metatree, path);
1154 continue;
1155 }
1156
1157 TObjString *metaObjString = dynamic_cast<TObjString*>(objRef);
1158 if (metaObjString) {
1159 addMetadata(metaObjString, path);
1160 continue;
1161 }
1162
1163 ATH_MSG_WARNING("Unsupported metadata type: " << objRef->ClassName());
1164 }
1165}
1166
1167void RootNtupleEventSelector::addMetadata(TTree *metatree, const std::string &path) const
1168{
1169 if (metatree->GetEntry(0) < 0) {
1170 ATH_MSG_INFO("Problem retrieving data from metadata-tree [" << path << "] !!");
1171 return;
1172 }
1173
1174 if (!createMetaDataRootBranchAddresses(m_imetaStore.get(), metatree, path).isSuccess()) {
1175 ATH_MSG_INFO("Could not create metadata for tree [" << path << "]");
1176 }
1177}
1178
1179void RootNtupleEventSelector::addMetadata(TObjString *metastring, const std::string &path) const
1180{
1181 std::string *converted = new std::string(metastring->String());
1182 if (!m_imetaStore->record(converted, path).isSuccess()) {
1183 ATH_MSG_INFO("Could not create metadata for string [" << path << "]");
1184 }
1185}
1186
1187StatusCode
1189{
1190 // std::cout << "::fetchNtuple..." << std::endl;
1191
1192 // initialize some helper structures and data
1193 {
1195 zero.min_entries = -1;
1196 zero.max_entries = -1;
1197 zero.entries = -1;
1198 m_collEvts.resize (m_tupleNames.size());
1199 for (size_t i = 0; i < m_collEvts.size(); i++) {
1200 m_collEvts[i].resize(m_inputCollectionsName.value().size(), zero);
1201 }
1202 }
1203
1205 m_tupleNames[0]);
1206 if (!m_tuple) {
1207 throw "RootNtupleEventSelector: Unable to fetch Ntuple";
1208 }
1209
1210 // std::cout << "::clear-root-addresses..." << std::endl;
1211 // reset the list of branches
1212 m_needReload = true;
1213
1214 // skip events we are asked to skip
1216 m_nbrEvts = 0;
1217
1218 // std::cout << "::fetchNtuple...[done]" << std::endl;
1219 return StatusCode::SUCCESS;
1220}
1221
1226void
1228 long& coll_idx,
1229 long& tuple_idx) const
1230{
1231 coll_idx = -1;
1232 tuple_idx = -1;
1233
1234 // std::cout << "--find_coll_idx(" << evtidx << ")..." << std::endl
1235 // << "--collsize: " << m_collEvts.size() << std::endl;
1236 for (size_t ituple = 0; ituple < m_collEvts.size(); ++ituple) {
1237 for (size_t icoll = 0; icoll < m_collEvts[ituple].size(); ++icoll) {
1238 CollMetaData &itr = m_collEvts[ituple][icoll];
1239 if (itr.min_entries == -1) {
1240 TTree *tree = fetchNtuple(m_inputCollectionsName.value()[icoll],
1241 m_tupleNames[ituple]);
1242 if (tree) {
1243 long offset = 0;
1244 if (icoll > 0) {
1245 offset = m_collEvts[ituple][icoll-1].max_entries;
1246 }
1247 else if (ituple > 0) {
1248 offset = m_collEvts[ituple-1].back().max_entries;
1249 }
1250 itr.entries = tree->GetEntriesFast();
1251 itr.min_entries = offset;
1252 itr.max_entries = offset + itr.entries;
1253 } else {
1254 throw "RootNtupleEventSelector: Unable to fetch ntuple";
1255 }
1256 }
1257 // std::cout << "--[" << i << "] => [" << itr.min_entries << ", "
1258 // << itr.max_entries << ") evtidx=[" << evtidx << "]"
1259 // << std::endl;
1260 if (itr.min_entries <= evtidx && evtidx < itr.max_entries) {
1261 coll_idx = icoll;
1262 tuple_idx = ituple;
1263 return;
1264 }
1265 }
1266 }
1267}
1268
1270int RootNtupleEventSelector::size (Context& /*refCtxt*/) const {
1271 //use find_coll_idx to trigger a population of the m_collEvts
1272 long coll_idx, tuple_idx;
1273 find_coll_idx(-1, coll_idx, tuple_idx);
1274 return m_collEvts.back().back().max_entries;
1275}
1276
1277
1278void RootNtupleEventSelector::handle(const Incident& incident) {
1279 if(m_fireBIF && incident.type() == IncidentType::BeginEvent) {
1280 //fire the BeginInputFile
1281 m_incsvc->fireIncident(FileIncident(name(), "BeginInputFile", m_tuple->GetCurrentFile()->GetName()));
1282 m_fireBIF=false;
1283 }
1284}
1285
1286} //> namespace Athena
#define endmsg
#define ATH_MSG_ERROR(x)
#define ATH_MSG_FATAL(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
macros to associate a CLID to a type
#define CLASS_DEF(NAME, CID, VERSION)
associate a clid and a version to a type eg
#define CHECK(...)
Evaluate an expression and check for errors.
This class provides a unique identification for each event, in terms of run/event number and/or a tim...
This class provides general information about an event.
uint32_t CLID
The Class ID type.
Include TBranchElement.h, suppressing clang warnings.
int imax(int i, int j)
A simple class to hold the buffer of a TBranch from a TTree.
state of a few global resources from ROOT and restores their initial value upon d-tor call.
ROOT specific event selector context.
virtual void * identifier() const
context identifier
long m_tupleIdx
current tuple index (into ‘m_tupleNames’)
void setTree(TTree *tree)
set the tree used to iterate
std::size_t fileIndex() const
access to the file iterator
std::vector< std::string > FileNames_t
definition of the file container
const std::string & fid() const
access to the connection FID
virtual ~RootNtupleEventContext()
standard d-tor
void setFileIndex(std::size_t idx)
set file iterator
long m_collIdx
current collection index (into m_inputCollectionsName)
int64_t entry() const
access to the current event entry number
const RootNtupleEventSelector * m_evtsel
reference to the hosting event selector instance
TTree * tree() const
access to the tree used to iterate
void setFID(const std::string &fid)
set connection FID
RootNtupleEventContext(const RootNtupleEventSelector *sel)
standard c-tor with initialization
Class implementing the GAUDI IEvtSelector interface using ROOT TTree as a backend.
RootNtupleEventSelector * self() const
non-const access to self (b/c next() is const)
virtual StatusCode seek(Context &refCtxt, int evtnum) const override
Seek to a given event number.
virtual StatusCode finalize() override
RootNtupleEventSelector(const std::string &name, ISvcLocator *svcLoc)
Constructor with parameters:
virtual StatusCode releaseContext(Context *&refCtxt) const override
virtual int curEvent(const Context &refCtxt) const override
return the current event number.
void setupInputCollection(Gaudi::Details::PropertyBase &inputCollectionsName)
callback to synchronize the list of input files
virtual StatusCode loadAddresses(StoreID::type storeID, tadList &list) override
get all new addresses from Provider for this Event.
virtual StatusCode last(Context &refContext) const override
virtual int size(Context &refCtxt) const override
ICollectionSize interface
void find_coll_idx(int evtidx, long &coll_idx, long &tuple_idx) const
helper method to get the collection index (into m_inputCollectionsName) and tuple index (into ‘m_tupl...
virtual StatusCode resetCriteria(const std::string &cr, Context &ctx) const override
virtual StatusCode preLoadAddresses(StoreID::type storeID, tadList &list) override
IAddressProvider interface get all addresses from Provider : Called before Begin Event
StringArrayProperty m_activeBranchNames
List of branches to activate in the TTree.
TTree * m_tuple
current tree being read
std::vector< std::vector< CollMetaData > > m_collEvts
cache of the number of entries for each collection Indexed like [tuple][collection]
bool m_needReload
The (python) selection function to apply on the TChain we are reading.
virtual StatusCode updateAddress(StoreID::type storeID, SG::TransientAddress *tad, const EventContext &ctx) override
update a transient Address
IDictSvc_t m_dictsvc
Pointer to the IDictLoaderSvc.
std::vector< std::string > m_tupleNames
Names of all trees over which to iterate.
virtual StatusCode next(Context &refCtxt) const override
StoreGateSvc_t m_imetaStore
Pointer to the StoreGateSvc input metadata store.
StatusCode endInputFile(RootNtupleEventContext *rctx) const
StatusCode do_init_io()
helper method to init the i/o components
StatusCode createMetaDataRootBranchAddresses(StoreGateSvc *store, TTree *tree, const std::string &prefix) const
helper method to create proxies for the metadata store
IIncSvc_t m_incsvc
Handle to the incident service.
void addMetadataFromDirectoryName(const std::string &metadirname, TFile *fileObj, const std::string &prefix="") const
StringArrayProperty m_inputCollectionsName
List of input files containing TTree.
virtual StatusCode createContext(Context *&refpCtxt) const override
ICLIDSvc_t m_clidsvc
Pointer to the IClassIDSvc.
StringProperty m_tupleName
Name of TTree to load from collection of input files.
StoreGateSvc_t m_dataStore
Pointer to the StoreGateSvc event store.
void addMetadataFromDirectory(TDirectoryFile *metadir, const std::string &prefix="") const
void addMetadata(TTree *metatree, const std::string &path="") const
TTree * fetchNtuple(const std::string &fname, const std::string &tupleName) const
helper method to retrieve the correct tuple
virtual void handle(const Incident &incident) override
StatusCode createRootBranchAddresses(StoreID::type storeID, tadList &tads)
helper method to create proxies
virtual StatusCode initialize() override
virtual StatusCode previous(Context &refCtxt) const override
StoreGateSvc_t m_ometaStore
Pointer to the StoreGateSvc output metadata store.
long m_skipEvts
Number of events to skip at the beginning.
virtual StatusCode io_reinit() override
Callback method to reinitialize the internal state of the component for I/O purposes (e....
virtual StatusCode rewind(Context &refCtxt) const override
virtual StatusCode createAddress(const Context &refCtxt, IOpaqueAddress *&) const override
long m_nbrEvts
Number of Events read so far.
Simple smart pointer for Gaudi-style refcounted objects.
void record(const T *p, const std::string &key)
Definition TestStore.h:81
virtual const std::string & name() const override
Definition TestStore.cxx:97
SG::Accessor< T, ALLOC > Accessor
Definition AuxElement.h:572
sgkey_t sgkey() const
Set the primary (hashed) SG key.
The Athena Transient Store API.
@ EVENT_STORE
Definition StoreID.h:26
void zero(TH2 *h)
zero the contents of a 2d histogram
std::vector< std::string > files
file names and file pointers
Definition hcg.cxx:50
Some weak symbol referencing magic... These are declared in AthenaKernel/getMessageSvc....
RootNtupleEventContext::FileNames_t FileNames_t
StatusCode ROOTMessageFilterSvc::initialize ATLAS_NOT_THREAD_SAFE()
Return the file descriptor fataldump() uses for output.
StatusCode parse(std::tuple< Tup... > &tup, const Gaudi::Parsers::InputData &input)
@ active
Definition Layer.h:47
EventInfo_v1 EventInfo
Definition of the latest event info version.
long entries
number of entries in this collection.
long min_entries
number of entries up to this collection
long max_entries
number of entries after this collection
TChain * tree