ATLAS Offline Software
Loading...
Searching...
No Matches
Control/xAODRootAccess/Root/TEvent.cxx
Go to the documentation of this file.
1// Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
2
3// Local include(s).
5
6#include "IOUtils.h"
7
8// System include(s):
9#include <cassert>
10#include <cstring>
11#include <iomanip>
12#include <sstream>
13
14// ROOT include(s):
15#include <TBranch.h>
16#include <TChain.h>
17#include <TChainElement.h>
18#include <TError.h>
19#include <TFile.h>
20#include <TFriendElement.h>
21#include <TKey.h>
22#include <TMethodCall.h>
23#include <TSystem.h>
24#include <TTree.h>
25
26// Gaudi/Athena include(s):
33#ifndef XAOD_STANDALONE
35#include "SGTools/DataProxy.h"
36#endif // not XAOD_STANDALONE
37#include "CxxUtils/ClassName.h"
39
40// Interface include(s):
42
43// xAOD include(s):
48
49// Local include(s):
67
68namespace xAOD {
69
71static const ::Int_t CACHE_SIZE = -1;
73const char *const TEvent::EVENT_TREE_NAME = "CollectionTree";
75static const char *const METADATA_TREE_NAME = "MetaData";
76
77TEvent::TEvent(EAuxMode mode) : Event("xAOD::TEvent"), m_auxMode(mode) {}
79TEvent::TEvent(::TFile *file, EAuxMode mode) : TEvent(mode) {
81 // Let the initialisation function deal with setting up the object.
82 readFrom(file).ignore();
83}
84
85TEvent::TEvent(::TTree *tree, EAuxMode mode) : TEvent(mode) {
86
87 // Let the initialisation function deal with setting up the object.
88 readFrom(tree).ignore();
89}
90
92
93 // Check that the user didn't forget to call finishWritingTo().
94 if (m_outTree) {
96 "Did not call finishWritingTo() before destroying the TEvent object!");
97 }
98
99 // Clear the input and output objects before the input/output files would be
100 // closed. Otherwise we can be left with "TTree related" objects pointing
101 // nowhere.
102 m_inputObjects.clear();
103 m_outputObjects.clear();
104}
105
109
110void TEvent::setOtherMetaDataTreeNamePattern(const std::string &pattern) {
111 // Only change if pattern provided is not empty
112 if (pattern.size()) {
113 // User provided a regular expression for other MetaData trees
114 m_otherMetaDataTreeNamePattern = std::regex(pattern);
115 }
116}
117
127StatusCode TEvent::readFrom(::TFile *file, bool useTreeCache,
128 std::string_view treeName) {
129
130 // If no file was specified, return gracefully.
131 if (file == nullptr) {
132 ATH_MSG_DEBUG("No input file specified for readFrom(...)");
133 return StatusCode::SUCCESS;
134 }
135
136 // Clear the cached input objects.
137 m_inputObjects.clear();
138 m_inputMissingObjects.clear();
139 m_inputMetaObjects.clear();
140 {
142 lock.upgrade();
143 m_branches.clear();
144 }
145
146 // Reset the internal flags.
147 m_inTreeMissing = kFALSE;
148 m_entry = -1;
149
150 // Make sure we return to the current directory:
152
153 // Set up the file access tracer.
155 tracer.add(*file);
156
157 // Look for the metadata tree:
158 m_inMetaTree = file->Get<TTree>(METADATA_TREE_NAME);
159 if (m_inMetaTree == nullptr) {
160 ATH_MSG_ERROR("Couldn't find metadata tree on input. Object is unusable!");
161 return StatusCode::FAILURE;
162 }
163
164 // Set metadata entry to be read
165 // NB: no reading is done calling LoadTree
166 if (m_inMetaTree->LoadTree(0) < 0) {
167 ATH_MSG_ERROR("Failed to load entry 0 for metadata tree");
168 return StatusCode::FAILURE;
169 }
170
171 // A sanity check.
172 if (m_inMetaTree->GetEntries() != 1) {
173 ATH_MSG_WARNING("Was expecting a metadata tree with size 1, instead of "
174 << m_inMetaTree->GetEntries() << ".");
175 ATH_MSG_WARNING("The input file was most probably produced by hadd...");
176 }
177
178 // Make sure that the xAOD::EventFormat dictonary is loaded.
179 // This may not be the case if streamer information reading is turned
180 // off.
181 static const std::string eventFormatTypeName =
183 ::TClass *cl = ::TClass::GetClass(eventFormatTypeName.c_str());
184 if (cl == nullptr) {
185 ATH_MSG_WARNING("Couldn't load the xAOD::EventFormat dictionary");
186 }
187
188 // Helper lambda for collecting the event format metadata from an RNTuple
189 // with a given name.
190 auto readEventFormatMetadata =
191 [&](std::string_view thisTreeName) -> StatusCode {
192 // Look for the metadata tree:
193 TTree *metaTree = file->Get<TTree>(thisTreeName.data());
194 if (metaTree == nullptr) {
195 ATH_MSG_ERROR("Couldn't find metadata tree \"" << thisTreeName
196 << "\"on input.");
197 return StatusCode::FAILURE;
198 }
199 // Set metadata entry to be read.
200 if (metaTree->LoadTree(0) < 0) {
201 ATH_MSG_ERROR("Failed to load entry 0 for metadata tree \""
202 << thisTreeName << "\"");
203 return StatusCode::FAILURE;
204 }
205
206 // Check if the EventFormat branch is available:
207 const std::string eventFormatBranchName =
209 if (!metaTree->GetBranch(eventFormatBranchName.c_str())) {
210 // This can happen when the file was produced by an Athena job that
211 // didn't have any input events itself. This means that the file
212 // doesn't actually have any useful metadata.
213 ATH_MSG_INFO("Input file provides no event or metadata");
214 return StatusCode::RECOVERABLE;
215 }
216
217 // Read in the event format object:
218 EventFormat *format = 0;
219 ::TBranch *br = 0;
220 const Int_t status =
221 metaTree->SetBranchAddress(eventFormatBranchName.c_str(), &format, &br);
222 if (status < 0) {
223 ATH_MSG_ERROR("Failed to connect to xAOD::EventFormat object");
224 return StatusCode::FAILURE;
225 }
226
227 // Merge the object into our private member.
228 br->GetEntry(0);
229 for (const auto &[key, element] : *format) {
230 m_inputEventFormat.add(element);
231 }
232
233 // This is a strange place. The object has to be deleted, as it is the
234 // responsibility of the user code to do so. But if I also explicitly
235 // tell the branch to forget about the address of the pointer, then
236 // all hell breaks loose...
237 delete format;
238
239 // Return gracefully.
240 return StatusCode::SUCCESS;
241 };
242
243 // Read in the metadata from the "main" metadata ntuple.
245 const StatusCode sc = readEventFormatMetadata(METADATA_TREE_NAME);
246 if (sc.isRecoverable()) {
247 m_inTree = nullptr;
248 m_inTreeMissing = true;
249 return StatusCode::SUCCESS;
250 }
251 ATH_CHECK(sc);
252
253 // List all the other Metadata trees in the input file
254 // Having several metatrees can happen for augmented files for instance
255 // as one metadata tree per stream is produced
256 std::set<std::string> lOtherMetaTreeNames = {};
257 TList *lKeys = file->GetListOfKeys();
258
259 if (lKeys) {
260 for (int iKey = 0; iKey < lKeys->GetEntries(); iKey++) {
261 // iterate over keys and add
262 std::string keyName = lKeys->At(iKey)->GetName();
263 // Make sure the key corresponds to a metadata tree but
264 // do not add the current metadata tree in the list of other trees
265 // and do not add the metadata tree handlers to the list
266 if ((keyName != METADATA_TREE_NAME) &&
267 std::regex_match(keyName, m_otherMetaDataTreeNamePattern)) {
268 // Make sure key corresponds to a tree
269 const char *className = ((::TKey *)lKeys->At(iKey))->GetClassName();
270 static constexpr Bool_t LOAD = kFALSE;
271 static constexpr Bool_t SILENT = kTRUE;
272 ::TClass *cl = ::TClass::GetClass(className, LOAD, SILENT);
273 if ((cl != nullptr) && cl->InheritsFrom(::TTree::Class())) {
274 // key is corresponding to a metadata tree
275 lOtherMetaTreeNames.insert(std::move(keyName));
276 }
277 }
278 }
279 }
280
281 // Loop over the other metadata trees found (if any).
282 for (const std::string &metaTreeName : lOtherMetaTreeNames) {
283 ATH_CHECK(readEventFormatMetadata(metaTreeName));
284 }
285
286 // Look for the event tree in the input file.
287 m_inTree = file->Get<TTree>(treeName.data());
288 if (m_inTree == nullptr) {
289 // This is no longer an error condition. As it can happen for DxAODs
290 // that don't have any events in them. But they still have metadata
291 // that needs to be collected.
292 m_inTreeMissing = kTRUE;
293 }
294
295 // Turn on the cache if requested.
296 if (m_inTree && useTreeCache && (!m_inTree->GetCacheSize())) {
297 m_inTree->SetCacheSize(CACHE_SIZE);
298 m_inTree->SetCacheLearnEntries(10);
299 }
300
301 // Init the statistics collection.
303 // Update the event counter in the statistics object.
305 if (m_inTree) {
306 stats.setNEvents(stats.nEvents() + m_inTree->GetEntries());
307 }
308
309 // Notify the listeners that a new file was opened.
310 const TIncident beginIncident(IncidentType::BeginInputFile);
311 for (TVirtualIncidentListener *listener : m_listeners) {
312 listener->handle(beginIncident);
313 }
314 // For now implement a very simple scheme in which we claim already
315 // at the start that the entire file was processed. Since we have no way
316 // of ensuring that the user indeed does this. And we can't delay calling
317 // this function, as the user may likely close his/her output file before
318 // closing the last opened input file.
319 const TIncident endIncident(IncidentType::EndInputFile);
320 for (TVirtualIncidentListener *listener : m_listeners) {
321 listener->handle(endIncident);
322 }
323
324 // The initialisation was successful.
325 return StatusCode::SUCCESS;
326}
327
336StatusCode TEvent::readFrom(::TTree *tree, bool useTreeCache) {
337
338 // Remember the info:
339 m_inTree = nullptr;
340 m_inTreeMissing = false;
341 m_inChain = dynamic_cast<TChain *>(tree);
342 m_inMetaTree = nullptr;
343
344 if (m_inChain) {
345
346 // Set up the caching on the chain level. The individual trees of the
347 // input files will get a cache set up automatically after this.
348 if (useTreeCache && (!m_inChain->GetCacheSize())) {
349 m_inChain->SetCacheSize(CACHE_SIZE);
350 m_inChain->SetCacheLearnEntries(10);
351 }
352
353 // Explicitly open the first file of the chain. To correctly auto-load
354 // the dictionaries necessary. This doesn't happen automatically with
355 // some ROOT versions...
356 const TObjArray *files = m_inChain->GetListOfFiles();
357 if (!files) {
358 ATH_MSG_ERROR("Couldn't get the list of files from the input TChain");
359 return StatusCode::FAILURE;
360 }
361 if (!files->GetEntries()) {
362 ATH_MSG_ERROR("No files are present in the received TChain");
363 return StatusCode::FAILURE;
364 }
365 const ::TChainElement *chEl =
366 dynamic_cast<const ::TChainElement *>(files->At(0));
367 if (!chEl) {
368 ATH_MSG_ERROR("Couldn't cast object to TChainElement");
369 return StatusCode::FAILURE;
370 }
371 {
372 std::unique_ptr<TFile> dummyFile{TFile::Open(chEl->GetTitle())};
373 if (!dummyFile) {
374 ATH_MSG_ERROR("Couldn't open file " << chEl->GetTitle());
375 return StatusCode::FAILURE;
376 }
377 }
378
379 // Set up a tracker for the chain.
380 if (!m_inChainTracker) {
381 m_inChainTracker = std::make_unique<TChainStateTracker>();
382 }
383 m_inChainTracker->reset();
384 tree->SetNotify(m_inChainTracker.get());
385
386 // Stop at this point. The first file will be opened when the user
387 // asks for the first event. Otherwise we open the first file of the
388 // chain multiple times.
389 m_inTreeNumber = -1;
390 return StatusCode::SUCCESS;
391
392 } else {
393
394 // If it's a simple TTree, then let's fully initialise the object
395 // using its file:
396 m_inTreeNumber = -1;
397 if (m_inChainTracker) {
398 m_inChainTracker.reset();
399 }
400 ::TFile *file = tree->GetCurrentFile();
401 return readFrom(file, useTreeCache, tree->GetName());
402 }
403}
404
413StatusCode TEvent::writeTo(::TFile *file, int autoFlush,
414 std::string_view treeName) {
415
416 // Just a simple security check.
417 if (!file) {
418 ATH_MSG_ERROR("Null pointer received!");
419 return StatusCode::FAILURE;
420 }
421
422 // Check that the object is in the "right state":
423 if (m_outTree) {
424 ATH_MSG_ERROR("Object already writing to a file. Close that file first!");
425 return StatusCode::FAILURE;
426 }
427
428 // Make sure we return to the current directory:
430
431 // Create the output TTree:
432 file->cd();
433 m_outTree = std::make_unique<TTree>(treeName.data(), "xAOD event tree");
434 m_outTree->SetDirectory(file);
435 m_outTree->SetAutoSave(1000000);
436 m_outTree->SetAutoFlush(autoFlush);
437
438 // Access the EventFormat object associated with this file:
441
442 // Return gracefully:
443 return StatusCode::SUCCESS;
444}
445
452StatusCode TEvent::finishWritingTo(::TFile *file) {
453
454 // A small sanity check:
455 if (!m_outTree) {
456 ATH_MSG_ERROR("The object doesn't seem to be connected to an output file!");
457 return StatusCode::FAILURE;
458 }
459
460 // Make sure we return to the current directory:
462
463 // Notify the listeners that they should write out their metadata, if they
464 // have any.
466 for (auto &listener : m_listeners) {
467 listener->handle(incident);
468 }
469
470 // Write out the event tree, and delete it:
471 m_outTree->AutoSave("FlushBaskets");
472 m_outTree->SetDirectory(0);
473 m_outTree.reset();
474
475 // Now go to the output file:
476 file->cd();
477
478 // Check if there's already a metadata tree in the output:
479 if (file->Get(METADATA_TREE_NAME)) {
480 // Let's assume that the metadata is complete in the file already.
481 return StatusCode::SUCCESS;
482 }
483
484 // Create the metadata tree.
485 auto metatree =
486 std::make_unique<TTree>(METADATA_TREE_NAME, "xAOD metadata tree");
487 metatree->SetAutoSave(10000);
488 metatree->SetAutoFlush(-30000000);
489 metatree->SetDirectory(file);
490
491 // Create the xAOD::EventFormat branch in it.
492 try {
493 metatree->Branch(
494 "EventFormat",
497 } catch (const CxxUtils::ClassName::ExcBadClassName &e) {
498 ::Error("xAOD::TEvent::finishWritingTo",
499 XAOD_MESSAGE("Class name parsing fails for %s ! "), e.what());
500 return StatusCode::FAILURE;
501 }
502
503 // Create a copy of the m_outputMetaObjects variable. This is necessary
504 // because the putAux(...) function will modify this variable while we
505 // loop over it.
506 std::vector<std::pair<std::string, TObjectManager *>> outputMetaObjects;
507 outputMetaObjects.reserve(m_outputMetaObjects.size());
508 for (const auto &[key, mgr] : m_outputMetaObjects) {
509 TObjectManager *objMgr = dynamic_cast<TObjectManager *>(mgr.get());
510 if (objMgr == nullptr) {
511 ATH_MSG_FATAL("Internal logic error detected");
512 return StatusCode::FAILURE;
513 }
514 outputMetaObjects.emplace_back(key, objMgr);
515 }
516
517 // Now loop over all the metadata objects that need to be put into the
518 // output file:
519 for (auto &[key, mgr] : outputMetaObjects) {
520
521 // Select a split level depending on whether this is an interface or an
522 // auxiliary object:
523 const ::Int_t splitLevel = (key.ends_with("Aux.") ? 1 : 0);
524 // Create the new branch:
525 *(mgr->branchPtr()) =
526 metatree->Branch(key.c_str(), mgr->holder()->getClass()->GetName(),
527 mgr->holder()->getPtr(), 32000, splitLevel);
528 if (!mgr->branch()) {
529 ATH_MSG_ERROR("Failed to create metadata branch \""
530 << mgr->holder()->getClass()->GetName() << "/" << key
531 << "\"");
532 return StatusCode::FAILURE;
533 }
534 // Set up the saving of all the dynamic auxiliary properties
535 // of the object if it has any:
536 static constexpr bool METADATA = true;
537 ATH_CHECK(putAux(*metatree, *mgr, METADATA));
538 }
539
540 // Write the metadata objects:
541 if (metatree->Fill() <= 0) {
542 ATH_MSG_ERROR("Failed to write event format metadata into the output");
543 metatree->SetDirectory(nullptr);
544 return StatusCode::FAILURE;
545 }
546
547 // Now clean up:
548 metatree->Write();
549 metatree->SetDirectory(nullptr);
550 m_outputEventFormat = nullptr;
551 m_outputObjects.clear();
552 m_outputMetaObjects.clear();
553
554 // Return gracefully:
555 return StatusCode::SUCCESS;
556}
557
567SG::IAuxStore *TEvent::recordAux(const std::string &key,
569
570 // A sanity check:
571 if (!m_outTree) {
572 ATH_MSG_ERROR("No output tree given to the object");
573 return nullptr;
574 }
575
576 // Check for an object with this name in the output list:
577 Object_t::iterator itr = m_outputObjects.find(key);
578 if (itr == m_outputObjects.end()) {
579 // Create one if if it doesn't exist yet...
580 // Translate the store type:
582 switch (type) {
585 break;
588 break;
589 default:
590 ATH_MSG_ERROR("Unknown store type (" << type << ") requested");
591 return nullptr;
592 }
593 // Create and record the object:
594 static constexpr bool TOP_STORE = true;
595 if (record(std::make_unique<TAuxStore>(key, TOP_STORE, mode), key)
596 .isFailure()) {
597 ATH_MSG_ERROR("Couldn't connect TAuxStore object to the output");
598 return nullptr;
599 }
600 // Update the iterator:
601 itr = m_outputObjects.find(key);
602 }
603
604 // A security check:
605 if (itr == m_outputObjects.end()) {
606 ATH_MSG_ERROR("Internal logic error detected");
607 return nullptr;
608 }
609
610 // Check that it is of the right type:
611 TAuxManager *mgr = dynamic_cast<TAuxManager *>(itr->second.get());
612 if (!mgr) {
613 ATH_MSG_ERROR("Internal logic error detected");
614 return nullptr;
615 }
616
617 // Extract the pointer out of it:
618 TAuxStore *store = mgr->getStore();
619
620 // Give it to the user:
621 return store;
622}
623
626::Long64_t TEvent::getEntries() const {
627
628 if (m_inChain) {
629 return m_inChain->GetEntries();
630 } else if (m_inTree) {
631 return m_inTree->GetEntries();
632 } else if (m_inTreeMissing) {
633 // The input file is empty:
634 return 0;
635 } else {
636 ATH_MSG_ERROR("Function called on an uninitialised object");
637 return 0;
638 }
639}
640
655::Int_t TEvent::getEntry(::Long64_t entry, ::Int_t getall) {
656
657 // A little sanity check:
658 if ((!m_inTree) && (!m_inChain)) {
659 ATH_MSG_ERROR("Function called on an uninitialised object");
660 return -1;
661 }
662
663 // If we have a chain as input:
664 if (m_inChain) {
665 // Make sure that the correct tree is loaded:
666 const ::Long64_t fileEntry = m_inChain->LoadTree(entry);
667 if (fileEntry < 0) {
668 ATH_MSG_ERROR("Failure in loading entry " << entry
669 << " from the input chain");
670 return -1;
671 }
672 // Check if a new file was loaded:
673 if ((m_inTreeNumber != m_inChain->GetTreeNumber()) ||
674 m_inChainTracker->internalStateChanged()) {
675 // Reset the tracker:
676 m_inChainTracker->reset();
677 // Connect to this new file:
678 m_inTreeNumber = m_inChain->GetTreeNumber();
679 ::TFile *file = m_inChain->GetFile();
680 // The useTreeCache parameter is set to false, since the cache
681 // is anyway set up through the TChain. It shouldn't be modified
682 // on the file level.
683 static constexpr bool USE_TREE_CACHE = false;
684 if (readFrom(file, USE_TREE_CACHE, m_inChain->GetName()).isFailure()) {
685 ATH_MSG_ERROR("Couldn't connect to input file #"
686 << m_inTreeNumber << " of the input chain");
687 return -1;
688 }
689 }
690 // Restore the previously received entry number.
691 m_entry = fileEntry;
692 }
693 // If we have a regular file/tree as input:
694 else {
695 m_entry = entry;
696 }
697
698 // In order to make the reading of branches+tree cache work
699 // NB: TTree::LoadTree() only set the entry that should be read for each
700 // branch but no reading of the branch content is performed when calling that
701 // function. The entry set that can be retrieved with
702 // branch->GetTree()->GetReadEntry()
703 // For friend trees, if an index was built, then the entry which is set for
704 // the related branches is found by the LoadTree function by matching the the
705 // major and minor values of the main tree and friend tree
706 if (m_inTree && m_inTree->LoadTree(m_entry) < 0) {
707 ATH_MSG_ERROR("Failure in loading entry " << m_entry
708 << " from the input file");
709 return -1;
710 }
711
712 // Stats counter needs to know it's the next event:
714
715 // The final number of bytes read.
716 ::Int_t result = 0;
717
718 // Check if objects need to be read in.
719 if (getall) {
720 if (m_auxMode == kAthenaAccess) {
721 // In kAthenaAccess mode we need to use getInputObject(...) to load
722 // all the input objects correctly.
723 for (auto &[key, mgr] : m_inputObjects) {
724 static const std::string dynStorePostfix = "Aux.Dynamic";
725 if (key.ends_with(dynStorePostfix)) {
726 // Ignore the dynamic store objects. They get loaded through
727 // their parents.
728 } else {
729 // Load the objects and their auxiliary stores through the
730 // getInputObject(...) function, which takes care of correctly
731 // setting them up. The type is irrelevant here. We don't
732 // really care about the exact type of the objects.
733 static constexpr bool SILENT = true;
734 static constexpr bool METADATA = false;
735 getInputObject(key, typeid(int), SILENT, METADATA);
736 }
737 }
738 } else {
739 // In a "reasonable" access mode, we do something very simple:
740 for (auto &[key, mgr] : m_inputObjects) {
741 result += mgr->getEntry(getall);
742 }
743 }
744 }
745
746 // Notify the listeners that a new event was loaded:
747 const TIncident incident(IncidentType::BeginEvent);
748 for (auto &listener : m_listeners) {
749 listener->handle(incident);
750 }
751
752 // Return the number of bytes read:
753 return result;
754}
755
765::Long64_t TEvent::getFiles() const {
766
767 if (m_inChain) {
768 return m_inChain->GetListOfFiles()->GetEntries();
769 } else if (m_inTree || m_inTreeMissing) {
770 return 1;
771 } else {
772 return 0;
773 }
774}
775
785::Int_t TEvent::getFile(::Long64_t file, ::Int_t getall) {
786
787 // Check if the file number is valid:
788 if ((file < 0) || (file >= getFiles())) {
789 ATH_MSG_ERROR("Function called with invalid file number (" << file << ")");
790 return -1;
791 }
792
793 // If we are not reading a TChain, return at this point. As the one and
794 // only file is open already...
795 if (!m_inChain) {
796 return 0;
797 }
798
799 // Trigger the "scanning" of the input files, so the TChain would know
800 // how many entries are in the various files.
801 getEntries();
802
803 // Calculate which entry/event we need to load:
804 ::Long64_t entry = 0;
805 for (::Long64_t i = 0; i < file; ++i) {
806 entry += m_inChain->GetTreeOffset()[i];
807 }
808
809 // Load this entry using the regular event opening function:
810 return getEntry(entry, getall);
811}
812
819::Int_t TEvent::fill() {
820
821 // A little sanity check:
822 if (!m_outTree) {
823 ATH_MSG_ERROR("Object not connected to an output file!");
824 return 0;
825 }
826
827 // Make sure that all objects have been read in. The 99 as the value
828 // has a special meaning for TAuxStore. With this value it doesn't
829 // delete its transient (decoration) variables. Otherwise it does.
830 // (As it's supposed to, when moving to a new event.)
831 Int_t readBytes = 0;
832 if (m_inChain != nullptr) {
833 readBytes = getEntry(m_inChain->GetReadEntry(), 99);
834 } else if (m_inTree != nullptr) {
835 readBytes = getEntry(m_entry, 99);
836 }
837 if (readBytes < 0) {
838 ATH_MSG_ERROR("getEntry failed!");
839 return readBytes;
840 }
841
842 // Prepare the objects for writing. Note that we need to iterate over a
843 // copy of the m_outputObjects container. Since the putAux(...) function
844 // called inside the loop may itself add elements to the m_outputObject
845 // container.
846 std::string unsetObjects;
847 std::vector<std::pair<std::string, TVirtualManager *>> outputObjectsCopy;
848 outputObjectsCopy.reserve(m_outputObjects.size());
849 for (const auto &[key, mgr] : m_outputObjects) {
850 outputObjectsCopy.emplace_back(key, mgr.get());
851 }
852 for (auto &[key, mgr] : outputObjectsCopy) {
853 // Check that a new object was provided in the event:
854 if (!mgr->create()) {
855 // We are now going to fail. But let's collect the names of
856 // all the unset objects:
857 if (unsetObjects.size()) {
858 unsetObjects += ", ";
859 }
860 unsetObjects.append("\"" + key + "\"");
861 continue;
862 }
863 // Make sure that any dynamic auxiliary variables that
864 // were added to the object after it was put into the event,
865 // get added to the output:
866 static constexpr bool METADATA = false;
867 if (putAux(*m_outTree, *mgr, METADATA).isFailure()) {
868 ATH_MSG_ERROR("Failed to put dynamic auxiliary variables "
869 "in the output for object \""
870 << key << "\"");
871 return 0;
872 }
873 }
874
875 // Check if there were any unset objects:
876 if (unsetObjects.size()) {
877 ATH_MSG_ERROR("The following objects were not set in the current event: "
878 << unsetObjects);
879 return 0;
880 }
881
882 // Write the entry, and check the return value:
883 const ::Int_t ret = m_outTree->Fill();
884 if (ret <= 0) {
885 ATH_MSG_ERROR("Output tree filling failed with return value: " << ret);
886 }
887
888 // Reset the object managers.
889 for (auto &[key, mgr] : m_outputObjects) {
890 mgr->reset();
891 }
892
893 // Return the value:
894 return ret;
895}
896
897bool TEvent::hasInput() const {
898
899 return ((m_inTree != nullptr) || (m_inChain != nullptr));
900}
901
902bool TEvent::hasOutput() const { return (m_outTree.get() != nullptr); }
903
904StatusCode TEvent::getNames(const std::string &targetClassName,
905 std::vector<std::string> &vkeys,
906 bool metadata) const {
907 // The results go in here
908 std::set<std::string> keys;
909
910 // Get list of branches from
911 // the input metadata tree or input tree
912 std::vector<TObjArray *> fullListOfBranches = {};
913 if (metadata) {
914 if (m_inMetaTree) {
915 // No friend tree expected for metadata tree
916 // Only add the list of branches of the metadata tree
917 ATH_MSG_DEBUG("Scanning for input metadata objects");
918 fullListOfBranches.push_back(m_inMetaTree->GetListOfBranches());
919 }
920 } else {
921 if (m_inTree) {
922 ATH_MSG_DEBUG("Scanning for input data objects");
923 // Add the list of branches of the main tree
924 fullListOfBranches.push_back(m_inTree->GetListOfBranches());
925 // If the input tree has friend trees
926 // add as well the list of friend tree branches
927 if (m_inTree->GetListOfFriends()) {
928 // Get the list of friends
929 TList *fList = m_inTree->GetListOfFriends();
930 // Loop over friend elements
931 for (TObject *feObj : *fList) {
932 if (feObj) {
933 // Get corresponding friend tree
934 auto *pElement = dynamic_cast<TFriendElement *>(feObj);
935 if (pElement == nullptr) {
936 continue;
937 }
938 TTree *friendTree = pElement->GetTree();
939 // Add list of branches of the friend tree
940 fullListOfBranches.push_back(friendTree->GetListOfBranches());
941 }
942 }
943 }
944 }
945 }
946
947 // Loop over all list of branches (if any)
948 for (const TObjArray *in : fullListOfBranches) {
949 // Loop over all branches inside the current list of branches
950 for (const TObject *obj : *in) {
951
952 if (obj == nullptr) {
953 continue;
954 }
955 const TBranch *element = dynamic_cast<const TBranch *>(obj);
956 if (!element) {
957 ATH_MSG_ERROR("Failure inspecting input data objects");
958 return StatusCode::FAILURE;
959 }
960 const std::string objClassName = element->GetClassName();
961 std::string key = obj->GetName();
962 ATH_MSG_VERBOSE("Inspecting \"" << objClassName << "\" / \"" << key
963 << "\"");
964 if (objClassName == targetClassName) {
965 ATH_MSG_DEBUG("Matched \"" << targetClassName << "\" to key \"" << key
966 << "\"");
967 keys.insert(std::move(key));
968 }
969 }
970 }
971
972 const Object_t &inAux = (metadata ? m_inputMetaObjects : m_inputObjects);
973
974 ATH_MSG_DEBUG("Scanning input objects for \"" << targetClassName << "\"");
975 for (const auto &[key, vmgr] : inAux) {
976 // All (metadata) objects should be held by TObjectManager objects.
977 const TObjectManager *mgr =
978 dynamic_cast<const TObjectManager *>(vmgr.get());
979 if (mgr == nullptr) {
980 continue;
981 }
982 const std::string &objClassName = mgr->holder()->getClass()->GetName();
983 ATH_MSG_VERBOSE("Inspecting \"" << objClassName << "\" / \"" << key
984 << "\"");
985 if (objClassName == targetClassName) {
986 ATH_MSG_DEBUG("Matched \"" << targetClassName << "\" to key \"" << key
987 << "\"");
988 keys.insert(key);
989 }
990 }
991
992 // Check for output objects.
993 if ((metadata == false) && m_outTree) {
994 const TObjArray *out = m_outTree->GetListOfBranches();
995 ATH_MSG_DEBUG("Scanning for output data objects");
996
997 for (const TObject *obj : *out) {
998 if (obj == nullptr) {
999 continue;
1000 }
1001 const TBranch *element = dynamic_cast<const TBranch *>(obj);
1002 if (element == nullptr) {
1003 ATH_MSG_ERROR("Failure inspecting output objects");
1004 return StatusCode::FAILURE;
1005 }
1006 const std::string objClassName = element->GetClassName();
1007 std::string key = obj->GetName();
1008 ATH_MSG_VERBOSE("Inspecting \"" << objClassName << "\" / \"" << key
1009 << "\"");
1010 if (objClassName == targetClassName) {
1011 ATH_MSG_DEBUG("Matched \"" << targetClassName << "\" to key \"" << key
1012 << "\"");
1013 keys.insert(std::move(key));
1014 }
1015 }
1016 }
1017
1018 const Object_t &outAux = (metadata ? m_outputMetaObjects : m_outputObjects);
1019
1020 // Search though the in-memory output objects.
1021 ATH_MSG_DEBUG("Scanning output objects for \"" << targetClassName << "\"");
1022 for (const auto &[key, vmgr] : outAux) {
1023 // All (metadata) objects should be held by TObjectManager objects.
1024 TObjectManager *mgr = dynamic_cast<TObjectManager *>(vmgr.get());
1025 if (mgr == nullptr) {
1026 continue;
1027 }
1028 const std::string &objClassName = mgr->holder()->getClass()->GetName();
1029 ATH_MSG_VERBOSE("Inspecting \"" << objClassName << "\" / \"" << key
1030 << "\"");
1031 if (objClassName == targetClassName) {
1032 ATH_MSG_DEBUG("Matched \"" << targetClassName << "\" to key \"" << key
1033 << "\"");
1034 keys.insert(key);
1035 }
1036 }
1037
1038 vkeys.insert(vkeys.end(), keys.begin(), keys.end());
1039
1040 // Return gracefully.
1041 return StatusCode::SUCCESS;
1042}
1043
1061StatusCode TEvent::connectObject(const std::string &key, bool silent) {
1062
1063 // A little sanity check:
1064 if (hasInput() == false) {
1065 ATH_MSG_ERROR("Function called on un-initialised object");
1066 return StatusCode::FAILURE;
1067 }
1068
1069 // Increment the access counter on this container:
1071
1072 // Check if the branch is already connected:
1073 if (m_inputObjects.contains(key)) {
1074 return StatusCode::SUCCESS;
1075 }
1076 // Check if it was already found to be missing.
1077 if (m_inputMissingObjects.contains(key)) {
1078 if (silent == false) {
1079 ATH_MSG_WARNING("Branch \"" << key << "\" not available on input");
1080 }
1081 return StatusCode::RECOVERABLE;
1082 }
1083
1084 // Check if we have metadata about this branch:
1085 const xAOD::EventFormatElement *ef = nullptr;
1086 if (m_inputEventFormat.exists(key) == false) {
1087 if (silent == false) {
1088 ATH_MSG_WARNING("No metadata available for branch: " << key);
1089 }
1090 } else {
1091 ef = m_inputEventFormat.get(key);
1092 }
1093
1094 // Check if the branch exists in our input tree:
1095 ::TBranch *br = m_inTree->GetBranch(key.c_str());
1096 if (br == nullptr) {
1097 if (!silent) {
1098 ATH_MSG_WARNING("Branch \"" << key << "\" not available on input");
1099 }
1100 m_inputMissingObjects.insert(key);
1101 return StatusCode::RECOVERABLE;
1102 }
1103
1104 // Make sure that it's not in "MakeClass mode":
1105 br->SetMakeClass(0);
1106
1107 // Decide about the type that we need to use for the reading of this
1108 // branch:
1109 std::string className = br->GetClassName();
1110 if (className == "") {
1111 if (ef) {
1112 // This is a fairly weird situation, but let's fall back to taking
1113 // the class name from the metadata object in this case.
1114 className = ef->className();
1115 } else {
1117 "Couldn't find an appropriate type with a dictionary for branch \""
1118 << key << "\"");
1119 return StatusCode::FAILURE;
1120 }
1121 }
1122 ::TClass *realClass = ::TClass::GetClass(className.c_str());
1123 if (((!realClass) || (!realClass->IsLoaded())) && ef) {
1124 // We may need to do an actual schema evolution here, in which
1125 // case let's fall back on the class name coming from the metadata
1126 // object.
1127 className = ef->className();
1128 realClass = ::TClass::GetClass(className.c_str());
1129 }
1130 if ((!realClass) || (!realClass->IsLoaded())) {
1131 // Now we're in trouble...
1133 "Couldn't find an appropriate type with a dictionary for branch \""
1134 << key << "\"");
1135 return StatusCode::FAILURE;
1136 }
1137
1138 // Make sure that the current object is the "active event":
1139 setActive();
1140
1141 // The data type is always "other" for us:
1142 static const ::EDataType dataType = kOther_t;
1143
1144 // Check if the output already has this object. If it does, let's
1145 // assume that we have been copying the object to the output. Which
1146 // means that we need to resume filling the same memory address that
1147 // the output holder points to.
1148 void *ptr = nullptr;
1149 Object_t::const_iterator out_itr = m_outputObjects.find(key);
1150 if (out_itr != m_outputObjects.end()) {
1151 // It needs to be an object manager...
1152 TObjectManager *mgr = dynamic_cast<TObjectManager *>(out_itr->second.get());
1153 if (mgr == nullptr) {
1154 ATH_MSG_ERROR("Couldn't access output manager for: " << key);
1155 return StatusCode::FAILURE;
1156 }
1157 // Get the pointer out of it:
1158 ptr = mgr->holder()->get();
1159 }
1160
1161 // If there is no output object, then let's create one ourselves.
1162 // This is the only way in which we can have the memory management of
1163 // THolder do the right thing with this object.
1164 if (ptr == nullptr) {
1165 ptr = realClass->New();
1166 }
1167
1168 // Create the new manager object that will hold this EDM object:
1169 const bool renewOnRead = (m_auxMode == kAthenaAccess);
1170 auto mgr = std::make_unique<TObjectManager>(
1171 nullptr, std::make_unique<THolder>(ptr, realClass), renewOnRead);
1172
1173 // One final check. If it's not an auxiliary store, then it must have
1174 // a split level of 0. Otherwise read rules may not work on it. Causing
1175 // *very* serious silent corruption in the data read, if we don't use
1176 // the "Athena read mode".
1177 if ((m_auxMode != kAthenaAccess) && (br->GetSplitLevel() != 0) &&
1178 (Details::isAuxStore(*(mgr->holder()->getClass())) == false)) {
1179 ATH_MSG_ERROR("Split level for branch \""
1180 << key << "\" is " << br->GetSplitLevel()
1181 << ". This can only be read in kAthenaAccess mode.");
1182 // Clean up:
1183 *(mgr->holder()->getPtr()) = nullptr;
1184 m_inputObjects.erase(key);
1185 return StatusCode::FAILURE;
1186 }
1187
1188 // Now try to connect to the branch:
1189 const ::Int_t status =
1190 m_inTree->SetBranchAddress(key.c_str(), mgr->holder()->getPtr(),
1191 mgr->branchPtr(), realClass, dataType, kTRUE);
1192 if (status < 0) {
1193 ATH_MSG_ERROR("Couldn't connect variable of type \""
1194 << className << "\" to input branch \"" << key
1195 << "\". Return code: " << status);
1196 // Clean up:
1197 *(mgr->holder()->getPtr()) = 0;
1198 m_inputObjects.erase(key);
1199 return StatusCode::FAILURE;
1200 }
1201
1202 // At this point we have successfully connected the branch.
1203 TObjectManager *mgrPtr = mgr.get();
1204 m_inputObjects[key] = std::move(mgr);
1205
1206 // If it's an auxiliary store object, set it up correctly:
1207 if (Details::isAuxStore(*(mgrPtr->holder()->getClass()))) {
1209 }
1210
1211 // If there may be an auxiliary object connected to this one,
1212 // connect that as well:
1213 if (Details::hasAuxStore(*(mgrPtr->holder()->getClass()))) {
1215 key + "Aux.", Details::isStandalone(*(mgrPtr->holder()->getClass()))));
1216 }
1217
1218 // Return gracefully.
1219 return StatusCode::SUCCESS;
1220}
1221
1230StatusCode TEvent::connectMetaObject(const std::string &key, bool silent) {
1231
1232 // A little sanity check:
1233 if (!m_inMetaTree) {
1234 ATH_MSG_ERROR("Function called on un-initialised object");
1235 return StatusCode::FAILURE;
1236 }
1237
1238 // Check if the branch is already connected:
1239 if (m_inputMetaObjects.contains(key)) {
1240 return StatusCode::SUCCESS;
1241 }
1242
1243 // Check if the branch exists in our metadata tree:
1244 ::TBranch *br = m_inMetaTree->GetBranch(key.c_str());
1245 if (br == nullptr) {
1246 if (silent == false) {
1247 ATH_MSG_WARNING("Metadata branch \"" << key
1248 << "\" not available on input");
1249 }
1250 return StatusCode::RECOVERABLE;
1251 }
1252
1253 // Check that we have an entry in the branch:
1254 if (br->GetEntries() == 0) {
1255 if (silent == false) {
1256 ATH_MSG_WARNING("Metadata branch \"" << key
1257 << "\" doesn't hold any data");
1258 }
1259 return StatusCode::RECOVERABLE;
1260 }
1261
1262 // Make sure that it's not in "MakeClass mode":
1263 br->SetMakeClass(0);
1264
1265 // Extract the type of the branch:
1266 ::TClass *cl = 0;
1267 ::EDataType dt = kOther_t;
1268 if (br->GetExpectedType(cl, dt) || (!cl)) {
1269 ATH_MSG_ERROR("Couldn't get the type for metadata branch \"" << key
1270 << "\"");
1271 return StatusCode::FAILURE;
1272 }
1273
1274 // Create the object, and all of the managers around it:
1275 void *ptr = cl->New();
1276 const bool renewOnRead = (m_auxMode == kAthenaAccess);
1277 auto mgr = std::make_unique<TObjectManager>(
1278 nullptr, std::make_unique<THolder>(ptr, cl), renewOnRead);
1279
1280 // Now try to connect to the branch:
1281 const ::Int_t status = m_inMetaTree->SetBranchAddress(
1282 key.c_str(), mgr->holder()->getPtr(), mgr->branchPtr(), cl, dt, kTRUE);
1283 if (status < 0) {
1284 ATH_MSG_ERROR("Couldn't connect variable of type \""
1285 << cl->GetName() << "\" to input branch \"" << key
1286 << "\". Return code: " << status);
1287 // Clean up:
1288 *(mgr->holder()->getPtr()) = 0;
1289 m_inputMetaObjects.erase(key);
1290 return StatusCode::FAILURE;
1291 }
1292
1293 // Store the manager.
1294 TObjectManager *mgrPtr = mgr.get();
1295 m_inputMetaObjects[key] = std::move(mgr);
1296
1297 // Read in the object:
1298 if (mgrPtr->getEntry() < 0) {
1299 ATH_MSG_ERROR("Couldn't read in metadata object with key \"" << key
1300 << "\"");
1301 return StatusCode::FAILURE;
1302 }
1303
1304 // If it's an auxiliary store object, set it up correctly:
1305 if (Details::isAuxStore(*(mgrPtr->holder()->getClass()))) {
1307 }
1308
1309 // If there may be an auxiliary object connected to this one,
1310 // connect that as well.
1311 if (Details::hasAuxStore(*(mgrPtr->holder()->getClass()))) {
1313 key + "Aux.", Details::isStandalone(*(mgrPtr->holder()->getClass()))));
1314 static constexpr bool METADATA = true;
1315 ATH_CHECK(setAuxStore(key, *mgrPtr, METADATA));
1316 }
1317
1318 // We succeeded:
1319 return StatusCode::SUCCESS;
1320}
1321
1331StatusCode TEvent::connectAux(const std::string &prefix, bool standalone) {
1332
1333 // A simple test...
1334 if (hasInput() == false) {
1335 ATH_MSG_ERROR("No input tree is available");
1336 return StatusCode::FAILURE;
1337 }
1338
1339 // Check if we know anything about this auxiliary object:
1340 if ((!m_inTree->GetBranch(prefix.c_str())) &&
1342 // If not, then let's just return right away. Not having
1343 // an auxiliary object with this name is not an error per se.
1344 return StatusCode::SUCCESS;
1345 }
1346
1347 // Check if the branch is already connected.
1348 if (m_inputObjects.contains(prefix)) {
1349 return StatusCode::SUCCESS;
1350 }
1351
1352 // Do different things based on the "auxiliary mode" we are in.
1353 if ((m_auxMode == kClassAccess) || (m_auxMode == kAthenaAccess)) {
1354
1355 // In "class" and "athena" access modes just connect the concrete auxiliary
1356 // object to the input.
1357 static constexpr bool SILENT = false;
1358 ATH_CHECK(connectObject(prefix, SILENT));
1359
1360 // Return gracefully.
1361 return StatusCode::SUCCESS;
1362
1363 } else if (m_auxMode == kBranchAccess) {
1364
1365 // In "branch access mode" let's create a TAuxStore object, and let
1366 // that take care of the auxiliary store access.
1367 static constexpr bool TOP_STORE = true;
1368 auto store = std::make_unique<TAuxStore>(
1369 prefix, TOP_STORE,
1372
1373 // Connect it to the input tree.
1374 ATH_CHECK(store->readFrom(*m_inTree));
1375
1376 // We're using this object to read from the input, it needs to be
1377 // locked:
1378 store->lock();
1379
1380 // Finally, set up an appropriate manager for it.
1381 static constexpr bool IS_OWNER = true;
1382 m_inputObjects[prefix] =
1383 std::make_unique<TAuxManager>(store.release(), IS_OWNER);
1384
1385 // Return gracefully:
1386 return StatusCode::SUCCESS;
1387 }
1388
1389 // There was some problem:
1390 ATH_MSG_ERROR("Unknown auxiliary access mode set (" << m_auxMode << ")");
1391 return StatusCode::FAILURE;
1392}
1393
1403StatusCode TEvent::connectMetaAux(const std::string &prefix, bool standalone) {
1404
1405 // Check if the branch is already connected:
1406 if (m_inputMetaObjects.contains(prefix)) {
1407 return StatusCode::SUCCESS;
1408 }
1409
1410 // A sanity check:
1411 if (!m_inMetaTree) {
1412 ATH_MSG_FATAL("Internal logic error detected");
1413 return StatusCode::FAILURE;
1414 }
1415
1416 // Do different things based on the "auxiliary mode" we are in:
1418
1419 // In "class" and "athena" access modes just connect the concrete auxiliary
1420 // object to the input.
1421 static constexpr bool SILENT = false;
1422 ATH_CHECK(connectMetaObject(prefix, SILENT));
1423
1424 // Return gracefully:
1425 return StatusCode::SUCCESS;
1426
1427 } else if (m_auxMode == kBranchAccess) {
1428
1429 // In "branch access mode" let's create a TAuxStore object, and let
1430 // that take care of the auxiliary store access.
1431 static constexpr bool TOP_STORE = true;
1432 auto store = std::make_unique<TAuxStore>(
1433 prefix, TOP_STORE,
1436
1437 // Connect it to the input tree.
1438 ATH_CHECK(store->readFrom(*m_inMetaTree));
1439
1440 // We're using this object to read from the input, it needs to be
1441 // locked:
1442 store->lock();
1443
1444 // Finally, set up an appropriate manager for it.
1445 static constexpr bool IS_OWNER = true;
1446 m_inputMetaObjects[prefix] =
1447 std::make_unique<TAuxManager>(store.release(), IS_OWNER);
1448
1449 // Return gracefully.
1450 return StatusCode::SUCCESS;
1451 }
1452
1453 // There was some problem:
1454 ATH_MSG_ERROR("Unknown auxiliary access mode set (" << m_auxMode << ")");
1455 return StatusCode::FAILURE;
1456}
1457
1467StatusCode TEvent::setAuxStore(const std::string &key,
1468 Details::IObjectManager &mgr, bool metadata) {
1469
1470 // Pre-compute some values.
1471 const bool isAuxStore = Details::isAuxStore(*(mgr.holder()->getClass()));
1472
1473 // Check if we need to do anything.
1474 if ((Details::hasAuxStore(*(mgr.holder()->getClass())) == false) &&
1475 (isAuxStore == false)) {
1476 return StatusCode::SUCCESS;
1477 }
1478
1479 // Select which object container to use:
1480 Object_t &objects = (metadata ? m_inputMetaObjects : m_inputObjects);
1481
1482 // Look up the auxiliary object's manager:
1483 TVirtualManager *auxMgr = nullptr;
1484 std::string auxKey;
1485 if (isAuxStore) {
1486 auxMgr = &mgr;
1487 auxKey = key;
1488 } else {
1489 auto itr = objects.find(key + "Aux.");
1490 if (itr == objects.end()) {
1491 // Apparently there's no auxiliary object for this DV, so let's
1492 // give up:
1493 return StatusCode::SUCCESS;
1494 }
1495 auxMgr = itr->second.get();
1496 auxKey = key + "Aux.";
1497 }
1498
1499 if (metadata == false) {
1500 // Make sure the auxiliary object is up to date:
1501 const ::Int_t readBytes = auxMgr->getEntry();
1502 if (readBytes < 0) {
1504 "Couldn't load current entry for auxiliary object with key \""
1505 << auxKey << "\"");
1506 return StatusCode::FAILURE;
1507 }
1508
1509 // Check if there is a separate auxiliary object for the dynamic
1510 // variables:
1511 const std::string dynAuxKey = auxKey + "Dynamic";
1512 auto dynAuxMgr = objects.find(dynAuxKey);
1513
1514 if ((dynAuxMgr != objects.end()) &&
1515 (readBytes || (m_auxMode == kAthenaAccess) || (auxMgr == &mgr))) {
1516 // Do different things based on the access mode:
1517 if (m_auxMode != kAthenaAccess) {
1518 // In "normal" access modes just tell the dynamic store object
1519 // to switch to a new event.
1520 dynAuxMgr->second->getEntry();
1521 } else {
1522 // In "Athena mode" this object has already been deleted when
1523 // the main auxiliary store object was switched to the new
1524 // event. So let's re-create it:
1525 xAOD::TObjectManager &auxMgrRef =
1526 dynamic_cast<xAOD::TObjectManager &>(*auxMgr);
1527 ATH_CHECK(
1528 setUpDynamicStore(auxMgrRef, (metadata ? m_inMetaTree : m_inTree)));
1529 // Now tell the newly created dynamic store object which event
1530 // it should be looking at:
1531 auto dynAuxMgr = objects.find(dynAuxKey);
1532 if (dynAuxMgr == objects.end()) {
1533 ATH_MSG_ERROR("Internal logic error detected");
1534 return StatusCode::FAILURE;
1535 }
1536 dynAuxMgr->second->getEntry();
1537 }
1538 }
1539 }
1540
1541 // Stop here if we've set up an auxiliary store.
1542 if (isAuxStore) {
1543 return StatusCode::SUCCESS;
1544 }
1545
1546 // Access the auxiliary base class of the object/vector:
1548 SG::AuxElement *aux = 0;
1549 switch (mgr.holder()->typeKind()) {
1550 case THolder::DATAVECTOR: {
1551 void *vvec = mgr.holder()->getAs(typeid(SG::AuxVectorBase));
1552 vec = reinterpret_cast<SG::AuxVectorBase *>(vvec);
1553 } break;
1554 case THolder::AUXELEMENT: {
1555 void *vaux = mgr.holder()->getAs(typeid(SG::AuxElement));
1556 aux = reinterpret_cast<SG::AuxElement *>(vaux);
1557 } break;
1558 default:
1559 break;
1560 }
1561
1562 // Check whether index tracking is enabled for the type. If not, then
1563 // we need to fix it...
1564 if (vec && (!vec->trackIndices())) {
1565 Details::forceTrackIndices(*vec);
1566 }
1567
1568 // Check if we were successful:
1569 if ((!vec) && (!aux)) {
1570 ATH_MSG_FATAL("Couldn't access class \""
1571 << mgr.holder()->getClass()->GetName()
1572 << "\" as SG::AuxVectorBase or SG::AuxElement");
1573 return StatusCode::FAILURE;
1574 }
1575
1576 // Get the auxiliary store object:
1577 const SG::IConstAuxStore *store = 0;
1578 if (m_auxMode == kBranchAccess) {
1579 // Get the concrete auxiliary manager:
1580 TAuxManager *amgr = dynamic_cast<TAuxManager *>(auxMgr);
1581 if (!amgr) {
1582 ATH_MSG_FATAL("Auxiliary manager for \""
1583 << auxKey << "\" is not of the right type");
1584 return StatusCode::FAILURE;
1585 }
1586 store = amgr->getConstStore();
1587 // If the store still doesn't know its type, help it now:
1588 if (amgr->getStore()->structMode() ==
1590 const TAuxStore::EStructMode mode =
1593 amgr->getStore()->setStructMode(mode);
1594 }
1595 } else if (m_auxMode == kClassAccess || m_auxMode == kAthenaAccess) {
1596 // Get the concrete auxiliary manager:
1597 TObjectManager *omgr = dynamic_cast<TObjectManager *>(auxMgr);
1598 if (!omgr) {
1599 ATH_MSG_FATAL("Auxiliary manager for \""
1600 << auxKey << "\" is not of the right type");
1601 return StatusCode::FAILURE;
1602 }
1603 void *p = omgr->holder()->getAs(typeid(SG::IConstAuxStore));
1604 store = reinterpret_cast<const SG::IConstAuxStore *>(p);
1605 }
1606 if (!store) {
1607 ATH_MSG_FATAL("Logic error detected in the code");
1608 return StatusCode::FAILURE;
1609 }
1610
1611 // Connect the two:
1612 if (vec) {
1613 vec->setStore(store);
1614 } else if (aux) {
1615 aux->setStore(store);
1616 } else {
1617 ATH_MSG_FATAL("Logic error detected in the code");
1618 return StatusCode::FAILURE;
1619 }
1620
1621 // We succeeded:
1622 return StatusCode::SUCCESS;
1623}
1624
1640StatusCode TEvent::record(void *obj, const std::string &typeName,
1641 const std::string &key, bool overwrite, bool metadata,
1642 bool isOwner) {
1643
1644 // Check if we have an output tree when writing an event:
1645 if (!m_outTree && !metadata) {
1647 "No output tree defined. Did you forget to call writeTo(...)?");
1648 return StatusCode::FAILURE;
1649 }
1650 assert(m_outputEventFormat != 0);
1651
1652 // If this is metadata, just take ownership of it. The object will only
1653 // be recorded into the output file when calling finishWritingTo(...).
1654 if (metadata) {
1655 // Check whether we already have such an object:
1656 if ((!overwrite) &&
1657 (m_outputMetaObjects.find(key) != m_outputMetaObjects.end())) {
1658 ATH_MSG_ERROR("Meta-object \"" << typeName << "\"/\"" << key
1659 << "\" already recorded");
1660 return StatusCode::FAILURE;
1661 }
1662 // Check if we have a dictionary for this object:
1663 TClass *cl = TClass::GetClass(typeName.c_str());
1664 if (!cl) {
1665 ATH_MSG_ERROR("Didn't find dictionary for type: " << typeName);
1666 return StatusCode::FAILURE;
1667 }
1668 // Let's create a holder for the object:
1669 const bool renewOnRead = (m_auxMode == kAthenaAccess);
1670 m_outputMetaObjects[key] = std::make_unique<TObjectManager>(
1671 nullptr, std::make_unique<THolder>(obj, cl, isOwner), renewOnRead);
1672 // We're done. The rest will be done later on.
1673 return StatusCode::SUCCESS;
1674 }
1675
1676 // Check if we accessed this object on the input. If yes, then this
1677 // key may not be used for recording.
1678 if ((!overwrite) && (m_inputObjects.find(key) != m_inputObjects.end())) {
1679 ATH_MSG_ERROR("Object \"" << typeName << "\"/\"" << key
1680 << "\" already accessed from the input, can't be "
1681 "overwritten in memory");
1682 return StatusCode::FAILURE;
1683 }
1684
1685 // Choose a split level.
1686 const Int_t splitLevel = (key.ends_with("Aux.") ? 1 : 0);
1687
1688 // Check if we need to add it to the event record:
1689 Object_t::iterator vitr = m_outputObjects.find(key);
1690 if (vitr == m_outputObjects.end()) {
1691
1692 // Check if we have a dictionary for this object:
1693 TClass *cl = TClass::GetClass(typeName.c_str());
1694 if (cl == nullptr) {
1695 ATH_MSG_ERROR("Didn't find dictionary for type: " << typeName);
1696 return StatusCode::FAILURE;
1697 }
1698
1699 // Check if this is a new object "type" or not.
1700 if (!m_outputEventFormat->exists(key)) {
1702 EventFormatElement(key, cl->GetName(), "", getHash(key)));
1703 }
1704
1705 // Let's create a holder for the object.
1706 const bool renewOnRead = (m_auxMode == kAthenaAccess);
1707 auto mgr = std::make_unique<TObjectManager>(
1708 nullptr, std::make_unique<THolder>(obj, cl, isOwner), renewOnRead);
1709 TObjectManager *mgrPtr = mgr.get();
1710 m_outputObjects[key] = std::move(mgr);
1711
1712 // ... and let's add it to the output TTree.
1713 static constexpr Int_t basketSize = 32000;
1714 *(mgrPtr->branchPtr()) =
1715 m_outTree->Branch(key.c_str(), cl->GetName(),
1716 mgrPtr->holder()->getPtr(), basketSize, splitLevel);
1717 if (!mgrPtr->branch()) {
1718 ATH_MSG_ERROR("Failed to create branch \"" << key << "\" out of type \""
1719 << cl->GetName() << "\"");
1720 // Clean up:
1721 mgrPtr->holder()->setOwner(kFALSE);
1722 return StatusCode::FAILURE;
1723 }
1724
1725 // Set up the saving of all the dynamic auxiliary properties
1726 // of the object if it has any:
1727 static constexpr bool METADATA = false;
1728 ATH_CHECK(putAux(*m_outTree, *mgrPtr, METADATA));
1729
1730 // Return at this point, as we don't want to run the rest of
1731 // the function's code:
1732 return StatusCode::SUCCESS;
1733 }
1734
1735 // Access the object manager:
1736 TObjectManager *omgr = dynamic_cast<TObjectManager *>(vitr->second.get());
1737 if (!omgr) {
1738 ATH_MSG_ERROR("Manager object of the wrong type encountered");
1739 return StatusCode::FAILURE;
1740 }
1741
1742 // Check that the type of the object matches that of the previous
1743 // object:
1744 if (typeName != omgr->holder()->getClass()->GetName()) {
1745 // This may still be, when the ROOT dictionary name differs from the
1746 // "simple type name" known to C++. So let's get the ROOT name of the
1747 // new type:
1748 TClass *cl = TClass::GetClass(typeName.c_str());
1749 if ((!cl) ||
1750 ::strcmp(cl->GetName(), omgr->holder()->getClass()->GetName())) {
1751 ATH_MSG_ERROR("For output key \""
1752 << key << "\" the previous type was \""
1753 << omgr->holder()->getClass()->GetName()
1754 << "\", but the newly requested type is \"" << typeName
1755 << "\"");
1756 return StatusCode::FAILURE;
1757 }
1758 }
1759
1760 // Replace the managed object.
1761 omgr->setObject(obj);
1762
1763 // Replace the auxiliary objects.
1764 static constexpr bool METADATA = false;
1765 ATH_CHECK(putAux(*m_outTree, *omgr, METADATA));
1766
1767 // Return gracefully.
1768 return StatusCode::SUCCESS;
1769}
1770
1771StatusCode TEvent::recordAux(TVirtualManager &mgr, const std::string &key,
1772 bool metadata) {
1773
1774 // Check if the auxiliary store is a generic object.
1776 dynamic_cast<Details::IObjectManager *>(&mgr);
1777 if (iomgr != nullptr) {
1778 // Record the auxiliary object using the main record function.
1779 static const bool OVERWRITE = true;
1780 static const bool IS_OWNER = true;
1781 ATH_CHECK(record(iomgr->object(), iomgr->holder()->getClass()->GetName(),
1782 key, OVERWRITE, metadata, IS_OWNER));
1783 return StatusCode::SUCCESS;
1784 }
1785
1786 // Check if it's a TAuxStore object.
1787 TAuxManager *auxmgr = dynamic_cast<TAuxManager *>(&mgr);
1788 if (auxmgr != nullptr) {
1789 // This type has to be an event object.
1790 if (metadata) {
1792 "TAuxStore auxiliary objects can only be recorded for event data");
1793 return StatusCode::FAILURE;
1794 }
1795 // Record the auxiliary object with the dedicated record function.
1796 ATH_CHECK(recordAux(auxmgr->getStore(), key));
1797 return StatusCode::SUCCESS;
1798 }
1799
1800 // Apparently we didn't recorgnize the auxiliary store type.
1801 ATH_MSG_ERROR("Unknown auxiliary store manager type encountered");
1802 return StatusCode::FAILURE;
1803}
1804
1811StatusCode TEvent::initStats() {
1812
1813 // If we're dealing with an empty input file, stop here:
1814 if (m_inTreeMissing) {
1815 return StatusCode::SUCCESS;
1816 }
1817
1818 // A little sanity check:
1819 if (!m_inTree) {
1820 ATH_MSG_ERROR("Function called on an uninitialised object");
1821 return StatusCode::FAILURE;
1822 }
1823
1824 // Reset the number of input branches information:
1826
1827 // Loop over the EventFormat information
1830 for (; itr != end; ++itr) {
1831
1832 // Get the name of the branch in question:
1833 const std::string &branchName = itr->second.branchName();
1834
1835 // If it's an auxiliary container, scan it using TAuxStore:
1836 if (branchName.find("Aux.") != std::string::npos) {
1837
1838 // But first decide whether it describes a container, or just
1839 // a single object. Since the file may have been written in
1840 // kBranchAccess mode, it's not necessarily a good idea to check
1841 // the type of the auxiliary class. So let's check the interface
1842 // class instead.
1843 //
1844 // Get the name of the interface object/container:
1845 const std::string intName = branchName.substr(0, branchName.size() - 4);
1846 if (!m_inputEventFormat.exists(intName)) {
1847 // When this happens, it may still be that both the interface and
1848 // the auxiliary container is missing from the file. As we didn't
1849 // check yet whether the auxiliary container is in place or not.
1850 // So, before printing a warning, let's check for this.
1851 // Unfortunately the check is pretty expensive, but this should
1852 // not be performance critical code after all...
1853 ::Bool_t auxFound = kFALSE;
1854 const std::string dynName = Utils::dynBranchPrefix(branchName);
1855
1856 std::vector<TObjArray *> fullListOfBranches = {};
1857 // Add the list of branches of the main tree
1858 fullListOfBranches.push_back(m_inTree->GetListOfBranches());
1859 // If input tree has friend trees
1860 // add as well the list of friend tree branches
1861 if (m_inTree->GetListOfFriends()) {
1862 // Get the list of friends
1863 TList *fList = m_inTree->GetListOfFriends();
1864 // Loop over friend elements
1865 for (TObject *feObj : *fList) {
1866 if (feObj) {
1867 // Get corresponding friend tree
1868 auto *pElement = dynamic_cast<TFriendElement *>(feObj);
1869 if (not pElement)
1870 continue;
1871 TTree *friendTree = pElement->GetTree();
1872 // Add list of branches of the friend tree
1873 fullListOfBranches.push_back(friendTree->GetListOfBranches());
1874 }
1875 }
1876 }
1877
1878 for (TObjArray *branches : fullListOfBranches) {
1879 for (Int_t i = 0; i < branches->GetEntriesFast(); ++i) {
1880 if (!branches->At(i))
1881 continue;
1882
1883 const TString name(branches->At(i)->GetName());
1884 if (name.BeginsWith(branchName) || name.BeginsWith(dynName)) {
1885 auxFound = kTRUE;
1886 break;
1887 }
1888 }
1889 }
1890 if (auxFound) {
1891 ATH_MSG_WARNING("Couldn't find interface object/container \""
1892 << intName << "\" belonging to branch \""
1893 << branchName << "\"");
1894 }
1895 continue;
1896 }
1897
1898 // Get the type of the interface:
1899 const EventFormatElement *el = m_inputEventFormat.get(intName);
1900 ::TClass *cl = ::TClass::GetClass(el->className().c_str());
1901 if ((!cl) || (!cl->IsLoaded())) {
1902 ATH_MSG_WARNING("Couldn't find dictionary for type \""
1903 << el->className() << "\"");
1904 continue;
1905 }
1906
1907 // Get the dictionary for the DataVector base class:
1908 static const std::type_info &baseTi = typeid(SG::AuxVectorBase);
1909 static const std::string baseName = SG::normalizedTypeinfoName(baseTi);
1910 static ::TClass *const baseCl = ::TClass::GetClass(baseName.c_str());
1911 if (!baseCl) {
1912 ATH_MSG_ERROR("Couldn't get dictionary for type \"" << baseName
1913 << "\"");
1914 return StatusCode::FAILURE;
1915 }
1916
1917 // The type of the auxiliary store is finally deduced from the
1918 // inheritance of the interface container.
1919 const TAuxStore::EStructMode mode =
1920 (cl->InheritsFrom(baseCl) ? TAuxStore::EStructMode::kContainerStore
1922
1923 // Scan the branches using a temporary TAuxStore instance:
1924 static constexpr bool TOP_STORE = true;
1925 TAuxStore temp(branchName, TOP_STORE, mode);
1926 static constexpr bool PRINT_WARNINGS = false;
1927 ATH_CHECK(temp.readFrom(*m_inTree, PRINT_WARNINGS));
1928
1929 // Conveninence variable:
1930 ReadStats &stats = IOStats::instance().stats();
1931
1932 // Teach the cache about all the branches:
1933 for (SG::auxid_t id : temp.getAuxIDs()) {
1934 stats.branch(branchName, id);
1935 }
1936
1937 // Increment the number of known branches:
1938 stats.setBranchNum(stats.branchNum() + temp.getAuxIDs().size());
1939 }
1940 // If it's an interface container:
1941 else {
1942 // Try to access the branch:
1943 const ::TBranch *container = m_inTree->GetBranch(branchName.c_str());
1944 // If it exists, let's remember it:
1945 if (container) {
1946 IOStats::instance().stats().container(branchName);
1947 }
1948 }
1949 }
1950
1951 // Return gracefully:
1952 return StatusCode::SUCCESS;
1953}
1954
1967StatusCode TEvent::record(std::unique_ptr<TAuxStore> store,
1968 const std::string &key) {
1969
1970 // Check if we have an output tree:
1971 if (!m_outTree) {
1973 "No output tree defined. Did you forget to call writeTo(...)?");
1974 return StatusCode::FAILURE;
1975 }
1976
1977 // Check if we have a filtering rule for this key:
1978 const std::set<std::string> *filter = 0;
1979 auto filter_itr = m_auxItemList.find(key);
1980 if (filter_itr != m_auxItemList.end()) {
1981 filter = &(filter_itr->second);
1982 }
1983
1984 // Check if we need to add it to the event record:
1985 Object_t::iterator vitr = m_outputObjects.find(key);
1986 if (vitr == m_outputObjects.end()) {
1987
1988 // Configure the object for variable filtering:
1989 if (filter) {
1990 store->selectAux(*filter);
1991 }
1992 // Tell the object where to write its contents:
1993 ATH_CHECK(store->writeTo(*m_outTree));
1994 // Record it to the output list:
1995 static constexpr bool OWNS_STORE = true;
1996 m_outputObjects[key] =
1997 std::make_unique<TAuxManager>(store.release(), OWNS_STORE);
1998
1999 // We're done:
2000 return StatusCode::SUCCESS;
2001 }
2002
2003 // Check if the output has the right store:
2004 if (vitr->second->object() == store.get()) {
2005 // We're done already:
2006 return StatusCode::SUCCESS;
2007 }
2008
2009 // If not, update the output manager. This can happen when we copy
2010 // objects from the input to the output files, and we process
2011 // multiple input files.
2012
2013 // Check if the output manager is of the right type:
2014 TAuxManager *mgr = dynamic_cast<TAuxManager *>(vitr->second.get());
2015 if (mgr == nullptr) {
2016 ATH_MSG_ERROR("Output object with key \""
2017 << key << "\" already exists, and is not of type TAuxStore");
2018 return StatusCode::FAILURE;
2019 }
2020
2021 // Configure the object for variable filtering:
2022 if (filter) {
2023 store->selectAux(*filter);
2024 }
2025
2026 // Connect the auxiliary store to the output tree:
2027 ATH_CHECK(store->writeTo(*m_outTree));
2028
2029 // Update the manager:
2030 mgr->setObject(store.release());
2031
2032 // Return gracefully:
2033 return StatusCode::SUCCESS;
2034}
2035
2045
2046 // Check if we can call setName(...) on the object:
2047 ::TMethodCall setNameCall;
2048 // Don't use this code in Athena access mode. And just accept that access
2049 // monitoring is disabled in this case...
2050 if (m_auxMode != kAthenaAccess) {
2051 setNameCall.InitWithPrototype(mgr.holder()->getClass(), "setName",
2052 "const char*");
2053 if (setNameCall.IsValid()) {
2054 // Yes, there is such a function. Let's call it with the branch
2055 // name:
2056 const ::TString params =
2057 ::TString::Format("\"%s\"", mgr.branch()->GetName());
2058 const char *charParams = params.Data();
2059 setNameCall.Execute(mgr.holder()->get(), charParams);
2060 } else {
2061 // This is weird. What sort of auxiliary container is this? :-/
2062 ATH_MSG_WARNING("Couldn't find setName(...) function for container \""
2063 << mgr.branch()->GetName() << "\" (type: "
2064 << mgr.holder()->getClass()->GetName() << ")");
2065 }
2066 }
2067
2068 // Check if we can switch out the internal store of this object:
2069 static const TClass *const holderClass =
2070 TClass::GetClass(typeid(SG::IAuxStoreHolder));
2071 if (!mgr.holder()->getClass()->InheritsFrom(holderClass)) {
2072 // Nope... So let's just end the journey here.
2073 return StatusCode::SUCCESS;
2074 }
2075
2076 // Try to get the object as an IAuxStoreHolder:
2077 SG::IAuxStoreHolder *storeHolder = reinterpret_cast<SG::IAuxStoreHolder *>(
2078 mgr.holder()->getAs(typeid(SG::IAuxStoreHolder)));
2079 if (!storeHolder) {
2080 ATH_MSG_FATAL("There's a logic error in the code");
2081 return StatusCode::FAILURE;
2082 }
2083
2084 // Create a TAuxStore instance that will read the dynamic variables
2085 // of this container. Notice that the TAuxManager doesn't own the
2086 // TAuxStore object. It will be owned by the SG::IAuxStoreHolder
2087 // object.
2088 static constexpr bool TOP_STORE = false;
2089 auto store = std::make_unique<TAuxStore>(
2090 mgr.branch()->GetName(), TOP_STORE,
2094 // This object is used to read data from the input, it needs to be
2095 // locked:
2096 store->lock();
2097
2098 // Set it up to read from the input RNTuple.
2099 ATH_CHECK(store->readFrom(*tree));
2100
2101 // Set it up to read from the input TTree.
2102 ATH_CHECK(store->readFrom(*tree));
2103 // Tell the auxiliary store which entry to use. This is essential for
2104 // metadata objects, and non-important for event data objects, which will
2105 // get a possibly different entry loaded in setAuxStore(...).
2106 store->getEntry(0);
2107
2108 // Set up a manager for it.
2109 static constexpr bool SHARED_OWNER = false;
2110 m_inputObjects[std::string(mgr.branch()->GetName()) + "Dynamic"] =
2111 std::make_unique<TAuxManager>(store.get(), SHARED_OWNER);
2112
2113 // Give this object to the store holder:
2114 storeHolder->setStore(store.release());
2115
2116 // Return gracefully:
2117 return StatusCode::SUCCESS;
2118}
2119
2130StatusCode TEvent::putAux(::TTree &outTree, TVirtualManager &vmgr,
2131 bool metadata) {
2132
2133 // A little sanity check:
2134 assert(m_outputEventFormat != 0);
2135
2136 // Do the conversion:
2137 TObjectManager *mgr = dynamic_cast<TObjectManager *>(&vmgr);
2138 if (!mgr) {
2139 // It's not an error any more when we don't get a TObjectManager.
2140 return StatusCode::SUCCESS;
2141 }
2142
2143 // Check if we need to do anything here:
2144 if (!mgr->holder()->getClass()->InheritsFrom("SG::IAuxStoreIO")) {
2145 return StatusCode::SUCCESS;
2146 }
2147
2148 // Get a pointer to the auxiliary store I/O interface:
2149 SG::IAuxStoreIO *aux = reinterpret_cast<SG::IAuxStoreIO *>(
2150 mgr->holder()->getAs(typeid(SG::IAuxStoreIO)));
2151 if (!aux) {
2152 ATH_MSG_FATAL("There is a logic error in the code!");
2153 return StatusCode::FAILURE;
2154 }
2155
2156 // Check if we have rules defined for which auxiliary properties
2157 // to write out:
2159 if (!metadata) {
2160 auto item_itr = m_auxItemList.find(mgr->branch()->GetName());
2161 if (item_itr != m_auxItemList.end()) {
2162 sel.selectAux(item_itr->second);
2163 }
2164 }
2165
2166 // Get the dynamic auxiliary variables held by this object, which
2167 // were selected to be written:
2168 const SG::auxid_set_t auxids =
2169 sel.getSelectedAuxIDs(aux->getSelectedAuxIDs());
2170
2171 // If there are no dynamic auxiliary variables in the object, return
2172 // right away:
2173 if (auxids.empty()) {
2174 return StatusCode::SUCCESS;
2175 }
2176
2177 // Decide what should be the prefix of all the dynamic branches:
2178 const std::string dynNamePrefix =
2179 Utils::dynBranchPrefix(mgr->branch()->GetName());
2180
2181 // Select which container to add the variables to:
2182 Object_t &objects = (metadata ? m_outputMetaObjects : m_outputObjects);
2183
2184 // This iteration will determine the ordering of branches within
2185 // the tree, so sort auxids by name.
2187 typedef std::pair<std::string, SG::auxid_t> AuxVarSort_t;
2188 std::vector<AuxVarSort_t> varsort;
2189 varsort.reserve(auxids.size());
2190 for (SG::auxid_t id : auxids) {
2191 varsort.emplace_back(r.getName(id), id);
2192 }
2193 std::sort(varsort.begin(), varsort.end());
2194
2195 // Extract all the dynamic variables from the object:
2196 for (const auto &p : varsort) {
2197
2198 // The auxiliary ID:
2199 const SG::auxid_t id = p.second;
2200
2201 // Construct a name for the branch that we will write:
2202 const std::string brName = dynNamePrefix + p.first;
2203
2204 // Try to find the branch:
2205 Object_t::iterator bmgr = objects.find(brName);
2206
2207 // Check if we already know about this variable:
2208 if (bmgr == objects.end()) {
2209
2210 // Construct the full type name of the variable:
2211 const std::type_info *brType = aux->getIOType(id);
2212 if (!brType) {
2213 ATH_MSG_ERROR("No I/O type found for variable " << brName);
2214 return StatusCode::FAILURE;
2215 }
2216 const std::string brTypeName = Utils::getTypeName(*brType);
2217 std::string brProperTypeName = "<unknown>";
2218
2219 // The branch that will hopefully be created:
2220 ::TBranch *br = 0;
2221
2222 // Check if it's a primitive type or not:
2223 if (strlen(brType->name()) == 1) {
2224
2225 // Making the "proper" type name is simple in this case:
2226 brProperTypeName = brTypeName;
2227
2228 // Get the character describing this type for ROOT:
2229 const char rootType = Utils::rootType(brType->name()[0]);
2230 if (rootType == '\0') {
2231 ATH_MSG_ERROR("Type not known for variable \""
2232 << brName << "\" of type \"" << brTypeName << "\"");
2233 return StatusCode::FAILURE;
2234 }
2235
2236 // Create the full description of the variable for ROOT:
2237 std::ostringstream leaflist;
2238 leaflist << brName << "/" << rootType;
2239
2240 // Let's create a holder for this property:
2241 static constexpr bool IS_OWNER = false;
2242 auto auxmgr = std::make_unique<TPrimitiveAuxBranchManager>(
2243 id, nullptr, new THolder(aux->getIOData(id), nullptr, IS_OWNER));
2244
2245 // ... and let's add it to the output TTree:
2246 static constexpr Int_t BASKET_SIZE = 32000;
2247 *(auxmgr->branchPtr()) =
2248 outTree.Branch(brName.c_str(), auxmgr->holder()->get(),
2249 leaflist.str().c_str(), BASKET_SIZE);
2250 if (!auxmgr->branch()) {
2251 ATH_MSG_ERROR("Failed to create branch \""
2252 << brName << "\" out of type \"" << brProperTypeName
2253 << "\"");
2254 // Clean up:
2255 *(auxmgr->holder()->getPtr()) = 0;
2256 return StatusCode::FAILURE;
2257 }
2258 br = auxmgr->branch();
2259
2260 // Store it in the output list.
2261 objects[brName] = std::move(auxmgr);
2262
2263 } else {
2264
2265 // Check if we have a dictionary for this type:
2266 static constexpr Bool_t LOAD_IF_NOT_FOUND = kTRUE;
2267 static constexpr Bool_t SILENT = kTRUE;
2268 TClass *cl = TClass::GetClass(*brType, LOAD_IF_NOT_FOUND, SILENT);
2269 if (cl == nullptr) {
2270 // The dictionary needs to be loaded now. This could be an
2271 // issue. But let's hope for the best...
2272 cl = TClass::GetClass(brTypeName.c_str());
2273 // If still not found...
2274 if (cl == nullptr) {
2275 ATH_MSG_ERROR("Dictionary not available for variable \""
2276 << brName << "\" of type \"" << brTypeName << "\"");
2277 return StatusCode::FAILURE;
2278 }
2279 }
2280
2281 // The proper type name comes from the dictionary in this case:
2282 brProperTypeName = cl->GetName();
2283
2284 // Let's create a holder for this property:
2285 static constexpr bool IS_OWNER = false;
2286 auto auxmgr = std::make_unique<TAuxBranchManager>(
2287 id, nullptr, new THolder(aux->getIOData(id), cl, IS_OWNER));
2288
2289 // ... and let's add it to the output TTree.
2290 static constexpr Int_t BASKET_SIZE = 32000;
2291 static constexpr Int_t SPLIT_LEVEL = 0;
2292 *(auxmgr->branchPtr()) = outTree.Branch(brName.c_str(), cl->GetName(),
2293 auxmgr->holder()->getPtr(),
2294 BASKET_SIZE, SPLIT_LEVEL);
2295 if (!auxmgr->branch()) {
2296 ATH_MSG_ERROR("Failed to create branch \""
2297 << brName << "\" out of type \"" << brProperTypeName
2298 << "\"");
2299 // Clean up:
2300 *(auxmgr->holder()->getPtr()) = 0;
2301 return StatusCode::FAILURE;
2302 }
2303 br = auxmgr->branch();
2304
2305 // Store it in the output list.
2306 objects[brName] = std::move(auxmgr);
2307 }
2308
2309 // If this is not the first event, fill up the already filled
2310 // events with (empty) content:
2311 if (outTree.GetEntries()) {
2312 void *ptr = br->GetAddress();
2313 br->SetAddress(0);
2314 for (::Long64_t i = 0; i < outTree.GetEntries(); ++i) {
2315 br->Fill();
2316 }
2317 br->SetAddress(ptr);
2318 }
2319
2320 // If all went fine, let's add this branch to the event format
2321 // metadata:
2322 if (!m_outputEventFormat->exists(brName)) {
2323 m_outputEventFormat->add(EventFormatElement(brName, brProperTypeName,
2324 mgr->branch()->GetName(),
2325 getHash(brName)));
2326 }
2327
2328 // We don't need to do the rest:
2329 continue;
2330 }
2331
2332 // Access the object manager:
2333 bmgr = objects.find(brName);
2334 if (bmgr == objects.end()) {
2335 ATH_MSG_FATAL("There is an internal logic error in the code...");
2336 return StatusCode::FAILURE;
2337 }
2338
2339 // Replace the managed object:
2340 void *nc_data ATLAS_THREAD_SAFE = // we hold non-const pointers but check
2341 // on retrieve
2342 const_cast<void *>(static_cast<const void *>(aux->getIOData(id)));
2343 bmgr->second->setObject(nc_data);
2344 }
2345
2346 // Return gracefully:
2347 return StatusCode::SUCCESS;
2348}
2349
2350StatusCode TEvent::recordAux(TAuxStore *store, const std::string &key) {
2351
2352 // Check if we have an output tree:
2353 if (hasOutput() == false) {
2354 ATH_MSG_ERROR("No output tree set up.");
2355 return StatusCode::FAILURE;
2356 }
2357
2358 // Check if we have a filtering rule for this key:
2359 const std::set<std::string> *filter = 0;
2360 auto filter_itr = m_auxItemList.find(key);
2361 if (filter_itr != m_auxItemList.end()) {
2362 filter = &(filter_itr->second);
2363 }
2364
2365 // Check if we need to add it to the event record:
2366 Object_t::iterator vitr = m_outputObjects.find(key);
2367 if (vitr == m_outputObjects.end()) {
2368
2369 // Configure the object for variable filtering:
2370 if (filter) {
2371 store->selectAux(*filter);
2372 }
2373 // Tell the object where to write its contents:
2374 ATH_CHECK(store->writeTo(*m_outTree));
2375 // Record it to the output list.
2376 static constexpr bool OWNS_STORE = false;
2377 m_outputObjects[key] = std::make_unique<TAuxManager>(store, OWNS_STORE);
2378
2379 // We're done:
2380 return StatusCode::SUCCESS;
2381 }
2382
2383 // Check if the output has the right store:
2384 if (vitr->second->object() == store) {
2385 // We're done already:
2386 return StatusCode::SUCCESS;
2387 }
2388
2389 // If not, update the output manager. This can happen when we copy
2390 // objects from the input to the output files, and we process
2391 // multiple input files.
2392
2393 // Check if the output manager is of the right type:
2394 TAuxManager *mgr = dynamic_cast<TAuxManager *>(vitr->second.get());
2395 if (mgr == nullptr) {
2396 ATH_MSG_ERROR("Output object with key \""
2397 << key << "\" already exists, and is not of type TAuxStore");
2398 return StatusCode::FAILURE;
2399 }
2400
2401 // Configure the object for variable filtering:
2402 if (filter) {
2403 store->selectAux(*filter);
2404 }
2405
2406 // Connect the auxiliary store to the output tree:
2407 ATH_CHECK(store->writeTo(*m_outTree));
2408
2409 // Update the manager:
2410 mgr->setObject(store);
2411
2412 // Return gracefully:
2413 return StatusCode::SUCCESS;
2414}
2415
2416} // namespace xAOD
#define ATH_CHECK
Evaluate an expression and check for errors.
#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)
Base class for elements of a container that can have aux data.
Handle mappings between names and auxid_t.
Manage index tracking and synchronization of auxiliary data.
std::vector< size_t > vec
#define XAOD_MESSAGE(MESSAGE)
Simple macro for printing error/verbose messages.
Recursively separate out template arguments in a C++ class name.
Interface providing I/O for a generic auxiliary store.
static Double_t sc
Hold a pointer to the current event store.
void upgrade()
Convert the lock from upgrade to exclusive.
Exception to signal a malformed class name.
bit_t size() const
Count the number of 1 bits in the set.
bool empty() const
Return true if there are no 1 bits in the set.
Base class for elements of a container that can have aux data.
Definition AuxElement.h:483
Handle mappings between names and auxid_t.
static AuxTypeRegistry & instance()
Return the singleton registry instance.
Manage index tracking and synchronization of auxiliary data.
Interface for objects taking part in direct ROOT I/O.
AuxStoreType
Type of the auxiliary store.
@ AST_ContainerStore
The store describes a container.
@ AST_ObjectStore
The store describes a single object.
virtual AuxStoreType getStoreType() const =0
Return the type of the store object.
virtual void setStore(IAuxStore *store)=0
Give an auxiliary store object to the holder object.
Interface providing I/O for a generic auxiliary store.
Definition IAuxStoreIO.h:44
Interface for non-const operations on an auxiliary store.
Definition IAuxStore.h:48
Interface for const operations on an auxiliary store.
A set of aux data identifiers.
Definition AuxTypes.h:47
Class helping in dealing with dynamic branch selection.
Manager for EDM objects created by ROOT.
const THolder * holder() const
Accessor to the Holder object.
Class describing one branch of the ROOT file.
KeyedData_t::const_iterator const_iterator
Iterator for looping over the elements of the object.
EventFormat m_inputEventFormat
Format of the current input file.
Definition Event.h:321
const std::string & name() const override
Get the name of the instance.
std::set< std::string > m_inputMissingObjects
Objects that have been asked for, but were found to be missing in the current input.
Definition Event.h:311
const void * getInputObject(SG::sgkey_t key, const std::type_info &ti, bool silent) override
Function for retrieving an input object in a non-template way.
upgrade_mutex_t m_branchesMutex
Mutex for multithread synchronization.
Definition Event.h:354
AthContainers_detail::upgrading_lock< upgrade_mutex_t > upgrading_lock_t
Lock type for multithread synchronization.
Definition Event.h:351
Object_t m_inputObjects
Collection of all the managed input objects.
Definition Event.h:308
Event(std::string_view name)
Constructor with a name.
Definition EventCore.cxx:27
std::unordered_map< std::string, std::unique_ptr< TVirtualManager > > Object_t
Definition of the internal data structure type.
Definition Event.h:304
StatusCode keys(std::vector< std::string > &vkeys, bool metadata) const
Provide a list of all data object keys associated with a specific type.
void setActive() const
Set this event object as the currently active one.
Definition EventCore.cxx:54
SG::sgkey_t getHash(const std::string &key) const override
Function returning the hash describing an object name.
Object_t m_inputMetaObjects
Collection of all the managed input meta-objects.
Definition Event.h:316
std::unordered_map< std::string, std::set< std::string > > m_auxItemList
Rules for selecting which auxiliary branches to write.
Definition Event.h:326
EventFormat * m_outputEventFormat
Format of the current output file.
Definition Event.h:323
Object_t m_outputObjects
Collection of all the managed output object.
Definition Event.h:313
SG::SGKeyMap< BranchInfo > m_branches ATLAS_THREAD_SAFE
Map from hashed sgkey to BranchInfo.
Definition Event.h:358
std::vector< TVirtualIncidentListener * > m_listeners
Listeners who should be notified when certain incidents happen.
Definition Event.h:329
Object_t m_outputMetaObjects
Collection of all the managed output meta-objects.
Definition Event.h:318
ReadStats & stats()
Access the object belonging to the current thread.
Definition IOStats.cxx:17
static IOStats & instance()
Singleton object accessor.
Definition IOStats.cxx:11
Class describing the access statistics of a collection of branches.
Definition ReadStats.h:123
void nextEvent()
Function incrementing the processed event counter.
BranchStats * container(const std::string &name)
Access the description of a container. Creating it if necessary.
void setBranchNum(::Int_t num)
Set the total number of branches on the input.
void readContainer(const std::string &name)
Function incrementing the read counter on a specific container.
Manager for TAuxStore objects.
Definition TAuxManager.h:33
TAuxStore * getStore()
Get a type-specific pointer to the managed object.
const SG::IConstAuxStore * getConstStore() const
Get a convenience pointer to the managed object.
"ROOT @c TTree implementation" of IAuxStore
Definition TAuxStore.h:30
Helper class for making sure the current directory is preserved.
static const TEventFormatRegistry & instance()
Access the only instance of the object in memory.
EventFormat & getEventFormat(const TFile *file) const
Access the managed EventFormat object.
@ kAthenaAccess
Access containers/objects like Athena does.
@ kClassAccess
Access auxiliary data using the aux containers.
@ kBranchAccess
Access auxiliary data branch-by-branch.
::TTree * m_inMetaTree
Pointer to the metadata tree in the input file.
StatusCode connectObject(const std::string &key, bool silent) override
Function setting up access to a particular object.
StatusCode connectMetaAux(const std::string &prefix, bool standalone) override
Function setting up access to a set of auxiliary branches for a metadata object.
StatusCode connectAux(const std::string &prefix, bool standalone) override
Function setting up access to a set of auxiliary branches.
StatusCode writeTo(::TFile *file, int autoFlush=200, std::string_view treeName=EVENT_TREE_NAME)
Connect the object to an output file.
bool hasOutput() const override
Check if an output file is connected to the object.
std::unique_ptr< TChainStateTracker > m_inChainTracker
Optional object for tracking the state changes of an input TChain.
::Long64_t getEntries() const
Get how many entries are available from the current input file(s)
StatusCode finishWritingTo(::TFile *file)
Finish writing to an output file.
::Int_t fill()
Function filling one event into the output tree.
StatusCode setAuxStore(const std::string &key, Details::IObjectManager &mgr, bool metadata) override
Function connecting a DV object to its auxiliary store.
EAuxMode auxMode() const
Get what auxiliary access mode the object was constructed with.
bool hasInput() const override
Check if an input file is connected to the object.
StatusCode initStats()
Function to initialise the statistics for all Tree content.
::Long64_t m_entry
The entry to look at from the input tree.
::Long64_t getFiles() const
Get how many files are available on the currently defined input.
void setOtherMetaDataTreeNamePattern(const std::string &pattern)
Change the pattern used for collecting information from other MetaData trees NB: Additional MetaData ...
StatusCode getNames(const std::string &targetClassName, std::vector< std::string > &vkeys, bool metadata) const override
Function determining the list keys associated with a type name.
StatusCode setUpDynamicStore(TObjectManager &mgr, ::TTree *tree)
Function adding dynamic variable reading capabilities to an auxiliary store object.
::TChain * m_inChain
The (optional) chain provided as input.
StatusCode readFrom(::TFile *file, bool useTreeCache=true, std::string_view treeName=EVENT_TREE_NAME)
Connect the object to a new input file.
StatusCode putAux(::TTree &outTree, TVirtualManager &mgr, bool metadata)
Function saving the dynamically created auxiliary properties.
EAuxMode m_auxMode
The auxiliary access mode.
TEvent(EAuxMode mode=kClassAccess)
Default constructor.
::Int_t getEntry(::Long64_t entry, ::Int_t getall=0)
Function loading a given entry of the input TTree.
SG::IAuxStore * recordAux(const std::string &key, SG::IAuxStoreHolder::AuxStoreType type=SG::IAuxStoreHolder::AST_ContainerStore)
Add an auxiliary store object to the output.
StatusCode record(void *obj, const std::string &typeName, const std::string &key, bool overwrite, bool metadata, bool isOwner) override
Record an object into a connected output file.
std::unique_ptr<::TTree > m_outTree
The tree that we are writing to.
bool m_inTreeMissing
Internal status flag showing that an input file is open, but it doesn't contain an event tree.
::Int_t m_inTreeNumber
The number of the currently open tree in the input chain.
::Int_t getFile(::Long64_t file, ::Int_t getall=0)
Load the first event for a given file from the input TChain.
static const char *const EVENT_TREE_NAME
Default name of the event tree.
::TTree * m_inTree
The main tree that we are reading from.
StatusCode connectMetaObject(const std::string &key, bool silent) override
Function setting up access to a particular metadata object.
Helper class keeping track of the files that got accessed.
This class takes care of holding EDM objects in memory.
Definition THolder.h:35
void setOwner(::Bool_t state=kTRUE)
Set whether the holder should own its object.
Definition THolder.cxx:258
void ** getPtr()
Return a typeless pointer to the held object's pointer.
Definition THolder.cxx:226
const ::TClass * getClass() const
Definition THolder.cxx:402
virtual void * getAs(const std::type_info &tid, ::Bool_t silent=kFALSE) const
Return the object as a specific pointer.
Definition THolder.cxx:371
@ DATAVECTOR
A DataVector container.
Definition THolder.h:105
@ AUXELEMENT
A type inheriting from SG::AuxElement.
Definition THolder.h:106
Class describing a certain "incident" that is communicated to user code.
Definition TIncident.h:58
Manager for EDM objects created by ROOT.
::TBranch ** branchPtr()
Pointer to the branch's pointer.
virtual void setObject(void *obj) override
Function replacing the object being handled.
virtual::Int_t getEntry(::Int_t getall=0) override
Function for updating the object in memory if needed.
::TBranch * branch()
Accessor to the branch.
Class providing an interface for classes listening to xAOD incidents.
Interface class for the "manager classes".
virtual const void * object() const =0
Function getting a const pointer to the object being handled.
virtual::Int_t getEntry(::Int_t getall=0)=0
Function for updating the object in memory if needed.
void setStructMode(EStructMode mode)
Set the structure mode of the object to a new value.
EStructMode
"Structural" modes of the object
@ kUndefinedStore
The structure mode is not defined.
@ kObjectStore
The object describes a single object.
@ kContainerStore
The object describes an entire container.
EStructMode structMode() const
Get what structure mode the object was constructed with.
int r
Definition globals.cxx:22
std::vector< std::string > files
file names and file pointers
Definition hcg.cxx:50
std::string normalizedTypeinfoName(const std::type_info &info)
Convert a type_info to a normalized string representation (matching the names used in the root dictio...
size_t auxid_t
Identifier for a particular aux data item.
Definition AuxTypes.h:27
void sort(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end)
Specialization of sort for DataVector/List.
bool hasAuxStore(const TClass &cl)
Helper function deciding if a given type "has an auxiliary store".
Definition IOUtils.cxx:40
bool isAuxStore(const TClass &cl)
Helper function deciding if a given type "is an auxiliary store".
Definition IOUtils.cxx:53
bool isStandalone(const TClass &cl)
Helper function deciding if a given type "is a standalone object".
Definition IOUtils.cxx:65
static const ::Int_t BeginEvent
A new event was just loaded.
Definition TIncident.h:29
static const ::Int_t EndInputFile
The processing of an input file has finished.
Definition TIncident.h:40
static const ::Int_t MetaDataStop
The metadata for the output file should be written out.
Definition TIncident.h:31
static const ::Int_t BeginInputFile
A new input file was just opened.
Definition TIncident.h:27
std::string dynBranchPrefix(const std::string &key)
This function is used to figure out what to name dynamic auxiliary branches coming from a container c...
char rootType(char typeidType)
This function is used internally in the code when creating primitive dynamic auxiliary branches.
std::string getFirstBranchMatch(TTree *tree, const std::string &pre)
This function is used to search for a branch in a TTree that contains a given substring.
std::string getTypeName(const std::type_info &ti)
This function is necessary in order to create type names that ROOT can understand.
ICaloAffectedTool is abstract interface for tools checking if 4 mom is in calo affected region.
EventFormat_v1 EventFormat
Definition of the current event format version.
Definition EventFormat.h:16
static const char *const METADATA_TREE_NAME
Name of the metadata tree.
static const ::Int_t CACHE_SIZE
Size of a possible TTreeCache.
Helper to disable undefined behavior sanitizer for a function.
Convert a type_info to a normalized string representation (matching the names used in the root dictio...
TChain * tree
TFile * file