17#include <unordered_map>
18#include <unordered_set>
24#include "TClassEdit.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"
52#include "AthenaRootComps/TransferTree.h"
55#include "EventInfo/EventInfo.h"
67#include "boost/tokenizer.hpp"
71 root_typename(
const std::string& root_type_name)
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))},
77 {
"Long_t", System::typeinfoName(
typeid(Long_t))},
78 {
"ULong_t", System::typeinfoName(
typeid(ULong_t))},
80 {
"Long64_t", System::typeinfoName(
typeid(Long64_t))},
81 {
"ULong64_t", System::typeinfoName(
typeid(ULong64_t))},
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))},
88 {
"Bool_t", System::typeinfoName(
typeid(Bool_t))},
89 {
"Char_t", System::typeinfoName(
typeid(Char_t))},
90 {
"UChar_t", System::typeinfoName(
typeid(UChar_t))},
92 {
"Short_t", System::typeinfoName(
typeid(Short_t))},
93 {
"UShort_t", System::typeinfoName(
typeid(UShort_t))}
96 return s.at(root_type_name);
100 std::vector<std::string>
101 get_active_leaves(TTree *tuple)
103 std::vector<std::string>
active;
104 TObjArray *leaves = tuple->GetListOfLeaves();
107 for (Int_t i = 0;
i < leaves->GetEntries(); ++
i) {
108 TLeaf *leaf = (TLeaf *)leaves->At(i);
109 TBranch *branch = leaf->GetBranch();
111 const char *brname = branch->GetName();
112 if (tuple->GetBranchStatus(brname)) {
113 active.push_back(std::string(brname));
130 public ::IEvtSelector::Context
164 {
return m_evtsel->m_inputCollectionsName.value(); }
202 if (cur &&
tree != cur) {
203 TFile *old_file = cur->GetCurrentFile();
223 ISvcLocator* svcLoc ) :
224 extends ( name, svcLoc ),
226 m_imetaStore(
"StoreGateSvc/InputMetaDataStore", name ),
238 declareProperty(
"DataStore",
240 "Store where to publish data");
242 declareProperty(
"InputMetaStore",
244 "Store where to publish (input) metadata");
246 declareProperty(
"MetaStore",
248 "Store where to publish (output) metadata");
250 declareProperty(
"InputCollections",
252 "List of input (ROOT) file names" );
256 declareProperty(
"TupleName",
258 "Name of the TTree to load/read from input file(s). "
259 "May be a semicolon-separated string to read multiple TTrees.");
261 declareProperty(
"SkipEvents",
263 "Number of events to skip at the beginning" );
265 declareProperty(
"ActiveBranches",
267 "List of branch names to activate" );
277 ATH_MSG_INFO (
"Enter RootNtupleEventSelector initialization...");
280 if ( !
m_clidsvc.retrieve().isSuccess() ) {
282 (
"Could not retrieve [" <<
m_clidsvc.typeAndName() <<
"]");
283 return StatusCode::FAILURE;
287 if ( !
m_dictsvc.retrieve().isSuccess() ) {
289 (
"Could not retrieve [" <<
m_dictsvc.typeAndName() <<
"]");
290 return StatusCode::FAILURE;
293 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
294 boost::char_separator<char> sep (
" ;");
300 (
"You have to give a TTree name to read from the ROOT files !");
301 return StatusCode::FAILURE;
305 m_incsvc->addListener(
this,IncidentType::BeginEvent,99);
310 if ( nbrInputFiles < 1 ) {
312 (
"You need to give at least 1 input file !!" <<
endmsg
313 <<
"(Got [" << nbrInputFiles <<
"] file instead !)");
314 return StatusCode::FAILURE;
317 (
"Selector configured to read [" << nbrInputFiles <<
"] file(s)..."
325 if (!iomgr.retrieve().isSuccess()) {
327 return StatusCode::FAILURE;
329 if (!iomgr->io_register(
this).isSuccess()) {
330 ATH_MSG_FATAL(
"Could not register myself with the IoComponentMgr !");
331 return StatusCode::FAILURE;
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 !");
343 ATH_MSG_VERBOSE(
"io_register[" << this->name() <<
"](" << incol[icol] <<
") [ok]");
347 return StatusCode::FAILURE;
352 return StatusCode::FAILURE;
384 std::vector<std::string> propVal;
386 bool foundSvc(
false);
387 for(
const std::string& s : propVal) {
388 if(s==
"Athena::xAODCnvSvc") { foundSvc=
true;
break; }
391 propVal.push_back(
"Athena::NtupleCnvSvc");
392 CHECK( epSvc->setProperty(
"CnvServices", Gaudi::Utils::toString( propVal ) ));
397 CHECK( ppSvc.retrieve() );
398 ppSvc->addProvider(
this );
402 return StatusCode::SUCCESS;
419 return StatusCode::SUCCESS;
430 m_incsvc->fireIncident(FileIncident(name(),
"EndInputFile", fnames[fidx]));
445 dp->setAddress (
nullptr);
450 const bool forceRemove =
false;
454 return StatusCode::SUCCESS;
467 ATH_MSG_ERROR (
"Could not dyn-cast to RootNtupleEventContext !!");
468 throw "RootNtupleEventSelector: Unable to get RootNtupleEventContext";
480 const std::string& fname = fnames[fidx];
483 throw "RootNtupleEventSelector: Unable to get tree";
497 return StatusCode::FAILURE;
500 int64_t global_entry = rctx->
entry();
503 int64_t
entry = global_entry;
504 if (
m_collEvts[tupleIdx][collIdx].min_entries < 0) {
506 long coll_idx, tuple_idx;
523 if ( nentries > entry ) {
527 if (
tree->LoadTree(entry) < 0) {
529 (
"Problem loading tree for event [" <<
m_curEvt <<
"] !!");
530 throw "RootNtupleEventSelector: Problem loading input tree";
540 EventType* evtType =
new EventType;
541 const std::size_t runNbr = 0;
543 if ( !
m_dataStore->record( evtInfo,
"TTreeEventInfo" ).isSuccess() ) {
545 delete evtInfo; evtInfo = 0;
546 return StatusCode::FAILURE;
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);
578 return StatusCode::SUCCESS;
599 return StatusCode::FAILURE;
607 return next( ctx, -1 );
613 return next( ctx, -jump );
619 ATH_MSG_ERROR (
"............. Last Event Not Implemented .............");
620 return StatusCode::FAILURE;
635 return StatusCode::SUCCESS;
640 IOpaqueAddress*& )
const
643 return StatusCode::SUCCESS;
652 return StatusCode::SUCCESS;
655 return StatusCode::FAILURE;
661 ATH_MSG_ERROR (
"............. resetCriteria Not Implemented .............");
662 return StatusCode::FAILURE;
678 return StatusCode::FAILURE;
685 long coll_idx, tuple_idx;
692 if ((coll_idx == -1 || tuple_idx == -1) && evtnum <
m_curEvt) {
697 if (coll_idx == -1 || tuple_idx == -1) {
699 return StatusCode::RECOVERABLE;
702 if (coll_idx !=
static_cast<int>(rctx->
fileIndex()) ||
703 tuple_idx !=
static_cast<int>(rctx->
tupleIndex()))
714 return StatusCode::SUCCESS;
735 if (!iomgr.retrieve().isSuccess()) {
737 return StatusCode::FAILURE;
739 if (!iomgr->io_hasitem(
this)) {
740 ATH_MSG_FATAL(
"IoComponentMgr does not know about myself !");
741 return StatusCode::FAILURE;
750 std::string &fname = inputCollections[i];
752 if (!iomgr->io_contains(
this, fname)) {
753 ATH_MSG_ERROR(
"IoComponentMgr does not know about [" << fname <<
"] !");
754 return StatusCode::FAILURE;
756 if (!iomgr->io_retrieve(
this, fname).isSuccess()) {
757 ATH_MSG_FATAL(
"Could not retrieve new value for [" << fname <<
"] !");
758 return StatusCode::FAILURE;
778 return StatusCode::FAILURE;
782 return StatusCode::SUCCESS;
796 return StatusCode::SUCCESS;
807 return StatusCode::SUCCESS;
813 const EventContext& )
817 return StatusCode::SUCCESS;
819 return StatusCode::FAILURE;
822 return StatusCode::SUCCESS;
844 return(StatusCode::SUCCESS);
849 return StatusCode::FAILURE;
852 TObjArray *leaves =
m_tuple->GetListOfLeaves();
855 return StatusCode::SUCCESS;
859 for (Int_t i = 0; i < leaves->GetEntries(); ++i) {
860 TLeaf *leaf = (TLeaf *)leaves->At(i);
861 TBranch *branch = leaf->GetBranch();
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;
869 TClass *cls = TClass::GetClass(type_name.c_str());
870 const std::type_info *ti = 0;
873 ti = cls->GetTypeInfo();
883 std::string ti_typename = System::typeinfoName(*ti);
884 if (!
m_clidsvc->getIDOfTypeInfoName(ti_typename,
id)
891 R__WRITE_LOCKGUARD(ROOT::gCoreMutex);
892 ti_typename = TClassEdit::ShortType(ti_typename.c_str(),
893 TClassEdit::kDropAllDefault);
895 if (!
m_clidsvc->getIDOfTypeInfoName(ti_typename,
id)
898 << System::typeinfoName(*ti) <<
"]");
899 ATH_MSG_DEBUG(
"** could not find a CLID from type-info-alias ["
900 << ti_typename <<
"]");
906 if (!
m_clidsvc->getIDOfTypeName(::root_typename(type_name),
id)
909 << type_name <<
"]");
915 << type_name <<
"]");
919 (ROOT_StorageType,
id,
922 (
unsigned long)(value_ptr),
928 proxy->setAddress (addr);
932 taddr->setProvider(
this, storeID);
935 tads.push_back(taddr);
948 return StatusCode::SUCCESS;
954 const std::string& prefix)
const
958 return StatusCode::FAILURE;
963 return StatusCode::FAILURE;
968 if (store->
record(temp,prefix).isFailure())
ATH_MSG_ERROR(
"Unable to record metadata tree " <<
tree->GetName());
970 const std::string tree_name =
tree->GetName();
971 TObjArray *branches =
tree->GetListOfBranches();
974 return StatusCode::SUCCESS;
978 for (Int_t i = 0; i < branches->GetEntries(); ++i) {
979 TBranch *branch = (TBranch *)branches->At(i);
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()
988 : prefix +
"/" + br_name;
990 if (!type_name.empty()) {
991 cls = TClass::GetClass(type_name.c_str());
993 const std::type_info *ti = 0;
996 ti = cls->GetTypeInfo();
1006 std::string ti_typename = System::typeinfoName(*ti);
1007 if (!
m_clidsvc->getIDOfTypeInfoName(ti_typename,
id)
1014 R__WRITE_LOCKGUARD(ROOT::gCoreMutex);
1015 ti_typename = TClassEdit::ShortType(ti_typename.c_str(),
1016 TClassEdit::kDropAllDefault);
1018 if (!
m_clidsvc->getIDOfTypeInfoName(ti_typename,
id)
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 <<
"]");
1029 TObjArray *leaves = branch->GetListOfLeaves();
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)
1035 ATH_MSG_INFO(
"** could not find a CLID for type-name ["
1036 << type_name <<
"]");
1042 ATH_MSG_INFO(
"** could not find a CLID for type-name ["
1043 << type_name <<
"]");
1048 (ROOT_StorageType,
id,
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() <<
"]");
1064 return StatusCode::SUCCESS;
1069 const std::string& tupleName)
const
1075 TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(fname.c_str());
1076 TFile* fnew =
nullptr;
1078 f = TFile::Open(fname.c_str(),
"READ");
1081 f->SetName(fname.c_str());
1084 if (!f || f->IsZombie()) {
1085 ATH_MSG_ERROR(
"could not open next file in input collection ["
1093 tree = (TTree*)f->Get(tupleName.c_str());
1095 ATH_MSG_ERROR(
"could not retrieve tree [" << tupleName <<
"]"
1096 <<
" from file [" << fname <<
"]");
1106 tree->SetBranchStatus(
"*", 0);
1120 TDirectoryFile *metadir = (TDirectoryFile*)fileObj->Get(metadirname.c_str());
1121 if (!metadir)
return;
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));
1135 const std::string meta_key = key->GetName();
1136 if (!meta_keys.emplace(key->GetName()).second) {
1144 std::string fullPrefix(prefix);
1145 if (prefix !=
"") fullPrefix +=
"/";
1146 const std::string path = fullPrefix + key->GetName();
1148 TString fullKeyName(TString::Format(
"%s;%hi", key->GetName(), key->GetCycle()));
1149 TObject *objRef = metadir->Get(fullKeyName);
1151 TTree *metatree =
dynamic_cast<TTree*
>(objRef);
1157 TObjString *metaObjString =
dynamic_cast<TObjString*
>(objRef);
1158 if (metaObjString) {
1163 ATH_MSG_WARNING(
"Unsupported metadata type: " << objRef->ClassName());
1169 if (metatree->GetEntry(0) < 0) {
1170 ATH_MSG_INFO(
"Problem retrieving data from metadata-tree [" << path <<
"] !!");
1175 ATH_MSG_INFO(
"Could not create metadata for tree [" << path <<
"]");
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 <<
"]");
1195 zero.min_entries = -1;
1196 zero.max_entries = -1;
1199 for (
size_t i = 0; i <
m_collEvts.size(); i++) {
1207 throw "RootNtupleEventSelector: Unable to fetch Ntuple";
1219 return StatusCode::SUCCESS;
1229 long& tuple_idx)
const
1236 for (
size_t ituple = 0; ituple <
m_collEvts.size(); ++ituple) {
1237 for (
size_t icoll = 0; icoll <
m_collEvts[ituple].size(); ++icoll) {
1245 offset =
m_collEvts[ituple][icoll-1].max_entries;
1247 else if (ituple > 0) {
1248 offset =
m_collEvts[ituple-1].back().max_entries;
1254 throw "RootNtupleEventSelector: Unable to fetch ntuple";
1272 long coll_idx, tuple_idx;
1279 if(
m_fireBIF && incident.type() == IncidentType::BeginEvent) {
1281 m_incsvc->fireIncident(FileIncident(name(),
"BeginInputFile",
m_tuple->GetCurrentFile()->GetName()));
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(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.
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
std::string m_fid
connection FID
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::size_t tupleIndex() const
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)
const FileNames_t & files() const
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 setTupleIndex(std::size_t idx)
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 ~RootNtupleEventSelector()
Destructor:
virtual StatusCode finalize() override
RootNtupleEventSelector(const std::string &name, ISvcLocator *svcLoc)
Constructor with parameters:
virtual StatusCode releaseContext(Context *&refCtxt) const override
long m_curEvt
current event index
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.
std::vector< TFile * > m_files
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
friend class Athena::RootNtupleEventContext
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)
virtual const std::string & name() const override
SG::Accessor< T, ALLOC > Accessor
sgkey_t sgkey() const
Set the primary (hashed) SG key.
The Athena Transient Store API.
void zero(TH2 *h)
zero the contents of a 2d histogram
std::vector< std::string > files
file names and file pointers
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)
EventInfo_v1 EventInfo
Definition of the latest event info version.