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 <TTree.h>
15#include <TFile.h>
16#include <TKey.h>
17#include <TClass.h>
18
20 RootFileInfo::RootFileInfo(const std::string& filename)
21 {
22 // make sure TDirectory is reset after this function
23 TDirectory::TContext directoryGuard;
24 // Open the file
25 m_file.reset(TFile::Open(filename.c_str(), "READ"));
26 if (!m_file || !m_file->IsOpen()) throw std::invalid_argument("Could not open file");
27 // We want to get two trees the same way but only need that here ... lambda it is
28 auto getTree = [&file = this->m_file](const std::string & label, const std::string & name, std::unique_ptr<TTree>& destination) {
29 TTree* tmp{nullptr};
30 file->GetObject(name.c_str(), tmp);
31 if (!tmp) throw std::runtime_error("No " + label + " tree found");
32 destination.reset(tmp);
33 };
34 // So get the trees from the file and store them in the members
35 getTree("persistent", c_treeNames[DataStore::c_Persistent], m_persistent);
36 auto description = getFileMetaData().getDataDescription();
37 auto isNtuple = description.find("isNtupleMetaData");
38 if ((isNtuple == description.end()) || (isNtuple->second != "True")) {
39 getTree("event", c_treeNames[DataStore::c_Event], m_events);
40 }
41 // And finally check the number of entries in the persistent tree
42 if (auto npersistent = m_persistent->GetEntries(); npersistent != 1) {
43 throw std::runtime_error("Expected exactly one entry in persistent tree, found " + std::to_string(npersistent));
44 }
45 }
46
48 {
49 if (!m_metadata) {
50 // object not set yet, get it from file
51 FileMetaData* metadata{nullptr};
52 auto branchStatus = m_persistent->SetBranchAddress("FileMetaData", &metadata);
53 if (branchStatus < 0) throw std::runtime_error("Error retrieving FileMetaData branch: " + std::to_string(branchStatus));
54 if (m_persistent->GetEntry(0) <= 0 || !metadata) throw std::runtime_error("Cannot read FileMetaData");
55 // and remembber
56 m_metadata.reset(metadata);
57 }
58 return *m_metadata;
59 }
60
61 const std::set<std::string>& RootFileInfo::getBranchNames(bool persistent)
62 {
63 // which set of branches are we looking at?
64 std::optional<std::set<std::string>>& cache{persistent ? m_persistentBranches : m_eventBranches};
65 // if we didn't create the list already do it now
66 if (!cache) {
67 TTree& tree{persistent ? *m_persistent :* m_events};
68 std::set<std::string> result;
69 for (const TObject* obj : * (tree.GetListOfBranches())) {
70 const auto* branch = dynamic_cast<const TBranch*>(obj);
71 if (!branch) throw std::runtime_error("Entry in list of branches is no branch");
72 result.emplace(branch->GetName());
73 }
74 // and remember
75 cache.emplace(std::move(result));
76 }
77 // and just return the content
78 return *cache;
79 }
80
81 const std::set<std::string> RootFileInfo::getNtupleBranchNames(std::string treeName)
82 {
83 std::set<std::string> branches;
84 auto* tree = dynamic_cast<TTree*>(m_file->Get(treeName.c_str()));
85 for (const TObject* obj : * (tree->GetListOfBranches())) {
86 const auto* branch = dynamic_cast<const TBranch*>(obj);
87 if (!branch) throw std::runtime_error("Entry in list of branches is no branch");
88 branches.emplace(branch->GetName());
89 }
90 return branches;
91 }
92
93 void RootFileInfo::checkMissingBranches(const std::set<std::string>& required, bool persistent)
94 {
95 // So let's get the list of existing branches
96 const auto& existing = getBranchNames(persistent);
97 // and fill a list of branches which are in required but not existing
98 std::vector<std::string> missing;
99 std::set_difference(required.begin(), required.end(), existing.begin(), existing.end(),
100 std::inserter(missing, missing.begin()));
101 // and if that is not empty we complain
102 if (!missing.empty()) {
103 std::stringstream message;
104 message << "Branches missing from event tree: ";
105 for (const auto& name : missing) {
106 message << name << ", ";
107 }
108 throw std::runtime_error(message.str());
109 }
110 }
111
112 const std::set<std::string> RootFileInfo::getTreeNames()
113 {
114 std::set<std::string> treeNames;
115 TList* keylist = m_file->GetListOfKeys();
116 TIter next(keylist);
117 while (TObject* keyObj = next()) {
118 auto* key = dynamic_cast<TKey*>(keyObj);
119 if (!key) continue;
120 if (strcmp(key->GetName(), "persistent") == 0) continue;
121 TClass* cls = TClass::GetClass(key->GetClassName());
122 if (cls && cls->InheritsFrom(TTree::Class())) {
123 treeNames.emplace(key->GetName());
124 }
125 }
126 return treeNames;
127 }
128
129 /* Destructor. Declared here to allow forward declaration of TFile,TTree,... in header */
130 RootFileInfo::~RootFileInfo() = default;
131}
@ 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.
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.
const std::set< std::string > getNtupleBranchNames(std::string treeName)
Return a set of branch names residing in the passed tree.
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.