MaCh3  2.8.0
Reference Guide
ProcessMCMCModule.cpp
Go to the documentation of this file.
1 
4 //MaCh3 includes
6 #include "Manager/Manager.h"
8 
9 namespace M3{
11 
13  m_parser = std::make_unique<MaCh3ArgumentParser>("process", "1.0", argparse::default_arguments::help);
14  m_parser->add_description("Main executable responsible for different types of MCMC processing like drawing posteriors, triangle plots etc.");
15  m_parser->add_epilog("""\
16  ProcessMCMC The main application for analysing the ND280 chain.\n\
17  It prints posterior distributions after the burn-in cut and allows comparison of two or three different chains.\n\
18  Several options can be configured directly in the app, such as selection, burn-in cut, and whether to plot xsec+flux or only flux.\n\
19  \n\
20  Additional functionality includes:\n\
21  Produce a covariance matrix with multithreading (RAM intensive due to caching)\n\
22  Violin plots\n\
23  Credible intervals and regions\n\
24  Calculation of Bayes factors with significance based on the Jeffreys scale\n\
25  Triangle plots\n\
26  Study of covariance matrix stability\n""");
27  m_parser->add_argument("--corr")
28  .help("Enable plotting correlations and 2D posterior")
29  .flag();
30  m_parser->add_argument("--MakeCredibleIntervals")
31  .help("Produce Credible intervals (requires --corr)")
32  .flag();
33  m_parser->add_argument("--CalcBayesFactor")
34  .help("Calculate Bayes Factor")
35  .flag();
36  m_parser->add_argument("--CalcSavageDickey")
37  .help("Calculate Bayes Factor using Savage-Dickey")
38  .flag();
39  m_parser->add_argument("--CalcBipolarPlot")
40  .help("Calculate Bipolar plots")
41  .flag();
42  m_parser->add_argument("--CalcParameterEvolution")
43  .help("Produce Parameter Evolution .gif")
44  .flag();
45  m_parser->add_argument("config")
46  .help("Config file.")
47  .metavar("CONFIG")
48  .required();
49  m_parser->add_argument("mcmc-chain")
50  .help("MCMC chain root files and titles.\n"
51  "single chain mode: MCMC_CHAIN1\n"
52  "two chain mode : MCMC_CHAIN1 TITLE1 MCMC_CHAIN2 TITLE2\n"
53  "three chain mode : MCMC_CHAIN1 TITLE1 MCMC_CHAIN2 TITLE2 MCMC_CHAIN3 TITLE3")
54  .metavar("MCMC_CHAIN1 [TITLE1 MCMC_CHAIN2 TITLE2 [MCMC_CHAIN3 TITLE3]]")
55  .nargs(1, 6)
56  .required();
57  return m_parser.get();
58 }
59 
62  nFiles = 0;
63  config = m_parser->get<std::string>("config");
64  auto mcmc_chain_args = m_parser->get<std::vector<std::string>>("mcmc-chain");
65 
66  int nargs = static_cast<int>(mcmc_chain_args.size());
67  if (nargs != 1 && nargs !=4 && nargs != 6)
68  {
69  MACH3LOG_ERROR("invalid number of arguments: {}", nargs);
70  std::cerr << *m_parser;
71  MACH3LOG_ERROR("invalid number of arguments: {}", nargs);
72  throw MaCh3Exception(__FILE__ , __LINE__ );
73  }
74 
75  YAML::Node card_yaml = M3OpenConfig(config);
76  if (!CheckNodeExists(card_yaml, "ProcessMCMC")) {
77  MACH3LOG_ERROR("The 'ProcessMCMC' node is not defined in the YAML configuration.");
78  throw MaCh3Exception(__FILE__ , __LINE__ );
79  }
80 
81  if (mcmc_chain_args.size() == 1)
82  {
83  MACH3LOG_INFO("Producing single fit output");
84  std::string filename = mcmc_chain_args[0];
85  this->ProcessMCMC(filename);
86  }
87  // If we want to compare two or more fits (e.g. binning changes or introducing new params/priors)
88  else if (mcmc_chain_args.size() > 1)
89  {
90  for (std::size_t i = 0; i < mcmc_chain_args.size(); i += 2) {
91  FileNames.push_back(mcmc_chain_args[i]);
92  TitleNames.push_back(mcmc_chain_args[i + 1]);
93  }
94  this->MultipleProcessMCMC();
95  }
96  return 0;
97 }
98 
113 std::map<std::string, std::pair<double, double>> ProcessMCMCModule::GetCustomBinning(const YAML::Node& Settings)
114 {
115  std::map<std::string, std::pair<double, double>> CustomBinning;
116  if (Settings["CustomBinEdges"]) {
117  const YAML::Node& edges = Settings["CustomBinEdges"];
118 
119  for (const auto& node : edges) {
120  std::string key = node.first.as<std::string>();
121  auto values = node.second.as<std::vector<double>>();
122 
123  if (values.size() == 2) {
124  CustomBinning[key] = std::make_pair(values[0], values[1]);
125  MACH3LOG_DEBUG("Adding custom binning {} with {:.4f}, {:.4f}", key, values[0], values[1]);
126  } else {
127  MACH3LOG_ERROR("Invalid number of values for key: {}", key);
128  throw MaCh3Exception(__FILE__ , __LINE__ );
129  }
130  }
131  }
132  return CustomBinning;
133 }
134 
142 void ProcessMCMCModule::ProcessMCMC(const std::string& inputFile)
143 {
144  MACH3LOG_INFO("File for study: {} with config {}", inputFile, config);
145  // Make the processor)
146  auto Processor = std::make_unique<OscProcessor>(inputFile);
147 
148  YAML::Node card_yaml = M3OpenConfig(config.c_str());
149  YAML::Node Settings = card_yaml["ProcessMCMC"];
150 
151  const bool PlotCorr = m_parser->get<bool>("--corr") || GetFromManager<bool>(Settings["PlotCorr"], false, __FILE__, __LINE__);
152 
153  Processor->SetExcludedTypes(GetFromManager<std::vector<std::string>>(Settings["ExcludedTypes"], {}, __FILE__, __LINE__));
154  Processor->SetExcludedNames(GetFromManager<std::vector<std::string>>(Settings["ExcludedNames"], {}, __FILE__, __LINE__));
155  Processor->SetExcludedGroups(GetFromManager<std::vector<std::string>>(Settings["ExcludedGroups"], {}, __FILE__, __LINE__));
156 
157  //Apply additional cuts to 1D posterior
158  Processor->SetPosterior1DCut(GetFromManager<std::string>(Settings["Posterior1DCut"], "", __FILE__, __LINE__));
159 
160  if(PlotCorr) Processor->SetOutputSuffix("_drawCorr");
161  //KS:Turn off plotting detector and some other setting, should be via some config
162  Processor->SetPlotRelativeToPrior(GetFromManager<bool>(Settings["PlotRelativeToPrior"], false, __FILE__, __LINE__));
163  Processor->SetPrintToPDF(GetFromManager<bool>(Settings["PrintToPDF"], true, __FILE__, __LINE__));
164 
165  //KS: Whether you want prior error bands for parameters with flat prior or not
166  Processor->SetPlotErrorForFlatPrior(GetFromManager<bool>(Settings["PlotErrorForFlatPrior"], true, __FILE__, __LINE__));
167  Processor->SetFancyNames(GetFromManager<bool>(Settings["FancyNames"], true, __FILE__, __LINE__));
168  Processor->SetPlotBinValue(GetFromManager<bool>(Settings["PlotBinValue"], false, __FILE__, __LINE__));
169  //KS: Plot only 2D posteriors with correlations greater than 0.2
170  Processor->SetPost2DPlotThreshold(GetFromManager<double>(Settings["Post2DPlotThreshold"], 0.2, __FILE__, __LINE__));
171  // Weight to be considered
172  Processor->SetReweightNames(GetFromManager<std::vector<std::string>>(Settings["WeightNames"], {"Weight"}, __FILE__, __LINE__));
173 
174  Processor->Initialise();
175 
176  if(Settings["BurnInSteps"]) {
177  Processor->SetStepCut(Settings["BurnInSteps"].as<int>());
178  } else {
179  MACH3LOG_WARN("BurnInSteps not set, defaulting to 20%");
180  Processor->SetStepCut(static_cast<int>(Processor->GetnSteps()/5));
181  }
182  if(Settings["MaxEntries"]) {
183  Processor->SetEntries(Get<int>(Settings["MaxEntries"], __FILE__, __LINE__));
184  }
185  if(Settings["NBins"]) {
186  Processor->SetNBins(Get<int>(Settings["NBins"], __FILE__, __LINE__));
187  }
188  if(Settings["Thinning"])
189  {
190  if(Settings["Thinning"][0].as<bool>()){
191  Processor->ThinMCMC(Settings["Thinning"][1].as<int>());
192  }
193  }
194  // Make the postfit
195  Processor->MakePostfit(this->GetCustomBinning(Settings));
196  Processor->DrawPostfit();
197  //KS: Should set via config whether you want below or not
198  if(m_parser->get<bool>("--MakeCredibleIntervals") || GetFromManager<bool>(Settings["MakeCredibleIntervals"], true, __FILE__, __LINE__)) {
199  Processor->MakeCredibleIntervals(GetFromManager<std::vector<double>>(Settings["CredibleIntervals"], {0.99, 0.90, 0.68}, __FILE__, __LINE__),
200  GetFromManager<std::vector<short int>>(Settings["CredibleIntervalsColours"], {436, 430, 422}, __FILE__, __LINE__),
201  GetFromManager<bool>(Settings["CredibleInSigmas"], false, __FILE__, __LINE__));
202  }
203  if(m_parser->get<bool>("--CalcBayesFactor") || GetFromManager<bool>(Settings["CalcBayesFactor"], true, __FILE__, __LINE__)) this->CalcBayesFactor(Processor.get());
204  if(m_parser->get<bool>("--CalcSavageDickey") || GetFromManager<bool>(Settings["CalcSavageDickey"], true, __FILE__, __LINE__)) this->CalcSavageDickey(Processor.get());
205  if(m_parser->get<bool>("--CalcBipolarPlot") || GetFromManager<bool>(Settings["CalcBipolarPlot"], false, __FILE__, __LINE__)) this->CalcBipolarPlot(Processor.get());
206  if(m_parser->get<bool>("--CalcParameterEvolution") || GetFromManager<bool>(Settings["CalcParameterEvolution"], false, __FILE__, __LINE__)) this->CalcParameterEvolution(Processor.get());
207 
208  if(PlotCorr)
209  {
210  Processor->SetSmoothing(GetFromManager<bool>(Settings["Smoothing"], true, __FILE__, __LINE__));
211  //KS: Since we cached let's make fancy violins :)
212  if(GetFromManager<bool>(Settings["MakeViolin"], true, __FILE__, __LINE__)) Processor->MakeViolin();
213  Processor->MakeCovariance();
214 
215  Processor->DrawCovariance();
216  if(GetFromManager<bool>(Settings["MakeCovarianceYAML"], true, __FILE__, __LINE__)) Processor->MakeCovarianceYAML(GetFromManager<std::string>(Settings["CovarianceYAMLOutName"], "UpdatedCorrelationMatrix.yaml", __FILE__, __LINE__), GetFromManager<std::string>(Settings["CovarianceYAMLMeansMethod"], "HPD", __FILE__, __LINE__));
217 
218  auto const &MakeSubOptimality = Settings["MakeSubOptimality"];
219  if(MakeSubOptimality[0].as<bool>()) Processor->MakeSubOptimality(MakeSubOptimality[1].as<int>());
220 
221  if(GetFromManager<bool>(Settings["MakeCredibleRegions"], false, __FILE__, __LINE__)) {
222  Processor->MakeCredibleRegions(GetFromManager<std::vector<double>>(Settings["CredibleRegions"], {0.99, 0.90, 0.68}, __FILE__, __LINE__),
223  GetFromManager<std::vector<short int>>(Settings["CredibleRegionStyle"], {2, 1, 3}, __FILE__, __LINE__),
224  GetFromManager<std::vector<short int>>(Settings["CredibleRegionColor"], {413, 406, 416}, __FILE__, __LINE__),
225  GetFromManager<bool>(Settings["CredibleInSigmas"], false, __FILE__, __LINE__),
226  GetFromManager<bool>(Settings["Draw2DPosterior"], true, __FILE__, __LINE__),
227  GetFromManager<bool>(Settings["DrawBestFit"], true, __FILE__, __LINE__));
228  }
229  if(GetFromManager<bool>(Settings["GetTrianglePlot"], true, __FILE__, __LINE__)) this->GetTrianglePlot(Processor.get());
230 
231  //KS: When creating covariance matrix longest time is spend on caching every step, since we already cached we can run some fancy covariance stability diagnostic
232  if(GetFromManager<bool>(Settings["DiagnoseCovarianceMatrix"], false, __FILE__, __LINE__)) this->DiagnoseCovarianceMatrix(Processor.get(), inputFile);
233  }
234  Processor->ProduceChi2(GetFromManager<std::string>(Settings["Chi2Group"], "Osc", __FILE__, __LINE__));
235  if(GetFromManager<bool>(Settings["JarlskogAnalysis"], true, __FILE__, __LINE__)) Processor->PerformJarlskogAnalysis();
236  if(GetFromManager<bool>(Settings["ProducePMNSElements"], true, __FILE__, __LINE__)) Processor->ProducePMNSElements();
237  if(GetFromManager<bool>(Settings["ProduceUnitarityTriangles"], true, __FILE__, __LINE__)) Processor->ProduceUnitarityTriangles();
238  if(GetFromManager<bool>(Settings["MakePiePlot"], true, __FILE__, __LINE__)) Processor->MakePiePlot();
239 }
240 
247 {
248  YAML::Node card_yaml = M3OpenConfig(config.c_str());
249  YAML::Node Settings = card_yaml["ProcessMCMC"];
250 
251  constexpr Color_t PosteriorColor[] = {kBlue-1, kRed, kGreen+2};
252  //constexpr Style_t PosteriorStyle[] = {kSolid, kDashed, kDotted};
253  nFiles = int(FileNames.size());
254  std::vector<std::unique_ptr<MCMCProcessor>> Processor(nFiles);
255 
256  if(!Settings["BurnInSteps"]) {
257  MACH3LOG_WARN("BurnInSteps not set, defaulting to 20%");
258  }
259 
260  for (int ik = 0; ik < nFiles; ik++)
261  {
262  MACH3LOG_INFO("File for study: {}", FileNames[ik]);
263  // Make the processor
264  Processor[ik] = std::make_unique<MCMCProcessor>(FileNames[ik]);
265  Processor[ik]->SetOutputSuffix(("_" + std::to_string(ik)).c_str());
266 
267  Processor[ik]->SetExcludedTypes(GetFromManager<std::vector<std::string>>(Settings["ExcludedTypes"], {}, __FILE__, __LINE__));
268  Processor[ik]->SetExcludedNames(GetFromManager<std::vector<std::string>>(Settings["ExcludedNames"], {}, __FILE__, __LINE__));
269  Processor[ik]->SetExcludedGroups(GetFromManager<std::vector<std::string>>(Settings["ExcludedGroups"], {}, __FILE__, __LINE__));
270 
271  //Apply additional cuts to 1D posterior
272  Processor[ik]->SetPosterior1DCut(GetFromManager<std::string>(Settings["Posterior1DCut"], "", __FILE__, __LINE__));
273 
274  Processor[ik]->SetPlotRelativeToPrior(GetFromManager<bool>(Settings["PlotRelativeToPrior"], false, __FILE__, __LINE__));
275  Processor[ik]->SetFancyNames(GetFromManager<bool>(Settings["FancyNames"], true, __FILE__, __LINE__));
276 
277  // Weight to be considered
278  Processor[ik]->SetReweightNames(GetFromManager<std::vector<std::string>>(Settings["WeightNames"], {"Weight"}, __FILE__, __LINE__));
279  Processor[ik]->Initialise();
280 
281  if(Settings["BurnInSteps"]) {
282  Processor[ik]->SetStepCut(Settings["BurnInSteps"].as<int>());
283  }else {
284  Processor[ik]->SetStepCut(static_cast<int>(Processor[ik]->GetnSteps()/5));
285  }
286 
287  if(Settings["MaxEntries"]) {
288  Processor[ik]->SetEntries(Get<int>(Settings["MaxEntries"], __FILE__, __LINE__));
289  }
290  if(Settings["NBins"]) {
291  Processor[ik]->SetNBins(Get<int>(Settings["NBins"], __FILE__, __LINE__));
292  }
293  }
294 
295  Processor[0]->MakePostfit(this->GetCustomBinning(Settings));
296  Processor[0]->DrawPostfit();
297  // Get edges from first histogram to ensure all params use same binning
298  std::map<std::string, std::pair<double, double>> ParamEdges;
299  for(int i = 0; i < Processor[0]->GetNParams(); ++i) {
300  // Get the histogram for the i-th parameter
301  const auto& hist = Processor[0]->GetHpost(i);
302  if (!hist) {
303  MACH3LOG_DEBUG("Histogram for parameter {} is null.", i);
304  continue;
305  }
306 
307  // Get the parameter name (title of the histogram)
308  std::string paramName = hist->GetTitle();
309 
310  // Get the axis limits (edges)
311  TAxis* axis = hist->GetXaxis();
312  double xmin = axis->GetXmin();
313  double xmax = axis->GetXmax();
314 
315  MACH3LOG_DEBUG("Adding bin edges for {} equal to {:.4f}, {:.4f}",paramName, xmin, xmax);
316  // Insert into the map
317  ParamEdges[paramName] = std::make_pair(xmin, xmax);
318  }
319 
320  //KS: Multithreading here is very tempting but there are some issues with root that need to be resovled :(
321  for (int ik = 1; ik < nFiles; ik++)
322  {
323  // Make the postfit
324  Processor[ik]->MakePostfit(ParamEdges);
325  Processor[ik]->DrawPostfit();
326  }
327 
328  // Open a TCanvas to write the posterior onto
329  auto Posterior = std::make_unique<TCanvas>("PosteriorMulti", "PosteriorMulti", 0, 0, 1024, 1024);
330  gStyle->SetOptStat(0);
331  gStyle->SetOptTitle(0);
332  Posterior->SetGrid();
333  Posterior->SetBottomMargin(0.1f);
334  Posterior->SetTopMargin(0.05f);
335  Posterior->SetRightMargin(0.03f);
336  Posterior->SetLeftMargin(0.15f);
337 
338  // First filename: keep path, just remove ".root"
339  // Would be nice to specify outpath in a later update
340  size_t pos = FileNames[0].rfind(".root");
341  std::string base = (pos == std::string::npos) ? FileNames[0] : FileNames[0].substr(0, pos);
342  TString canvasname = base;
343 
344  // Remaining filenames: strip path and ".root"
345  // So if you have /path/to/file1.root and /path/to/file2.root or /another/path/to/file2.root, canvasname = /path/to/file1_file2.root
346  for (int ik = 1; ik < nFiles; ik++) {
347  pos = FileNames[ik].find_last_of('/');
348  base = (pos == std::string::npos) ? FileNames[ik] : FileNames[ik].substr(pos + 1);
349  pos = base.rfind(".root");
350  if (pos != std::string::npos) base = base.substr(0, pos);
351  canvasname += "_" + TString(base);
352  }
353 
354  canvasname = canvasname +".pdf[";
355 
356  Posterior->Print(canvasname);
357  // Once the pdf file is open no longer need to bracket
358  canvasname.ReplaceAll("[","");
359 
360  for(int i = 0; i < Processor[0]->GetNParams(); ++i)
361  {
362  // This holds the posterior density
363  std::vector<std::unique_ptr<TH1D>> hpost(nFiles);
364  std::vector<std::unique_ptr<TLine>> hpd(nFiles);
365  hpost[0] = M3::Clone(Processor[0]->GetHpost(i));
366  hpost[0]->GetYaxis()->SetTitle("Posterior Density");
367  bool Skip = false;
368  for (int ik = 1 ; ik < nFiles; ik++)
369  {
370  // KS: If somehow this chain doesn't given params we skip it
371  const int Index = Processor[ik]->GetParamIndexFromName(hpost[0]->GetTitle());
372  if(Index == M3::_BAD_INT_)
373  {
374  Skip = true;
375  break;
376  }
377  hpost[ik] = M3::Clone(Processor[ik]->GetHpost(Index));
378  }
379 
380  // Don't plot if this is a fixed histogram (i.e. the peak is the whole integral)
381  if(hpost[0]->GetMaximum() == hpost[0]->Integral()*1.5 || Skip) {
382  continue;
383  }
384  for (int ik = 0; ik < nFiles; ik++)
385  {
386  RemoveFitter(hpost[ik].get(), "Gauss");
387 
388  // Set some nice colours
389  hpost[ik]->SetLineColor(PosteriorColor[ik]);
390  //hpost[ik]->SetLineStyle(PosteriorStyle[ik]);
391  hpost[ik]->SetLineWidth(2);
392 
393  // Area normalise the distributions
394  hpost[ik]->Scale(1./hpost[ik]->Integral());
395  }
396  TString Title;
397  double Prior = 1.0;
398  double PriorError = 1.0;
399 
400  Processor[0]->GetNthParameter(i, Prior, PriorError, Title);
401 
402  // Now make the TLine for the Asimov
403  auto Asimov = std::make_unique<TLine>(Prior, hpost[0]->GetMinimum(), Prior, hpost[0]->GetMaximum());
404  Asimov->SetLineColor(kRed-3);
405  Asimov->SetLineWidth(2);
406  Asimov->SetLineStyle(kDashed);
407 
408  // Make a nice little TLegend
409  auto leg = std::make_unique<TLegend>(0.20, 0.7, 0.6, 0.97);
410  leg->SetTextSize(0.03f);
411  leg->SetFillColor(0);
412  leg->SetFillStyle(0);
413  leg->SetLineColor(0);
414  leg->SetLineStyle(0);
415  TString asimovLeg = Form("#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError);
416  leg->AddEntry(Asimov.get(), asimovLeg, "l");
417 
418  for (int ik = 0; ik < nFiles; ik++)
419  {
420  TString rebinLeg = Form("#splitline{%s}{#mu = %.2f, #sigma = %.2f}", TitleNames[ik].c_str(), hpost[ik]->GetMean(), hpost[ik]->GetRMS());
421  leg->AddEntry(hpost[ik].get(), rebinLeg, "l");
422 
423  hpd[ik] = std::make_unique<TLine>(hpost[ik]->GetBinCenter(hpost[ik]->GetMaximumBin()), hpost[ik]->GetMinimum(),
424  hpost[ik]->GetBinCenter(hpost[ik]->GetMaximumBin()), hpost[ik]->GetMaximum());
425  hpd[ik]->SetLineColor(hpost[ik]->GetLineColor());
426  hpd[ik]->SetLineWidth(2);
427  hpd[ik]->SetLineStyle(kSolid);
428  }
429 
430  // Find the maximum value to nicely resize hist
431  double maximum = 0;
432  for (int ik = 0; ik < nFiles; ik++) maximum = std::max(maximum, hpost[ik]->GetMaximum());
433  for (int ik = 0; ik < nFiles; ik++) hpost[ik]->SetMaximum(1.3*maximum);
434 
435  hpost[0]->Draw("hist");
436  for (int ik = 1; ik < nFiles; ik++) hpost[ik]->Draw("hist same");
437  Asimov->Draw("same");
438  for (int ik = 0; ik < nFiles; ik++) hpd[ik]->Draw("same");
439  leg->Draw("same");
440  Posterior->cd();
441  Posterior->Print(canvasname);
442  }//End loop over parameters
443 
444  // Finally draw the parameter plot onto the PDF
445  // Close the .pdf file with all the posteriors
446  Posterior->cd();
447  Posterior->Clear();
448 
449  if(GetFromManager<bool>(Settings["PerformKStest"], true, __FILE__, __LINE__)) this->KolmogorovSmirnovTest(Processor, Posterior, canvasname);
450 
451  // Close the pdf file
452  MACH3LOG_INFO("Closing pdf {}", canvasname);
453  canvasname+="]";
454  Posterior->Print(canvasname);
455 }
456 
465 {
466  YAML::Node card_yaml = M3OpenConfig(config.c_str());
467  YAML::Node Settings = card_yaml["ProcessMCMC"];
468 
469  std::vector<std::string> ParNames;
470  std::vector<std::vector<double>> Model1Bounds;
471  std::vector<std::vector<double>> Model2Bounds;
472  std::vector<std::vector<std::string>> ModelNames;
473  for (const auto& dg : Settings["BayesFactor"])
474  {
475  ParNames.push_back(dg[0].as<std::string>());
476  ModelNames.push_back(dg[1].as<std::vector<std::string>>());
477  Model1Bounds.push_back(dg[2].as<std::vector<double>>());
478  Model2Bounds.push_back(dg[3].as<std::vector<double>>());
479  }
480 
481  Processor->GetBayesFactor(ParNames, Model1Bounds, Model2Bounds, ModelNames);
482 }
483 
492 {
493  YAML::Node card_yaml = M3OpenConfig(config.c_str());
494  YAML::Node Settings = card_yaml["ProcessMCMC"];
495 
496  std::vector<std::string> ParNames;
497  std::vector<double> EvaluationPoint;
498  std::vector<std::vector<double>> Bounds;
499 
500  for (const auto& d : Settings["SavageDickey"])
501  {
502  ParNames.push_back(d[0].as<std::string>());
503  EvaluationPoint.push_back(d[1].as<double>());
504  Bounds.push_back(d[2].as<std::vector<double>>());
505  }
506  Processor->GetSavageDickey(ParNames, EvaluationPoint, Bounds);
507 }
508 
517 {
518  YAML::Node card_yaml = M3OpenConfig(config.c_str());
519  YAML::Node Settings = card_yaml["ProcessMCMC"];
520 
521  std::vector<std::string> ParNames;
522  std::vector<int> Intervals;
523  for (const auto& d : Settings["ParameterEvolution"])
524  {
525  ParNames.push_back(d[0].as<std::string>());
526  Intervals.push_back(d[1].as<int>());
527  }
528  Processor->ParameterEvolution(ParNames, Intervals);
529 }
530 
539 {
540  YAML::Node card_yaml = M3OpenConfig(config.c_str());
541  YAML::Node Settings = card_yaml["ProcessMCMC"];
542 
543  std::vector<std::string> ParNames;
544  for (const auto& d : Settings["BipolarPlot"])
545  {
546  ParNames.push_back(d[0].as<std::string>());
547  }
548  Processor->GetPolarPlot(ParNames);
549 }
550 
559  YAML::Node card_yaml = M3OpenConfig(config.c_str());
560  YAML::Node Settings = card_yaml["ProcessMCMC"];
561 
562  for (const auto& dg : Settings["TrianglePlot"])
563  {
564  std::string ParName = dg[0].as<std::string>();
565 
566  std::vector<std::string> NameVec = dg[1].as<std::vector<std::string>>();
567  Processor->MakeTrianglePlot(NameVec,
568  GetFromManager<std::vector<double>>(Settings["CredibleIntervals"], {0.99, 0.90, 0.68}, __FILE__, __LINE__),
569  GetFromManager<std::vector<short int>>(Settings["CredibleIntervalsColours"], {436, 430, 422}, __FILE__, __LINE__),
570  GetFromManager<std::vector<double>>(Settings["CredibleRegions"], {0.99, 0.90, 0.68}, __FILE__, __LINE__),
571  GetFromManager<std::vector<short int>>(Settings["CredibleRegionStyle"], {2, 1, 3}, __FILE__, __LINE__),
572  GetFromManager<std::vector<short int>>(Settings["CredibleRegionColor"], {413, 406, 416}, __FILE__, __LINE__),
573  GetFromManager<bool>(Settings["CredibleInSigmas"], false, __FILE__, __LINE__));
574  }
575 }
576 
585 void ProcessMCMCModule::DiagnoseCovarianceMatrix(MCMCProcessor* Processor, const std::string& inputFile)
586 {
587  //Turn of plots from Processor
588  Processor->SetPrintToPDF(false);
589  // Open a TCanvas to write the posterior onto
590  auto Canvas = std::make_unique<TCanvas>("Canvas", "Canvas", 0, 0, 1024, 1024);
591  Canvas->SetGrid();
592  gStyle->SetOptStat(0);
593  gStyle->SetOptTitle(0);
594  Canvas->SetTickx();
595  Canvas->SetTicky();
596  Canvas->SetBottomMargin(0.1f);
597  Canvas->SetTopMargin(0.05f);
598  Canvas->SetRightMargin(0.15f);
599  Canvas->SetLeftMargin(0.10f);
600 
601  //KS: Fancy colours
602  const int NRGBs = 10;
603  TColor::InitializeColors();
604  Double_t stops[NRGBs] = { 0.00, 0.10, 0.25, 0.35, 0.50, 0.60, 0.65, 0.75, 0.90, 1.00 };
605  Double_t red[NRGBs] = { 0.50, 1.00, 1.00, 0.25, 0.00, 0.10, 0.50, 1.00, 0.75, 0.55 };
606  Double_t green[NRGBs] = { 0.00, 0.25, 1.00, 0.25, 0.00, 0.60, 0.90, 1.00, 0.75, 0.75 };
607  Double_t blue[NRGBs] = { 0.00, 0.25, 1.00, 1.00, 0.50, 0.60, 0.90, 1.00, 0.05, 0.05 };
608  TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, 255);
609  gStyle->SetNumberContours(255);
610 
611  std::string OutName = inputFile;
612  OutName = OutName.substr(0, OutName.find(".root"));
613  Canvas->Print(Form("Correlation_%s.pdf[", OutName.c_str()), "pdf");
614  Canvas->Print(Form("Covariance_%s.pdf[", OutName.c_str()), "pdf");
615 
616  YAML::Node card_yaml = M3OpenConfig(config.c_str());
617  YAML::Node Settings = card_yaml["ProcessMCMC"];
618 
619  const int entries = int(Processor->GetnSteps());
620  const int NIntervals = GetFromManager<int>(Settings["NIntervals"], 5, __FILE__, __LINE__);
621  const int IntervalsSize = entries/NIntervals;
622  //We start with burn from 0 (no burn in at all)
623  int BurnIn = 0;
624  MACH3LOG_INFO("Diagnosing matrices with entries={}, NIntervals={} and IntervalsSize={}", entries, NIntervals, IntervalsSize);
625 
626  TMatrixDSym *Covariance = nullptr;
627  TMatrixDSym *Correlation = nullptr;
628 
629  TH2D *CovariancePreviousHist = nullptr;
630  TH2D *CorrelationPreviousHist = nullptr;
631 
632  TH2D *CovarianceHist = nullptr;
633  TH2D *CorrelationHist = nullptr;
634 
635  //KS: Get first covariances, we need two for comparison...
636  Processor->SetStepCut(BurnIn);
637  Processor->GetCovariance(Covariance, Correlation);
638 
639  CovariancePreviousHist = this->TMatrixIntoTH2D(Covariance, "Covariance");
640  CorrelationPreviousHist = this->TMatrixIntoTH2D(Correlation, "Correlation");
641 
642  delete Covariance;
643  Covariance = nullptr;
644  delete Correlation;
645  Correlation = nullptr;
646 
647  //KS: Loop over all desired cuts
648  for(int k = 1; k < NIntervals; ++k)
649  {
650  BurnIn = k*IntervalsSize;
651  Processor->SetStepCut(BurnIn);
652  Processor->GetCovariance(Covariance, Correlation);
653  Processor->Reset2DPosteriors();
654 
655  CovarianceHist = this->TMatrixIntoTH2D(Covariance, "Covariance");
656  CorrelationHist = this->TMatrixIntoTH2D(Correlation, "Correlation");
657 
658  TH2D *CovarianceDiff = static_cast<TH2D*>(CovarianceHist->Clone("Covariance_Ratio"));
659  TH2D *CorrelationDiff = static_cast<TH2D*>(CorrelationHist->Clone("Correlation_Ratio"));
660 
661  //KS: Bit messy but quite often covariance is 0 is divided by 0 is problematic so
662  #ifdef MULTITHREAD
663  #pragma omp parallel for
664  #endif
665  for (int j = 1; j < CovarianceDiff->GetXaxis()->GetNbins()+1; ++j)
666  {
667  for (int i = 1; i < CovarianceDiff->GetYaxis()->GetNbins()+1; ++i)
668  {
669  if( std::fabs (CovarianceDiff->GetBinContent(j, i)) < 1.e-5 && std::fabs (CovariancePreviousHist->GetBinContent(j, i)) < 1.e-5)
670  {
671  CovarianceDiff->SetBinContent(j, i, M3::_BAD_DOUBLE_);
672  CovariancePreviousHist->SetBinContent(j, i, M3::_BAD_DOUBLE_);
673  }
674  if( std::fabs (CorrelationDiff->GetBinContent(j, i)) < 1.e-5 && std::fabs (CorrelationPreviousHist->GetBinContent(j, i)) < 1.e-5)
675  {
676  CorrelationDiff->SetBinContent(j, i, M3::_BAD_DOUBLE_);
677  CorrelationPreviousHist->SetBinContent(j, i, M3::_BAD_DOUBLE_);
678  }
679  }
680  }
681  //Divide matrices
682  CovarianceDiff->Divide(CovariancePreviousHist);
683  CorrelationDiff->Divide(CorrelationPreviousHist);
684 
685  //Now it is time for fancy names etc.
686  for (int j = 0; j < CovarianceDiff->GetXaxis()->GetNbins(); ++j)
687  {
688  TString Title = "";
689  double Prior = 1.0;
690  double PriorError = 1.0;
691 
692  Processor->GetNthParameter(j, Prior, PriorError, Title);
693 
694  CovarianceDiff->GetXaxis()->SetBinLabel(j+1, Title);
695  CovarianceDiff->GetYaxis()->SetBinLabel(j+1, Title);
696  CorrelationDiff->GetXaxis()->SetBinLabel(j+1, Title);
697  CorrelationDiff->GetYaxis()->SetBinLabel(j+1, Title);
698  }
699  CovarianceDiff->GetXaxis()->SetLabelSize(0.015f);
700  CovarianceDiff->GetYaxis()->SetLabelSize(0.015f);
701  CorrelationDiff->GetXaxis()->SetLabelSize(0.015f);
702  CorrelationDiff->GetYaxis()->SetLabelSize(0.015f);
703 
704  std::stringstream ss;
705  ss << "BCut_";
706  ss << BurnIn;
707  ss << "/";
708  ss << "BCut_";
709  ss << (k-1)*IntervalsSize;
710  std::string str = ss.str();
711 
712  TString Title = "Cov " + str;
713  CovarianceDiff->GetZaxis()->SetTitle( Title );
714  Title = "Corr " + str;
715  CorrelationDiff->GetZaxis()->SetTitle(Title);
716 
717  CovarianceDiff->SetMinimum(-2);
718  CovarianceDiff->SetMaximum(2);
719  CorrelationDiff->SetMinimum(-2);
720  CorrelationDiff->SetMaximum(2);
721 
722  Canvas->cd();
723  CovarianceDiff->Draw("colz");
724  Canvas->Print(Form("Covariance_%s.pdf", OutName.c_str()), "pdf");
725 
726  CorrelationDiff->Draw("colz");
727  Canvas->Print(Form("Correlation_%s.pdf", OutName.c_str()), "pdf");
728 
729  //KS: Current hist become previous as we need it for further comparison
730  delete CovariancePreviousHist;
731  CovariancePreviousHist = static_cast<TH2D*>(CovarianceHist->Clone());
732  delete CorrelationPreviousHist;
733  CorrelationPreviousHist = static_cast<TH2D*>(CorrelationHist->Clone());
734 
735  delete CovarianceHist;
736  CovarianceHist = nullptr;
737  delete CorrelationHist;
738  CorrelationHist = nullptr;
739 
740  delete CovarianceDiff;
741  delete CorrelationDiff;
742  delete Covariance;
743  Covariance = nullptr;
744  delete Correlation;
745  Correlation = nullptr;
746  }
747  Canvas->cd();
748  Canvas->Print(Form("Covariance_%s.pdf]", OutName.c_str()), "pdf");
749  Canvas->Print(Form("Correlation_%s.pdf]", OutName.c_str()), "pdf");
750 
751  Processor->SetPrintToPDF(true);
752  if(Covariance != nullptr) delete Covariance;
753  if(Correlation != nullptr) delete Correlation;
754  if(CovariancePreviousHist != nullptr) delete CovariancePreviousHist;
755  if(CorrelationPreviousHist != nullptr) delete CorrelationPreviousHist;
756  if(CovarianceHist != nullptr) delete CovarianceHist;
757  if(CorrelationHist != nullptr) delete CorrelationHist;
758 }
759 
768 TH2D* ProcessMCMCModule::TMatrixIntoTH2D(TMatrixDSym* Matrix, const std::string& title)
769 {
770  TH2D* hMatrix = new TH2D(title.c_str(), title.c_str(), Matrix->GetNrows(), 0.0, Matrix->GetNrows(), Matrix->GetNcols(), 0.0, Matrix->GetNcols());
771  for(int i = 0; i < Matrix->GetNrows(); i++)
772  {
773  for(int j = 0; j < Matrix->GetNcols(); j++)
774  {
775  //KS: +1 because there is offset in histogram relative to TMatrix
776  hMatrix->SetBinContent(i+1,j+1, (*Matrix)(i,j));
777  }
778  }
779  return hMatrix;
780 }
781 
791 void ProcessMCMCModule::KolmogorovSmirnovTest(const std::vector<std::unique_ptr<MCMCProcessor>>& Processor,
792  const std::unique_ptr<TCanvas>& Posterior,
793  const TString& canvasname)
794 {
795  constexpr Color_t CumulativeColor[] = {kBlue-1, kRed, kGreen+2};
796  constexpr Style_t CumulativeStyle[] = {kSolid, kDashed, kDotted};
797 
798  for(int i = 0; i < Processor[0]->GetNParams(); ++i)
799  {
800  // This holds the posterior density
801  std::vector<std::unique_ptr<TH1D>> hpost(nFiles);
802  std::vector<std::unique_ptr<TH1D>> CumulativeDistribution(nFiles);
803 
804  TString Title;
805  double Prior = 1.0;
806  double PriorError = 1.0;
807 
808  Processor[0]->GetNthParameter(i, Prior, PriorError, Title);
809  bool Skip = false;
810  for (int ik = 0 ; ik < nFiles; ik++)
811  {
812  int Index = 0;
813  if(ik == 0 ) Index = i;
814  else
815  {
816  // KS: If somehow this chain doesn't given params we skip it
817  Index = Processor[ik]->GetParamIndexFromName(hpost[0]->GetTitle());
818  if(Index == M3::_BAD_INT_)
819  {
820  Skip = true;
821  break;
822  }
823  }
824  hpost[ik] = M3::Clone(Processor[ik]->GetHpost(Index));
825  CumulativeDistribution[ik] = M3::Clone(Processor[ik]->GetHpost(Index));
826  CumulativeDistribution[ik]->Fill(0., 0.);
827  CumulativeDistribution[ik]->Reset();
828  CumulativeDistribution[ik]->SetMaximum(1.);
829  TString TempTitle = Title+" Kolmogorov Smirnov";
830  CumulativeDistribution[ik]->SetTitle(TempTitle);
831 
832  TempTitle = Title+" Value";
833  CumulativeDistribution[ik]->GetXaxis()->SetTitle(TempTitle);
834  CumulativeDistribution[ik]->GetYaxis()->SetTitle("Cumulative Probability");
835 
836  CumulativeDistribution[ik]->SetLineWidth(2);
837  CumulativeDistribution[ik]->SetLineColor(CumulativeColor[ik]);
838  CumulativeDistribution[ik]->SetLineStyle(CumulativeStyle[ik]);
839  }
840 
841  // Don't plot if this is a fixed histogram (i.e. the peak is the whole integral)
842  if(hpost[0]->GetMaximum() == hpost[0]->Integral()*1.5 || Skip) {
843  continue;
844  }
845 
846  for (int ik = 0 ; ik < nFiles; ik++)
847  {
848  const int NumberOfBins = hpost[ik]->GetXaxis()->GetNbins();
849  double Cumulative = 0;
850  const double Integral = hpost[ik]->Integral();
851  for (int j = 1; j < NumberOfBins+1; ++j)
852  {
853  Cumulative += hpost[ik]->GetBinContent(j)/Integral;
854  CumulativeDistribution[ik]->SetBinContent(j, Cumulative);
855  }
856  //KS: Set overflow to 1 just in case
857  CumulativeDistribution[ik]->SetBinContent(NumberOfBins+1, 1.);
858  }
859 
860  std::vector<int> TestStatBin(nFiles, 0);
861  std::vector<double> TestStatD(nFiles, -999);
862  std::vector<std::unique_ptr<TLine>> LineD(nFiles);
863  //Find KS statistic
864  for (int ik = 1 ; ik < nFiles; ik++)
865  {
866  const int NumberOfBins = CumulativeDistribution[0]->GetXaxis()->GetNbins();
867  for (int j = 1; j < NumberOfBins+1; ++j)
868  {
869  const double BinValue = CumulativeDistribution[0]->GetBinCenter(j);
870  const int BinNumber = CumulativeDistribution[ik]->FindBin(BinValue);
871  //KS: Calculate D statistic for this bin, only save it if it's bigger than previously found value
872  double TempDstat = std::fabs(CumulativeDistribution[0]->GetBinContent(j) - CumulativeDistribution[ik]->GetBinContent(BinNumber));
873  if(TempDstat > TestStatD[ik])
874  {
875  TestStatD[ik] = TempDstat;
876  TestStatBin[ik] = j;
877  }
878  }
879  }
880 
881  for (int ik = 0 ; ik < nFiles; ik++)
882  {
883  LineD[ik] = std::make_unique<TLine>(CumulativeDistribution[0]->GetBinCenter(TestStatBin[ik]), 0, CumulativeDistribution[0]->GetBinCenter(TestStatBin[ik]), CumulativeDistribution[0]->GetBinContent(TestStatBin[ik]));
884  LineD[ik]->SetLineColor(CumulativeColor[ik]);
885  LineD[ik]->SetLineWidth(2.0);
886  }
887  CumulativeDistribution[0]->Draw();
888  for (int ik = 0 ; ik < nFiles; ik++)
889  CumulativeDistribution[ik]->Draw("SAME");
890 
891  auto leg = std::make_unique<TLegend>(0.15, 0.7, 0.5, 0.90);
892  leg->SetTextSize(0.04f);
893  for (int ik = 0; ik < nFiles; ik++)
894  leg->AddEntry(CumulativeDistribution[ik].get(), TitleNames[ik].c_str(), "l");
895  for (int ik = 1; ik < nFiles; ik++)
896  leg->AddEntry(LineD[ik].get(), Form("#Delta D = %.4f", TestStatD[ik]), "l");
897 
898  leg->SetLineColor(0);
899  leg->SetLineStyle(0);
900  leg->SetFillColor(0);
901  leg->SetFillStyle(0);
902  leg->Draw("SAME");
903 
904  for (int ik = 1; ik < nFiles; ik++)
905  LineD[ik]->Draw("sam");
906 
907  Posterior->cd();
908  Posterior->Print(canvasname);
909  } //End loop over parameter
910 }
911 }
#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
Module for processing MCMC chains and producing diagnostic plots.
Type GetFromManager(const YAML::Node &node, const Type defval, const std::string &File, const int Line)
Get content of config file if node is not found take default value specified.
Definition: YamlHelper.h:328
bool CheckNodeExists(const YAML::Node &node, Args... args)
KS: Wrapper function to call the recursive helper.
Definition: YamlHelper.h:59
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:589
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
virtual ~ProcessMCMCModule()
Destructor.
void CalcBipolarPlot(MCMCProcessor *Processor)
Create bipolar plots for parameter visualization.
std::vector< std::string > FileNames
List of MCMC chain file paths.
std::map< std::string, std::pair< double, double > > GetCustomBinning(const YAML::Node &Settings)
Parse custom binning edges from YAML configuration.
void CalcSavageDickey(MCMCProcessor *Processor)
Calculate Savage-Dickey ratios for Bayes factor estimation.
void CalcParameterEvolution(MCMCProcessor *Processor)
Calculate parameter evolution over MCMC steps.
void CalcBayesFactor(MCMCProcessor *Processor)
Calculate Bayes factors for hypothesis testing.
std::string config
Path to the configuration file.
void GetTrianglePlot(MCMCProcessor *Processor)
Generate triangle plots showing parameter correlations.
void DiagnoseCovarianceMatrix(MCMCProcessor *Processor, const std::string &inputFile)
Diagnose covariance matrix stability across burn-in cuts.
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
std::vector< std::string > TitleNames
List of titles for each chain.
TH2D * TMatrixIntoTH2D(TMatrixDSym *Matrix, const std::string &title)
Convert TMatrixDSym to TH2D histogram for plotting.
void ProcessMCMC(const std::string &inputFile)
Process a single MCMC chain.
void KolmogorovSmirnovTest(const std::vector< std::unique_ptr< MCMCProcessor >> &Processor, const std::unique_ptr< TCanvas > &Posterior, const TString &canvasname)
Perform Kolmogorov-Smirnov test between posterior distributions.
int Run() override
Execute the MCMC processing.
int nFiles
Number of MCMC files being processed.
void MultipleProcessMCMC()
Compare and process multiple MCMC chains.
Class responsible for processing MCMC chains, performing diagnostics, generating plots,...
Definition: MCMCProcessor.h:61
void GetNthParameter(const int param, double &Prior, double &PriorError, TString &Title) const
Get properties of parameter by passing it number.
void Reset2DPosteriors()
Reset 2D posteriors, in case we would like to calculate in again with different BurnInCut.
void GetBayesFactor(const std::vector< std::string > &ParName, const std::vector< std::vector< double >> &Model1Bounds, const std::vector< std::vector< double >> &Model2Bounds, const std::vector< std::vector< std::string >> &ModelNames)
Calculate Bayes factor for vector of params, and model boundaries.
void MakeTrianglePlot(const std::vector< std::string > &ParNames, const std::vector< double > &CredibleIntervals={0.99, 0.90, 0.68 }, const std::vector< Color_t > &CredibleIntervalsColours={kCyan+4, kCyan-2, kCyan-10}, const std::vector< double > &CredibleRegions={0.99, 0.90, 0.68}, const std::vector< Style_t > &CredibleRegionStyle={kDashed, kSolid, kDotted}, const std::vector< Color_t > &CredibleRegionColor={kGreen-3, kGreen-10, kGreen}, const bool CredibleInSigmas=false)
Make fancy triangle plot for selected parameters.
void SetPrintToPDF(const bool PlotOrNot)
Whether to dump all plots into PDF.
Long64_t GetnSteps()
Get Number of Steps that Chain has, for merged chains will not be the same nEntries.
void GetPolarPlot(const std::vector< std::string > &ParNames)
Make funny polar plot.
void ParameterEvolution(const std::vector< std::string > &Names, const std::vector< int > &NIntervals)
Make .gif of parameter evolution.
void GetCovariance(TMatrixDSym *&Cov, TMatrixDSym *&Corr)
Get the post-fit covariances and correlations.
void SetStepCut(const std::string &Cuts)
Set the step cutting by string.
void GetSavageDickey(const std::vector< std::string > &ParName, const std::vector< double > &EvaluationPoint, const std::vector< std::vector< double >> &Bounds)
Calculate Bayes factor for point like hypothesis using SavageDickey.
Custom exception class used throughout MaCh3.
Main namespace for MaCh3 software.
constexpr static const double _BAD_DOUBLE_
Default value used for double initialisation.
Definition: Core.h:53
constexpr static const int _BAD_INT_
Default value used for int initialisation.
Definition: Core.h:55