MaCh3  2.2.3
Reference Guide
Functions | Variables
PlotSigmaVariation.cpp File Reference
#include "plottingUtils/plottingUtils.h"
#include "plottingUtils/plottingManager.h"
Include dependency graph for PlotSigmaVariation.cpp:

Go to the source code of this file.

Functions

void ScanInput (std::vector< std::string > &DialNameVecr, std::vector< std::string > &SampleNameVec, std::vector< double > &SigmaValues, const std::string &filename)
 Scan inputs to figure out dial name and used sample names. More...
 
bool SkipDirectory (const std::vector< std::string > &ExcludeString, const std::vector< std::string > &IncludeString, const std::string &dirname)
 Check whether to skip directory or not based on defined strings. More...
 
std::vector< double > GetDialValues (const std::vector< std::unique_ptr< TH1D >> &Poly)
 
void PlotRatio (const std::vector< std::unique_ptr< TH1D >> &Poly, const std::unique_ptr< TCanvas > &canv, const std::string &Title, const std::string &outfilename)
 
void CompareSigVar1D (const std::string &filename, const YAML::Node &Settings)
 
int main (int argc, char **argv)
 

Variables

std::vector< std::string > DialNameVector
 
std::vector< std::string > SampleNameVector
 
std::vector< double > sigmaArray
 
int PriorKnot = M3::_BAD_INT_
 
constexpr const int NVars = 5
 
constexpr Color_t Colours [NVars] = {kRed, kGreen+1, kBlack, kBlue+1, kOrange+1}
 
constexpr ELineStyle Style [NVars] = {kDotted, kDashed, kSolid, kDashDotted, kDashDotted}
 

Detailed Description

Todo:

Integrate within StylePlotting to get fancy labels etc

Add support for 2D and by mode etc.

Author
Kamil Skwarczynski

Definition in file PlotSigmaVariation.cpp.

Function Documentation

◆ CompareSigVar1D()

void CompareSigVar1D ( const std::string &  filename,
const YAML::Node &  Settings 
)

Definition at line 288 of file PlotSigmaVariation.cpp.

289 {
290  //Get input file, make canvas and output file
291  auto canvas = std::make_unique<TCanvas>("canv", "canv", 1080, 1080);
292  TFile *infile = TFile::Open(filename.c_str());
293  TDirectoryFile *SigmaDir = infile->Get<TDirectoryFile>("SigmaVar");
294 
295  std::string outfilename = filename.substr(0, filename.find(".root"));
296  outfilename = outfilename + "_RatioPlots1d.pdf";
297  gErrorIgnoreLevel = kWarning;
298  gStyle->SetDrawBorder(0);
299  gStyle->SetTitleBorderSize(2);
300  gStyle->SetOptStat(0); //Set 0 to disable statistic box
301  canvas->SetGrid();
302  canvas->SetTopMargin(0.10);
303  canvas->SetBottomMargin(0.08);
304  canvas->SetRightMargin(0.05);
305  canvas->SetLeftMargin(0.12);
306  canvas->Print((outfilename+"[").c_str());
307 
308  auto IncludeString = GetFromManager<std::vector<std::string>>(Settings["IncludeString"], {});
309  auto ExcludeString = GetFromManager<std::vector<std::string>>(Settings["ExcludeString"], {});
310  TDirectory *dir = nullptr;
311 
312  for(size_t id = 0; id < DialNameVector.size(); id++)
313  {
314  for(size_t is = 0; is < SampleNameVector.size(); is++)
315  {
316  if(SkipDirectory(ExcludeString, IncludeString, (DialNameVector[id] + "/" + SampleNameVector[is]).c_str())) continue;
317  MACH3LOG_INFO("Entering {}/{}", DialNameVector[id], SampleNameVector[is]);
318  SigmaDir->cd((DialNameVector[id] + "/" + SampleNameVector[is]).c_str());
319 
320  //set dir to current directory
321  dir = gDirectory;
322 
323  //make -3,-1,0,1,3 polys
324  std::vector<std::unique_ptr<TH1D>> Projection;
325  TIter nextsub(dir->GetListOfKeys());
326  TKey *subsubkey = nullptr;
327 
328  //loop over items in directory, hard code which th2poly we want
329  while ((subsubkey = static_cast<TKey*>(nextsub())))
330  {
331  auto name = std::string(subsubkey->GetName());
332  auto classname = std::string(subsubkey->GetClassName());
333 
334  if (classname == "TH1D")
335  {
336  name = DialNameVector[id] + "/" + SampleNameVector[is] + "/" + name;
337  Projection.emplace_back(M3::Clone(SigmaDir->Get<TH1D>(name.c_str())));
338  }
339  }
340  std::string Title = DialNameVector[id] + " " + SampleNameVector[is];
341  PlotRatio(Projection, canvas, Title, outfilename);
342  gDirectory->cd("..");
343  }
344  }
345 
346  canvas->Print((outfilename+"]").c_str());
347  infile->Close();
348  delete infile;
349 }
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:25
void PlotRatio(const std::vector< std::unique_ptr< TH1D >> &Poly, const std::unique_ptr< TCanvas > &canv, const std::string &Title, const std::string &outfilename)
std::vector< std::string > DialNameVector
std::vector< std::string > SampleNameVector
bool SkipDirectory(const std::vector< std::string > &ExcludeString, const std::vector< std::string > &IncludeString, const std::string &dirname)
Check whether to skip directory or not based on defined strings.
std::unique_ptr< ObjectType > Clone(const ObjectType *obj, const std::string &name="")
KS: Creates a copy of a ROOT-like object and wraps it in a smart pointer.
TFile * Open(const std::string &Name, const std::string &Type, const std::string &File, const int Line)
Opens a ROOT file with the given name and mode.

◆ GetDialValues()

std::vector<double> GetDialValues ( const std::vector< std::unique_ptr< TH1D >> &  Poly)

Definition at line 145 of file PlotSigmaVariation.cpp.

145  {
146  std::vector<double> values;
147  for (const auto& hist : Poly) {
148  std::string title = hist->GetTitle();
149  auto pos = title.rfind("_val_");
150  if (pos != std::string::npos) {
151  std::string val_str = title.substr(pos + 5); // skip "_val_"
152  double val = std::stod(val_str);
153  values.push_back(val);
154  MACH3LOG_DEBUG("Extracted dial value {} from title '{}'", val, title);
155  } else {
156  MACH3LOG_DEBUG("Failed to extract dial value from title '{}'", title);
157  throw MaCh3Exception(__FILE__, __LINE__);
158  }
159  }
160  return values;
161 }
#define MACH3LOG_DEBUG
Definition: MaCh3Logger.h:24
Custom exception class for MaCh3 errors.

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 351 of file PlotSigmaVariation.cpp.

352 {
354  if (argc != 3)
355  {
356  MACH3LOG_ERROR("Need two inputs: output of sigma var and config");
357  throw MaCh3Exception(__FILE__, __LINE__);
358  }
359  std::string filename = argv[1];
360  std::string ConfigName = argv[2];
361  MACH3LOG_INFO("Running {} with {} {}", argv[0], filename, ConfigName);
362  // Load the YAML file
363  YAML::Node Config = M3OpenConfig(ConfigName);
364 
365  // Access the "MatrixPlotter" section
366  YAML::Node settings = Config["PlotSigmaVariation"];
367 
369 
370  CompareSigVar1D(filename, settings);
371 
372  return 0;
373 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:27
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Definition: MaCh3Logger.h:51
void CompareSigVar1D(const std::string &filename, const YAML::Node &Settings)
std::vector< double > sigmaArray
void ScanInput(std::vector< std::string > &DialNameVecr, std::vector< std::string > &SampleNameVec, std::vector< double > &SigmaValues, const std::string &filename)
Scan inputs to figure out dial name and used sample names.
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:561

◆ PlotRatio()

void PlotRatio ( const std::vector< std::unique_ptr< TH1D >> &  Poly,
const std::unique_ptr< TCanvas > &  canv,
const std::string &  Title,
const std::string &  outfilename 
)

Definition at line 163 of file PlotSigmaVariation.cpp.

167 {
168  canv->Clear();
169 
170  TPad* pad1 = new TPad("pad1","pad1",0.,0.25,1.,1.0);
171  pad1->AppendPad();
172  TPad* pad2 = new TPad("pad2","pad2",0.,0.,1.,0.25);
173  pad2->AppendPad();
174 
175  pad1->SetLeftMargin(canv->GetLeftMargin());
176  pad1->SetRightMargin(canv->GetRightMargin());
177  pad1->SetTopMargin(canv->GetTopMargin());
178  pad1->SetBottomMargin(0);
179 
180  pad2->SetLeftMargin(canv->GetLeftMargin());
181  pad2->SetRightMargin(canv->GetRightMargin());
182  pad2->SetTopMargin(0);
183  pad2->SetBottomMargin(0.30);
184 
185  pad1->SetGrid();
186  pad2->SetGrid();
187 
188  pad1->cd();
189 
190  auto DialValues = GetDialValues(Poly);
191  double max = 0;
192  for(int ik = 0; ik < static_cast<int>(sigmaArray.size()); ++ik)
193  {
194  Poly[ik]->SetLineWidth(2.);
195  Poly[ik]->SetLineColor(Colours[ik]);
196  Poly[ik]->SetLineStyle(Style[ik]);
197 
198  max = std::max(max, Poly[ik]->GetMaximum());
199  }
200  Poly[0]->SetTitle(Title.c_str());
201  Poly[0]->SetMaximum(max*1.2);
202  Poly[0]->Draw("HIST");
203  for(int ik = 1; ik < static_cast<int>(sigmaArray.size()); ++ik)
204  {
205  Poly[ik]->Draw("HIST SAME");
206  }
207 
208  std::vector<double> Integral(sigmaArray.size());
209  for(int ik = 0; ik < static_cast<int>(sigmaArray.size()); ++ik)
210  Integral[ik] = Poly[ik]->Integral();
211 
212  auto leg = std::make_unique<TLegend>(0.55, 0.55, 0.8, 0.88);
213  leg->SetTextSize(0.04);
214  for (int j = 0; j < static_cast<int>(sigmaArray.size()); j++)
215  {
216  if(j == PriorKnot) {
217  leg->AddEntry(Poly[j].get(), Form("Prior (%.2f), #int=%.2f", DialValues[j], Integral[j]), "l");
218  } else {
219  leg->AddEntry(Poly[j].get(), Form("%.0f#sigma (%.2f), #int=%.2f", sigmaArray[j], DialValues[j], Integral[j]), "l");
220  }
221  }
222  leg->SetLineColor(0);
223  leg->SetLineStyle(0);
224  leg->SetFillColor(0);
225  leg->SetFillStyle(0);
226  leg->SetBorderSize(0);
227  leg->Draw("SAME");
228 
229  pad2->cd();
230 
231  auto line = std::make_unique<TLine>(Poly[0]->GetXaxis()->GetBinLowEdge(Poly[0]->GetXaxis()->GetFirst()), 1.0, Poly[0]->GetXaxis()->GetBinUpEdge(Poly[0]->GetXaxis()->GetLast()), 1.0);
232  std::vector<std::unique_ptr<TH1D>> Ratio(sigmaArray.size()-1);
233 
234  size_t ratio_index = 0; // Track position in Ratio vector
235  for (int i = 0; i < static_cast<int>(Poly.size()); ++i) {
236  if (i == PriorKnot) continue; // Skip PriorKnot
237  Ratio[ratio_index] = M3::Clone(Poly[i].get());
238  Ratio[ratio_index]->Divide(Poly[PriorKnot].get());
239  ratio_index++;
240  }
241 
242  Ratio[0]->GetYaxis()->SetTitle("Ratio to Prior");
243  Ratio[0]->SetBit(TH1D::kNoTitle);
244  Ratio[0]->GetXaxis()->SetTitleSize(0.12);
245  Ratio[0]->GetYaxis()->SetTitleOffset(0.4);
246  Ratio[0]->GetYaxis()->SetTitleSize(0.10);
247 
248  Ratio[0]->GetXaxis()->SetLabelSize(0.10);
249  Ratio[0]->GetYaxis()->SetLabelSize(0.10);
250 
251  Ratio[0]->SetBit(TH1D::kNoTitle);
252 
253  double maxz = -999;
254  double minz = +999;
255  for (int j = 0; j < static_cast<int>(sigmaArray.size())-1; j++)
256  {
257  for (int i = 1; i < Ratio[0]->GetXaxis()->GetNbins(); i++)
258  {
259  maxz = std::max(maxz, Ratio[j]->GetBinContent(i));
260  minz = std::min(minz, Ratio[j]->GetBinContent(i));
261  }
262  }
263  maxz = maxz*1.001;
264  minz = minz*1.001;
265 
266  if (std::fabs(1 - maxz) > std::fabs(1-minz))
267  Ratio[0]->GetYaxis()->SetRangeUser(1-std::fabs(1-maxz),1+std::fabs(1-maxz));
268  else
269  Ratio[0]->GetYaxis()->SetRangeUser(1-std::fabs(1-minz),1+std::fabs(1-minz));
270 
271  Ratio[0]->Draw("HIST");
272 
273  for(int ik = 1; ik < static_cast<int>(sigmaArray.size())-1; ++ik)
274  {
275  Ratio[ik]->Draw("HIST SAME");
276  }
277 
278  line->SetLineWidth(2);
279  line->SetLineColor(kBlack);
280  line->Draw("SAME");
281 
282  canv->Print((outfilename).c_str());
283 
284  delete pad1;
285  delete pad2;
286 }
TCanvas * canv
constexpr ELineStyle Style[NVars]
constexpr Color_t Colours[NVars]
std::vector< double > GetDialValues(const std::vector< std::unique_ptr< TH1D >> &Poly)
int PriorKnot

◆ ScanInput()

void ScanInput ( std::vector< std::string > &  DialNameVecr,
std::vector< std::string > &  SampleNameVec,
std::vector< double > &  SigmaValues,
const std::string &  filename 
)

Scan inputs to figure out dial name and used sample names.

Definition at line 24 of file PlotSigmaVariation.cpp.

28 {
29  MACH3LOG_DEBUG("Starting {}", __func__);
30  TFile *infile = TFile::Open(filename.c_str());
31  TDirectoryFile *SigmaDir = infile->Get<TDirectoryFile>("SigmaVar");
32 
33  //Get all entries in input file
34  TIter next(SigmaDir->GetListOfKeys());
35  TKey *key = nullptr;
36 
37  // Loop through all entries
38  while ((key = static_cast<TKey*>(next()))) {
39  // get directory names, ignore flux
40  auto classname = std::string(key->GetClassName());
41  auto dirname = std::string(key->GetName());
42 
43  if (classname != "TDirectoryFile") continue;
44  dirname = std::string(key->GetName());
45 
46  SigmaDir->cd(dirname.c_str());
47  TIter nextsub(gDirectory->GetListOfKeys());
48  TKey *subkey = nullptr;
49 
50  DialNameVecr.push_back(dirname);
51  MACH3LOG_DEBUG("Entering Dial {}", dirname);
52 
53  if(SampleNameVec.size() != 0) continue;
54  //loop over items in directory, hard code which th2poly we want
55  while ((subkey = static_cast<TKey*>(nextsub())))
56  {
57  auto subdirname = std::string(subkey->GetName());
58  SampleNameVec.push_back(subdirname);
59  MACH3LOG_DEBUG("Entering Sample {}", subdirname);
60 
61  if(SigmaValues.size() != 0) continue;
62  SigmaDir->cd((dirname + "/" + subdirname).c_str());
63 
64  TKey *subsubkey = nullptr;
65  TIter nextsubsub(gDirectory->GetListOfKeys());
66  while ((subsubkey = static_cast<TKey*>(nextsubsub())))
67  {
68  auto subsubdirname = std::string(subsubkey->GetTitle());
69  MACH3LOG_DEBUG("Entering Hist {}", subsubdirname);
70  std::string histname = subsubdirname;
71 
72  auto StripPrefix = [](std::string& str, const std::string& prefix) {
73  if (str.find(prefix + "_") == 0) {
74  str.erase(0, prefix.length() + 1);
75  if (str.find(prefix) == 0) {
76  MACH3LOG_ERROR("Failed to strip prefix '{}' from string '{}'", prefix, str);
77  throw MaCh3Exception(__FILE__, __LINE__);
78  }
79  } else {
80  MACH3LOG_ERROR("String '{}' does not start with expected prefix '{}'", str, prefix);
81  throw MaCh3Exception(__FILE__, __LINE__);
82  }
83  };
84  // Remove sample and dial name to avoid potential issues
85  StripPrefix(histname, subdirname);
86  StripPrefix(histname, dirname);
87 
88  MACH3LOG_DEBUG("Name afters striping {}", histname);
89 
90  double sigma = 0.0;
91  // Find the "_sig_" part in the name
92  size_t sig_pos = histname.find("_sig_");
93  // Extract the part after "_sig_"
94  std::string sigma_part = histname.substr(sig_pos + 5);
95 
96  // Check if it starts with 'n' (negative) or 'p' (positive) or 'nom' (0 or prior)
97  if (histname.find("nom_") != std::string::npos) {
98  sigma = 0.0;
99  PriorKnot = static_cast<int>(SigmaValues.size());
100  MACH3LOG_DEBUG("Found prior knot {}", PriorKnot);
101  } else if (sigma_part.size() > 0 && sigma_part[0] == 'n') {
102  sigma = -std::stod(sigma_part.substr(1));
103  } else if (sigma_part.size() > 0 && sigma_part[0] == 'p') {
104  sigma = std::stod(sigma_part.substr(1));
105  } else {
106  MACH3LOG_ERROR("Weirdly formatted string {}", sigma_part);
107  throw MaCh3Exception(__FILE__ , __LINE__ );
108  }
109  MACH3LOG_DEBUG("Adding sigma {}", sigma);
110 
111  SigmaValues.push_back(sigma);
112  }
113  }
114  }
115 
116  if(PriorKnot == M3::_BAD_INT_){
117  MACH3LOG_ERROR("Didn't find prior knot, something is not right...");
118  throw MaCh3Exception(__FILE__ , __LINE__ );
119  }
120 
121  if(sigmaArray.size() < NVars){
122  MACH3LOG_ERROR("Found sigma {}, while I have some hardcoding for {}",sigmaArray.size(), NVars);
123  throw MaCh3Exception(__FILE__ , __LINE__ );
124  }
125 
126  infile->Close();
127  delete infile;
128 }
constexpr const int NVars
constexpr static const int _BAD_INT_
Default value used for int initialisation.
Definition: Core.h:48

◆ SkipDirectory()

bool SkipDirectory ( const std::vector< std::string > &  ExcludeString,
const std::vector< std::string > &  IncludeString,
const std::string &  dirname 
)

Check whether to skip directory or not based on defined strings.

Definition at line 131 of file PlotSigmaVariation.cpp.

132 {
133  bool Skip = false;
134  for(unsigned int i = 0; i < ExcludeString.size(); i++)
135  {
136  if (dirname.find(ExcludeString[i]) != std::string::npos){ Skip = true; break; }
137  }
138  for(unsigned int i = 0; i < IncludeString.size(); i++)
139  {
140  if (!(dirname.find(IncludeString[i]) != std::string::npos)){ Skip = true; break; }
141  }
142  return Skip;
143 }

Variable Documentation

◆ Colours

constexpr Color_t Colours[NVars] = {kRed, kGreen+1, kBlack, kBlue+1, kOrange+1}
constexpr

Definition at line 20 of file PlotSigmaVariation.cpp.

◆ DialNameVector

std::vector<std::string> DialNameVector

Definition at line 13 of file PlotSigmaVariation.cpp.

◆ NVars

constexpr const int NVars = 5
constexpr

Definition at line 19 of file PlotSigmaVariation.cpp.

◆ PriorKnot

int PriorKnot = M3::_BAD_INT_

Definition at line 17 of file PlotSigmaVariation.cpp.

◆ SampleNameVector

std::vector<std::string> SampleNameVector

Definition at line 14 of file PlotSigmaVariation.cpp.

◆ sigmaArray

std::vector<double> sigmaArray

Definition at line 15 of file PlotSigmaVariation.cpp.

◆ Style

constexpr ELineStyle Style[NVars] = {kDotted, kDashed, kSolid, kDashDotted, kDashDotted}
constexpr

Definition at line 21 of file PlotSigmaVariation.cpp.