MaCh3  2.8.0
Reference Guide
GetPenaltyTermModule.cpp
Go to the documentation of this file.
1 // MaCh3 includes
2 #include "Manager/Manager.h"
7 
9 // ROOT includes
10 #include "TFile.h"
11 #include "TBranch.h"
12 #include "TCanvas.h"
13 #include "TLine.h"
14 #include "TLegend.h"
15 #include "TString.h"
16 #include "TStyle.h"
17 #include "TMatrixT.h"
18 #include "TMatrixDSym.h"
19 #include "TVectorD.h"
20 #include "TObject.h"
21 #include "TChain.h"
22 #include "TH1.h"
23 #include "TColor.h"
24 #include "TObjString.h"
25 #include "TROOT.h"
27 
28 namespace M3{
30 
32  m_parser = std::make_unique<MaCh3ArgumentParser>("penaltyterm", "1.0", argparse::default_arguments::help);
33  m_parser->add_description("Calculate penalty term for selected parameters, for every step");
34  m_parser->add_argument("config")
35  .help("Config file.")
36  .metavar("CONFIG")
37  .required();
38  m_parser->add_argument("inputfile")
39  .help("Root file to analyse.")
40  .metavar("INPUTFILE")
41  .required();
42  return m_parser.get();
43 }
44 
45 int GetPenaltyTermModule::Run()//int argc, char *argv[])
46 {
49  std::string inputFile = m_parser->get<std::string>("inputfile");
50  std::string config = m_parser->get<std::string>("config");
51  this->GetPenaltyTerm(inputFile, config);
52 
53  return 0;
54 }
55 
67 void GetPenaltyTermModule::ReadCovFile(const std::string& inputFile,
68  std::vector <double>& Prior,
69  std::vector <bool>& isFlat,
70  std::vector<std::string>& ParamNames,
71  std::vector<std::vector<double>>& invCovMatrix,
72  int& nParams)
73 {
74  // Now read the MCMC file
75  TFile *TempFile = M3::Open(inputFile, "open", __FILE__, __LINE__);
76 
77  // Get the matrix
78  TDirectory* CovarianceFolder = TempFile->Get<TDirectory>("CovarianceFolder");
79  TMatrixDSym *CovMatrix = M3::GetCovMatrixFromChain(CovarianceFolder);
80 
81  // Get the settings for the MCMC
82  TMacro *Config = TempFile->Get<TMacro>("MaCh3_Config");
83  if (Config == nullptr) {
84  MACH3LOG_ERROR("Didn't find MaCh3_Config tree in MCMC file! {}", inputFile);
85  TempFile->ls();
86  throw MaCh3Exception(__FILE__ , __LINE__ );
87  }
88 
89  YAML::Node Settings = TMacroToYAML(*Config);
90 
91  //CW: Get the Covariance matrix
92  std::vector<std::string> CovPos = GetFromManager<std::vector<std::string>>(Settings["General"]["Systematics"]["XsecCovFile"], {"none"}, __FILE__, __LINE__);
93  if(CovPos.back() == "none")
94  {
95  MACH3LOG_WARN("Couldn't find Cov branch in output");
96  M3::Utils::PrintConfig(Settings);
97  throw MaCh3Exception(__FILE__ , __LINE__ );
98  }
99 
100  //KS:Most inputs are in ${MACH3}/inputs/blarb.root
101  if (std::getenv("MACH3") != nullptr) {
102  MACH3LOG_INFO("Found MACH3 environment variable: {}", std::getenv("MACH3"));
103  for(unsigned int i = 0; i < CovPos.size(); i++)
104  CovPos[i].insert(0, std::string(std::getenv("MACH3"))+"/");
105  }
106 
107  YAML::Node CovFile;
108  CovFile["Systematics"] = YAML::Node(YAML::NodeType::Sequence);
109  for(unsigned int i = 0; i < CovPos.size(); i++)
110  {
111  YAML::Node YAMLDocTemp = M3OpenConfig(CovPos[i]);
112  for (const auto& item : YAMLDocTemp["Systematics"]) {
113  CovFile["Systematics"].push_back(item);
114  }
115  }
116 
117  nParams = CovMatrix->GetNrows();
118 
119  auto systematics = CovFile["Systematics"];
120  for (auto it = systematics.begin(); it != systematics.end(); ++it)
121  {
122  auto const &param = *it;
123 
124  ParamNames.push_back(param["Systematic"]["Names"]["FancyName"].as<std::string>());
125  Prior.push_back( param["Systematic"]["ParameterValues"]["PreFitValue"].as<double>() );
126 
127  bool flat = false;
128  if (param["Systematic"]["FlatPrior"]) { flat = param["Systematic"]["FlatPrior"].as<bool>(); }
129  isFlat.push_back( flat );
130  }
131 
132  CovMatrix->Invert();
133  //KS: Let's use double as it is faster than TMatrix
134  invCovMatrix.resize(nParams, std::vector<double>(nParams, -999));
135 
136  #ifdef MULTITHREAD
137  #pragma omp parallel for collapse(2)
138  #endif
139  for (int i = 0; i < nParams; i++)
140  {
141  for (int j = 0; j < nParams; ++j)
142  {
143  invCovMatrix[i][j] = (*CovMatrix)(i,j);
144  }
145  }
146 
147  TempFile->Close();
148  delete TempFile;
149 }
150 
162 void GetPenaltyTermModule::LoadSettings(YAML::Node& Settings,
163  std::vector<std::string>& SetsNames,
164  std::vector<std::string>& FancyTitle,
165  std::vector<std::vector<bool>>& isRelevantParam,
166  const std::vector<std::string>& ParamNames,
167  const int nParams)
168  {
169  std::vector<std::string> node = Settings["GetPenaltyTerm"]["PenaltySets"].as<std::vector<std::string>>();
170  std::vector<std::vector<std::string>> RemoveNames;
171  std::vector<bool> Exclude;
172 
173  for (unsigned int i = 0; i < node.size(); i++)
174  {
175  std::string ParName = node[i];
176  SetsNames.push_back(ParName);
177 
178  const auto& Set = Settings["GetPenaltyTerm"][ParName];
179 
180  RemoveNames.push_back(Set[0].as<std::vector<std::string>>());
181  Exclude.push_back(Set[1].as<bool>());
182  FancyTitle.push_back(Set[2].as<std::string>());
183  }
184 
185  const int NSets = int(SetsNames.size());
186 
187  isRelevantParam.resize(NSets);
188  //Loop over sets in the config
189  for(int i = 0; i < NSets; i++)
190  {
191  isRelevantParam[i].resize(nParams);
192  int counter = 0;
193  //Loop over parameters in the Covariance object
194  for (int j = 0; j < nParams; j++)
195  {
196  isRelevantParam[i][j] = false;
197 
198  //KS: Here we loop over all names and if parameters wasn't matched then we set it is relevant.
199  if(Exclude[i])
200  {
201  bool found = false;
202  for (unsigned int k = 0; k < RemoveNames[i].size(); k++)
203  {
204  if (ParamNames[j].rfind(RemoveNames[i][k], 0) == 0)
205  {
206  found = true;
207  }
208  }
209  if(!found)
210  {
211  isRelevantParam[i][j] = true;
212  counter++;
213  }
214  }
215  //KS: Here is much simpler, if parameter matched then it is relevant
216  else
217  {
218  for (unsigned int k = 0; k < RemoveNames[i].size(); k++)
219  {
220  if (ParamNames[j].rfind(RemoveNames[i][k], 0) == 0)
221  {
222  isRelevantParam[i][j] = true;
223  counter++;
224  break;
225  }
226  }
227  }
228  }
229  MACH3LOG_INFO(" Found {} params for set {}", counter, SetsNames[i]);
230  }
231 }
232 
241 void GetPenaltyTermModule::GetPenaltyTerm(const std::string& inputFile, const std::string& configFile)
242 {
243  auto canvas = std::make_unique<TCanvas>("canvas", "canvas", 0, 0, 1024, 1024);
244  canvas->SetGrid();
245  canvas->SetTickx();
246  canvas->SetTicky();
247 
248  canvas->SetBottomMargin(0.1f);
249  canvas->SetTopMargin(0.02f);
250  canvas->SetRightMargin(0.08f);
251  canvas->SetLeftMargin(0.15f);
252 
253  gStyle->SetOptTitle(0);
254  gStyle->SetOptStat(0);
255  gStyle->SetPalette(51);
256 
257  std::vector <double> Prior;
258  std::vector <bool> isFlat;
259  std::vector<std::string> ParamNames;
260  std::vector<std::vector<double>> invCovMatrix;
261  int nParams;
262  this->ReadCovFile(inputFile, Prior, isFlat, ParamNames, invCovMatrix, nParams);
263 
264  std::vector<TString> BranchNames;
265 
266  // Open the Chain
267  TChain* Chain = new TChain("posteriors","");
268  Chain->Add(inputFile.c_str());
269 
270  // Get the list of branches
271  TObjArray* brlis = Chain->GetListOfBranches();
272 
273  // Get the number of branches
274  int nBranches = brlis->GetEntries();
275  int RelevantBranches = 0;
276  for (int i = 0; i < nBranches; i++)
277  {
278  // Get the TBranch and its name
279  TBranch* br = static_cast<TBranch*>(brlis->At(i));
280  if(!br){
281  MACH3LOG_ERROR("Invalid branch at position {}", i);
282  throw MaCh3Exception(__FILE__,__LINE__);
283  }
284  TString bname = br->GetName();
285 
286  // If we're on beam systematics
287  if(bname.BeginsWith("param_"))
288  {
289  BranchNames.push_back(bname);
290  RelevantBranches++;
291  }
292  }
293 
294  // Set all the branches to off
295  Chain->SetBranchStatus("*", false);
296 
297  std::vector<double> fParProp(RelevantBranches);
298  // Turn on the branches which we want for parameters
299  for (int i = 0; i < RelevantBranches; ++i)
300  {
301  Chain->SetBranchStatus(BranchNames[i].Data(), true);
302  Chain->SetBranchAddress(BranchNames[i].Data(), &fParProp[i]);
303  }
304 
305  YAML::Node Settings = M3OpenConfig(configFile);
306  std::vector<std::string> SetsNames;
307  std::vector<std::string> FancyTitle;
308  std::vector<std::vector<bool>> isRelevantParam;
309 
310  this->LoadSettings(Settings, SetsNames, FancyTitle, isRelevantParam, ParamNames, nParams);
311 
312  const int NSets = int(SetsNames.size());
313  int AllEvents = int(Chain->GetEntries());
314  std::vector<std::unique_ptr<TH1D>> hLogL(NSets);
315  for (int i = 0; i < NSets; i++) {
316  std::string NameTemp = "LogL_" + SetsNames[i];
317  hLogL[i] = std::make_unique<TH1D>(NameTemp.c_str(), NameTemp.c_str(), AllEvents, 0, AllEvents);
318  hLogL[i]->SetLineColor(kBlue);
319  }
320  #pragma GCC diagnostic push
321  #pragma GCC diagnostic ignored "-Walloca"
322  for(int n = 0; n < AllEvents; ++n)
323  {
324  if(n%10000 == 0) M3::Utils::PrintProgressBar(n, AllEvents);
325  Chain->GetEntry(n);
326 
327  std::vector<double> logL(NSets, 0.0);
328  double* _restrict_ logL_array = logL.data();
329  #ifdef MULTITHREAD
330  #pragma omp parallel for reduction(+:logL_array[:NSets])
331  #endif
332  for (int i = 0; i < nParams; i++)
333  {
334  for (int j = 0; j <= i; ++j)
335  {
336  //check if flat prior
337  if (!isFlat[i] && !isFlat[j])
338  {
339  for(int k = 0; k < NSets; ++k)
340  {
341  //Check if parameter is relevant for this set
342  if (isRelevantParam[k][i] && isRelevantParam[k][j])
343  {
344  //KS: Since matrix is symmetric we can calculate non diagonal elements only once and multiply by 2, can bring up to factor speed decrease.
345  int scale = 1;
346  if(i != j) scale = 2;
347  logL_array[k] += scale * 0.5*(fParProp[i] - Prior[i])*(fParProp[j] - Prior[j])*invCovMatrix[i][j];
348  }
349  }
350  }
351  }
352  } // end loop over params
353  for(int k = 0; k < NSets; ++k)
354  {
355  hLogL[k]->SetBinContent(n, logL_array[k]);
356  }
357  } //End loop over steps
358  #pragma GCC diagnostic pop
359  // Directory for posteriors
360  std::string OutputName = inputFile + "_PenaltyTerm" +".root";
361  TFile *OutputFile = M3::Open(OutputName, "recreate", __FILE__, __LINE__);
362  TDirectory *PenaltyTermDir = OutputFile->mkdir("PenaltyTerm");
363 
364  canvas->Print(Form("%s_PenaltyTerm.pdf[",inputFile.c_str()), "pdf");
365  for(int i = 0; i < NSets; i++)
366  {
367  const double Maximum = hLogL[i]->GetMaximum();
368  hLogL[i]->GetYaxis()->SetRangeUser(0., Maximum*1.2);
369  hLogL[i]->SetTitle(FancyTitle[i].c_str());
370  hLogL[i]->GetXaxis()->SetTitle("Step");
371  hLogL[i]->GetYaxis()->SetTitle(FancyTitle[i].c_str());
372  hLogL[i]->GetYaxis()->SetTitleOffset(1.4f);
373 
374  hLogL[i]->Draw("");
375 
376  PenaltyTermDir->cd();
377  hLogL[i]->Write();
378 
379  canvas->Print(Form("%s_PenaltyTerm.pdf",inputFile.c_str()), "pdf");
380  }
381  canvas->Print(Form("%s_PenaltyTerm.pdf]",inputFile.c_str()), "pdf");
382  delete Chain;
383 
384  OutputFile->Close();
385  delete OutputFile;
386 }
387 }
#define _MaCh3_Safe_Include_Start_
KS: Avoiding warning checking for headers.
Definition: Core.h:126
#define _MaCh3_Safe_Include_End_
#define _restrict_
KS: Using restrict limits the effects of pointer aliasing, aiding optimizations. While reading I foun...
Definition: Core.h:108
Module for extracting penalty terms from systematic chains.
#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
bool isFlat(TSpline3_red *&spl)
CW: Helper function used in the constructor, tests to see if the spline is flat.
YAML::Node TMacroToYAML(const TMacro &macro)
KS: Convert a ROOT TMacro object to a YAML node.
Definition: YamlHelper.h:151
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:589
void LoadSettings(YAML::Node &Settings, std::vector< std::string > &SetsNames, std::vector< std::string > &FancyTitle, std::vector< std::vector< bool >> &isRelevantParam, const std::vector< std::string > &ParamNames, const int nParams)
Load penalty term sets from YAML configuration.
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
void ReadCovFile(const std::string &inputFile, std::vector< double > &Prior, std::vector< bool > &isFlat, std::vector< std::string > &ParamNames, std::vector< std::vector< double >> &invCovMatrix, int &nParams)
Read covariance matrix and parameter information from file.
void GetPenaltyTerm(const std::string &inputFile, const std::string &configFile)
Calculate and plot penalty terms for parameter sets.
int Run() override
Execute the penalty term extraction.
virtual ~GetPenaltyTermModule()
Destructor.
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 PrintConfig(const YAML::Node &node)
KS: Print Yaml config using logger.
Definition: Monitor.cpp:311
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
Definition: Monitor.cpp:229
void MaCh3Welcome()
KS: Prints welcome message with MaCh3 logo.
Definition: Monitor.cpp:13
Main namespace for MaCh3 software.
TMatrixDSym * GetCovMatrixFromChain(TDirectory *TempFile)
KS: Retrieve the cross-section covariance matrix from the given TDirectory. Historically,...