Belle II Software development
RootFileInfo.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8
9#include <framework/io/RootFileInfo.h>
10#include <framework/io/RootIOUtilities.h>
11#include <framework/dataobjects/FileMetaData.h>
12#include <framework/datastore/DataStore.h>
13
14#include <sstream>
15#include <TTree.h>
16#include <TFile.h>
17#include <TKey.h>
18#include <TClass.h>
19
21 RootFileInfo::RootFileInfo(const std::string& filename)
22 {
23 // make sure TDirectory is reset after this function
24 TDirectory::TContext directoryGuard;
25 // Open the file
26 m_file.reset(TFile::Open(filename.c_str(), "READ"));
27 if (!m_file || !m_file->IsOpen()) throw std::invalid_argument("Could not open file");
28 // We want to get two trees the same way but only need that here ... lambda it is
29 auto getTree = [&file = this->m_file](const std::string & label, const std::string & name, std::unique_ptr<TTree>& destination) {
30 TTree* tmp{nullptr};
31 file->GetObject(name.c_str(), tmp);
32 if (!tmp) throw std::runtime_error("No " + label + " tree found");
33 destination.reset(tmp);
34 };
35 // So get the trees from the file and store them in the members
36 getTree("persistent", c_treeNames[DataStore::c_Persistent], m_persistent);
37 auto description = getFileMetaData().getDataDescription();
38 auto isNtuple = description.find("isNtupleMetaData");
39 if ((isNtuple == description.end()) || (isNtuple->second != "True")) {
40 getTree("event", c_treeNames[DataStore::c_Event], m_events);
41 }
42 // And finally check the number of entries in the persistent tree
43 if (auto npersistent = m_persistent->GetEntries(); npersistent != 1) {
44 throw std::runtime_error("Expected exactly one entry in persistent tree, found " + std::to_string(npersistent));
45 }
46 }
47
49 {
50 if (!m_metadata) {
51 // object not set yet, get it from file
52 FileMetaData* metadata{nullptr};
53 auto branchStatus = m_persistent->SetBranchAddress("FileMetaData", &metadata);
54 if (branchStatus < 0) throw std::runtime_error("Error retrieving FileMetaData branch: " + std::to_string(branchStatus));
55 if (m_persistent->GetEntry(0) <= 0 || !metadata) throw std::runtime_error("Cannot read FileMetaData");
56 // and remembber
57 m_metadata.reset(metadata);
58 }
59 return *m_metadata;
60 }
61
62 const std::set<std::string>& RootFileInfo::getBranchNames(bool persistent)
63 {
64 // which set of branches are we looking at?
65 std::optional<std::set<std::string>>& cache{persistent ? m_persistentBranches : m_eventBranches};
66 // if we didn't create the list already do it now
67 if (!cache) {
68 TTree& tree{persistent ? *m_persistent :* m_events};
69 std::set<std::string> result;
70 for (const TObject* obj : * (tree.GetListOfBranches())) {
71 const auto* branch = dynamic_cast<const TBranch*>(obj);
72 if (!branch) throw std::runtime_error("Entry in list of branches is no branch");
73 result.emplace(branch->GetName());
74 }
75 // and remember
76 cache.emplace(std::move(result));
77 }
78 // and just return the content
79 return *cache;
80 }
81
82 const std::set<std::string> RootFileInfo::getNtupleBranchNames(const std::string& treeName)
83 {
84 std::set<std::string> branches;
85 auto* tree = dynamic_cast<TTree*>(m_file->Get(treeName.c_str()));
86 for (const TObject* obj : * (tree->GetListOfBranches())) {
87 const auto* branch = dynamic_cast<const TBranch*>(obj);
88 if (!branch) throw std::runtime_error("Entry in list of branches is no branch");
89 branches.emplace(branch->GetName());
90 }
91 return branches;
92 }
93
94 void RootFileInfo::checkMissingBranches(const std::set<std::string>& required, bool persistent)
95 {
96 // So let's get the list of existing branches
97 const auto& existing = getBranchNames(persistent);
98 // and fill a list of branches which are in required but not existing
99 std::vector<std::string> missing;
100 std::set_difference(required.begin(), required.end(), existing.begin(), existing.end(),
101 std::inserter(missing, missing.begin()));
102 // and if that is not empty we complain
103 if (!missing.empty()) {
104 std::stringstream message;
105 message << "Branches missing from event tree: ";
106 for (const auto& name : missing) {
107 message << name << ", ";
108 }
109 throw std::runtime_error(message.str());
110 }
111 }
112
113 const std::set<std::string> RootFileInfo::getTreeNames()
114 {
115 std::set<std::string> treeNames;
116 TList* keylist = m_file->GetListOfKeys();
117 TIter next(keylist);
118 while (TObject* keyObj = next()) {
119 auto* key = dynamic_cast<TKey*>(keyObj);
120 if (!key) continue;
121 if (strcmp(key->GetName(), "persistent") == 0) continue;
122 TClass* cls = TClass::GetClass(key->GetClassName());
123 if (cls && cls->InheritsFrom(TTree::Class())) {
124 treeNames.emplace(key->GetName());
125 }
126 }
127 return treeNames;
128 }
129
130 /* Destructor. Declared here to allow forward declaration of TFile,TTree,... in header */
131 RootFileInfo::~RootFileInfo() = default;
132}
@ c_Persistent
Object is available during entire execution time.
Definition DataStore.h:60
@ c_Event
Different object in each event, all objects/arrays are invalidated after event() function has been ca...
Definition DataStore.h:59
Metadata information about a file.
const std::map< std::string, std::string > & getDataDescription() const
get data description.
const std::set< std::string > getTreeNames()
Return a set of event tree names in the file.
const FileMetaData & getFileMetaData()
Return the event metadata from the file.
std::unique_ptr< TTree > m_events
Pointer to the event tree.
void checkMissingBranches(const std::set< std::string > &required, bool persistent=false)
Check if the event or persistent tree contain at least all the branches in the set of required branch...
std::unique_ptr< FileMetaData > m_metadata
Pointer to the file metadata once it has been read.
std::optional< std::set< std::string > > m_persistentBranches
Cached set of persistent branch names.
std::unique_ptr< TFile > m_file
Pointer to the file object.
const std::set< std::string > getNtupleBranchNames(const std::string &treeName)
Return a set of branch names residing in the passed tree.
std::optional< std::set< std::string > > m_eventBranches
Cached set of event branch names.
RootFileInfo(const std::string &filename)
Create an object from a given filename or url.
~RootFileInfo()
Close the file and delete all structures associated with it.
std::unique_ptr< TTree > m_persistent
Pointer to the persistent tree.
const std::set< std::string > & getBranchNames(bool persistent=false)
Return a set of branch names for either the event or the persistent tree.
Some constants and helpers common to the RootInput and RootOutput modules.
const std::string c_treeNames[]
Names of trees.