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