MaCh3  2.8.0
Reference Guide
CombineModule.cpp
Go to the documentation of this file.
7 #include "Manager/Manager.h"
9 
10 namespace M3{
12 
14  m_parser = std::make_unique<MaCh3ArgumentParser>("combine", "1.0", argparse::default_arguments::help);
15  m_parser->add_description("Tool for combining multiple MaCh3 chains into a single output.");
16  m_parser->add_argument("-o", "--output")
17  .help("Output ROOT file.")
18  .store_into(OutFileName)
19  .metavar("OUTPUT_FILE");
20  m_parser->add_argument("-c", "--compression-level")
21  .help("Compression level for the output ROOT file.")
22  .store_into(targetCompression)
23  .metavar("COMPRESSION_LEVEL")
24  .default_value(1);
25  m_parser->add_argument("-f", "--force")
26  .help("Force overwrite of the output file if it exists.")
27  .store_into(forceOverwrite)
28  .flag();
29  m_parser->add_argument("-m", "--merge-mode")
30  .help("Merge files in-spite of differences")
31  .store_into(forceMerge)
32  .flag();
33  m_parser->add_argument("input")
34  .help("Input ROOT files.")
35  .metavar("INPUT")
36  .store_into(inpFileList)
37  .nargs(argparse::nargs_pattern::at_least_one)
38  .required();
39  return m_parser.get();
40 }
41 
46  if(OutFileName == ""){
47  MACH3LOG_INFO("Using first file in list as output: ", inpFileList[0].c_str());
49  inpFileList.erase(inpFileList.begin());
50  }
51 
52  if(forceOverwrite){
53  MACH3LOG_INFO("Will overwrite {} if it exists already", OutFileName.c_str());
54  }
55  MACH3LOG_INFO("Combining a total of {} files into {}", inpFileList.size(), OutFileName.c_str());
56  CombineChain();
57  return 0;
58 }
59 
61 bool CombineModule::ShouldSkipLine(const std::string& line, const std::vector<std::string>& SkipVector) {
62  // Otherwise, check if the line contains any word from SkipVector
63  for (const auto& word : SkipVector) {
64  MACH3LOG_TRACE("{} : {}",line, word);
65  if (line.find(word) != std::string::npos) {
66  MACH3LOG_TRACE("Found matching word, therefore Skipping");
67  return true;
68  }
69  }
70  return false;
71 }
72 
77 bool CombineModule::CompareTwoConfigs(const std::string& File1, const std::string& File2, const std::vector<std::string>& SkipVector) {
78  std::istringstream file1(File1);
79  std::istringstream file2(File2);
80 
81  std::string line1, line2;
82  int lineNumber = 1;
83  bool areEqual = true;
84 
85  while (std::getline(file1, line1) && std::getline(file2, line2)) {
86  if (ShouldSkipLine(line1, SkipVector) || ShouldSkipLine(line2, SkipVector)) {
87  ++lineNumber;
88  continue;
89  }
90  if (line1 != line2) {
91  areEqual = false;
92  MACH3LOG_WARN("Difference found on line {}:", lineNumber);
93  MACH3LOG_WARN("Config1: {}", line1);
94  MACH3LOG_WARN("Config2: {}", line2);
95  }
96  ++lineNumber;
97  }
98  // Check if one file has extra lines
99  while (std::getline(file1, line1)) {
100  MACH3LOG_WARN("Extra line in {} on line {}: {}", File1, lineNumber, line1);
101  ++lineNumber;
102  }
103  while (std::getline(file2, line2)) {
104  MACH3LOG_WARN("Extra line in {} on line {}: {}", File2, lineNumber, line2);
105  ++lineNumber;
106  }
107  return areEqual;
108 }
109 
111 bool CombineModule::checkSoftwareVersions(TFile *file, TFile *prevFile, const std::string& ConfigName, const std::vector<std::string>& SkipVector)
112 {
113  bool weirdFile = false;
114 
115  TMacro *versionHeader = file->Get<TMacro>(ConfigName.c_str());
116  TMacro *prevVersionHeader = prevFile->Get<TMacro>(ConfigName.c_str());
117 
118  // EM: compare the digest of the version header file in this file, with the previous one
119  if(!CompareTwoConfigs(TMacroToString(*versionHeader), TMacroToString(*prevVersionHeader), SkipVector)){
120  MACH3LOG_ERROR("Looks like the {} embedded config for file {} is different to the previous ones", ConfigName, file->GetName());
121  MACH3LOG_ERROR("This strongly suggests that this file was made with different software versions than the previous ones");
122  weirdFile = true;
123  }
124 
125  return weirdFile;
126 }
127 
129 void CombineModule::CopyDir(TDirectory *source) {
130  //copy all objects and subdirs of directory source as a subdir of the current directory
131  source->ls();
132  TDirectory *savdir = gDirectory;
133  TDirectory *adir = savdir->Get<TDirectory>(source->GetName());
134  // if directory doesn't exist make it
135  if (!adir) {
136  adir = savdir->mkdir(source->GetName());
137  }
138  adir->cd();
139  //loop on all entries of this directory
140  TKey *key;
141  TIter nextkey(source->GetListOfKeys());
142  while ((key = static_cast<TKey*>(nextkey()))) {
143  const char *classname = key->GetClassName();
144  TClass *cl = gROOT->GetClass(classname);
145  if (!cl) continue;
146  if (cl->InheritsFrom("TDirectory")) {
147  source->cd(key->GetName());
148  TDirectory *subdir = gDirectory;
149  adir->cd();
150  CopyDir(subdir);
151  adir->cd();
152  } else if (cl->InheritsFrom("TTree")) {
153  TTree *T = source->Get<TTree>(key->GetName());
154  adir->cd();
155  TTree *newT = T->CloneTree();
156  newT->Write();
157  } else {
158  source->cd();
159  TObject *obj = key->ReadObj();
160  adir->cd();
161  obj->Write();
162  delete obj;
163  }
164  }
165  adir->SaveSelf(kTRUE);
166  savdir->cd();
167 }
168 
171 bool CombineModule::CompareHistograms(const TH1* h1, const TH1* h2, const std::string& histName, const std::string& folderName)
172 {
173  if (!h1 || !h2) {
174  MACH3LOG_ERROR("Null pointer passed to CompareHistograms for '{}'", histName);
175  return false;
176  }
177 
178  const double int1 = h1->Integral();
179  const double int2 = h2->Integral();
180  if (std::abs(int1 - int2) > 1e-6) {
181  MACH3LOG_ERROR("Histogram '{}' in folder '{}' has different integrals: current = {}, previous = {}",
182  histName, folderName, int1, int2);
183  return false;
184  }
185  return true;
186 }
187 
189 bool CombineModule::CheckFolder(TFile* file, TFile* prevFile, const std::string& FolderName, const std::vector<std::string>& SkipVector)
190 {
191  bool mismatch = false;
192  TDirectory* dir = file->GetDirectory(FolderName.c_str());
193  TDirectory* prevDir = prevFile->GetDirectory(FolderName.c_str());
194 
195  if (!dir || !prevDir) {
196  MACH3LOG_ERROR("Could not find folder '{}' in one or both files", FolderName);
197  return true;
198  }
199 
200  TIter nextKey(dir->GetListOfKeys());
201  TKey* key;
202 
203  while ((key = static_cast<TKey*>(nextKey()))) {
204  const std::string objName = key->GetName();
205  TObject* obj = key->ReadObj();
206  if (!obj) continue;
207 
208  // Handle TH1 comparison
209  if (obj->InheritsFrom("TH1")) {
210  TH1* hist = static_cast<TH1*>(obj);
211  TH1* prevHist = dynamic_cast<TH1*>(prevDir->Get(objName.c_str()));
212  if (!prevHist) {
213  MACH3LOG_ERROR("Missing histogram '{}' in previous file (folder '{}')", objName, FolderName);
214  mismatch = true;
215  continue;
216  }
217  if (!CompareHistograms(hist, prevHist, objName, FolderName)) {
218  mismatch = true;
219  }
220  }
221  // Handle TMacro comparison
222  else if (obj->InheritsFrom("TMacro")) {
223  TMacro* macro = static_cast<TMacro*>(obj);
224  TMacro* prevMacro = dynamic_cast<TMacro*>(prevDir->Get(objName.c_str()));
225  if (!prevMacro) {
226  MACH3LOG_ERROR("Missing TMacro '{}' in previous file (folder '{}')", objName, FolderName);
227  mismatch = true;
228  continue;
229  }
230  if (!CompareTwoConfigs(TMacroToString(*macro), TMacroToString(*prevMacro), SkipVector)) {
231  mismatch = true;
232  }
233  }
234  }
235  return mismatch;
236 }
237 
240 void CombineModule::FastMergeTTrees(const std::vector<std::string>& files, const std::string& outFile, const std::string& TTreeName) {
241  TChain chain(TTreeName.c_str());
242  for (const auto& f : files) chain.Add(f.c_str());
243 
244  TFile* outF = TFile::Open(outFile.c_str(), "UPDATE");
245 
246  TTree* newTree = chain.CloneTree(-1, "fast");
247  newTree->SetName(TTreeName.c_str());
248  outF->cd();
249  newTree->Write("", TObject::kOverwrite);
250  outF->Close();
251  delete outF;
252 }
253 
255 {
256  std::string outFileOption;
257  if(forceOverwrite) outFileOption = "RECREATE";
258  else outFileOption = "CREATE";
259 
260  TFile *prevFile = nullptr;
261 
262  // EM: loop through all the files in the provided list, compare the embedded version and config files
263  // If they match, we add the file to the list of files to be merged.
264  // If not, we throw an error and provide a (hopefully) helpful message telling the user why the files couldn't be merged.
265  for(uint fileId = 0; fileId < inpFileList.size(); fileId++)
266  {
267  std::string fileName = inpFileList[fileId];
268  TFile *file = new TFile(fileName.c_str());
269 
270  if(file->Get<TTree>("posteriors")->GetEntries() == 0){
271  MACH3LOG_WARN("Hmmm, file {} Doesn't seem to have any entries", fileName.c_str());
272  MACH3LOG_WARN("That's weird but I guess there's no rule that says a file can't be empty");
273  MACH3LOG_WARN("I'll skip it but maybe double check that this doesn't indicate some deeper problem");
274  continue;
275  }
276 
277  // EM: need to set this in the initial case
278  if(prevFile == nullptr) {
279  prevFile = file;
280  }
281 
282  MACH3LOG_DEBUG("############ File {} #############", fileId);
283 
284  bool weirdFile = false;
285  if(checkSoftwareVersions(file, prevFile, "MaCh3Engine/version_header")) weirdFile = true;
286  if(checkSoftwareVersions(file, prevFile, "MaCh3_Config", {"OutputFile:", "NSteps:"})) weirdFile = true;
287  if(CheckFolder(file, prevFile, "SampleFolder")) weirdFile = true;
288  if(CheckFolder(file, prevFile, "CovarianceFolder")) weirdFile = true;
289 
290  if(weirdFile && !forceMerge){
291  MACH3LOG_ERROR("");
292  MACH3LOG_ERROR("=====================================================================================");
293  MACH3LOG_ERROR("This is not a great idea and could lead to weird outputs and cause some big headaches");
294  MACH3LOG_ERROR("further down the road. But if you reeeeally wanna do it and you know what you're");
295  MACH3LOG_ERROR("doing you can come here and remove the 'throw'");
296  MACH3LOG_ERROR("Or use -m option");
297  MACH3LOG_ERROR("{}:{}", __FILE__, __LINE__ + 2);
298  MACH3LOG_ERROR("=====================================================================================");
299  throw MaCh3Exception(__FILE__ , __LINE__ );
300  }
301 
302  if(prevFile != file) {
303  prevFile->Close();
304  delete prevFile;
305  }
306 
307  // EM: set these for the next iteration
308  prevFile = file;
309  }
310 
311  if (!forceOverwrite && access(OutFileName.c_str(), F_OK) != -1) {
312  MACH3LOG_ERROR("Output file '{}' already exists. Use -f to force overwrite.", OutFileName);
313  throw MaCh3Exception(__FILE__, __LINE__);
314  }
315  //KS: Create new file
316  TFile* outputFile = M3::Open(OutFileName, "recreate", __FILE__, __LINE__);
317  outputFile->Close();
318  delete outputFile;
319 
320  TStopwatch clock;
321  clock.Start();
322 
323  MACH3LOG_INFO("Starting merging");
324  FastMergeTTrees(inpFileList, OutFileName, "posteriors");
326 
327  clock.Stop();
328  MACH3LOG_INFO("Merging of took {:.2f}s to finish", clock.RealTime());
329 
330  //KS: Sadly we need to open file to save TDirectories to not have weird copy of several obejcts there...
331  outputFile = M3::Open(OutFileName, "UPDATE", __FILE__, __LINE__);
332  outputFile->cd();
333 
334  // EM: Write out the version and config files to the combined file
335  std::vector<std::string> configNames = {"MaCh3_Config", "Reweight_Config", "Smearing_Config"};
336  for (std::size_t i = 0; i < configNames.size(); ++i) {
337  const std::string& name = configNames[i];
338  TMacro* macro = prevFile->Get<TMacro>(name.c_str());
339  if (macro != nullptr) {
340  macro->Write();
341  delete macro;
342  }
343  }
344 
345  // Get the source directory
346  TDirectory *MaCh3EngineDir = prevFile->Get<TDirectory>("MaCh3Engine");
347  TDirectory *CovarianceFolderDir = prevFile->Get<TDirectory>("CovarianceFolder");
348  TDirectory *SampleFolderDir = prevFile->Get<TDirectory>("SampleFolder");
349 
350  CopyDir(MaCh3EngineDir);
351  CopyDir(CovarianceFolderDir);
352  CopyDir(SampleFolderDir);
353 
354  outputFile->Close();
355  delete outputFile;
356 
357  delete prevFile;
358  MACH3LOG_INFO("Done!");
359 }
360 }
Allows you to combine multiple chains or ROOT files into a single output.
#define MACH3LOG_DEBUG
Definition: MaCh3Logger.h:34
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Definition: MaCh3Logger.h:60
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
#define MACH3LOG_TRACE
Definition: MaCh3Logger.h:33
std::string TMacroToString(const TMacro &macro)
KS: Convert a ROOT TMacro object to a string representation.
Definition: YamlHelper.h:122
void FastMergeTTrees(const std::vector< std::string > &files, const std::string &outFile, const std::string &TTreeName)
custom function for merging TTree, should be similar to what HADD is using
std::vector< std::string > inpFileList
int Run() override
Execute the application.
virtual ~CombineModule()
Destructor.
bool ShouldSkipLine(const std::string &line, const std::vector< std::string > &SkipVector)
KS: This allow us to skip output name etc in config. We expect Output name will be different but this...
bool CompareTwoConfigs(const std::string &File1, const std::string &File2, const std::vector< std::string > &SkipVector)
make sure two configs are identical but skip specified fields. For example when comparing two chains ...
bool CompareHistograms(const TH1 *h1, const TH1 *h2, const std::string &histName, const std::string &folderName)
Compare two histograms if they are identical.
std::string OutFileName
void CopyDir(TDirectory *source)
When we merge two chains they have TDirectory ROOT didn't provide method for this so here we have thi...
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
bool CheckFolder(TFile *file, TFile *prevFile, const std::string &FolderName, const std::vector< std::string > &SkipVector={})
Loop through TH1 and TMacro objects in FolderName in 'file' and compare with those in 'prevFile'.
bool checkSoftwareVersions(TFile *file, TFile *prevFile, const std::string &ConfigName, const std::vector< std::string > &SkipVector={})
EM: Will compare the version header contained in the two provided files and shout if they don't match...
Extended ArgumentParser with MaCh3-specific functionality.
Definition: m3argparse.hpp:17
std::unique_ptr< MaCh3ArgumentParser > m_parser
Argument parser for this plugin.
Definition: plugin.hpp:47
Custom exception class used throughout MaCh3.
void MaCh3Welcome()
KS: Prints welcome message with MaCh3 logo.
Definition: Monitor.cpp:13
Main namespace for MaCh3 software.