MaCh3  2.8.0
Reference Guide
Public Member Functions | Private Member Functions | List of all members
M3::GetPenaltyTermModule Class Reference

Module for extracting specific penalty terms from MCMC chains. More...

#include <CLI/Modules/GetPenaltyTermModule.hpp>

Inheritance diagram for M3::GetPenaltyTermModule:
[legend]
Collaboration diagram for M3::GetPenaltyTermModule:
[legend]

Public Member Functions

virtual ~GetPenaltyTermModule ()
 Destructor. More...
 
MaCh3ArgumentParser * get_parser () override
 Get the argument parser for this module. More...
 
int Run () override
 Execute the penalty term extraction. More...
 
- Public Member Functions inherited from M3::PluginBase
virtual ~PluginBase ()=default
 
- Public Member Functions inherited from M3::IPlugin
virtual ~IPlugin ()=default
 

Private Member Functions

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. More...
 
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. More...
 
void GetPenaltyTerm (const std::string &inputFile, const std::string &configFile)
 Calculate and plot penalty terms for parameter sets. More...
 

Additional Inherited Members

- Protected Attributes inherited from M3::PluginBase
std::unique_ptr< MaCh3ArgumentParser > m_parser
 Argument parser for this plugin. More...
 

Detailed Description

Module for extracting specific penalty terms from MCMC chains.

This module retrieves penalty terms from flux and cross-section systematic chains, since these systematic uncertainties are handled separately and the penalty term cannot be taken directly from the chain.

Definition at line 24 of file GetPenaltyTermModule.hpp.

Constructor & Destructor Documentation

◆ ~GetPenaltyTermModule()

M3::GetPenaltyTermModule::~GetPenaltyTermModule ( )
virtualdefault

Destructor.

Member Function Documentation

◆ get_parser()

MaCh3ArgumentParser * M3::GetPenaltyTermModule::get_parser ( )
overridevirtual

Get the argument parser for this module.

Returns
Pointer to the configured MaCh3ArgumentParser

Implements M3::IPlugin.

Definition at line 31 of file GetPenaltyTermModule.cpp.

31  {
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 }
std::unique_ptr< MaCh3ArgumentParser > m_parser
Argument parser for this plugin.
Definition: plugin.hpp:47

◆ GetPenaltyTerm()

void M3::GetPenaltyTermModule::GetPenaltyTerm ( const std::string &  inputFile,
const std::string &  configFile 
)
private

Calculate and plot penalty terms for parameter sets.

Calculate and plot penalty terms for each parameter set.

Parameters
inputFilePath to the MCMC chain ROOT file
configFilePath to the YAML configuration file

Main function that reads the covariance, loads configuration, iterates through MCMC steps, and calculates penalty terms for each defined set. Results are saved to ROOT file and PDF plots.

Parameters
inputFilePath to the MCMC chain ROOT file
configFilePath to the YAML configuration file

Definition at line 241 of file GetPenaltyTermModule.cpp.

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 }
#define _restrict_
KS: Using restrict limits the effects of pointer aliasing, aiding optimizations. While reading I foun...
Definition: Core.h:108
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
bool isFlat(TSpline3_red *&spl)
CW: Helper function used in the constructor, tests to see if the spline is flat.
#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.
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.
Custom exception class used throughout MaCh3.
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
Definition: Monitor.cpp:229

◆ LoadSettings()

void M3::GetPenaltyTermModule::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 
)
private

Load penalty term sets from YAML configuration.

Load penalty term set definitions from YAML configuration.

Parameters
SettingsYAML configuration node
SetsNamesVector to store set names
FancyTitleVector to store fancy titles for each set
isRelevantParam2D vector indicating which parameters belong to each set
ParamNamesVector of all parameter names
nParamsTotal number of parameters

Parses the configuration to determine which parameters belong to each penalty term set, based on either inclusion or exclusion patterns.

Parameters
SettingsYAML configuration node
SetsNamesVector to be filled with set names
FancyTitleVector to be filled with fancy titles for plotting
isRelevantParam2D vector to be filled with parameter relevance flags
ParamNamesVector of all parameter names from the covariance
nParamsTotal number of parameters

Definition at line 162 of file GetPenaltyTermModule.cpp.

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 }
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35

◆ ReadCovFile()

void M3::GetPenaltyTermModule::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 
)
private

Read covariance matrix and parameter information from file.

Read covariance matrix and prior information from ROOT file.

Parameters
inputFilePath to the ROOT file containing the covariance
PriorVector to store prior parameter values
isFlatVector to store flat prior flags
ParamNamesVector to store parameter names
invCovMatrix2D vector to store inverted covariance matrix
nParamsReference to store the number of parameters

Loads the covariance matrix, inverts it, and extracts parameter priors and flat prior flags from the MCMC output file.

Parameters
inputFilePath to the ROOT file containing MCMC output
PriorVector to be filled with prior parameter values
isFlatVector to be filled with flat prior flags
ParamNamesVector to be filled with parameter names
invCovMatrix2D vector to be filled with inverted covariance matrix
nParamsReference to store the number of parameters

Definition at line 67 of file GetPenaltyTermModule.cpp.

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 }
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
YAML::Node TMacroToYAML(const TMacro &macro)
KS: Convert a ROOT TMacro object to a YAML node.
Definition: YamlHelper.h:151
void PrintConfig(const YAML::Node &node)
KS: Print Yaml config using logger.
Definition: Monitor.cpp:311
TMatrixDSym * GetCovMatrixFromChain(TDirectory *TempFile)
KS: Retrieve the cross-section covariance matrix from the given TDirectory. Historically,...

◆ Run()

int M3::GetPenaltyTermModule::Run ( )
overridevirtual

Execute the penalty term extraction.

Returns
Exit code (0 on success)

Implements M3::IPlugin.

Definition at line 45 of file GetPenaltyTermModule.cpp.

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 }
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Definition: MaCh3Logger.h:60
void GetPenaltyTerm(const std::string &inputFile, const std::string &configFile)
Calculate and plot penalty terms for parameter sets.
void MaCh3Welcome()
KS: Prints welcome message with MaCh3 logo.
Definition: Monitor.cpp:13

The documentation for this class was generated from the following files: