MaCh3  2.8.0
Reference Guide
MCMCProcessor.cpp
Go to the documentation of this file.
2 
4 #include "TChain.h"
5 #include "TF1.h"
6 #include "TVirtualFFT.h"
8 
9 //Only if GPU is enabled
10 #ifdef MaCh3_CUDA
12 #endif
13 
14 //this file has lots of usage of the ROOT plotting interface that only takes floats, turn this warning off for this CU for now
15 #pragma GCC diagnostic ignored "-Wfloat-conversion"
16 
17 // ****************************
18 MCMCProcessor::MCMCProcessor(const std::string &InputFile) :
19  Chain(nullptr), StepCut(""), MadePostfit(false) {
20 // ****************************
21  MCMCFile = InputFile;
22 
25  MACH3LOG_INFO("Making post-fit processor for: {}", MCMCFile);
26 
27  ParStep = nullptr;
28  StepNumber = nullptr;
29  ReweightPosterior = false;
30 
31  Posterior = nullptr;
32  hviolin = nullptr;
33  hviolin_prior = nullptr;
34 
35  OutputFile = nullptr;
36 
37  BatchedAverages = nullptr;
38  SampleValues = nullptr;
39  SystValues = nullptr;
40  AccProbValues = nullptr;
41  AccProbBatchedAverages = nullptr;
42 
43  //KS:Hardcoded should be a way to get it via config or something
44  plotRelativeToPrior = false;
45  printToPDF = false;
46  plotBinValue = false;
47  PlotFlatPrior = true;
48  ApplySmoothing = true;
49  FancyPlotNames = true;
50  doDiagMCMC = false;
51 
52  // KS: ROOT can compile FFT code but it will crash during run time. Turn off FFT dynamically
53 #ifdef MaCh3_FFT
54  useFFTAutoCorrelation = true;
55 #else
56  useFFTAutoCorrelation = false;
57 #endif
58  OutputSuffix = "_Process";
59  Post2DPlotThreshold = 1.e-5;
60 
61  nDraw = 0;
62  nEntries = 0;
64  nSteps = 0;
65  nBatches = 0;
66  AutoCorrLag = 0;
67 
68  nBins = 70;
69  DrawRange = 1.5;
70 
71  Posterior1DCut = "";
72  //KS:Those keep basic information for ParameterEnum
76  ParamFlat.resize(kNParameterEnum);
79  nParam.resize(kNParameterEnum);
80  CovPos.resize(kNParameterEnum);
82  CovConfig.resize(kNParameterEnum);
83 
84  ReweightNames = {"Weight"};
85  for(int i = 0; i < kNParameterEnum; i++)
86  {
87  ParamTypeStartPos[i] = 0;
88  nParam[i] = 0;
89  }
90  //Only if GPU is enabled
91  #ifdef MaCh3_CUDA
92  GPUProcessor = std::make_unique<MCMCProcessorGPU>();
93  #endif
94 }
95 
96 // ****************************
97 // The destructor
99 // ****************************
100  // Close the pdf file
101  MACH3LOG_INFO("Closing pdf in MCMCProcessor: {}", CanvasName.Data());
102  CanvasName += "]";
103  if(printToPDF) Posterior->Print(CanvasName);
104 
105  delete Covariance;
106  delete Correlation;
107  delete Central_Value;
108  delete Means;
109  delete Errors;
110  delete Means_Gauss;
111  delete Errors_Gauss;
112  delete Means_HPD;
113  delete Errors_HPD;
114  delete Errors_HPD_Positive;
115  delete Errors_HPD_Negative;
116 
117  for (int i = 0; i < nDraw; ++i) {
118  if(ParStep) delete[] ParStep[i];
119  }
120  if(ParStep) delete[] ParStep;
121  if(StepNumber != nullptr) delete[] StepNumber;
122 
123  if(OutputFile != nullptr) OutputFile->Close();
124  if(OutputFile != nullptr) delete OutputFile;
125  delete Chain;
126 }
127 
128 // ***************
130 // ***************
131  // Scan the ROOT file for useful branches
132  ScanInput();
133 
134  // Setup the output
135  SetupOutput();
136 }
137 
138 // ***************
139 void MCMCProcessor::GetPostfit(TVectorD *&Central_PDF, TVectorD *&Errors_PDF, TVectorD *&Central_G, TVectorD *&Errors_G, TVectorD *&Peak_Values) {
140 // ***************
141  // Make the post fit
142  MakePostfit();
143 
144  // We now have the private members
145  Central_PDF = Means;
146  Errors_PDF = Errors;
147  Central_G = Means_Gauss;
148  Errors_G = Errors_Gauss;
149  Peak_Values = Means_HPD;
150 }
151 
152 // ***************
153 // Get post-fits for the ParameterEnum type, e.g. xsec params, ND params or flux params etc
154 void MCMCProcessor::GetPostfit_Ind(TVectorD *&PDF_Central, TVectorD *&PDF_Errors, TVectorD *&Peak_Values, ParameterEnum kParam) {
155 // ***************
156  // Make the post fit
157  MakePostfit();
158 
159  // Loop over the loaded param types
160  const int ParamTypeSize = int(ParamType.size());
161  int ParamNumber = 0;
162  for (int i = 0; i < ParamTypeSize; ++i) {
163  if (ParamType[i] != kParam) continue;
164  (*PDF_Central)(ParamNumber) = (*Means)(i);
165  (*PDF_Errors)(ParamNumber) = (*Errors)(i);
166  (*Peak_Values)(ParamNumber) = (*Means_HPD)(i);
167  ++ParamNumber;
168  }
169 }
170 
171 // ***************
172 void MCMCProcessor::GetCovariance(TMatrixDSym *&Cov, TMatrixDSym *&Corr) {
173 // ***************
174  MakeCovariance();
175  Cov = static_cast<TMatrixDSym*>(Covariance->Clone());
176  Corr = static_cast<TMatrixDSym*>(Correlation->Clone());
177 }
178 
179 // ***************
181 // ***************
182  //KS: ROOT hates me... but we can create several instances of MCMC Processor, each with own TCanvas ROOT is mad and will delete if there is more than one canvas with the same name, so we add random number to avoid issue
183  // KS: Update, now we also check if such canvas already exist, hence while/do loop
184  std::string name = "";
185  do {
186  const int uniform = M3::rand::UniformInt(0, 9999);
187  name = "Posterior" + std::to_string(uniform);
188  } while (gROOT->GetListOfCanvases()->FindObject(name.c_str()) != nullptr);
189 
190  // Open a TCanvas to write the posterior onto
191  Posterior = std::make_unique<TCanvas>(name.c_str(), name.c_str(), 0, 0, 1024, 1024);
192  //KS: No idea why but ROOT changed treatment of violin in R6. If you have non uniform binning this will results in very hard to see violin plots.
193  TCandle::SetScaledViolin(false);
194 
195  Posterior->SetGrid();
196  gStyle->SetOptStat(0);
197  gStyle->SetOptTitle(0);
198  Posterior->SetTickx();
199  Posterior->SetTicky();
200 
201  Posterior->SetBottomMargin(0.1);
202  Posterior->SetTopMargin(0.05);
203  Posterior->SetRightMargin(0.03);
204  Posterior->SetLeftMargin(0.15);
205 
206  //To avoid TCanvas::Print> messages
207  gErrorIgnoreLevel = kWarning;
208 
209  // Output file to write to
210  OutputName = MCMCFile + OutputSuffix +".root";
211 
212  // Output file
213  OutputFile = M3::Open(OutputName, "recreate", __FILE__, __LINE__);
214  OutputFile->cd();
215 }
216 
217 // ***************
218 void MCMCProcessor::DrawPosterior(const int i, TDirectory* PostDir, TDirectory* PostHistDir) {
219 // ***************
220  TString Title = "";
221  double Prior = 1.0, PriorError = 1.0;
222  GetNthParameter(i, Prior, PriorError, Title);
223  bool isFlat = GetParamFlat(i);
224 
225  hpost[i]->SetMinimum(0);
226  hpost[i]->GetYaxis()->SetTitle("Steps");
227  hpost[i]->GetYaxis()->SetNoExponent(false);
228 
229  if(ApplySmoothing) hpost[i]->Smooth();
230 
231  (*Central_Value)(i) = Prior;
232 
233  double Mean, Err, Err_p, Err_m;
234  GetArithmetic(hpost[i].get(), Mean, Err);
235  (*Means)(i) = Mean;
236  (*Errors)(i) = Err;
237  // KS: needed for compilation reasons
238  auto HistRaw = hpost[i].get();
239  GetGaussian(HistRaw, Gauss.get(), Mean, Err);
240  (*Means_Gauss)(i) = Mean;
241  (*Errors_Gauss)(i) = Err;
242 
243  GetHPD(hpost[i].get(), Mean, Err, Err_p, Err_m);
244  (*Means_HPD)(i) = Mean;
245  (*Errors_HPD)(i) = Err;
246  (*Errors_HPD_Positive)(i) = Err_p;
247  (*Errors_HPD_Negative)(i) = Err_m;
248 
249  // Write the results from the projection into the TVectors and TMatrices
250  (*Covariance)(i,i) = (*Errors)(i)*(*Errors)(i);
251  (*Correlation)(i,i) = 1.0;
252 
253  //KS: This need to be before SetMaximum(), this way plot is nicer as line end at the maximum
254  auto hpd = std::make_unique<TLine>((*Means_HPD)(i), hpost[i]->GetMinimum(), (*Means_HPD)(i), hpost[i]->GetMaximum());
255  SetTLineStyle(hpd.get(), kBlack, 2, kSolid);
256 
257  hpost[i]->SetLineWidth(2);
258  hpost[i]->SetLineColor(kBlue-1);
259  hpost[i]->SetMaximum(hpost[i]->GetMaximum()*DrawRange);
260  hpost[i]->SetTitle(Title);
261  hpost[i]->GetXaxis()->SetTitle(hpost[i]->GetTitle());
262 
263  // Now make the TLine for the Asimov
264  auto Asimov = std::make_unique<TLine>(Prior, hpost[i]->GetMinimum(), Prior, hpost[i]->GetMaximum());
265  SetTLineStyle(Asimov.get(), kRed-3, 2, kDashed);
266 
267  auto leg = std::make_unique<TLegend>(0.15, 0.6, 0.6, 0.95);
268  SetLegendStyle(leg.get(), 0.04);
269  leg->AddEntry(hpost[i].get(), Form("#splitline{PDF}{#mu = %.2f, #sigma = %.2f}", hpost[i]->GetMean(), hpost[i]->GetRMS()), "l");
270  leg->AddEntry(Gauss.get(), Form("#splitline{Gauss}{#mu = %.2f, #sigma = %.2f}", Gauss->GetParameter(1), Gauss->GetParameter(2)), "l");
271  leg->AddEntry(hpd.get(), Form("#splitline{HPD}{#mu = %.2f, #sigma = %.2f (+%.2f-%.2f)}", (*Means_HPD)(i), (*Errors_HPD)(i), (*Errors_HPD_Positive)(i), (*Errors_HPD_Negative)(i)), "l");
272  if(isFlat && !PlotFlatPrior) leg->AddEntry(Asimov.get(), Form("#splitline{Prior}{x = %.2f}", Prior), "l");
273  else leg->AddEntry(Asimov.get(), Form("#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError), "l");
274 
275  // Write to file
276  Posterior->SetName(Title);
277  Posterior->SetTitle(Title);
278 
279  //CW: Don't plot if this is a fixed histogram (i.e. the peak is the whole integral)
280  if (hpost[i]->GetMaximum() == hpost[i]->Integral()*DrawRange)
281  {
282  MACH3LOG_WARN("Found fixed parameter: {} ({}), moving on", Title, i);
283  ParamVaried[i] = false;
284  //KS:Set mean and error to prior for fixed parameters, it looks much better when fixed parameter has mean on prior rather than on 0 with 0 error.
285  (*Means_HPD)(i) = Prior;
286  (*Errors_HPD)(i) = PriorError;
287  (*Errors_HPD_Positive)(i) = PriorError;
288  (*Errors_HPD_Negative)(i) = PriorError;
289 
290  (*Means_Gauss)(i) = Prior;
291  (*Errors_Gauss)(i) = PriorError;
292 
293  (*Means)(i) = Prior;
294  (*Errors)(i) = PriorError;
295  return;
296  }
297 
298  // Store that this parameter is indeed being varied
299  ParamVaried[i] = true;
300 
301  // Draw onto the TCanvas
302  hpost[i]->Draw("hist");
303  hpd->Draw("same");
304  Asimov->Draw("same");
305  leg->Draw("same");
306 
307  if(printToPDF) Posterior->Print(CanvasName);
308 
309  // cd into params directory in root file
310  PostDir->cd();
311  Posterior->Write();
312 
313  hpost[i]->SetName(Title);
314  hpost[i]->SetTitle(Title);
315  PostHistDir->cd();
316  hpost[i]->Write();
317 }
318 
319 // ****************************
320 std::pair<double, double> MCMCProcessor::GetHistRange(const int iParam) const {
321 // ****************************
322  return {
323  hpost[iParam]->GetXaxis()->GetXmin(),
324  hpost[iParam]->GetXaxis()->GetXmax()
325  };
326 }
327 
328 // *********************
329 // Build RDataFrame for MCMC Processor
330 ROOT::RDF::RNode MCMCProcessor::GetFilteredDataFrame() const {
331 // *********************
332  //KS: Apply additional Cuts, like mass ordering
333  std::string CutPosterior1D = StepCut;
334  if (Posterior1DCut != "") {
335  CutPosterior1D = "(" + StepCut + ") && (" + Posterior1DCut + ")";
336  }
337  MACH3LOG_DEBUG("Using following cut {}", CutPosterior1D);
338 
339  // Define RDataFrame
340  ROOT::RDataFrame df(*Chain);
341  // Apply selection once
342  ROOT::RDF::RNode dfToUse = df.Filter(CutPosterior1D);
343 
344  // Apply reweighting once
345  TString WeightExpression = "1.0";
346  if(ReweightPosterior){
347  for (const auto &name : ReweightNames) {
348  WeightExpression = "(" + WeightExpression + ")*(" + name + ")";
349  }
350  }
351  dfToUse = dfToUse.Define("MCMC_RDF_WEIGHT", WeightExpression.Data());
352  return dfToUse;
353 }
354 
355 // ****************************
356 //CW: Function to make the post-fit
357 void MCMCProcessor::MakePostfit(const std::map<std::string, std::pair<double, double>>& Edges) {
358 // ****************************
359  // Check if we've already made post-fit
360  if (MadePostfit == true) return;
361  MadePostfit = true;
362 
363  // Check if the output file is ready
364  if (OutputFile == nullptr) MakeOutputFile();
365 
366  MACH3LOG_INFO("Starting {}", __func__);
367  TStopwatch clock;
368  clock.Start();
369 
370  int originalErrorLevel = gErrorIgnoreLevel;
371  gErrorIgnoreLevel = kFatal;
372 
373  // Directory for posteriors
374  TDirectory *PostDir = OutputFile->mkdir("Post");
375  TDirectory *PostHistDir = OutputFile->mkdir("Post_1d_hists");
376 
377  M3::EnableROOTMultiThreading();
378  auto dfToUse = GetFilteredDataFrame();
379  OutputFile->cd();
380  std::vector<ROOT::RDF::RResultPtr<TH1D>> Histograms(nDraw);
381  for (int i = 0; i < nDraw; ++i) {
382  TString Title = "";
383  double Prior = 1.0, PriorError = 1.0;
384  GetNthParameter(i, Prior, PriorError, Title);
385  // Get bin edges for histograms
386  double maxi, mini = M3::_BAD_DOUBLE_;
387  if (Edges.find(Title.Data()) != Edges.end()) {
388  mini = Edges.at(Title.Data()).first;
389  maxi = Edges.at(Title.Data()).second;
390  } else {
391  maxi = Chain->GetMaximum(BranchNames[i]);
392  mini = Chain->GetMinimum(BranchNames[i]);
393  }
394  MACH3LOG_DEBUG("Initialising histogram for {} with binning {:.4f}, {:.4f}", Title, mini, maxi);
395  // This holds the posterior density
396  hpost[i] = std::make_unique<TH1D>(BranchNames[i], BranchNames[i], nBins, mini, maxi);
397  hpost[i]->SetDirectory(nullptr);
398  // Build the model (name, title, binning, range) from the existing histogram
399  const ROOT::RDF::TH1DModel model(*hpost[i].get());
400  Histograms[i] = dfToUse.Histo1D(model, BranchNames[i].Data(), "MCMC_RDF_WEIGHT");
401  }
402  MACH3LOG_INFO("Finished booking {} histograms. Now executing RDF event loop...", Histograms.size());
403 
404  // The first GetPtr() triggers the RDF event loop.
405  // Because ALL histograms have already been booked, RDF fills all of them in one pass.
406  if (!Histograms.empty()) {
407  TH1D *dummy = Histograms[0].GetPtr();
408  (void)dummy;
409  }
410  MACH3LOG_INFO("RDataFrame event loop took {:.2f}s for {} entries", clock.RealTime(), nEntries);
411 
412  M3::DisableROOTMultiThreading();
413  // Now we can plot actual histogram
414  for (int i = 0; i < nDraw; ++i) {
415  if (i % std::max(1, nDraw/5) == 0) {
417  }
418  OutputFile->cd();
419 
420  // Move RDF result into the pre-existing histogram (axis titles, min etc. already set)
421  hpost[i]->Add(Histograms[i].GetPtr());
422  DrawPosterior(i, PostDir, PostHistDir);
423  } // end the for loop over nDraw
424 
425  SavePostfit();
426 
427  PostDir->Close();
428  delete PostDir;
429  PostHistDir->Close();
430  delete PostHistDir;
431 
432  clock.Stop();
433  MACH3LOG_INFO("{} took {:.2f}s to", __func__, clock.RealTime());
434 
435  // restore original warning setting
436  gErrorIgnoreLevel = originalErrorLevel;
437 } // Have now written the postfit projections
438 
439 // *******************
440 //CW: Save the postfit
442 // *******************
443  OutputFile->cd();
444  TTree *SettingsBranch = new TTree("Settings", "Settings");
445  int NDParameters = nParam[kNDPar];
446  SettingsBranch->Branch("NDParameters", &NDParameters);
447  int NDParametersStartingPos = ParamTypeStartPos[kNDPar];
448  SettingsBranch->Branch("NDParametersStartingPos", &NDParametersStartingPos);
449 
450  SettingsBranch->Branch("NDSamplesBins", &NDSamplesBins);
451  SettingsBranch->Branch("NDSamplesNames", &NDSamplesNames);
452 
453  SettingsBranch->Fill();
454  SettingsBranch->Write();
455  delete SettingsBranch;
456 
457  TDirectory *Names = OutputFile->mkdir("Names");
458  Names->cd();
459  for (std::vector<TString>::iterator it = BranchNames.begin(); it != BranchNames.end(); ++it) {
460  TObjString((*it)).Write();
461  }
462  Names->Close();
463  delete Names;
464 
465  OutputFile->cd();
466  Central_Value->Write("Central_Value");
467  Means->Write("PDF_Means");
468  Errors->Write("PDF_Error");
469  Means_Gauss->Write("Gauss_Means");
470  Errors_Gauss->Write("Gauss_Errors");
471  Means_HPD->Write("Means_HPD");
472  Errors_HPD->Write("Errors_HPD");
473  Errors_HPD_Positive->Write("Errors_HPD_Positive");
474  Errors_HPD_Negative->Write("Errors_HPD_Negative");
475 }
476 
477 // *******************
478 //CW: Draw the postfit
480 // *******************
481  if (OutputFile == nullptr) MakeOutputFile();
482 
483  // Make the prefit plot
484  std::unique_ptr<TH1D> prefit = MakePrefit();
485 
486  prefit->GetXaxis()->SetTitle("");
487  // cd into the output file
488  OutputFile->cd();
489 
490  std::string CutPosterior1D = "";
491  if(Posterior1DCut != "") {
492  CutPosterior1D = StepCut +" && " + Posterior1DCut;
493  }
494  else CutPosterior1D = StepCut;
495 
496  // Make a TH1D of the central values and the errors
497  std::unique_ptr<TH1D> paramPlot = std::make_unique<TH1D>("paramPlot", "paramPlot", nDraw, 0, nDraw);
498  paramPlot->SetDirectory(nullptr);
499  paramPlot->SetName("mach3params");
500  paramPlot->SetTitle(CutPosterior1D.c_str());
501  paramPlot->SetFillStyle(3001);
502  paramPlot->SetFillColor(kBlue-1);
503  paramPlot->SetMarkerColor(paramPlot->GetFillColor());
504  paramPlot->SetMarkerStyle(20);
505  paramPlot->SetLineColor(paramPlot->GetFillColor());
506  paramPlot->SetMarkerSize(prefit->GetMarkerSize());
507  paramPlot->GetXaxis()->SetTitle("");
508 
509  // Same but with Gaussian output
510  std::unique_ptr<TH1D> paramPlot_Gauss = M3::Clone(paramPlot);
511  paramPlot_Gauss->SetMarkerColor(kOrange-5);
512  paramPlot_Gauss->SetMarkerStyle(23);
513  paramPlot_Gauss->SetLineWidth(2);
514  paramPlot_Gauss->SetMarkerSize((prefit->GetMarkerSize())*0.75);
515  paramPlot_Gauss->SetFillColor(paramPlot_Gauss->GetMarkerColor());
516  paramPlot_Gauss->SetFillStyle(3244);
517  paramPlot_Gauss->SetLineColor(paramPlot_Gauss->GetMarkerColor());
518  paramPlot_Gauss->GetXaxis()->SetTitle("");
519 
520  // Same but with Gaussian output
521  std::unique_ptr<TH1D> paramPlot_HPD = M3::Clone(paramPlot);
522  paramPlot_HPD->SetMarkerColor(kBlack);
523  paramPlot_HPD->SetMarkerStyle(25);
524  paramPlot_HPD->SetLineWidth(2);
525  paramPlot_HPD->SetMarkerSize((prefit->GetMarkerSize())*0.5);
526  paramPlot_HPD->SetFillColor(0);
527  paramPlot_HPD->SetFillStyle(0);
528  paramPlot_HPD->SetLineColor(paramPlot_HPD->GetMarkerColor());
529  paramPlot_HPD->GetXaxis()->SetTitle("");
530 
531  // Set labels and data
532  for (int i = 0; i < nDraw; ++i)
533  {
534  //Those keep which parameter type we run currently and relative number
535  int ParamEnu = ParamType[i];
536  int ParamNo = i - ParamTypeStartPos[ParameterEnum(ParamEnu)];
537 
538  //KS: Slightly hacky way to get relative to prior or nominal as this is convention we use
539  //This only applies for xsec for other systematic types doesn't matter
540  double CentralValueTemp = 0;
541  double Central, Central_gauss, Central_HPD;
542  double Err, Err_Gauss, Err_HPD;
543 
545  {
546  CentralValueTemp = ParamCentral[ParamEnu][ParamNo];
547  // Normalise the prior relative the nominal/prior, just the way we get our fit results in MaCh3
548  if ( CentralValueTemp != 0)
549  {
550  Central = (*Means)(i) / CentralValueTemp;
551  Err = (*Errors)(i) / CentralValueTemp;
552 
553  Central_gauss = (*Means_Gauss)(i) / CentralValueTemp;
554  Err_Gauss = (*Errors_Gauss)(i) / CentralValueTemp;
555 
556  Central_HPD = (*Means_HPD)(i) / CentralValueTemp;
557  Err_HPD = (*Errors_HPD)(i) / CentralValueTemp;
558  }
559  else {
560  Central = 1+(*Means)(i);
561  Err = (*Errors)(i);
562 
563  Central_gauss = 1+(*Means_Gauss)(i);
564  Err_Gauss = (*Errors_Gauss)(i);
565 
566  Central_HPD = 1+(*Means_HPD)(i) ;
567  Err_HPD = (*Errors_HPD)(i);
568  }
569  }
570  //KS: Just get value of each parameter without dividing by prior
571  else
572  {
573  Central = (*Means)(i);
574  Err = (*Errors)(i);
575 
576  Central_gauss = (*Means_Gauss)(i);
577  Err_Gauss = (*Errors_Gauss)(i);
578 
579  Central_HPD = (*Means_HPD)(i) ;
580  Err_HPD = (*Errors_HPD)(i);
581  }
582 
583  paramPlot->SetBinContent(i+1, Central);
584  paramPlot->SetBinError(i+1, Err);
585 
586  paramPlot_Gauss->SetBinContent(i+1, Central_gauss);
587  paramPlot_Gauss->SetBinError(i+1, Err_Gauss);
588 
589  paramPlot_HPD->SetBinContent(i+1, Central_HPD);
590  paramPlot_HPD->SetBinError(i+1, Err_HPD);
591 
592  paramPlot->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
593  paramPlot_Gauss->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
594  paramPlot_HPD->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
595  }
596  prefit->GetXaxis()->LabelsOption("v");
597  paramPlot->GetXaxis()->LabelsOption("v");\
598  paramPlot_Gauss->GetXaxis()->LabelsOption("v");
599  paramPlot_HPD->GetXaxis()->LabelsOption("v");
600 
601  // Make a TLegend
602  auto CompLeg = std::make_unique<TLegend>(0.33, 0.73, 0.76, 0.95);
603  CompLeg->AddEntry(prefit.get(), "Prefit", "fp");
604  CompLeg->AddEntry(paramPlot.get(), "Postfit PDF", "fp");
605  CompLeg->AddEntry(paramPlot_Gauss.get(), "Postfit Gauss", "fp");
606  CompLeg->AddEntry(paramPlot_HPD.get(), "Postfit HPD", "lfep");
607  CompLeg->SetFillColor(0);
608  CompLeg->SetFillStyle(0);
609  CompLeg->SetLineWidth(0);
610  CompLeg->SetLineStyle(0);
611  CompLeg->SetBorderSize(0);
612 
613  const std::vector<double> Margins = GetMargins(Posterior);
614  Posterior->SetBottomMargin(0.2);
615 
616  OutputFile->cd();
617 
618  // Write the individual ones
619  prefit->Write("param_xsec_prefit");
620  paramPlot->Write("param_xsec");
621  paramPlot_Gauss->Write("param_xsec_gaus");
622  paramPlot_HPD->Write("param_xsec_HPD");
623 
624  // Plot the xsec parameters (0 to ~nXsec-nFlux) nXsec == xsec + flux, quite confusing I know
625  // Have already looked through the branches earlier
626  if(plotRelativeToPrior) prefit->GetYaxis()->SetTitle("Variation rel. prior");
627  else prefit->GetYaxis()->SetTitle("Parameter Value");
628  prefit->GetYaxis()->SetRangeUser(-2.5, 2.5);
629 
630  // And the combined
631  prefit->Draw("e2");
632  paramPlot->Draw("e2, same");
633  paramPlot_Gauss->Draw("e2, same");
634  paramPlot_HPD->Draw("e1, same");
635  CompLeg->Draw("same");
636  Posterior->Write("param_xsec_canv");
637 
638  //KS: Tells how many parameters in one canvas we want
639  constexpr int IntervalsSize = 20;
640  const int NIntervals = nDraw/IntervalsSize;
641 
642  for (int i = 0; i < NIntervals+1; ++i)
643  {
644  int RangeMin = i*IntervalsSize;
645  int RangeMax =RangeMin + IntervalsSize;
646  if(i == NIntervals+1) {
647  RangeMin = i*IntervalsSize;
648  RangeMax = nDraw;
649  }
650  if(RangeMin >= nDraw) break;
651 
652  double ymin = std::numeric_limits<double>::max();
653  double ymax = -std::numeric_limits<double>::max();
654  for (int b = RangeMin; b <= RangeMax; ++b) {
655  // prefit
656  {
657  double val = prefit->GetBinContent(b);
658  double err = prefit->GetBinError(b);
659  ymin = std::min(ymin, val - err);
660  ymax = std::max(ymax, val + err);
661  }
662  // paramPlot_HPD
663  {
664  double val = paramPlot_HPD->GetBinContent(b);
665  double err = paramPlot_HPD->GetBinError(b);
666  ymin = std::min(ymin, val - err);
667  ymax = std::max(ymax, val + err);
668  }
669  }
670 
671  double margin = 0.1 * (ymax - ymin);
672  prefit->GetYaxis()->SetRangeUser(ymin - margin, ymax + margin);
673 
674  prefit->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
675  paramPlot->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
676  paramPlot_Gauss->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
677  paramPlot_HPD->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
678 
679  // And the combined
680  prefit->Draw("e2");
681  paramPlot->Draw("e2, same");
682  paramPlot_Gauss->Draw("e2, same");
683  paramPlot_HPD->Draw("e1, same");
684  CompLeg->Draw("same");
685  if(printToPDF) Posterior->Print(CanvasName);
686  Posterior->Clear();
687  }
688 
689  if(nParam[kNDPar] > 0)
690  {
691  int Start = ParamTypeStartPos[kNDPar];
692  int NDbinCounter = Start;
693  //KS: Make prefit postfit for each ND sample, having all of them at the same plot is unreadable
694  for(unsigned int i = 0; i < NDSamplesNames.size(); i++ )
695  {
696  std::string NDname = NDSamplesNames[i];
697  NDbinCounter += NDSamplesBins[i];
698  OutputFile->cd();
699  prefit->GetYaxis()->SetTitle(("Variation for "+NDname).c_str());
700  prefit->GetYaxis()->SetRangeUser(0.6, 1.4);
701  prefit->GetXaxis()->SetRangeUser(Start, NDbinCounter);
702 
703  paramPlot->GetYaxis()->SetTitle(("Variation for "+NDname).c_str());
704  paramPlot->GetYaxis()->SetRangeUser(0.6, 1.4);
705  paramPlot->GetXaxis()->SetRangeUser(Start, NDbinCounter);
706  paramPlot->SetTitle(CutPosterior1D.c_str());
707 
708  paramPlot_Gauss->GetYaxis()->SetTitle(("Variation for "+NDname).c_str());
709  paramPlot_Gauss->GetYaxis()->SetRangeUser(0.6, 1.4);
710  paramPlot_Gauss->GetXaxis()->SetRangeUser(Start, NDbinCounter);
711  paramPlot_Gauss->SetTitle(CutPosterior1D.c_str());
712 
713  paramPlot_HPD->GetYaxis()->SetTitle(("Variation for "+NDname).c_str());
714  paramPlot_HPD->GetYaxis()->SetRangeUser(0.6, 1.4);
715  paramPlot_HPD->GetXaxis()->SetRangeUser(Start, NDbinCounter);
716  paramPlot_HPD->SetTitle(CutPosterior1D.c_str());
717 
718  prefit->Write(("param_"+NDname+"_prefit").c_str());
719  paramPlot->Write(("param_"+NDname).c_str());
720  paramPlot_Gauss->Write(("param_"+NDname+"_gaus").c_str());
721  paramPlot_HPD->Write(("param_"+NDname+"_HPD").c_str());
722 
723  prefit->Draw("e2");
724  paramPlot->Draw("e2, same");
725  paramPlot_Gauss->Draw("e1, same");
726  paramPlot_HPD->Draw("e1, same");
727  CompLeg->Draw("same");
728  Posterior->Write(("param_"+NDname+"_canv").c_str());
729  if(printToPDF) Posterior->Print(CanvasName);
730  Posterior->Clear();
731  Start += NDSamplesBins[i];
732  }
733  }
734  //KS: Return Margin to default one
735  SetMargins(Posterior, Margins);
736 }
737 
738 // *********************
739 // Make fancy Credible Intervals plots
740 void MCMCProcessor::MakeCredibleIntervals(const std::vector<double>& CredibleIntervals,
741  const std::vector<Color_t>& CredibleIntervalsColours,
742  const bool CredibleInSigmas) {
743 // *********************
744  if(hpost[0] == nullptr) MakePostfit();
745 
746  MACH3LOG_INFO("Starting {}", __func__);
747  const double LeftMargin = Posterior->GetLeftMargin();
748  Posterior->SetLeftMargin(0.15);
749 
750  // KS: Sanity check of size and ordering is correct
751  CheckCredibleIntervalsOrder(CredibleIntervals, CredibleIntervalsColours);
752  const int nCredible = int(CredibleIntervals.size());
753  std::vector<std::unique_ptr<TH1D>> hpost_copy(nDraw);
754  std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(nDraw);
755 
756  //KS: Copy all histograms to be thread safe
757  for (int i = 0; i < nDraw; ++i)
758  {
759  hpost_copy[i] = M3::Clone<TH1D>(hpost[i], Form("hpost_copy_%i", i));
760  hpost_cl[i].resize(nCredible);
761  for (int j = 0; j < nCredible; ++j)
762  {
763  hpost_cl[i][j] = M3::Clone<TH1D>(hpost[i], Form("hpost_copy_%i_CL_%f", i, CredibleIntervals[j]));
764 
765  //KS: Reset to get rid to TF1 otherwise we run into segfault :(
766  hpost_cl[i][j]->Reset("");
767  hpost_cl[i][j]->Fill(0.0, 0.0);
768  }
769  }
770 
771  #ifdef MULTITHREAD
772  #pragma omp parallel for
773  #endif
774  for (int i = 0; i < nDraw; ++i)
775  {
777  hpost_copy[i]->Scale(1. / hpost_copy[i]->Integral());
778  for (int j = 0; j < nCredible; ++j)
779  {
780  // Scale the histograms before getting credible intervals
781  hpost_cl[i][j]->Scale(1. / hpost_cl[i][j]->Integral());
782  GetCredibleIntervalSig(hpost_copy[i], hpost_cl[i][j], CredibleInSigmas, CredibleIntervals[j]);
783 
784  hpost_cl[i][j]->SetFillColor(CredibleIntervalsColours[j]);
785  hpost_cl[i][j]->SetLineWidth(1);
786  }
787  hpost_copy[i]->GetYaxis()->SetTitleOffset(1.8);
788  hpost_copy[i]->SetLineWidth(1);
789  hpost_copy[i]->SetMaximum(hpost_copy[i]->GetMaximum()*1.2);
790  hpost_copy[i]->SetLineWidth(2);
791  hpost_copy[i]->SetLineColor(kBlack);
792  hpost_copy[i]->GetYaxis()->SetTitle("Posterior Probability");
793  }
794 
795  OutputFile->cd();
796  TDirectory *CredibleDir = OutputFile->mkdir("Credible");
797 
798  for (int i = 0; i < nDraw; ++i)
799  {
800  if(!ParamVaried[i]) continue;
801 
802  // Now make the TLine for the Asimov
803  TString Title = "";
804  double Prior = 1.0, PriorError = 1.0;
805  GetNthParameter(i, Prior, PriorError, Title);
806 
807  auto Asimov = std::make_unique<TLine>(Prior, hpost_copy[i]->GetMinimum(), Prior, hpost_copy[i]->GetMaximum());
808  SetTLineStyle(Asimov.get(), kRed-3, 2, kDashed);
809 
810  auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
811  SetLegendStyle(legend.get(), 0.03);
812  hpost_copy[i]->Draw("HIST");
813 
814  for (int j = 0; j < nCredible; ++j)
815  hpost_cl[i][j]->Draw("HIST SAME");
816  for (int j = nCredible-1; j >= 0; --j)
817  {
818  if(CredibleInSigmas)
819  legend->AddEntry(hpost_cl[i][j].get(), Form("%.0f#sigma Credible Interval", CredibleIntervals[j]), "f");
820  else
821  legend->AddEntry(hpost_cl[i][j].get(), Form("%.0f%% Credible Interval", CredibleIntervals[j]*100), "f");
822  }
823  legend->AddEntry(Asimov.get(), Form("#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError), "l");
824  legend->Draw("SAME");
825  Asimov->Draw("SAME");
826 
827  // Write to file
828  Posterior->SetName(hpost[i]->GetName());
829  Posterior->SetTitle(hpost[i]->GetTitle());
830 
831  if(printToPDF) Posterior->Print(CanvasName);
832  // cd into directory in root file
833  CredibleDir->cd();
834  Posterior->Write();
835  }
836  CredibleDir->Close();
837  delete CredibleDir;
838 
839  OutputFile->cd();
840 
841  //Set back to normal
842  Posterior->SetLeftMargin(LeftMargin);
843 }
844 
845 // *********************
846 // Make fancy violin plots
848 // *********************
849  MACH3LOG_INFO("Starting {}", __func__);
850 
851  //KS: Find min and max to make histogram in range
852  double maxi_y = -9999;
853  double mini_y = +9999;
854  for (int i = 0; i < nDraw; ++i)
855  {
856  auto range = GetHistRange(i);
857  mini_y = std::min(mini_y, range.first);
858  maxi_y = std::max(maxi_y, range.second);
859  }
860 
861  const int vBins = (maxi_y-mini_y)*25;
862  hviolin = std::make_unique<TH2D>("hviolin", "hviolin", nDraw, 0, nDraw, vBins, mini_y, maxi_y);
863  hviolin->SetDirectory(nullptr);
864  //KS: Prior has larger errors so we increase range and number of bins
865  constexpr int PriorFactor = 4;
866  hviolin_prior = std::make_unique<TH2D>("hviolin_prior", "hviolin_prior", nDraw, 0, nDraw, PriorFactor*vBins, PriorFactor*mini_y, PriorFactor*maxi_y);
867  hviolin_prior->SetDirectory(nullptr);
868 
869  std::vector<double> PriorVec(nDraw);
870  std::vector<double> PriorErrorVec(nDraw);
871  std::vector<bool> PriorFlatVec(nDraw);
872 
873  for (int x = 0; x < nDraw; ++x)
874  {
875  TString Title;
876  double Prior, PriorError;
877 
878  GetNthParameter(x, Prior, PriorError, Title);
879  //Set fancy labels
880  hviolin->GetXaxis()->SetBinLabel(x+1, Title);
881  hviolin_prior->GetXaxis()->SetBinLabel(x+1, Title);
882  PriorVec[x] = Prior;
883  PriorErrorVec[x] = PriorError;
884 
885  PriorFlatVec[x] = GetParamFlat(x);
886  }
887 
888  TStopwatch clock;
889  clock.Start();
890  //KS: Posterior is filled by RDataFrame, all histograms are filled in ONE event loop over the tree
891  // Implicit MT parallelises reading and decompression, which was the serial bottleneck in CacheSteps
892  M3::EnableROOTMultiThreading();
893 
894  // Get RDataFrame
895  auto dfToUse = GetFilteredDataFrame();
896 
897  //KS: Binning is identical to Y axis of hviolin so bin number maps 1:1, including under/overflow
898  std::vector<ROOT::RDF::RResultPtr<TH1D>> hPar(nDraw);
899  for (int x = 0; x < nDraw; ++x) {
900  const ROOT::RDF::TH1DModel model(Form("hviolin_tmp_%d", x), "", vBins, mini_y, maxi_y);
901  hPar[x] = dfToUse.Histo1D<double, double>(model, BranchNames[x].Data(), "MCMC_RDF_WEIGHT");
902  }
903 
904  //KS: First access triggers the event loop, afterwards all histograms are ready
905  for (int x = 0; x < nDraw; ++x) {
906  for (int y = 0; y <= vBins+1; ++y) {
907  hviolin->SetBinContent(x+1, y, hPar[x]->GetBinContent(y));
908  }
909  }
910 
911  M3::DisableROOTMultiThreading();
912  // nDraw is number of draws we want to do
913  #ifdef MULTITHREAD
914  #pragma omp parallel for
915  #endif
916  for (int x = 0; x < nDraw; ++x)
917  {
918  //KS: If we set option to not plot flat prior and param has flat prior then we skip this step
919  if(!(!PlotFlatPrior && PriorFlatVec[x]))
920  {
921  for (int k = 0; k < nEntries; ++k)
922  {
923  const double Entry = M3::rand::Gaus(PriorVec[x], PriorErrorVec[x]);
924  const double y = hviolin_prior->GetYaxis()->FindBin(Entry);
925  hviolin_prior->SetBinContent(x+1, y, hviolin_prior->GetBinContent(x+1, y)+1);
926  }
927  }
928  } // end the for loop over nDraw
929  clock.Stop();
930  MACH3LOG_INFO("Making Violin plot took {:.2f}s to finish for {} steps", clock.RealTime(), nEntries);
931  // It's plotting time
932  PlotViolins();
933 }
934 
935 // *********************
936 // Plot fancy violin plots
938 // *********************
939  //KS: Tells how many parameters in one canvas we want
940  constexpr int IntervalsSize = 10;
941  const int NIntervals = nDraw/IntervalsSize;
942 
943  hviolin->GetYaxis()->SetTitle("Parameter Value");
944  hviolin->GetXaxis()->SetTitle();
945  hviolin->GetXaxis()->LabelsOption("v");
946 
947  hviolin_prior->GetYaxis()->SetTitle("Parameter Value");
948  hviolin_prior->GetXaxis()->SetTitle();
949  hviolin_prior->GetXaxis()->LabelsOption("v");
950 
951  hviolin_prior->SetLineColor(kRed);
952  hviolin_prior->SetMarkerColor(kRed);
953  hviolin_prior->SetFillColorAlpha(kRed, 0.35);
954  hviolin_prior->SetMarkerStyle(20);
955  hviolin_prior->SetMarkerSize(0.5);
956 
957  // These control violin width, if you use larger then 1 they will most likely overlay, so be cautious
958  hviolin_prior->SetBarWidth(1.0);
959  hviolin_prior->SetBarOffset(0);
960 
961  hviolin->SetLineColor(kBlue);
962  hviolin->SetMarkerColor(kBlue);
963  hviolin->SetFillColorAlpha(kBlue, 0.35);
964  hviolin->SetMarkerStyle(20);
965  hviolin->SetMarkerSize(1.0);
966 
967  const double BottomMargin = Posterior->GetBottomMargin();
968  Posterior->SetBottomMargin(0.2);
969 
970  OutputFile->cd();
971  hviolin->Write("param_violin");
972  hviolin_prior->Write("param_violin_prior");
973  //KS: This is mostly for example plots, we have full file in the ROOT file so can do much better plot later
974  hviolin->GetYaxis()->SetRangeUser(-1, +2);
975  hviolin_prior->GetYaxis()->SetRangeUser(-1, +2);
976  for (int i = 0; i < NIntervals+1; ++i)
977  {
978  int RangeMin = i*IntervalsSize;
979  int RangeMax = RangeMin + IntervalsSize;
980  if(i == NIntervals+1) {
981  RangeMin = i*IntervalsSize;
982  RangeMax = nDraw;
983  }
984  if(RangeMin >= nDraw) break;
985 
986  hviolin->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
987  hviolin_prior->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
988 
989  //KS: ROOT6 has some additional options, consider updating it. more https://root.cern/doc/master/classTHistPainter.html#HP140b
990  hviolin_prior->Draw("violinX(03100300)");
991  hviolin->Draw("violinX(03100300) SAME");
992  if(printToPDF) Posterior->Print(CanvasName);
993  }
994  //KS: Return Margin to default one
995  Posterior->SetBottomMargin(BottomMargin);
996 }
997 
998 // *********************
999 // Make the post-fit covariance matrix in all dimensions
1001 // *********************
1002  if (OutputFile == nullptr) MakeOutputFile();
1003  if (hpost2D.size() == 0) Prepare2DHistograms();
1004 
1005  MACH3LOG_INFO("Making post-fit covariances...");
1006  TStopwatch clock;
1007  clock.Start();
1008 
1009  TDirectory *PostHistDir = nullptr;
1010  if (!Mute) {
1011  PostHistDir = OutputFile->mkdir("Post_2d_hists");
1012  PostHistDir->cd();
1013  }
1014  gStyle->SetPalette(55);
1015 
1016  //KS: Posterior is filled by RDataFrame, all histograms are filled in ONE event loop over the tree
1017  // Implicit MT parallelises reading and decompression, which was the serial bottleneck in CacheSteps
1018  M3::EnableROOTMultiThreading();
1019 
1020  // Apply selection once
1021  auto dfToUse = GetFilteredDataFrame();
1022  // Only need the indices and the lazy result: titles/ranges live in hpost2D[i][j]
1023  struct CovarianceHistogram {
1024  int i, j;
1025  ROOT::RDF::RResultPtr<TH2D> Result;
1026  };
1027 
1028  std::vector<CovarianceHistogram> Histograms;
1029 
1030  // Number of covariance elements
1031  const int nCov = nDraw * (nDraw - 1) / 2;
1032  Histograms.reserve(nCov);
1033 
1034  MACH3LOG_INFO("Booking {} 2D histograms...", nCov);
1035  for (int i = 0; i < nDraw; ++i)
1036  {
1037  for (int j = 0; j < i; ++j) // j < i: diagonal is already done
1038  {
1039  // If this parameter isn't varied
1040  if (ParamVaried[j] == false) {
1041  (*Covariance)(i,j) = (*Covariance)(j,i) = 0.0;
1042  (*Correlation)(i,j) = (*Correlation)(j,i) = 0.0;
1043  continue;
1044  }
1045 
1046  // Clear so repeated calls to MakeCovariance don't double count
1047  hpost2D[i][j]->Reset();
1048 
1049  // Build the model (name, title, binning, range) from the existing histogram
1050  const ROOT::RDF::TH2DModel model(*hpost2D[i][j]);
1051  Histograms.push_back({i, j, dfToUse.Histo2D(model, BranchNames[i].Data(), BranchNames[j].Data(), "MCMC_RDF_WEIGHT")});
1052  } // End j loop
1053  } // End i loop
1054  MACH3LOG_INFO("Finished booking {} histograms. Now executing RDF event loop...", Histograms.size());
1055 
1056  // The first GetPtr() triggers the RDF event loop.
1057  // Because ALL histograms have already been booked, RDF fills all of them in one pass.
1058  if (!Histograms.empty()) {
1059  TH2D *dummy = Histograms[0].Result.GetPtr();
1060  (void)dummy;
1061  }
1062  clock.Stop();
1063  MACH3LOG_INFO("RDataFrame event loop took {:.2f}s for {} entries", clock.RealTime(), nEntries);
1064  M3::DisableROOTMultiThreading();
1065 
1066  TStopwatch processingClock;
1067  processingClock.Start();
1068 
1069  for (auto &Entry : Histograms)
1070  {
1071  const int i = Entry.i;
1072  const int j = Entry.j;
1073 
1074  // Move RDF result into the pre-existing histogram (axis titles, min etc. already set)
1075  TH2D *hpost_2D = hpost2D[i][j].get();
1076  hpost_2D->Add(Entry.Result.GetPtr());
1077 
1078  if (ApplySmoothing) hpost_2D->Smooth();
1079 
1080  // Get the Covariance for these two parameters
1081  (*Covariance)(i,j) = hpost2D[i][j]->GetCovariance();
1082  (*Covariance)(j,i) = (*Covariance)(i,j);
1083 
1084  //KS: Since we already have covariance consider calculating correlation using it, right now we effectively calculate covariance twice
1085  //https://root.cern.ch/doc/master/TH2_8cxx_source.html#l01099
1086  (*Correlation)(i,j) = hpost2D[i][j]->GetCorrelationFactor();
1087  (*Correlation)(j,i) = (*Correlation)(i,j);
1088  }
1089 
1090  if (!Mute)
1091  {
1092  WriteCovariance(PostHistDir);
1093  processingClock.Stop();
1094  MACH3LOG_INFO("Processing covariance histograms took {:.2f}s", processingClock.RealTime());
1095  } // end mute
1096 }
1097 
1098 // *********************
1099 // Write covariances to output file
1100 void MCMCProcessor::WriteCovariance(TDirectory *PostHistDir) {
1101 // *********************
1102  if (printToPDF)
1103  {
1104  Posterior->cd();
1105  for (int i = 0; i < nDraw; ++i)
1106  {
1107  for (int j = 0; j < i; ++j)
1108  {
1109  if (ParamVaried[j] == false) continue;
1110 
1111  if (ParamType[i] == kModelPar && ParamType[j] == kModelPar)
1112  {
1113  if (std::fabs((*Correlation)(i,j)) > Post2DPlotThreshold)
1114  {
1115  hpost2D[i][j]->Draw("colz");
1116  Posterior->SetName(hpost2D[i][j]->GetName());
1117  Posterior->SetTitle(hpost2D[i][j]->GetTitle());
1118  Posterior->Print(CanvasName);
1119  hpost2D[i][j]->Write(hpost2D[i][j]->GetTitle());
1120  }
1121  }
1122  } // End j loop
1123  } // End i loop
1124  } // end if pdf
1125 
1126  if (PostHistDir) {
1127  PostHistDir->Close();
1128  delete PostHistDir;
1129  }
1130  OutputFile->cd();
1131  Covariance->Write("Covariance");
1132  Correlation->Write("Correlation");
1133 }
1134 
1135 // ***************
1136 //KS: Cache all steps to allow multithreading, hit RAM quite a bit
1138 // ***************
1139  // Check that the diagonal entries have been filled
1140  // i.e. MakePostfit() has been called
1141  for (int i = 0; i < nDraw; ++i) {
1142  if ((*Covariance)(i,i) == M3::_BAD_DOUBLE_) {
1143  MACH3LOG_INFO("Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
1144  MakePostfit();
1145  break;
1146  }
1147  }
1148 
1149  if(hpost2D.size() != 0) return;
1150 
1151  // Calculate the total number of TH2D objects
1152  size_t nHistograms = nDraw * (nDraw + 1) / 2;
1153  MACH3LOG_INFO("Caching 2D posterior histograms...");
1154  MACH3LOG_INFO("Allocating {:.2f} MB for {} 2D Posteriors (each {}x{} bins)",
1155  double(nHistograms * nBins * nBins * sizeof(double)) / 1.E6, nHistograms, nBins, nBins);
1156 
1157  hpost2D.resize(nDraw);
1158  // Cache max and min in chain for covariance matrix
1159  for (int i = 0; i < nDraw; ++i)
1160  {
1161  TString Title_i = "";
1162  double Prior_i, PriorError_i;
1163  GetNthParameter(i, Prior_i, PriorError_i, Title_i);
1164  hpost2D[i].resize(nDraw);
1165  for (int j = 0; j <= i; ++j)
1166  {
1167  TString Title_j = "";
1168  double Prior_j, PriorError_j;
1169  GetNthParameter(j, Prior_j, PriorError_j, Title_j);
1170 
1171  auto range_x = GetHistRange(i);
1172  auto range_y = GetHistRange(j);
1173  // TH2D to hold the Correlation
1174  hpost2D[i][j] = std::make_unique<TH2D>((Title_i + "_" + Title_j).Data(), (Title_i + "_" + Title_j).Data(),
1175  nBins, range_x.first, range_x.second,
1176  nBins, range_y.first, range_y.second);
1177  hpost2D[i][j]->SetDirectory(nullptr);
1178  hpost2D[i][j]->SetMinimum(0);
1179  hpost2D[i][j]->GetXaxis()->SetTitle(Title_i);
1180  hpost2D[i][j]->GetYaxis()->SetTitle(Title_j);
1181  hpost2D[i][j]->GetZaxis()->SetTitle("Steps");
1182  }
1183  }
1184 }
1185 
1186 // *********************
1187 // Based on @cite roberts2009adaptive
1188 // all credits for finding and studying it goes to Henry
1189 void MCMCProcessor::MakeSubOptimality(const int NIntervals) {
1190 // *********************
1191  //Save burn in cut, at the end of the loop we will return to default values
1192  const int DefaultUpperCut = UpperCut;
1193  const int DefaultBurnInCut = BurnInCut;
1194  bool defaultPrintToPDF = printToPDF;
1195  BurnInCut = 0;
1196  UpperCut = 0;
1197  printToPDF = false;
1198 
1199  //Set via config in future
1200  int MaxStep = nSteps;
1201  int MinStep = 0;
1202  const int IntervalsSize = nSteps/NIntervals;
1203 
1204  MACH3LOG_INFO("Making Suboptimality");
1205  TStopwatch clock;
1206  clock.Start();
1207 
1208  std::unique_ptr<TH1D> SubOptimality = std::make_unique<TH1D>("Suboptimality", "Suboptimality", NIntervals, MinStep, MaxStep);
1209  SubOptimality->SetDirectory(nullptr);
1210  SubOptimality->GetXaxis()->SetTitle("Step");
1211  SubOptimality->GetYaxis()->SetTitle("Suboptimality");
1212  SubOptimality->SetLineWidth(2);
1213  SubOptimality->SetLineColor(kBlue);
1214 
1215  for(int i = 0; i < NIntervals; ++i)
1216  {
1217  //Reset our cov matrix
1219 
1220  //Set threshold for calculating new matrix
1221  UpperCut = i*IntervalsSize;
1222  //Calculate cov matrix
1223  MakeCovariance(true);
1224 
1225  //Calculate eigen values
1226  TMatrixDSymEigen eigen(*Covariance);
1227  TVectorD eigen_values;
1228  eigen_values.ResizeTo(eigen.GetEigenValues());
1229  eigen_values = eigen.GetEigenValues();
1230 
1231  //KS: Converting from ROOT to vector as to make using other libraires (Eigen) easier in future
1232  std::vector<double> EigenValues(eigen_values.GetNrows());
1233  for(unsigned int j = 0; j < EigenValues.size(); j++)
1234  {
1235  EigenValues[j] = eigen_values(j);
1236  }
1237  const double SubOptimalityValue = GetSubOptimality(EigenValues, nDraw);
1238  SubOptimality->SetBinContent(i+1, SubOptimalityValue);
1239  }
1240  clock.Stop();
1241  MACH3LOG_INFO("Making Suboptimality took {:.2f}s to finish for {} steps", clock.RealTime(), nEntries);
1242 
1243  UpperCut = DefaultUpperCut;
1244  BurnInCut = DefaultBurnInCut;
1245  printToPDF = defaultPrintToPDF;
1246 
1247  SubOptimality->Draw("l");
1248  Posterior->SetName(SubOptimality->GetName());
1249  Posterior->SetTitle(SubOptimality->GetTitle());
1250 
1251  if(printToPDF) Posterior->Print(CanvasName);
1252  // Write it to root file
1253  OutputFile->cd();
1254  Posterior->Write();
1255 }
1256 
1257 // *********************
1258 // Make the covariance plots
1260 // *********************
1261  const double RightMargin = Posterior->GetRightMargin();
1262  Posterior->SetRightMargin(0.15);
1263 
1264  // The Covariance matrix from the fit
1265  auto hCov = std::make_unique<TH2D>("hCov", "hCov", nDraw, 0, nDraw, nDraw, 0, nDraw);
1266  hCov->GetZaxis()->SetTitle("Covariance");
1267  hCov->SetDirectory(nullptr);
1268  // The Covariance matrix square root, with correct sign
1269  auto hCovSq = std::make_unique<TH2D>("hCovSq", "hCovSq", nDraw, 0, nDraw, nDraw, 0, nDraw);
1270  hCovSq->SetDirectory(nullptr);
1271  hCovSq->GetZaxis()->SetTitle("Covariance");
1272  // The Correlation
1273  auto hCorr = std::make_unique<TH2D>("hCorr", "hCorr", nDraw, 0, nDraw, nDraw, 0, nDraw);
1274  hCorr->SetDirectory(nullptr);
1275  hCorr->GetZaxis()->SetTitle("Correlation");
1276  hCorr->SetMinimum(-1);
1277  hCorr->SetMaximum(1);
1278  hCov->GetXaxis()->SetLabelSize(0.015);
1279  hCov->GetYaxis()->SetLabelSize(0.015);
1280  hCovSq->GetXaxis()->SetLabelSize(0.015);
1281  hCovSq->GetYaxis()->SetLabelSize(0.015);
1282  hCorr->GetXaxis()->SetLabelSize(0.015);
1283  hCorr->GetYaxis()->SetLabelSize(0.015);
1284 
1285  // Loop over the Covariance matrix entries
1286  for (int i = 0; i < nDraw; ++i)
1287  {
1288  TString titlex = "";
1289  double nom, err;
1290  GetNthParameter(i, nom, err, titlex);
1291 
1292  hCov->GetXaxis()->SetBinLabel(i+1, titlex);
1293  hCovSq->GetXaxis()->SetBinLabel(i+1, titlex);
1294  hCorr->GetXaxis()->SetBinLabel(i+1, titlex);
1295 
1296  for (int j = 0; j < nDraw; ++j)
1297  {
1298  // The value of the Covariance
1299  const double cov = (*Covariance)(i,j);
1300  const double corr = (*Correlation)(i,j);
1301 
1302  hCov->SetBinContent(i+1, j+1, cov);
1303  hCovSq->SetBinContent(i+1, j+1, ((cov > 0) - (cov < 0))*std::sqrt(std::fabs(cov)));
1304  hCorr->SetBinContent(i+1, j+1, corr);
1305 
1306  TString titley = "";
1307  double nom_j, err_j;
1308  GetNthParameter(j, nom_j, err_j, titley);
1309 
1310  hCov->GetYaxis()->SetBinLabel(j+1, titley);
1311  hCovSq->GetYaxis()->SetBinLabel(j+1, titley);
1312  hCorr->GetYaxis()->SetBinLabel(j+1, titley);
1313  }
1314  }
1315 
1316  // Take away the stat box
1317  gStyle->SetOptStat(0);
1318  if(plotBinValue)gStyle->SetPaintTextFormat("4.1f"); //Precision of value in matrix element
1319  // Make pretty Correlation colors (red to blue)
1320  constexpr int NRGBs = 5;
1321  TColor::InitializeColors();
1322  Double_t stops[NRGBs] = { 0.00, 0.25, 0.50, 0.75, 1.00 };
1323  Double_t red[NRGBs] = { 0.00, 0.25, 1.00, 1.00, 0.50 };
1324  Double_t green[NRGBs] = { 0.00, 0.25, 1.00, 0.25, 0.00 };
1325  Double_t blue[NRGBs] = { 0.50, 1.00, 1.00, 0.25, 0.00 };
1326  TColor::CreateGradientColorTable(5, stops, red, green, blue, 255);
1327  gStyle->SetNumberContours(255);
1328 
1329  // cd into the correlation directory
1330  OutputFile->cd();
1331 
1332  Posterior->cd();
1333  Posterior->Clear();
1334  if(plotBinValue) hCov->Draw("colz text");
1335  else hCov->Draw("colz");
1336  if(printToPDF) Posterior->Print(CanvasName);
1337 
1338  Posterior->cd();
1339  Posterior->Clear();
1340  if(plotBinValue) hCorr->Draw("colz text");
1341  else hCorr->Draw("colz");
1342  if(printToPDF) Posterior->Print(CanvasName);
1343 
1344  hCov->Write("Covariance_plot");
1345  hCovSq->Write("Covariance_sq_plot");
1346  hCorr->Write("Correlation_plot");
1347 
1348  //Back to normal
1349  Posterior->SetRightMargin(RightMargin);
1350  DrawCorrelationsGroup(hCorr);
1352 }
1353 
1354 // *********************
1355 void MCMCProcessor::MakeCovarianceYAML(const std::string& OutputYAMLFile, const std::string& MeansMethod) const {
1356 // *********************
1357  MACH3LOG_INFO("Making covariance matrix YAML file");
1358 
1359  if (ParamNames[kModelPar].size() != static_cast<size_t>(nDraw)) {
1360  MACH3LOG_ERROR("Using Legacy Parameters i.e. not one from Parameter Handler Generic, this will not work");
1361  throw MaCh3Exception(__FILE__, __LINE__);
1362  }
1363  std::vector<double> MeanArray(nDraw);
1364  std::vector<double> ErrorArray(nDraw);
1365  std::vector<std::vector<double>> CorrelationMatrix(nDraw, std::vector<double>(nDraw, 0.0));
1366 
1367  TVectorD* means_vec;
1368  TVectorD* errors_vec;
1369 
1370  if (MeansMethod == "Arithmetic") {
1371  means_vec = Means;
1372  errors_vec = Errors;
1373  } else if (MeansMethod == "Gaussian") {
1374  means_vec = Means_Gauss;
1375  errors_vec = Errors_Gauss;
1376  } else if (MeansMethod == "HPD") {
1377  means_vec = Means_HPD;
1378  errors_vec = Errors_HPD;
1379  } else {
1380  MACH3LOG_ERROR("Unknown means method: {}, should be either 'Arithmetic', 'Gaussian', or 'HPD'.", MeansMethod);
1381  throw MaCh3Exception(__FILE__, __LINE__);
1382  }
1383 
1384  //Make vectors of mean, error, and correlations
1385  for (int i = 0; i < nDraw; i++)
1386  {
1387  MeanArray[i] = (*means_vec)(i);
1388  ErrorArray[i] = (*errors_vec)(i);
1389  for (int j = 0; j <= i; j++)
1390  {
1391  CorrelationMatrix[i][j] = (*Correlation)(i,j);
1392  if(i != j) CorrelationMatrix[j][i] = (*Correlation)(i,j);
1393  }
1394  }
1395 
1396  //Make std::string param name vector
1397  std::vector<std::string> ParamStrings(ParamNames[kModelPar].size());
1398  for (size_t i = 0; i < ParamNames[kModelPar].size(); ++i) {
1399  ParamStrings[i] = static_cast<std::string>(ParamNames[kModelPar][i]);
1400  }
1401 
1402  YAML::Node ModelFile = CovConfig[kModelPar];
1403  M3::MakeCorrelationMatrix(ModelFile, MeanArray, ErrorArray, CorrelationMatrix, OutputYAMLFile, ParamStrings);
1404 }
1405 
1406 // *********************
1407 // Inspired by plot in Ewan thesis see https://www.t2k.org/docs/thesis/152/Thesis#page=147
1408 void MCMCProcessor::DrawCorrelationsGroup(const std::unique_ptr<TH2D>& CorrMatrix) const {
1409 // *********************
1410  MACH3LOG_INFO("Starting {}", __func__);
1411  const double RightMargin = Posterior->GetRightMargin();
1412  Posterior->SetRightMargin(0.15);
1413  auto MatrixCopy = M3::Clone(CorrMatrix);
1414 
1415  std::vector<std::string> GroupName;
1416  std::vector<int> GroupStart;
1417  std::vector<int> GroupEnd;
1418 
1419  // Loop over the Covariance matrix entries
1420  for (int iPar = 0; iPar < nDraw; ++iPar)
1421  {
1422  std::string GroupNameCurr;
1423  if(ParamType[iPar] == kModelPar){
1424  const int InternalNumeration = iPar - ParamTypeStartPos[kModelPar];
1425  GroupNameCurr = ParameterGroup[InternalNumeration];
1426  } else {
1427  GroupNameCurr = "Other"; // Use Other for all legacy params
1428  }
1429 
1430  if(iPar == 0) {
1431  GroupName.push_back(GroupNameCurr);
1432  GroupStart.push_back(0);
1433  } else if(GroupName.back() != GroupNameCurr ){
1434  GroupName.push_back(GroupNameCurr);
1435  GroupEnd.push_back(iPar);
1436  GroupStart.push_back(iPar);
1437  }
1438 
1439  MatrixCopy->GetXaxis()->SetBinLabel(iPar+1, "");
1440  MatrixCopy->GetYaxis()->SetBinLabel(iPar+1, "");
1441  }
1442  GroupEnd.push_back(nDraw);
1443 
1444  for(size_t iPar = 0; iPar < GroupName.size(); iPar++) {
1445  MACH3LOG_INFO("Group name {} from {} to {}", GroupName[iPar], GroupStart[iPar], GroupEnd[iPar]);
1446  }
1447  Posterior->cd();
1448  Posterior->Clear();
1449  MatrixCopy->Draw("colz");
1450 
1451  std::vector<std::unique_ptr<TLine>> groupLines; //((GroupStart.size() - 1) * 2);
1452 
1453  int nBinsX = MatrixCopy->GetNbinsX();
1454  int nBinsY = MatrixCopy->GetNbinsY();
1455 
1456  // Axis bounds from the histogram itself
1457  double xMin = MatrixCopy->GetXaxis()->GetBinLowEdge(1);
1458  double xMax = MatrixCopy->GetXaxis()->GetBinUpEdge(nBinsX);
1459  double yMin = MatrixCopy->GetYaxis()->GetBinLowEdge(1);
1460  double yMax = MatrixCopy->GetYaxis()->GetBinUpEdge(nBinsY);
1461 
1462  for (size_t g = 1; g < GroupStart.size(); ++g) {
1463  const double posX = MatrixCopy->GetXaxis()->GetBinLowEdge(GroupStart[g] + 1);
1464  const double posY = MatrixCopy->GetYaxis()->GetBinLowEdge(GroupStart[g] + 1);
1465 
1466  // Vertical line at group start
1467  auto vLine = std::make_unique<TLine>(posX, yMin, posX, yMax);
1468  vLine->SetLineColor(kBlack);
1469  vLine->SetLineWidth(2);
1470  vLine->Draw();
1471  groupLines.push_back(std::move(vLine));
1472 
1473  // Horizontal line at group start
1474  auto hLine = std::make_unique<TLine>(xMin, posY, xMax, posY);
1475  hLine->SetLineColor(kBlack);
1476  hLine->SetLineWidth(2);
1477  hLine->Draw();
1478  groupLines.push_back(std::move(hLine));
1479  }
1480 
1481  std::vector<std::unique_ptr<TText>> groupLabels(GroupName.size() * 2);
1482  const double yOffsetBelow = 0.05 * (yMax - yMin); // space below x-axis
1483  const double xOffsetRight = 0.02 * (xMax - xMin); // space right of y-axis
1484 
1485  for (size_t g = 0; g < GroupName.size(); ++g) {
1486  const int startBin = GroupStart[g] + 1; // hist bins start at 1
1487  const int endBin = GroupEnd[g];
1488 
1489  const double xStart = MatrixCopy->GetXaxis()->GetBinLowEdge(startBin);
1490  const double xEnd = MatrixCopy->GetXaxis()->GetBinUpEdge(endBin);
1491  const double xMid = 0.5 * (xStart + xEnd);
1492 
1493  const double yStart = MatrixCopy->GetYaxis()->GetBinLowEdge(startBin);
1494  const double yEnd = MatrixCopy->GetYaxis()->GetBinUpEdge(endBin);
1495  const double yMid = 0.5 * (yStart + yEnd);
1496 
1497  // Label along X-axis (below histogram)
1498  auto labelX = std::make_unique<TText>(xMid, yMin - yOffsetBelow, GroupName[g].c_str());
1499  labelX->SetTextAlign(23); // center horizontally, top-aligned vertically
1500  labelX->SetTextSize(0.025);
1501  labelX->Draw();
1502  groupLabels.push_back(std::move(labelX));
1503 
1504  // Label along Y-axis (left of histogram)
1505  auto labelY = std::make_unique<TText>(xMin - xOffsetRight, yMid, GroupName[g].c_str());
1506  labelY->SetTextAlign(32); // right-aligned horizontally, center vertically
1507  labelY->SetTextSize(0.025);
1508  labelY->Draw();
1509  groupLabels.push_back(std::move(labelY));
1510  }
1511 
1512  if(printToPDF) Posterior->Print(CanvasName);
1513  Posterior->SetRightMargin(RightMargin);
1514 }
1515 
1516 // *********************
1517 //KS: Make the 1D projections of Correlations inspired by Henry's slides (page 28) https://www.t2k.org/asg/oagroup/meeting/2023/2023-07-10-oa-pre-meeting/MaCh3FDUpdate
1519 // *********************
1520  //KS: Store it as we go back to them at the end
1521  const std::vector<double> Margins = GetMargins(Posterior);
1522  const int OptTitle = gStyle->GetOptTitle();
1523 
1524  Posterior->SetTopMargin(0.1);
1525  Posterior->SetBottomMargin(0.2);
1526  gStyle->SetOptTitle(1);
1527 
1528  constexpr int Nhists = 3;
1529  //KS: Highest value is just meant bo be slightly higher than 1 to catch >,
1530  constexpr double Thresholds[Nhists+1] = {0, 0.25, 0.5, 1.0001};
1531  constexpr Color_t CorrColours[Nhists] = {kRed-10, kRed-6, kRed};
1532 
1533  //KS: This store necessary entries for stripped covariance which store only "meaningful correlations
1534  std::vector<std::vector<double>> CorrOfInterest(nDraw);
1535  std::vector<std::vector<std::string>> NameCorrOfInterest(nDraw);
1536  std::vector<std::vector<std::unique_ptr<TH1D>>> Corr1DHist(nDraw);
1537  //KS: Initialising ROOT objects is never safe in MP loop
1538  for(int i = 0; i < nDraw; ++i)
1539  {
1540  TString Title = "";
1541  double Prior = 1.0, PriorError = 1.0;
1542  GetNthParameter(i, Prior, PriorError, Title);
1543 
1544  Corr1DHist[i].resize(Nhists);
1545  for(int j = 0; j < Nhists; ++j)
1546  {
1547  Corr1DHist[i][j] = std::make_unique<TH1D>(Form("Corr1DHist_%i_%i", i, j), Form("Corr1DHist_%i_%i", i, j), nDraw, 0, nDraw);
1548  Corr1DHist[i][j]->SetTitle(Form("%s", Title.Data()));
1549  Corr1DHist[i][j]->SetDirectory(nullptr);
1550  Corr1DHist[i][j]->GetYaxis()->SetTitle("Correlation");
1551  Corr1DHist[i][j]->SetFillColor(CorrColours[j]);
1552  Corr1DHist[i][j]->SetLineColor(kBlack);
1553 
1554  for (int k = 0; k < nDraw; ++k)
1555  {
1556  TString Title_y = "";
1557  double Prior_y = 1.0;
1558  double PriorError_y = 1.0;
1559  GetNthParameter(k, Prior_y, PriorError_y, Title_y);
1560  Corr1DHist[i][j]->GetXaxis()->SetBinLabel(k+1, Title_y.Data());
1561  }
1562  }
1563  }
1564 
1565  // KS: Do not add collapse(2) otherwise one can introduce race condition :(
1566  #ifdef MULTITHREAD
1567  #pragma omp parallel for
1568  #endif
1569  for(int i = 0; i < nDraw; ++i)
1570  {
1571  for(int j = 0; j < nDraw; ++j)
1572  {
1573  for(int k = 0; k < Nhists; ++k)
1574  {
1575  const double TempEntry = std::fabs((*Correlation)(i,j));
1576  if(Thresholds[k+1] > TempEntry && TempEntry >= Thresholds[k])
1577  {
1578  Corr1DHist[i][k]->SetBinContent(j+1, (*Correlation)(i,j));
1579  }
1580  }
1581  if(std::fabs((*Correlation)(i,j)) > Post2DPlotThreshold && i != j) {
1582  CorrOfInterest[i].push_back((*Correlation)(i,j));
1583  NameCorrOfInterest[i].push_back(Corr1DHist[i][0]->GetXaxis()->GetBinLabel(j+1));
1584  }
1585  }
1586  }
1587 
1588  TDirectory *CorrDir = OutputFile->mkdir("Corr1D");
1589  CorrDir->cd();
1590  for(int i = 0; i < nDraw; i++)
1591  {
1592  if (ParamVaried[i] == false) continue;
1593 
1594  Corr1DHist[i][0]->GetXaxis()->LabelsOption("v");
1595  Corr1DHist[i][0]->SetMaximum(+1.);
1596  Corr1DHist[i][0]->SetMinimum(-1.);
1597  Corr1DHist[i][0]->Draw();
1598  for(int k = 1; k < Nhists; k++) {
1599  Corr1DHist[i][k]->Draw("SAME");
1600  }
1601 
1602  auto leg = std::make_unique<TLegend>(0.3, 0.75, 0.6, 0.90);
1603  SetLegendStyle(leg.get(), 0.02);
1604  for(int k = 0; k < Nhists; k++) {
1605  leg->AddEntry(Corr1DHist[i][k].get(), Form("%.2f > |Corr| >= %.2f", Thresholds[k+1], Thresholds[k]), "f");
1606  }
1607  leg->Draw("SAME");
1608 
1609  Posterior->Write(Corr1DHist[i][0]->GetTitle());
1610  if(printToPDF) Posterior->Print(CanvasName);
1611  }
1612  //KS: Plot only meaningful correlations
1613  DrawCorrelations1DReduced(CorrOfInterest, NameCorrOfInterest);
1614  CorrDir->Close();
1615  delete CorrDir;
1616  OutputFile->cd();
1617 
1618  SetMargins(Posterior, Margins);
1619  gStyle->SetOptTitle(OptTitle);
1620 }
1621 
1622 // *********************
1623 void MCMCProcessor::DrawCorrelations1DReduced(const std::vector<std::vector<double>>& CorrOfInterest,
1624  const std::vector<std::vector<std::string>>& NameCorrOfInterest) {
1625 // *********************
1626  //KS: Plot only meaningful correlations
1627  for(int i = 0; i < nDraw; i++)
1628  {
1629  const int size = int(CorrOfInterest[i].size());
1630  if(size == 0) continue;
1631  TString Title = "";
1632  double Prior = 1.0, PriorError = 1.0;
1633  GetNthParameter(i, Prior, PriorError, Title);
1634 
1635  auto Corr1DHist_Reduced = std::make_unique<TH1D>("Corr1DHist_Reduced", "Corr1DHist_Reduced", size, 0, size);
1636  Corr1DHist_Reduced->SetDirectory(nullptr);
1637  Corr1DHist_Reduced->SetTitle(Title);
1638  Corr1DHist_Reduced->GetYaxis()->SetTitle("Correlation");
1639  Corr1DHist_Reduced->SetFillColor(kBlue);
1640  Corr1DHist_Reduced->SetLineColor(kBlue);
1641 
1642  for (int j = 0; j < size; ++j)
1643  {
1644  Corr1DHist_Reduced->GetXaxis()->SetBinLabel(j+1, NameCorrOfInterest[i][j].c_str());
1645  Corr1DHist_Reduced->SetBinContent(j+1, CorrOfInterest[i][j]);
1646  }
1647  Corr1DHist_Reduced->GetXaxis()->LabelsOption("v");
1648 
1649  Corr1DHist_Reduced->SetMaximum(+1.);
1650  Corr1DHist_Reduced->SetMinimum(-1.);
1651  Corr1DHist_Reduced->Draw();
1652 
1653  Posterior->Write(Form("%s_Red", Corr1DHist_Reduced->GetTitle()));
1654  if(printToPDF) Posterior->Print(CanvasName);
1655  }
1656 }
1657 
1658 // *********************
1659 // Convert posterior likelihood to Delta Chi2 used for comparison with frequentists fitter
1660 void MCMCProcessor::ProduceChi2(const std::string& GroupName) const {
1661 // *********************
1662  if(GroupName == "") return;
1663  MACH3LOG_INFO("Starting {}", __func__);
1664  TDirectory* Chi2Folder = OutputFile->mkdir("DeltaChi2");
1665 
1666  Chi2Folder->cd();
1667  for (int iPar = 0; iPar < nDraw; iPar++)
1668  {
1669  std::string GroupNameCurr;
1670  if(ParamType[iPar] == kModelPar){
1671  const int InternalNumeration = iPar - ParamTypeStartPos[kModelPar];
1672  GroupNameCurr = ParameterGroup[InternalNumeration];
1673  } else {
1674  GroupNameCurr = "Other"; // Use Other for all legacy params
1675  }
1676  if (ParamVaried[iPar] == false) continue;
1677  if (GroupName != "All" && GroupNameCurr != GroupName) continue;
1678 
1679  auto Chi2 = GetDeltaChi2(hpost[iPar].get());
1680  RemoveFitter(Chi2.get(), "Gauss");
1681 
1682  Chi2->Write();
1683  }
1684  Chi2Folder->Close();
1685  delete Chi2Folder;
1686  OutputFile->cd();
1687 }
1688 
1689 // *********************
1690 // Make fancy Credible Intervals plots
1691 void MCMCProcessor::MakeCredibleRegions(const std::vector<double>& CredibleRegions,
1692  const std::vector<Style_t>& CredibleRegionStyle,
1693  const std::vector<Color_t>& CredibleRegionColor,
1694  const bool CredibleInSigmas,
1695  const bool Draw2DPosterior,
1696  const bool DrawBestFit) {
1697 // *********************
1698  if(hpost2D.size() == 0) MakeCovariance();
1699  MACH3LOG_INFO("Making Credible Regions");
1700 
1701  CheckCredibleRegionsOrder(CredibleRegions, CredibleRegionStyle, CredibleRegionColor);
1702  const int nCredible = int(CredibleRegions.size());
1703 
1704  std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_copy(nDraw);
1705  std::vector<std::vector<std::vector<std::unique_ptr<TH2D>>>> hpost_2D_cl(nDraw);
1706  //KS: Copy all histograms to be thread safe
1707  for (int i = 0; i < nDraw; ++i)
1708  {
1709  hpost_2D_copy[i].resize(nDraw);
1710  hpost_2D_cl[i].resize(nDraw);
1711  for (int j = 0; j <= i; ++j)
1712  {
1713  hpost_2D_copy[i][j] = M3::Clone<TH2D>(hpost2D[i][j], Form("hpost_copy_%i_%i", i, j));
1714  hpost_2D_cl[i][j].resize(nCredible);
1715  for (int k = 0; k < nCredible; ++k)
1716  {
1717  hpost_2D_cl[i][j][k] = M3::Clone<TH2D>(hpost2D[i][j], Form("hpost_copy_%i_%i_CL_%f", i, j, CredibleRegions[k]));
1718  }
1719  }
1720  }
1721 
1722  #ifdef MULTITHREAD
1723  #pragma omp parallel for
1724  #endif
1725  //Calculate credible histogram
1726  for (int i = 0; i < nDraw; ++i)
1727  {
1728  for (int j = 0; j <= i; ++j)
1729  {
1730  for (int k = 0; k < nCredible; ++k)
1731  {
1732  GetCredibleRegionSig(hpost_2D_cl[i][j][k], CredibleInSigmas, CredibleRegions[k]);
1733  hpost_2D_cl[i][j][k]->SetLineColor(CredibleRegionColor[k]);
1734  hpost_2D_cl[i][j][k]->SetLineWidth(2);
1735  hpost_2D_cl[i][j][k]->SetLineStyle(CredibleRegionStyle[k]);
1736  }
1737  }
1738  }
1739 
1740  gStyle->SetPalette(51);
1741  for (int i = 0; i < nDraw; ++i)
1742  {
1743  for (int j = 0; j <= i; ++j)
1744  {
1745  // Skip the diagonal elements which we've already done above
1746  if (j == i) continue;
1747  if (ParamVaried[j] == false) continue;
1748 
1749  auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
1750  legend->SetTextColor(kRed);
1751  SetLegendStyle(legend.get(), 0.03);
1752 
1753  //Get Best point
1754  auto bestfitM = std::make_unique<TGraph>(1);
1755  const int MaxBin = hpost_2D_copy[i][j]->GetMaximumBin();
1756  int Mbx, Mby, Mbz;
1757  hpost_2D_copy[i][j]->GetBinXYZ(MaxBin, Mbx, Mby, Mbz);
1758  const double Mx = hpost_2D_copy[i][j]->GetXaxis()->GetBinCenter(Mbx);
1759  const double My = hpost_2D_copy[i][j]->GetYaxis()->GetBinCenter(Mby);
1760 
1761  bestfitM->SetPoint(0, Mx, My);
1762  bestfitM->SetMarkerStyle(22);
1763  bestfitM->SetMarkerSize(1);
1764  bestfitM->SetMarkerColor(kMagenta);
1765 
1766  //Plot default 2D posterior
1767 
1768  if(Draw2DPosterior){
1769  hpost_2D_copy[i][j]->Draw("COLZ");
1770  } else{
1771  hpost_2D_copy[i][j]->Draw("AXIS");
1772  }
1773 
1774  //Now credible regions
1775  for (int k = 0; k < nCredible; ++k)
1776  hpost_2D_cl[i][j][k]->Draw("CONT3 SAME");
1777  for (int k = nCredible-1; k >= 0; --k)
1778  {
1779  if(CredibleInSigmas)
1780  legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form("%.0f#sigma Credible Interval", CredibleRegions[k]), "l");
1781  else
1782  legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form("%.0f%% Credible Region", CredibleRegions[k]*100), "l");
1783  }
1784  legend->Draw("SAME");
1785 
1786  if(DrawBestFit){
1787  legend->AddEntry(bestfitM.get(),"Best Fit","p");
1788  bestfitM->Draw("SAME.P");
1789  }
1790 
1791  // Write to file
1792  Posterior->SetName(hpost2D[i][j]->GetName());
1793  Posterior->SetTitle(hpost2D[i][j]->GetTitle());
1794 
1795  //KS: Print only regions with correlation greater than specified value, by default 0.2. This is done to avoid dumping thousands of plots
1796  if(printToPDF && std::fabs((*Correlation)(i,j)) > Post2DPlotThreshold) Posterior->Print(CanvasName);
1797  // Write it to root file
1798  //OutputFile->cd();
1799  //if( std::fabs((*Correlation)(i,j)) > Post2DPlotThreshold ) Posterior->Write();
1800  }
1801  }
1802 
1803  OutputFile->cd();
1804 }
1805 
1806 // *********************
1807 // Make fancy triangle plot for selected parameters
1808 void MCMCProcessor::MakeTrianglePlot(const std::vector<std::string>& ParNames,
1809  // 1D
1810  const std::vector<double>& CredibleIntervals,
1811  const std::vector<Color_t>& CredibleIntervalsColours,
1812  //2D
1813  const std::vector<double>& CredibleRegions,
1814  const std::vector<Style_t>& CredibleRegionStyle,
1815  const std::vector<Color_t>& CredibleRegionColor,
1816  // Other
1817  const bool CredibleInSigmas) {
1818 // *********************
1819  if(hpost2D.size() == 0) MakeCovariance();
1820 
1821  const int nParamPlot = int(ParNames.size());
1822  std::vector<int> ParamNumber;
1823  std::string ParamInfoNames = "Making Triangle Plot for { ";
1824  for(int j = 0; j < nParamPlot; ++j)
1825  {
1826  ParamInfoNames += fmt::format("{} ", ParNames[j]);
1827  int ParamNo = GetParamIndexFromName(ParNames[j]);
1828  if(ParamNo == M3::_BAD_INT_)
1829  {
1830  MACH3LOG_WARN("Couldn't find param {}. Will not plot Triangle plot", ParNames[j]);
1831  return;
1832  }
1833  ParamNumber.push_back(ParamNo);
1834  }
1835  ParamInfoNames += "}";
1836  MACH3LOG_INFO("{}", ParamInfoNames);
1837 
1838  //KS: Store it as we go back to them at the end
1839  const std::vector<double> Margins = GetMargins(Posterior);
1840  Posterior->SetTopMargin(0.001);
1841  Posterior->SetBottomMargin(0.001);
1842  Posterior->SetLeftMargin(0.001);
1843  Posterior->SetRightMargin(0.001);
1844 
1845  // KS: We later format hist several times so make one unfired lambda
1846  auto FormatHistogram = [](auto& hist) {
1847  hist->GetXaxis()->SetTitle("");
1848  hist->GetYaxis()->SetTitle("");
1849  hist->SetTitle("");
1850 
1851  hist->GetXaxis()->SetLabelSize(0.1);
1852  hist->GetYaxis()->SetLabelSize(0.1);
1853 
1854  hist->GetXaxis()->SetNdivisions(4);
1855  hist->GetYaxis()->SetNdivisions(4);
1856  };
1857 
1858  Posterior->cd();
1859  Posterior->Clear();
1860  Posterior->Update();
1861 
1862  //KS: We sort to have parameters from highest to lowest, this is related to how we make 2D projections in MakeCovariance_MP
1863  std::sort(ParamNumber.begin(), ParamNumber.end(), std::greater<int>());
1864 
1865  //KS: Calculate how many pads/plots we need
1866  int Npad = 0;
1867  for(int j = 1; j < nParamPlot+1; j++) Npad += j;
1868  Posterior->cd();
1869  // KS: Sanity check of size and ordering is correct
1870  CheckCredibleIntervalsOrder(CredibleIntervals, CredibleIntervalsColours);
1871  CheckCredibleRegionsOrder(CredibleRegions, CredibleRegionStyle, CredibleRegionColor);
1872 
1873  const int nCredibleIntervals = int(CredibleIntervals.size());
1874  const int nCredibleRegions = int(CredibleRegions.size());
1875 
1876  //KS: Initialise Tpad histograms etc we will need
1877  std::vector<std::unique_ptr<TPad>> TrianglePad(Npad);
1878  //KS: 1D copy of posterior, we need it as we modify them
1879  std::vector<std::unique_ptr<TH1D>> hpost_copy(nParamPlot);
1880  std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(nParamPlot);
1881  std::vector<std::unique_ptr<TText>> TriangleText(nParamPlot * 2);
1882  std::vector<std::unique_ptr<TH2D>> hpost_2D_copy(Npad-nParamPlot);
1883  std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_cl(Npad-nParamPlot);
1884  gStyle->SetPalette(51);
1885 
1886  //KS: Super convoluted way of calculating ranges for our pads, trust me it works...
1887  std::vector<double> X_Min(nParamPlot);
1888  std::vector<double> X_Max(nParamPlot);
1889 
1890  //TN:
1891  // n = number of params (nParamPlot)
1892  // a_x = width of the left margin space for pad axis labels on the left in canvas coordinates
1893  // a_y = height of the bottom margin space for pad axis labels on the bottom in canvas coordinates
1894  // b_x = pad plot width in canvas coordinates
1895  // b_y = pad plot height in canvas coordinates
1896  // Pm = a/(a+b) = actual margin within the first plot from the left (a_x,b_x) or bottom (a_y,b_y); Pm = {left,bottom}
1897  // TPm = desired margin of the whole triangle plot in canvas coordinates; TPm = {left, bottom, right, top}
1898  // TPw = 1.-TPm[0]-TPm[2] width of the triangle plot in canvas coordinates
1899  // TPh = 1.-TPm[1]-TPm[3] height of the triangle plot in canvas coordinates
1900  // Then a_x+n*b_x = TPw = 1.-TPm[0]-TPm[1]
1901  // Hence from that:
1902  // a_x = Pm[0]*(a_x+b_x) = Pm[0]*(a_x+(TPw-a_x)/n) => a_x = (Pm[0]*TPw)/(n+Pm[0]*(1-n))
1903  // b_x = (TPw-a_x)/n
1904 
1905  // The inputs:
1906  const double TPm[4] = {.07,.07,.05,.05};
1907  const double Pm[2] = {.2,.1};
1908 
1909  // Auxiliary x-direction:
1910  const double TPw = 1. - TPm[0] - TPm[2];
1911  const double a_x = ( Pm[0] * TPw ) / ( 1. * nParamPlot + Pm[0] * ( 1. - 1.*nParamPlot ) );
1912  const double b_x = ( TPw - a_x ) / ( 1. * nParamPlot );
1913 
1914  X_Min[0] = TPm[0];
1915  X_Max[0] = X_Min[0] + a_x + b_x;
1916  for(int i = 1; i < nParamPlot; i++)
1917  {
1918  X_Min[i] = X_Max[i-1];
1919  X_Max[i] = X_Min[i]+b_x;
1920  }
1921 
1922  std::vector<double> Y_Min(nParamPlot);
1923  std::vector<double> Y_Max(nParamPlot);
1924 
1925  // Auxiliary y-direction:
1926  const double TPh = 1. - TPm[1] - TPm[3];
1927  const double a_y = ( Pm[1] * TPh ) / ( 1. * nParamPlot + Pm[1] * ( 1. - 1.*nParamPlot ) );
1928  const double b_y = ( TPh - a_y ) / ( 1. * nParamPlot );
1929 
1930  Y_Min[nParamPlot-1] = TPm[1];
1931  Y_Max[nParamPlot-1] = Y_Min[nParamPlot-1] + a_y + b_y;
1932  for(int i = nParamPlot-2; i >= 0; i--)
1933  {
1934  Y_Min[i] = Y_Max[i+1];
1935  Y_Max[i] = Y_Min[i]+b_y;
1936  }
1937 
1938  //KS: We store as numbering of isn't straightforward
1939  int counterPad = 0, counterText = 0, counterPost = 0, counter2DPost = 0;
1940  //KS: We start from top of the plot, might be confusing but works very well
1941  for(int y = 0; y < nParamPlot; y++)
1942  {
1943  //KS: start from left and go right, depending on y
1944  for(int x = 0; x <= y; x++)
1945  {
1946  //KS: Need to go to canvas every time to have our pads in the same canvas, not pads in the pads
1947  Posterior->cd();
1948  TrianglePad[counterPad] = std::make_unique<TPad>(Form("TPad_%i", counterPad), Form("TPad_%i", counterPad), X_Min[x], Y_Min[y], X_Max[x], Y_Max[y]);
1949 
1950  TrianglePad[counterPad]->SetTopMargin(0);
1951  TrianglePad[counterPad]->SetRightMargin(0);
1952 
1953  TrianglePad[counterPad]->SetGrid();
1954  TrianglePad[counterPad]->SetFrameBorderMode(0);
1955  TrianglePad[counterPad]->SetBorderMode(0);
1956  TrianglePad[counterPad]->SetBorderSize(0);
1957 
1958  //KS: Corresponds to bottom part of the plot, need margins for labels
1959  TrianglePad[counterPad]->SetBottomMargin(y == (nParamPlot - 1) ? Pm[1] : 0);
1960  //KS: Corresponds to left part, need margins for labels
1961  TrianglePad[counterPad]->SetLeftMargin(x == 0 ? Pm[0] : 0);
1962 
1963  TrianglePad[counterPad]->Draw();
1964  TrianglePad[counterPad]->cd();
1965 
1966  //KS:if diagonal plot main posterior
1967  if(x == y)
1968  {
1969  hpost_copy[counterPost] = M3::Clone<TH1D>(hpost[ParamNumber[x]], Form("hpost_copy_%i", ParamNumber[x]));
1970  hpost_cl[counterPost].resize(nCredibleIntervals);
1972  hpost_copy[counterPost]->Scale(1. / hpost_copy[counterPost]->Integral());
1973  for (int j = 0; j < nCredibleIntervals; ++j)
1974  {
1975  hpost_cl[counterPost][j] = M3::Clone<TH1D>(hpost[ParamNumber[x]], Form("hpost_copy_%i_CL_%f", ParamNumber[x], CredibleIntervals[j]));
1976  //KS: Reset to get rid to TF1 otherwise we run into segfault :(
1977  hpost_cl[counterPost][j]->Reset("");
1978  hpost_cl[counterPost][j]->Fill(0.0, 0.0);
1979 
1980  // Scale the histograms before gettindg credible intervals
1981  hpost_cl[counterPost][j]->Scale(1. / hpost_cl[counterPost][j]->Integral());
1982  GetCredibleIntervalSig(hpost_copy[counterPost], hpost_cl[counterPost][j], CredibleInSigmas, CredibleIntervals[j]);
1983 
1984  hpost_cl[counterPost][j]->SetFillColor(CredibleIntervalsColours[j]);
1985  hpost_cl[counterPost][j]->SetLineWidth(1);
1986  }
1987 
1988  hpost_copy[counterPost]->SetMaximum(hpost_copy[counterPost]->GetMaximum()*1.2);
1989  hpost_copy[counterPost]->SetLineWidth(2);
1990  hpost_copy[counterPost]->SetLineColor(kBlack);
1991 
1992  //KS: Don't want any titles
1993  FormatHistogram(hpost_copy[counterPost]);
1994 
1995  //TN: Scale the size of labels with the plots size.
1996  //Unfortunately, this needs to managed through absolute sizes
1997  //as each pad is of different size.
1998  hpost_copy[counterPost]->GetXaxis()->SetLabelFont(133);
1999  hpost_copy[counterPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*Posterior->GetWh());
2000 
2001  hpost_copy[counterPost]->GetYaxis()->SetLabelFont(133);
2002  hpost_copy[counterPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*Posterior->GetWh());
2003 
2004  hpost_copy[counterPost]->Draw("HIST");
2005  for (int j = 0; j < nCredibleIntervals; ++j){
2006  hpost_cl[counterPost][j]->Draw("HIST SAME");
2007  }
2008  counterPost++;
2009  }
2010  //KS: Here we plot 2D credible regions
2011  else
2012  {
2013  hpost_2D_copy[counter2DPost] = M3::Clone<TH2D>(hpost2D[ParamNumber[x]][ParamNumber[y]],
2014  Form("hpost_copy_%i_%i", ParamNumber[x], ParamNumber[y]));
2015  hpost_2D_cl[counter2DPost].resize(nCredibleRegions);
2016  //KS: Now copy for every credible region
2017  for (int k = 0; k < nCredibleRegions; ++k)
2018  {
2019  hpost_2D_cl[counter2DPost][k] = M3::Clone<TH2D>(hpost2D[ParamNumber[x]][ParamNumber[y]],
2020  Form("hpost_copy_%i_%i_CL_%f", ParamNumber[x], ParamNumber[y], CredibleRegions[k]));
2021  GetCredibleRegionSig(hpost_2D_cl[counter2DPost][k], CredibleInSigmas, CredibleRegions[k]);
2022 
2023  hpost_2D_cl[counter2DPost][k]->SetLineColor(CredibleRegionColor[k]);
2024  hpost_2D_cl[counter2DPost][k]->SetLineWidth(2);
2025  hpost_2D_cl[counter2DPost][k]->SetLineStyle(CredibleRegionStyle[k]);
2026  }
2027  //KS: Don't want any titles
2028  FormatHistogram(hpost_2D_copy[counter2DPost]);
2029 
2030  //TN: Scale the size of labels with the plots size.
2031  //Unfortunately, this needs to managed through absolute sizes
2032  //as each pad is of different size.
2033  hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelFont(133);
2034  hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*Posterior->GetWh());
2035 
2036  hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelFont(133);
2037  hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*Posterior->GetWh());
2038 
2039  hpost_2D_copy[counter2DPost]->Draw("COL");
2040  //Now credible regions
2041  for (int k = 0; k < nCredibleRegions; ++k){
2042  hpost_2D_cl[counter2DPost][k]->Draw("CONT3 SAME");
2043  }
2044  counter2DPost++;
2045  }
2046  //KS: Corresponds to bottom part of the plot
2047  if(y == (nParamPlot-1))
2048  {
2049  Posterior->cd();
2050  TriangleText[counterText] = std::make_unique<TText>(X_Min[x] + (X_Max[x]-X_Min[x]+(x == 0 ? a_x : .0))/2., .05, hpost[ParamNumber[x]]->GetTitle());
2051  //KS: Unfortunately for many plots or long names this can go out of bounds :(
2052  //TN: Align the axis titles and scale them with the size of the plots
2053  TriangleText[counterText]->SetTextAlign(22);
2054  TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2055  TriangleText[counterText]->SetNDC(true);
2056  TriangleText[counterText]->Draw();
2057  counterText++;
2058  }
2059  //KS: Corresponds to left part
2060  if(x == 0)
2061  {
2062  Posterior->cd();
2063  TriangleText[counterText] = std::make_unique<TText>(.05, Y_Min[y] + (Y_Max[y]-Y_Min[y]+(y == nParamPlot-1 ? a_y : .0))/2., hpost[ParamNumber[y]]->GetTitle());
2064  //KS: Rotate as this is y axis
2065  TriangleText[counterText]->SetTextAngle(90);
2066  //KS: Unfortunately for many plots or long names this can go out of bounds :(
2067  //TN: Align the axis titles and scale them with the size of the plots
2068  TriangleText[counterText]->SetTextAlign(22);
2069  TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2070  TriangleText[counterText]->SetNDC(true);
2071  TriangleText[counterText]->Draw();
2072  counterText++;
2073  }
2074  Posterior->Update();
2075  counterPad++;
2076  }
2077  }
2078 
2079  Posterior->cd();
2080  auto legend = std::make_unique<TLegend>(0.60, 0.7, 0.9, 0.9);
2081  SetLegendStyle(legend.get(), 0.03);
2082  //KS: Legend is shared so just take first histograms
2083  for (int j = nCredibleIntervals-1; j >= 0; --j)
2084  {
2085  if(CredibleInSigmas)
2086  legend->AddEntry(hpost_cl[0][j].get(), Form("%.0f#sigma Credible Interval", CredibleIntervals[j]), "f");
2087  else
2088  legend->AddEntry(hpost_cl[0][j].get(), Form("%.0f%% Credible Interval", CredibleIntervals[j]*100), "f");
2089  }
2090  for (int k = nCredibleRegions-1; k >= 0; --k)
2091  {
2092  if(CredibleInSigmas)
2093  legend->AddEntry(hpost_2D_cl[0][k].get(), Form("%.0f#sigma Credible Region", CredibleRegions[k]), "l");
2094  else
2095  legend->AddEntry(hpost_2D_cl[0][k].get(), Form("%.0f%% Credible Region", CredibleRegions[k]*100), "l");
2096  }
2097  legend->Draw("SAME");
2098  Posterior->Update();
2099 
2100  // Write to file
2101  Posterior->SetName("TrianglePlot");
2102  Posterior->SetTitle("TrianglePlot");
2103 
2104  if(printToPDF) Posterior->Print(CanvasName);
2105  // Write it to root file
2106  OutputFile->cd();
2107  Posterior->Write();
2108 
2109  //KS: Restore margin
2110  SetMargins(Posterior, Margins);
2111 }
2112 
2113 // **************************
2114 // Scan the input trees
2116 // **************************
2117  // Open the Chain
2118  Chain = new TChain("posteriors","posteriors");
2119  Chain->Add(MCMCFile.c_str());
2120 
2121  nEntries = int(Chain->GetEntries());
2122 
2123  //Only is suboptimality we might want to change it, therefore set it high enough so it doesn't affect other functionality
2124  UpperCut = nEntries+1;
2125 
2126  // Get the list of branches
2127  TObjArray* brlis = Chain->GetListOfBranches();
2128 
2129  // Get the number of branches
2130  nBranches = brlis->GetEntries();
2131 
2132  BranchNames.reserve(nBranches);
2133  ParamType.reserve(nBranches);
2134 
2135  // Read the input Covariances
2136  ReadInputCov();
2137 
2138  // Set all the branches to off
2139  Chain->SetBranchStatus("*", false);
2140 
2141  // Loop over the number of branches
2142  // Find the name and how many of each systematic we have
2143  for (int i = 0; i < nBranches; i++)
2144  {
2145  // Get the TBranch and its name
2146  TBranch* br = static_cast<TBranch*>(brlis->At(i));
2147  if(!br){
2148  MACH3LOG_ERROR("Invalid branch at position {}", i);
2149  throw MaCh3Exception(__FILE__,__LINE__);
2150  }
2151  TString bname = br->GetName();
2152 
2153  //KS: Exclude parameter types
2154  bool rejected = false;
2155  for(unsigned int ik = 0; ik < ExcludedTypes.size(); ++ik )
2156  {
2157  if(bname.BeginsWith(ExcludedTypes[ik]))
2158  {
2159  rejected = true;
2160  break;
2161  }
2162  }
2163  if(rejected) continue;
2164 
2165  // Turn on the branches which we want for parameters
2166  Chain->SetBranchStatus(bname.Data(), true);
2167 
2168  if (bname.BeginsWith("ndd_"))
2169  {
2170  BranchNames.push_back(bname);
2171  ParamType.push_back(kNDPar);
2172  nParam[kNDPar]++;
2173  }
2174  else if (bname.BeginsWith("skd_joint_"))
2175  {
2176  BranchNames.push_back(bname);
2177  ParamType.push_back(kFDDetPar);
2178  nParam[kFDDetPar]++;
2179  }
2180 
2181  //KS: as a bonus get LogL systematic
2182  if (bname.BeginsWith("LogL_sample_")) {
2183  SampleName_v.push_back(bname);
2184  }
2185  else if (bname.BeginsWith("LogL_systematic_")) {
2186  SystName_v.push_back(bname);
2187  }
2188  }
2189  nDraw = int(BranchNames.size());
2190 
2191  // Read the input Covariances
2193 
2194  // Check order of parameter types
2196 
2197  ParamVaried.resize(nDraw, true);
2198 
2199  // Print useful Info
2200  PrintInfo();
2201 
2202  nSteps = Chain->GetMaximum("step");
2203  // Set the step cut to be 20%
2204  int cut = nSteps/5;
2205  SetStepCut(cut);
2206 
2207  // Basically allow loading oscillation parameters
2209 }
2210 
2211 // ****************************
2212 // Set up the output files and canvases
2214 // ****************************
2215  // Make sure we can read files located anywhere and strip the .root ending
2216  MCMCFile = MCMCFile.substr(0, MCMCFile.find(".root"));
2217 
2218  // Check if the output file is ready
2219  if (OutputFile == nullptr) MakeOutputFile();
2220 
2221  CanvasName = MCMCFile + OutputSuffix + ".pdf[";
2222  if(printToPDF) Posterior->Print(CanvasName);
2223 
2224  // Once the pdf file is open no longer need to bracket
2225  CanvasName.ReplaceAll("[","");
2226 
2227  // We fit with this Gaussian
2228  Gauss = std::make_unique<TF1>("Gauss", "[0]/sqrt(2.0*3.14159)/[2]*TMath::Exp(-0.5*pow(x-[1],2)/[2]/[2])", -5, 5);
2229  Gauss->SetLineWidth(2);
2230  Gauss->SetLineColor(kOrange-5);
2231 
2232  // Declare the TVectors
2233  Covariance = new TMatrixDSym(nDraw);
2234  Correlation = new TMatrixDSym(nDraw);
2235  Central_Value = new TVectorD(nDraw);
2236  Means = new TVectorD(nDraw);
2237  Errors = new TVectorD(nDraw);
2238  Means_Gauss = new TVectorD(nDraw);
2239  Errors_Gauss = new TVectorD(nDraw);
2240  Means_HPD = new TVectorD(nDraw);
2241  Errors_HPD = new TVectorD(nDraw);
2242  Errors_HPD_Positive = new TVectorD(nDraw);
2243  Errors_HPD_Negative = new TVectorD(nDraw);
2244 
2245  // Initialise to something silly
2246  #ifdef MULTITHREAD
2247  #pragma omp parallel for
2248  #endif
2249  for (int i = 0; i < nDraw; ++i)
2250  {
2251  (*Central_Value)(i) = M3::_BAD_DOUBLE_;
2252  (*Means)(i) = M3::_BAD_DOUBLE_;
2253  (*Errors)(i) = M3::_BAD_DOUBLE_;
2254  (*Means_Gauss)(i) = M3::_BAD_DOUBLE_;
2255  (*Errors_Gauss)(i) = M3::_BAD_DOUBLE_;
2256  (*Means_HPD)(i) = M3::_BAD_DOUBLE_;
2257  (*Errors_HPD)(i) = M3::_BAD_DOUBLE_;
2258  (*Errors_HPD_Positive)(i) = M3::_BAD_DOUBLE_;
2259  (*Errors_HPD_Negative)(i) = M3::_BAD_DOUBLE_;
2260  for (int j = 0; j < nDraw; ++j) {
2261  (*Covariance)(i, j) = M3::_BAD_DOUBLE_;
2262  (*Correlation)(i, j) = M3::_BAD_DOUBLE_;
2263  }
2264  }
2265  hpost.resize(nDraw);
2266 }
2267 
2268 // ****************************
2269 // Check order of parameter types
2271 // *****************************
2272  for(int i = 0; i < kNParameterEnum; i++)
2273  {
2274  for(unsigned int j = 0; j < ParamType.size(); j++)
2275  {
2276  if(ParamType[j] == ParameterEnum(i))
2277  {
2278  //KS: When we find that i-th parameter types start at j, save and move to the next parameter.
2279  ParamTypeStartPos[i] = j;
2280  break;
2281  }
2282  }
2283  }
2284 }
2285 
2286 // *****************************
2287 // Make the prefit plots
2288 std::unique_ptr<TH1D> MCMCProcessor::MakePrefit() {
2289 // *****************************
2290  if (OutputFile == nullptr) MakeOutputFile();
2291 
2292  auto PreFitPlot = std::make_unique<TH1D>("Prefit", "Prefit", nDraw, 0, nDraw);
2293  PreFitPlot->SetDirectory(nullptr);
2294  for (int i = 0; i < PreFitPlot->GetNbinsX() + 1; ++i) {
2295  PreFitPlot->SetBinContent(i+1, 0);
2296  PreFitPlot->SetBinError(i+1, 0);
2297  }
2298 
2299  //KS: Slightly hacky way to get relative to prior or nominal as this is convention we use,
2300  //Only applies for xsec, for other systematic it make no difference
2301  double CentralValueTemp, Central, Error;
2302 
2303  // Set labels and data
2304  for (int i = 0; i < nDraw; ++i)
2305  {
2306  //Those keep which parameter type we run currently and relative number
2307  int ParamEnum = ParamType[i];
2308  int ParamNo = i - ParamTypeStartPos[ParameterEnum(ParamEnum)];
2309  CentralValueTemp = ParamCentral[ParamEnum][ParamNo];
2310  if(plotRelativeToPrior)
2311  {
2312  // Normalise the prior relative the nominal/prior, just the way we get our fit results in MaCh3
2313  if ( CentralValueTemp != 0) {
2314  Central = ParamCentral[ParamEnum][ParamNo] / CentralValueTemp;
2315  Error = ParamErrors[ParamEnum][ParamNo]/CentralValueTemp;
2316  } else {
2317  Central = CentralValueTemp + 1.0;
2318  Error = ParamErrors[ParamEnum][ParamNo];
2319  }
2320  }
2321  else
2322  {
2323  Central = CentralValueTemp;
2324  Error = ParamErrors[ParamEnum][ParamNo];
2325  }
2326  //KS: If plotting error for param with flat prior is turned off and given param really has flat prior set error to 0
2327  if(!PlotFlatPrior && ParamFlat[ParamEnum][ParamNo]) {
2328  Error = 0.;
2329  }
2330  PreFitPlot->SetBinContent(i+1, Central);
2331  PreFitPlot->SetBinError(i+1, Error);
2332  PreFitPlot->GetXaxis()->SetBinLabel(i+1, ParamNames[ParamEnum][ParamNo]);
2333  }
2334  PreFitPlot->SetDirectory(nullptr);
2335 
2336  PreFitPlot->SetFillStyle(1001);
2337  PreFitPlot->SetFillColor(kRed-3);
2338  PreFitPlot->SetMarkerStyle(21);
2339  PreFitPlot->SetMarkerSize(2.4);
2340  PreFitPlot->SetMarkerColor(kWhite);
2341  PreFitPlot->SetLineColor(PreFitPlot->GetFillColor());
2342  PreFitPlot->GetXaxis()->LabelsOption("v");
2343 
2344  return PreFitPlot;
2345 }
2346 
2347 // **************************
2348 //CW: Read the input Covariance matrix entries
2349 // Get stuff like parameter input errors, names, and so on
2351 // **************************
2352  FindInputFiles();
2353  if(CovPos[kModelPar].back() != "none") ReadModelFile();
2354 }
2355 
2356 // **************************
2357 //CW: Read the input Covariance matrix entries
2358 // Get stuff like parameter input errors, names, and so on
2360 // **************************
2362  if(nParam[kNDPar] > 0) ReadNDFile();
2363  if(nParam[kFDDetPar] > 0) ReadFDFile();
2364 }
2365 
2366 // **************************
2367 // Read the output MCMC file and find what inputs were used
2369 // **************************
2370  // Now read the MCMC file
2371  TFile *TempFile = M3::Open(MCMCFile, "open", __FILE__, __LINE__);
2372  TDirectory* CovarianceFolder = TempFile->Get<TDirectory>("CovarianceFolder");
2373 
2374  // Get the settings for the MCMC
2375  TMacro *Config = TempFile->Get<TMacro>("MaCh3_Config");
2376 
2377  if (Config == nullptr) {
2378  MACH3LOG_ERROR("Didn't find MaCh3_Config tree in MCMC file! {}", MCMCFile);
2379  TempFile->ls();
2380  throw MaCh3Exception(__FILE__ , __LINE__ );
2381  }
2382  MACH3LOG_INFO("Loading YAML config from MCMC chain");
2383 
2384  YAML::Node Settings = TMacroToYAML(*Config);
2385 
2386  bool InputNotFound = false;
2387  //CW: Get the xsec Covariance matrix
2388  CovPos[kModelPar] = GetFromManager<std::vector<std::string>>(Settings["General"]["Systematics"]["XsecCovFile"], {"none"}, __FILE__ , __LINE__);
2389  if(CovPos[kModelPar].back() == "none")
2390  {
2391  MACH3LOG_WARN("Couldn't find XsecCov branch in output");
2392  InputNotFound = true;
2393  }
2394 
2395  TMacro *XsecConfig = M3::GetConfigMacroFromChain(CovarianceFolder);
2396  if (XsecConfig == nullptr) {
2397  MACH3LOG_WARN("Didn't find Config_xsec_cov tree in MCMC file! {}", MCMCFile);
2398  } else {
2399  CovConfig[kModelPar] = TMacroToYAML(*XsecConfig);
2400  }
2401  if(InputNotFound) M3::Utils::PrintConfig(Settings);
2402 
2403  for(size_t i = 0; i < CovPos[kModelPar].size(); i++)
2405 
2406  // Delete the TTrees and the input file handle since we've now got the settings we need
2407  delete Config;
2408  delete XsecConfig;
2409 
2410  TMacro *ReweightConfig = TempFile->Get<TMacro>("Reweight_Config");
2411  TMacro *UmbrellaConfig = TempFile->Get<TMacro>("Umbrella_Config");
2412 
2413  YAML::Node ReweightSettings;
2414  YAML::Node UmbrellaSettings;
2415 
2416  if (ReweightConfig != nullptr) {
2417  ReweightSettings = TMacroToYAML(*ReweightConfig);
2418  }
2419 
2420  if (UmbrellaConfig != nullptr) {
2421  UmbrellaSettings = TMacroToYAML(*UmbrellaConfig);
2422  }
2423 
2424  ReweightPosterior = true;
2425  for (const auto &name : ReweightNames) {
2426  bool found = false;
2427  // KS: For now umbrella_weight is specialised
2428  if (name == "umbrella_weight") {
2429  found = UmbrellaConfig != nullptr;
2430  } else {
2431  found = (ReweightConfig != nullptr) && ReweightSettings[name];
2432  }
2433 
2434  if (found) {
2435  MACH3LOG_INFO("Found reweight config for {}", name);
2436  } else {
2437  MACH3LOG_WARN("Missing reweight config for {}", name);
2438  ReweightPosterior = false;
2439  break;
2440  }
2441  }
2442 
2443  if (ReweightPosterior) {
2444  MACH3LOG_INFO("Enabling reweighting with configured weights.");
2445  }
2446 
2447  if (ReweightConfig != nullptr) {
2448  M3::Utils::PrintConfig(ReweightSettings);
2449  }
2450 
2451  if (UmbrellaConfig != nullptr) {
2452  M3::Utils::PrintConfig(UmbrellaSettings);
2453  }
2454 
2455  // Delete the MCMCFile pointer we're reading
2456  CovarianceFolder->Close();
2457  delete CovarianceFolder;
2458  TempFile->Close();
2459  delete TempFile;
2460 }
2461 
2462 // **************************
2463 // Read the output MCMC file and find what inputs were used
2465 // **************************
2466  // Now read the MCMC file
2467  TFile *TempFile = M3::Open(MCMCFile, "open", __FILE__, __LINE__);
2468  // Get the settings for the MCMC
2469  TMacro *Config = TempFile->Get<TMacro>("MaCh3_Config");
2470 
2471  if (Config == nullptr) {
2472  MACH3LOG_ERROR("Didn't find MaCh3_Config tree in MCMC file! {}", MCMCFile);
2473  TempFile->ls();
2474  throw MaCh3Exception(__FILE__ , __LINE__ );
2475  }
2476  YAML::Node Settings = TMacroToYAML(*Config);
2477 
2478  //CW: And the ND Covariance matrix
2479  CovPos[kNDPar].push_back(GetFromManager<std::string>(Settings["General"]["Systematics"]["NDCovFile"], "none", __FILE__ , __LINE__));
2480 
2481  if(CovPos[kNDPar].back() == "none") {
2482  MACH3LOG_WARN("Couldn't find NDCov (legacy) branch in output");
2483  } else{
2484  //If the FD Cov is not none, then you need the name of the covariance object to grab
2485  CovNamePos[kNDPar] = GetFromManager<std::string>(Settings["General"]["Systematics"]["NDCovName"], "none", __FILE__ , __LINE__);
2486  MACH3LOG_INFO("Given NDCovFile {} and NDCovName {}", CovPos[kNDPar].back(), CovNamePos[kNDPar]);
2487  }
2488 
2489  //CW: And the FD Covariance matrix
2490  CovPos[kFDDetPar].push_back(GetFromManager<std::string>(Settings["General"]["Systematics"]["FDCovFile"], "none", __FILE__ , __LINE__));
2491 
2492  if(CovPos[kFDDetPar].back() == "none") {
2493  MACH3LOG_WARN("Couldn't find FDCov (legacy) branch in output");
2494  } else {
2495  //If the FD Cov is not none, then you need the name of the covariance object to grab
2496  CovNamePos[kFDDetPar] = GetFromManager<std::string>(Settings["General"]["Systematics"]["FDCovName"], "none", __FILE__ , __LINE__);
2497  MACH3LOG_INFO("Given FDCovFile {} and FDCovName {}", CovPos[kFDDetPar].back(), CovNamePos[kFDDetPar]);
2498  }
2499 
2500  for(size_t i = 0; i < CovPos[kNDPar].size(); i++)
2501  M3::AddPath(CovPos[kNDPar][i]);
2502 
2503  for(size_t i = 0; i < CovPos[kFDDetPar].size(); i++)
2505 
2506  TempFile->Close();
2507  delete TempFile;
2508 }
2509 
2510 // ***************
2511 // Read the model file and get the input central values and errors
2513 // ***************
2514  YAML::Node ModelFile = CovConfig[kModelPar];
2515 
2516  auto systematics = ModelFile["Systematics"];
2517  int paramIndex = 0;
2518  for (auto it = systematics.begin(); it != systematics.end(); ++it, ++paramIndex )
2519  {
2520  auto const &param = *it;
2521  // Push back the name
2522  std::string ParName = (param["Systematic"]["Names"]["FancyName"].as<std::string>());
2523  std::string Group = param["Systematic"]["ParameterGroup"].as<std::string>();
2524 
2525  bool rejected = false;
2526  for (unsigned int ik = 0; ik < ExcludedNames.size(); ++ik)
2527  {
2528  if (M3::CaseInsentiveMatch(ParName, ExcludedNames[ik]))
2529  {
2530  MACH3LOG_DEBUG("Excluding param {}, from group {}", ParName, Group);
2531  rejected = true;
2532  break;
2533  }
2534  }
2535  for (unsigned int ik = 0; ik < ExcludedGroups.size(); ++ik)
2536  {
2537  if (Group == ExcludedGroups[ik])
2538  {
2539  MACH3LOG_DEBUG("Excluding param {}, from group {}", ParName, Group);
2540  rejected = true;
2541  break;
2542  }
2543  }
2544  if(rejected) continue;
2545 
2546  ParamNames[kModelPar].push_back(ParName);
2547  ParamCentral[kModelPar].push_back(param["Systematic"]["ParameterValues"]["PreFitValue"].as<double>());
2548  ParamErrors[kModelPar].push_back(param["Systematic"]["Error"].as<double>() );
2549  ParamFlat[kModelPar].push_back(GetFromManager<bool>(param["Systematic"]["FlatPrior"], false, __FILE__ , __LINE__));
2550 
2551  if(CheckNodeExists(param["Systematic"],"SpecialProposal", "CircularBounds")) {
2552  ParamCircular[kModelPar].push_back(true);
2553  } else {
2554  ParamCircular[kModelPar].push_back(false);
2555  }
2556  ParameterGroup.push_back(Group);
2557 
2558  nParam[kModelPar]++;
2559  ParamType.push_back(kModelPar);
2560  // Params from osc group have branch name equal to fancy name while all others are basically xsec_0 for example
2561  if(ParameterGroup.back() == "Osc") {
2562  BranchNames.push_back(ParamNames[kModelPar].back());
2563  } else {
2564  BranchNames.push_back("param_" + std::to_string(paramIndex));
2565  }
2566 
2567  // Check that the branch exists before setting address
2568  if (!Chain->GetBranch(BranchNames.back())) {
2569  MACH3LOG_WARN("Couldn't find branch '{}', if you are not planning to draw posteriors this might be fine", BranchNames.back());
2570  }
2571  }
2572 }
2573 
2574 // ***************
2575 // Read the ND cov file and get the input central values and errors
2577 // ***************
2578  // Do the same for the ND280
2579  TFile *NDdetFile = M3::Open(CovPos[kNDPar].back(), "open", __FILE__, __LINE__);
2580  NDdetFile->cd();
2581 
2582  TMatrixDSym *NDdetMatrix = NDdetFile->Get<TMatrixDSym>(CovNamePos[kNDPar].c_str());
2583  TVectorD *NDdetNominal = NDdetFile->Get<TVectorD>("det_weights");
2584  TDirectory *BinningDirectory = NDdetFile->Get<TDirectory>("Binning");
2585 
2586  for (int i = 0; i < NDdetNominal->GetNrows(); ++i)
2587  {
2588  ParamCentral[kNDPar].push_back( (*NDdetNominal)(i) );
2589 
2590  ParamErrors[kNDPar].push_back( std::sqrt((*NDdetMatrix)(i,i)) );
2591  ParamNames[kNDPar].push_back( Form("ND Det %i", i) );
2592  //KS: Currently we can only set it via config, change it in future
2593  ParamFlat[kNDPar].push_back( false );
2594  ParamCircular[kNDPar].push_back( false );
2595  }
2596 
2597  TIter next(BinningDirectory->GetListOfKeys());
2598  TKey *key = nullptr;
2599  // Loop through all entries
2600  while ((key = static_cast<TKey*>(next())))
2601  {
2602  std::string name = std::string(key->GetName());
2603  TH2Poly* RefPoly = BinningDirectory->Get<TH2Poly>((name).c_str());
2604  int size = RefPoly->GetNumberOfBins();
2605  NDSamplesBins.push_back(size);
2606  NDSamplesNames.push_back(RefPoly->GetTitle());
2607  }
2608 
2609  NDdetFile->Close();
2610  delete NDdetFile;
2611 }
2612 
2613 // ***************
2614 // Read the FD cov file and get the input central values and errors
2616 // ***************
2617  // Do the same for the FD
2618  TFile *FDdetFile = M3::Open(CovPos[kFDDetPar].back(), "open", __FILE__, __LINE__);
2619  FDdetFile->cd();
2620 
2621  TMatrixD *FDdetMatrix = FDdetFile->Get<TMatrixD>(CovNamePos[kFDDetPar].c_str());
2622 
2623  for (int i = 0; i < FDdetMatrix->GetNrows(); ++i)
2624  {
2625  //KS: FD parameters start at 1. in contrary to ND280
2626  ParamCentral[kFDDetPar].push_back(1.);
2627 
2628  ParamErrors[kFDDetPar].push_back( std::sqrt((*FDdetMatrix)(i,i)) );
2629  ParamNames[kFDDetPar].push_back( Form("FD Det %i", i) );
2630 
2631  //KS: Currently we can only set it via config, change it in future
2632  ParamFlat[kFDDetPar].push_back( false );
2633  ParamCircular[kFDDetPar].push_back( false );
2634  }
2635  //KS: The last parameter is p scale
2636  //ETA: we need to be careful here, this is only true for SK in the T2K beam analysis...
2637  if(FancyPlotNames) ParamNames[kFDDetPar].back() = "Momentum Scale";
2638 
2639  FDdetFile->Close();
2640  delete FDdetFile;
2641  delete FDdetMatrix;
2642 }
2643 
2644 // ***************
2645 // Make the step cut from a string
2646 void MCMCProcessor::SetStepCut(const std::string& Cuts) {
2647 // ***************
2648  StepCut = Cuts;
2649  BurnInCut = std::stoi( Cuts );
2650 
2651  CheckStepCut();
2652 }
2653 
2654 // ***************
2655 // Make the step cut from an int
2656 void MCMCProcessor::SetStepCut(const int Cuts) {
2657 // ***************
2658  std::stringstream TempStream;
2659  TempStream << "step > " << Cuts;
2660  StepCut = TempStream.str();
2661  BurnInCut = Cuts;
2662  CheckStepCut();
2663 }
2664 
2665 // ***************
2666 // Make the step cut from an int
2668 // ***************
2669  const unsigned int maxNsteps = Chain->GetMaximum("step");
2670  if(BurnInCut > maxNsteps){
2671  MACH3LOG_ERROR("StepCut({}) is larger than highest value of step({})", BurnInCut, maxNsteps);
2672  throw MaCh3Exception(__FILE__ , __LINE__ );
2673  }
2674 }
2675 
2676 // ***************
2677 // Pass central value
2678 void MCMCProcessor::GetNthParameter(const int param, double &Prior, double &PriorError, TString &Title) const {
2679 // **************************
2680  ParameterEnum ParType = ParamType[param];
2681  int ParamNo = M3::_BAD_INT_;
2682  ParamNo = param - ParamTypeStartPos[ParType];
2683 
2684  Prior = ParamCentral[ParType][ParamNo];
2685  PriorError = ParamErrors[ParType][ParamNo];
2686  Title = ParamNames[ParType][ParamNo];
2687 }
2688 
2689 // ***************
2690 // Find Param Index based on name
2691 int MCMCProcessor::GetParamIndexFromName(const std::string& Name) const {
2692 // **************************
2693  int ParamNo = M3::_BAD_INT_;
2694  for (int i = 0; i < nDraw; ++i)
2695  {
2696  TString Title = "";
2697  double Prior = 1.0, PriorError = 1.0;
2698  GetNthParameter(i, Prior, PriorError, Title);
2699 
2700  if(Name == Title)
2701  {
2702  ParamNo = i;
2703  break;
2704  }
2705  }
2706  return ParamNo;
2707 }
2708 
2709 // **************************************************
2710 // Helper function to reset histograms
2712 // **************************************************
2713  #ifdef MULTITHREAD
2714  #pragma omp parallel for
2715  #endif
2716  for (int i = 0; i < nDraw; ++i)
2717  {
2718  for (int j = 0; j <= i; ++j)
2719  {
2720  // TH2D to hold the Correlation
2721  hpost2D[i][j]->Reset("");
2722  hpost2D[i][j]->Fill(0.0, 0.0, 0.0);
2723  }
2724  }
2725 }
2726 
2727 // **************************
2728 // KS: Get Super Fancy Polar Plot
2729 void MCMCProcessor::GetPolarPlot(const std::vector<std::string>& ParNames){
2730 // **************************
2731  if(hpost[0] == nullptr) MakePostfit();
2732 
2733  std::vector<double> Margins = GetMargins(Posterior);
2734 
2735  Posterior->SetTopMargin(0.1);
2736  Posterior->SetBottomMargin(0.1);
2737  Posterior->SetLeftMargin(0.1);
2738  Posterior->SetRightMargin(0.1);
2739  Posterior->Update();
2740 
2741  MACH3LOG_INFO("Calculating Polar Plot");
2742  TDirectory *PolarDir = OutputFile->mkdir("PolarDir");
2743  PolarDir->cd();
2744 
2745  for(unsigned int k = 0; k < ParNames.size(); ++k)
2746  {
2747  //KS: First we need to find parameter number based on name
2748  int ParamNo = GetParamIndexFromName(ParNames[k]);
2749  if(ParamNo == M3::_BAD_INT_)
2750  {
2751  MACH3LOG_WARN("Couldn't find param {}. Will not calculate Polar Plot", ParNames[k]);
2752  continue;
2753  }
2754 
2755  TString Title = "";
2756  double Prior = 1.0, PriorError = 1.0;
2757  GetNthParameter(ParamNo, Prior, PriorError, Title);
2758 
2759  std::vector<double> x_val(nBins);
2760  std::vector<double> y_val(nBins);
2761 
2762  constexpr double xmin = 0;
2763  constexpr double xmax = 2*TMath::Pi();
2764 
2765  double Integral = hpost[ParamNo]->Integral();
2766  for (Int_t ipt = 0; ipt < nBins; ipt++)
2767  {
2768  x_val[ipt] = ipt*(xmax-xmin)/nBins+xmin;
2769  y_val[ipt] = hpost[ParamNo]->GetBinContent(ipt+1)/Integral;
2770  }
2771 
2772  auto PolarGraph = std::make_unique<TGraphPolar>(nBins, x_val.data(), y_val.data());
2773  PolarGraph->SetLineWidth(2);
2774  PolarGraph->SetFillStyle(3001);
2775  PolarGraph->SetLineColor(kRed);
2776  PolarGraph->SetFillColor(kRed);
2777  PolarGraph->Draw("AFL");
2778 
2779  auto Text = std::make_unique<TText>(0.6, 0.1, Title);
2780  Text->SetTextSize(0.04);
2781  Text->SetNDC(true);
2782  Text->Draw("");
2783 
2784  Posterior->Print(CanvasName);
2785  Posterior->Write(Title);
2786  } //End loop over parameters
2787 
2788  PolarDir->Close();
2789  delete PolarDir;
2790 
2791  OutputFile->cd();
2792 
2793  SetMargins(Posterior, Margins);
2794 }
2795 
2796 // **************************
2797 // Get Bayes Factor for particular parameter
2798 void MCMCProcessor::GetBayesFactor(const std::vector<std::string>& ParNames,
2799  const std::vector<std::vector<double>>& Model1Bounds,
2800  const std::vector<std::vector<double>>& Model2Bounds,
2801  const std::vector<std::vector<std::string>>& ModelNames){
2802 // **************************
2803  if(hpost[0] == nullptr) MakePostfit();
2804 
2805  MACH3LOG_INFO("Calculating Bayes Factor");
2806  if((ParNames.size() != Model1Bounds.size()) || (Model2Bounds.size() != Model1Bounds.size()) || (Model2Bounds.size() != ModelNames.size()))
2807  {
2808  MACH3LOG_ERROR("Size doesn't match");
2809  throw MaCh3Exception(__FILE__ , __LINE__ );
2810  }
2811  for(unsigned int k = 0; k < ParNames.size(); ++k)
2812  {
2813  //KS: First we need to find parameter number based on name
2814  int ParamNo = GetParamIndexFromName(ParNames[k]);
2815  if(ParamNo == M3::_BAD_INT_)
2816  {
2817  MACH3LOG_WARN("Couldn't find param {}. Will not calculate Bayes Factor", ParNames[k]);
2818  continue;
2819  }
2820 
2821  const double M1_min = Model1Bounds[k][0];
2822  const double M2_min = Model2Bounds[k][0];
2823  const double M1_max = Model1Bounds[k][1];
2824  const double M2_max = Model2Bounds[k][1];
2825 
2826  long double IntegralMode1 = hpost[ParamNo]->Integral(hpost[ParamNo]->FindFixBin(M1_min), hpost[ParamNo]->FindFixBin(M1_max));
2827  long double IntegralMode2 = hpost[ParamNo]->Integral(hpost[ParamNo]->FindFixBin(M2_min), hpost[ParamNo]->FindFixBin(M2_max));
2828 
2829  double BayesFactor = 0.;
2830  std::string Name = "";
2831  //KS: Calc Bayes Factor
2832  //If M1 is more likely
2833  if(IntegralMode1 >= IntegralMode2)
2834  {
2835  BayesFactor = IntegralMode1/IntegralMode2;
2836  Name = "\\mathfrak{B}(" + ModelNames[k][0]+ "/" + ModelNames[k][1] + ") = " + std::to_string(BayesFactor);
2837  }
2838  else //If M2 is more likely
2839  {
2840  BayesFactor = IntegralMode2/IntegralMode1;
2841  Name = "\\mathfrak{B}(" + ModelNames[k][1]+ "/" + ModelNames[k][0] + ") = " + std::to_string(BayesFactor);
2842  }
2843  std::string JeffreysScale = GetJeffreysScale(BayesFactor);
2844  std::string DunneKabothScale = GetDunneKaboth(BayesFactor);
2845 
2846  MACH3LOG_INFO("{} for {}", Name, ParNames[k]);
2847  MACH3LOG_INFO("Following Jeffreys Scale = {}", JeffreysScale);
2848  MACH3LOG_INFO("Following Dunne-Kaboth Scale = {}", DunneKabothScale);
2849  MACH3LOG_INFO("");
2850  }
2851 }
2852 
2853 // **************************
2854 // KS: Get Savage Dickey point hypothesis test
2855 void MCMCProcessor::GetSavageDickey(const std::vector<std::string>& ParNames,
2856  const std::vector<double>& EvaluationPoint,
2857  const std::vector<std::vector<double>>& Bounds){
2858 // **************************
2859  if((ParNames.size() != EvaluationPoint.size()) || (Bounds.size() != EvaluationPoint.size()))
2860  {
2861  MACH3LOG_ERROR("Size doesn't match");
2862  throw MaCh3Exception(__FILE__ , __LINE__ );
2863  }
2864 
2865  if(hpost[0] == nullptr) MakePostfit();
2866 
2867  MACH3LOG_INFO("Calculating Savage Dickey");
2868  TDirectory *SavageDickeyDir = OutputFile->mkdir("SavageDickey");
2869  SavageDickeyDir->cd();
2870 
2871  for(unsigned int k = 0; k < ParNames.size(); ++k)
2872  {
2873  //KS: First we need to find parameter number based on name
2874  int ParamNo = GetParamIndexFromName(ParNames[k]);
2875  if(ParamNo == M3::_BAD_INT_)
2876  {
2877  MACH3LOG_WARN("Couldn't find param {}. Will not calculate SavageDickey", ParNames[k]);
2878  continue;
2879  }
2880 
2881  TString Title = "";
2882  double Prior = 1.0, PriorError = 1.0;
2883  GetNthParameter(ParamNo, Prior, PriorError, Title);
2884  bool FlatPrior = GetParamFlat(ParamNo);
2885 
2886  auto PosteriorHist = M3::Clone<TH1D>(hpost[ParamNo], std::string(Title));
2887  RemoveFitter(PosteriorHist.get(), "Gauss");
2888 
2889  std::unique_ptr<TH1D> PriorHist;
2890  //KS: If flat prior we need to have well defined bounds otherwise Prior distribution will not make sense
2891  if(FlatPrior)
2892  {
2893  int NBins = PosteriorHist->GetNbinsX();
2894  if(Bounds[k][0] > Bounds[k][1])
2895  {
2896  MACH3LOG_ERROR("Lower bound is higher than upper bound");
2897  throw MaCh3Exception(__FILE__ , __LINE__ );
2898  }
2899  PriorHist = std::make_unique<TH1D>("PriorHist", Title, NBins, Bounds[k][0], Bounds[k][1]);
2900  PriorHist->SetDirectory(nullptr);
2901  double FlatProb = ( Bounds[k][1] - Bounds[k][0]) / NBins;
2902  for (int g = 0; g < NBins + 1; ++g)
2903  {
2904  PriorHist->SetBinContent(g+1, FlatProb);
2905  }
2906  }
2907  else //KS: Otherwise throw from Gaussian
2908  {
2909  PriorHist = M3::Clone<TH1D>(PosteriorHist.get(), "Prior");
2910  PriorHist->Reset("");
2911  PriorHist->Fill(0.0, 0.0);
2912 
2913  //KS: Throw nice gaussian, just need big number to have smooth distribution
2914  for(int g = 0; g < 1000000; ++g)
2915  {
2916  PriorHist->Fill(M3::rand::Gaus(Prior, PriorError));
2917  }
2918  }
2919  SavageDickeyPlot(PriorHist, PosteriorHist, std::string(Title), EvaluationPoint[k]);
2920  } //End loop over parameters
2921 
2922  SavageDickeyDir->Close();
2923  delete SavageDickeyDir;
2924 
2925  OutputFile->cd();
2926 }
2927 
2928 // **************************
2929 // KS: Get Savage Dickey point hypothesis test
2930 void MCMCProcessor::SavageDickeyPlot(std::unique_ptr<TH1D>& PriorHist,
2931  std::unique_ptr<TH1D>& PosteriorHist,
2932  const std::string& Title,
2933  const double EvaluationPoint) const {
2934 // **************************
2935  // Area normalise the distributions
2936  PriorHist->Scale(1./PriorHist->Integral(), "width");
2937  PosteriorHist->Scale(1./PosteriorHist->Integral(), "width");
2938 
2939  PriorHist->SetLineColor(kRed);
2940  PriorHist->SetMarkerColor(kRed);
2941  PriorHist->SetFillColorAlpha(kRed, 0.35);
2942  PriorHist->SetFillStyle(1001);
2943  PriorHist->GetXaxis()->SetTitle(Title.c_str());
2944  PriorHist->GetYaxis()->SetTitle("Posterior Probability");
2945  PriorHist->SetMaximum(PosteriorHist->GetMaximum()*1.5);
2946  PriorHist->GetYaxis()->SetLabelOffset(999);
2947  PriorHist->GetYaxis()->SetLabelSize(0);
2948  PriorHist->SetLineWidth(2);
2949  PriorHist->SetLineStyle(kSolid);
2950 
2951  PosteriorHist->SetLineColor(kBlue);
2952  PosteriorHist->SetMarkerColor(kBlue);
2953  PosteriorHist->SetFillColorAlpha(kBlue, 0.35);
2954  PosteriorHist->SetFillStyle(1001);
2955 
2956  PriorHist->Draw("hist");
2957  PosteriorHist->Draw("hist same");
2958 
2959  double ProbPrior = PriorHist->GetBinContent(PriorHist->FindBin(EvaluationPoint));
2960  //KS: In case we go so far away that prior is 0, set this to small value to avoid dividing by 0
2961  if(ProbPrior < 0) ProbPrior = 0.00001;
2962  double ProbPosterior = PosteriorHist->GetBinContent(PosteriorHist->FindBin(EvaluationPoint));
2963  double SavageDickey = ProbPosterior/ProbPrior;
2964 
2965  std::string DunneKabothScale = GetDunneKaboth(SavageDickey);
2966  //Get Best point
2967  auto PostPoint = std::make_unique<TGraph>(1);
2968  PostPoint->SetPoint(0, EvaluationPoint, ProbPosterior);
2969  PostPoint->SetMarkerStyle(20);
2970  PostPoint->SetMarkerSize(1);
2971  PostPoint->Draw("P same");
2972 
2973  auto PriorPoint = std::make_unique<TGraph>(1);
2974  PriorPoint->SetPoint(0, EvaluationPoint, ProbPrior);
2975  PriorPoint->SetMarkerStyle(20);
2976  PriorPoint->SetMarkerSize(1);
2977  PriorPoint->Draw("P same");
2978 
2979  auto legend = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
2980  SetLegendStyle(legend.get(), 0.04);
2981  legend->AddEntry(PriorHist.get(), "Prior", "l");
2982  legend->AddEntry(PosteriorHist.get(), "Posterior", "l");
2983  legend->AddEntry(PostPoint.get(), Form("SavageDickey = %.2f, (%s)", SavageDickey, DunneKabothScale.c_str()),"");
2984  legend->Draw("same");
2985 
2986  Posterior->Print(CanvasName);
2987  Posterior->Write(Title.c_str());
2988 }
2989 
2990 // **************************
2991 // KS: Smear contours
2992 void MCMCProcessor::SmearChain(const std::vector<std::string>& Names,
2993  const std::vector<double>& Error,
2994  const bool& SaveBranch) const {
2995 // **************************
2996  MACH3LOG_INFO("Starting {}", __func__);
2997 
2998  if( (Names.size() != Error.size()))
2999  {
3000  MACH3LOG_ERROR("Size of passed vectors doesn't match in {}", __func__);
3001  throw MaCh3Exception(__FILE__ , __LINE__ );
3002  }
3003  std::vector<int> Param;
3004 
3005  //KS: First we need to find parameter number based on name
3006  for(unsigned int k = 0; k < Names.size(); ++k)
3007  {
3008  //KS: First we need to find parameter number based on name
3009  int ParamNo = GetParamIndexFromName(Names[k]);
3010  if(ParamNo == M3::_BAD_INT_)
3011  {
3012  MACH3LOG_WARN("Couldn't find param {}. Can't Smear", Names[k]);
3013  return;
3014  }
3015 
3016  TString Title = "";
3017  double Prior = 1.0, PriorError = 1.0;
3018  GetNthParameter(ParamNo, Prior, PriorError, Title);
3019 
3020  ParameterEnum ParType = ParamType[ParamNo];
3021  int ParamTemp = ParamNo - ParamTypeStartPos[ParType];
3022  auto isCircular = ParamCircular[ParType][ParamTemp];
3023  if(isCircular) {
3024  MACH3LOG_ERROR("Trying to apply smearing for param {}, which has circular prior", Names[k]);
3025  MACH3LOG_ERROR("Please implement me or gently ask someone");
3026  throw MaCh3Exception(__FILE__ , __LINE__ );
3027  }
3028 
3029  Param.push_back(ParamNo);
3030  }
3031  std::string InputFile = MCMCFile+".root";
3032  std::string OutputFilename = MCMCFile + "_smeared.root";
3033 
3034  //KS: Simply create copy of file and add there new branch
3035  int ret = system(("cp " + InputFile + " " + OutputFilename).c_str());
3036  if (ret != 0)
3037  MACH3LOG_WARN("Error: system call to copy file failed with code {}", ret);
3038 
3039  TFile *OutputChain = M3::Open(OutputFilename, "UPDATE", __FILE__, __LINE__);
3040  OutputChain->cd();
3041  TTree *post = OutputChain->Get<TTree>("posteriors");
3042  TTree *treeNew = post->CloneTree(0);
3043 
3044  std::vector<double> NewParameter(Names.size());
3045  for(size_t i = 0; i < Param.size(); i++) {
3046  post->SetBranchAddress(BranchNames[Param[i]], &NewParameter[i]);
3047  }
3048 
3049  std::vector<double> Unsmeared_Parameter;
3050  if(SaveBranch){
3051  Unsmeared_Parameter.resize(Param.size());
3052  for(size_t i = 0; i < Param.size(); i++) {
3053  treeNew->Branch((BranchNames[Param[i]] + "_unsmeared"), &Unsmeared_Parameter[i]);
3054  }
3055  }
3056 
3057  Long64_t AllEntries = post->GetEntries();
3058  for (Long64_t i = 0; i < AllEntries; ++i) {
3059  // Entry from the old chain
3060  post->GetEntry(i);
3061 
3062  if(SaveBranch){
3063  for(size_t iPar = 0; iPar < Param.size(); iPar++) {
3064  Unsmeared_Parameter[iPar] = NewParameter[iPar];
3065  }
3066  }
3067  // Smear it
3068  for(size_t iPar = 0; iPar < Param.size(); iPar++) {
3069  NewParameter[iPar] += M3::rand::Gaus(0, Error[iPar]);
3070  }
3071  // Fill to the new chain
3072  treeNew->Fill();
3073  }
3074 
3075  OutputChain->cd();
3076  treeNew->Write("posteriors", TObject::kOverwrite);
3077 
3078  // KS: Save smearing metadata
3079  YAML::Node yaml_node;
3080  yaml_node["Smearing"].SetStyle(YAML::EmitterStyle::Block);
3081 
3082  for (size_t k = 0; k < Names.size(); ++k) {
3083  YAML::Node entry;
3084  entry.SetStyle(YAML::EmitterStyle::Flow);
3085 
3086  entry.push_back(Error[k]);
3087  entry.push_back("Gauss");
3088 
3089  yaml_node["Smearing"][Names[k]] = entry;
3090  }
3091  TMacro ConfigSave = YAMLtoTMacro(yaml_node, "Smearing_Config");
3092  ConfigSave.Write();
3093 
3094  OutputChain->Close();
3095  delete OutputChain;
3096 }
3097 
3098 // **************************
3099 // Diagnose the MCMC
3100 void MCMCProcessor::ParameterEvolution(const std::vector<std::string>& Names,
3101  const std::vector<int>& NIntervals) {
3102 // **************************
3103  MACH3LOG_INFO("Starting {}", __func__);
3104 
3105  //KS: First we need to find parameter number based on name
3106  for(unsigned int k = 0; k < Names.size(); ++k)
3107  {
3108  //KS: First we need to find parameter number based on name
3109  int ParamNo = GetParamIndexFromName(Names[k]);
3110  if(ParamNo == M3::_BAD_INT_)
3111  {
3112  MACH3LOG_WARN("Couldn't find param {}. Can't reweight Prior", Names[k]);
3113  continue;
3114  }
3115 
3116  const int IntervalsSize = nSteps/NIntervals[k];
3117  // ROOT won't overwrite gifs so we need to delete the file if it's there already
3118  std::string filename = Names[k] + ".gif";
3119  std::ifstream f(filename);
3120  if (f.good()) {
3121  f.close();
3122  int ret = system(fmt::format("rm {}", filename).c_str());
3123  if (ret != 0) {
3124  MACH3LOG_WARN("Error: system call to delete {} failed with code {}", filename, ret);
3125  }
3126  }
3127 
3128  int Counter = 0;
3129  for(int i = NIntervals[k]-1; i >= 0; --i)
3130  {
3131  // This holds the posterior density
3132  // KS: WARNING do not change to smart pointer, it breaks and I don't know why
3133  TH1D* EvePlot = new TH1D(BranchNames[ParamNo], BranchNames[ParamNo], nBins,
3134  hpost[ParamNo]->GetXaxis()->GetXmin(), hpost[ParamNo]->GetXaxis()->GetXmax());
3135  EvePlot->SetMinimum(0);
3136  EvePlot->GetYaxis()->SetTitle("PDF");
3137  EvePlot->GetYaxis()->SetNoExponent(false);
3138 
3139  //KS: Apply additional Cuts, like mass ordering
3140  std::string CutPosterior1D = "step > " + std::to_string(i*IntervalsSize+IntervalsSize);
3141 
3142  // If Posterior1DCut is not empty, append it
3143  if (!Posterior1DCut.empty()) {
3144  CutPosterior1D += " && " + Posterior1DCut;
3145  }
3146 
3147  // Apply reweighting if requested
3148  if (ReweightPosterior) {
3149  for (const auto& name : ReweightNames) {
3150  CutPosterior1D = "(" + CutPosterior1D + ")*(" + name + ")";
3151  }
3152  }
3153 
3154  std::string TextTitle = "Steps = 0 - "+std::to_string(Counter*IntervalsSize+IntervalsSize);
3155  // Project BranchNames[ParamNo] onto hpost, applying stepcut
3156  Chain->Project(BranchNames[ParamNo], BranchNames[ParamNo], CutPosterior1D.c_str());
3157 
3158  EvePlot->SetLineWidth(2);
3159  EvePlot->SetLineColor(kBlue-1);
3160  EvePlot->SetTitle(Names[k].c_str());
3161  EvePlot->GetXaxis()->SetTitle(EvePlot->GetTitle());
3162  EvePlot->GetYaxis()->SetLabelOffset(1000);
3163  if(ApplySmoothing) EvePlot->Smooth();
3164 
3165  EvePlot->Scale(1. / EvePlot->Integral());
3166  EvePlot->Draw("HIST");
3167 
3168  TText text(0.3, 0.8, TextTitle.c_str());
3169  text.SetTextFont (43);
3170  text.SetTextSize (40);
3171  text.SetNDC(true);
3172  text.Draw("SAME");
3173 
3174  if(i == 0) Posterior->Print((Names[k] + ".gif++20").c_str()); // produces infinite loop animated GIF
3175  else Posterior->Print((Names[k] + ".gif+20").c_str()); // add picture to .gif
3176  delete EvePlot;
3177  Counter++;
3178  }
3179  }
3180 }
3181 
3182 // **************************
3183 // Diagnose the MCMC
3185 // **************************
3186  // Prepare branches etc for DiagMCMC
3187  PrepareDiagMCMC();
3188 
3189  // Draw the simple trace matrices
3190  ParamTraces();
3191 
3192  // Get the batched means
3193  BatchedMeans();
3194 
3195  // Draw the auto-correlations
3196  if (useFFTAutoCorrelation) {
3198  } else {
3199  AutoCorrelation();
3200  }
3201 
3202  // Calculate Power Spectrum for each param
3204 
3205  // Get Geweke Z score helping select burn-in
3206  GewekeDiagnostic();
3207 
3208  // Draw acceptance Probability
3210 }
3211 
3212 // Check if all entries in StepNumber are unique
3213 bool AllUnique(unsigned int* StepNumber, size_t size) {
3214  std::unordered_set<unsigned int> s(StepNumber, StepNumber + size);
3215  return s.size() == size;
3216 }
3217 
3218 // **************************
3219 //CW: Prepare branches etc. for DiagMCMC
3221 // **************************
3222  doDiagMCMC = true;
3223  if(nBatches == 0) {
3224  MACH3LOG_ERROR("nBatches is equal to 0");
3225  MACH3LOG_ERROR("please use SetnBatches to set other value fore example 20");
3226  throw MaCh3Exception(__FILE__ , __LINE__ );
3227  }
3228 
3229  // Initialise ParStep
3230  ParStep = new M3::float_t*[nDraw]();
3231  for (int j = 0; j < nDraw; ++j) {
3232  ParStep[j] = new M3::float_t[nEntries]();
3233  for (int i = 0; i < nEntries; ++i) {
3234  ParStep[j][i] = -999.99;
3235  }
3236  }
3237 
3238  SampleValues = new double*[nEntries]();
3239  SystValues = new double*[nEntries]();
3240  AccProbValues = new double[nEntries]();
3241  StepNumber = new unsigned int[nEntries]();
3242  for (int i = 0; i < nEntries; ++i) {
3243  SampleValues[i] = new double[SampleName_v.size()]();
3244  SystValues[i] = new double[SystName_v.size()]();
3245 
3246  for (size_t j = 0; j < SampleName_v.size(); ++j) {
3247  SampleValues[i][j] = -999.99;
3248  }
3249  for (size_t j = 0; j < SystName_v.size(); ++j) {
3250  SystValues[i][j] = -999.99;
3251  }
3252  AccProbValues[i] = -999.99;
3253  StepNumber[i] = 0;
3254  }
3255 
3256  MACH3LOG_INFO("Reading input tree...");
3257  TStopwatch clock;
3258  clock.Start();
3259 
3260  // Set all the branches to off
3261  Chain->SetBranchStatus("*", false);
3262 
3263  // 10 entries output
3264  const int countwidth = nEntries/10;
3265 
3266  // Can also do the batched means here to minimize excessive loops
3267  // The length of each batch
3268  const int BatchLength = nEntries/nBatches+1;
3269  BatchedAverages = new double*[nBatches]();
3270  AccProbBatchedAverages = new double[nBatches]();
3271  for (int i = 0; i < nBatches; ++i) {
3272  BatchedAverages[i] = new double[nDraw];
3273  AccProbBatchedAverages[i] = 0;
3274  for (int j = 0; j < nDraw; ++j) {
3275  BatchedAverages[i][j] = 0.0;
3276  }
3277  }
3278  std::vector<double> ParStepBranch(nDraw);
3279  std::vector<double> SampleValuesBranch(SampleName_v.size());
3280  std::vector<double> SystValuesBranch(SystName_v.size());
3281  unsigned int StepNumberBranch = 0;
3282  double AccProbValuesBranch = 0;
3283  // Set the branch addresses for params
3284  for (int j = 0; j < nDraw; ++j) {
3285  Chain->SetBranchStatus(BranchNames[j].Data(), true);
3286  Chain->SetBranchAddress(BranchNames[j].Data(), &ParStepBranch[j]);
3287  }
3288  // Set the branch addresses for samples
3289  for (size_t j = 0; j < SampleName_v.size(); ++j) {
3290  Chain->SetBranchStatus(SampleName_v[j].Data(), true);
3291  Chain->SetBranchAddress(SampleName_v[j].Data(), &SampleValuesBranch[j]);
3292  }
3293  // Set the branch addresses for systematics
3294  for (size_t j = 0; j < SystName_v.size(); ++j) {
3295  Chain->SetBranchStatus(SystName_v[j].Data(), true);
3296  Chain->SetBranchAddress(SystName_v[j].Data(), &SystValuesBranch[j]);
3297  }
3298  // Only needed for Geweke right now
3299  Chain->SetBranchStatus("step", true);
3300  Chain->SetBranchAddress("step", &StepNumberBranch);
3301  // Turn on the branches which we want for acc prob
3302  Chain->SetBranchStatus("accProb", true);
3303  Chain->SetBranchAddress("accProb", &AccProbValuesBranch);
3304 
3305  // Loop over the entries
3306  //KS: This is really a bottleneck right now, thus revisit with ROOT6 https://pep-root6.github.io/docs/analysis/parallell/root.html
3307  for (int i = 0; i < nEntries; ++i) {
3308  // Fill up the arrays
3309  Chain->GetEntry(i);
3310 
3311  if (i % countwidth == 0)
3313 
3314  // Set the branch addresses for params
3315  for (int j = 0; j < nDraw; ++j) {
3316  ParStep[j][i] = ParStepBranch[j];
3317  }
3318  // Set the branch addresses for samples
3319  for (size_t j = 0; j < SampleName_v.size(); ++j) {
3320  SampleValues[i][j] = SampleValuesBranch[j];
3321  }
3322  // Set the branch addresses for systematics
3323  for (size_t j = 0; j < SystName_v.size(); ++j) {
3324  SystValues[i][j] = SystValuesBranch[j];
3325  }
3326 
3327  // Set the branch addresses for Acceptance Probability
3328  AccProbValues[i] = AccProbValuesBranch;
3329  StepNumber[i] = StepNumberBranch;
3330 
3331  // Find which batch the event belongs in
3332  int BatchNumber = -1;
3333  // I'm so lazy! But it's OK, the major overhead here is GetEntry: saved by ROOT!
3334  for (int j = 0; j < nBatches; ++j) {
3335  if (i < (j+1)*BatchLength) {
3336  BatchNumber = j;
3337  break;
3338  }
3339  }
3340  // Fill up the sum for each j param
3341  for (int j = 0; j < nDraw; ++j) {
3342  BatchedAverages[BatchNumber][j] += ParStep[j][i];
3343  }
3344 
3345  //KS: Could easily add this to above loop but I accProb is different beast so better keep it like this
3346  AccProbBatchedAverages[BatchNumber] += AccProbValues[i];
3347  }
3348  clock.Stop();
3349  MACH3LOG_INFO("Took {:.2f}s to finish caching statistic for Diag MCMC with {} steps", clock.RealTime(), nEntries);
3350 
3351  if(AllUnique(StepNumber, nEntries) == false){
3352  MACH3LOG_ERROR("Found steps with duplicate StepNumber, this indicate merged chain has been passed to DiagMCMC");
3353  MACH3LOG_ERROR("Code hasn't been optimised to work with merged chains, results may be unintended");
3354  throw MaCh3Exception(__FILE__ , __LINE__ );
3355  }
3356  // Make the sums into average
3357  #ifdef MULTITHREAD
3358  #pragma omp parallel for
3359  #endif
3360  for (int i = 0; i < nDraw; ++i) {
3361  for (int j = 0; j < nBatches; ++j) {
3362  // Divide by the total number of events in the batch
3363  BatchedAverages[j][i] /= BatchLength;
3364  if(i == 0) AccProbBatchedAverages[j] /= BatchLength; //KS: we have only one accProb, keep it like this for now
3365  }
3366  }
3367 
3368  // And make our sweet output file
3369  if (OutputFile == nullptr) MakeOutputFile();
3370 }
3371 
3372 // *****************
3373 //CW: Draw trace plots of the parameters i.e. parameter vs step
3375 // *****************
3376  if (ParStep == nullptr) PrepareDiagMCMC();
3377  MACH3LOG_INFO("Making trace plots...");
3378  // Make the TH1Ds
3379  std::vector<std::unique_ptr<TH1D>> TraceParamPlots(nDraw);
3380  std::vector<std::unique_ptr<TH1D>> TraceSamplePlots(SampleName_v.size());
3381  std::vector<std::unique_ptr<TH1D>> TraceSystsPlots(SystName_v.size());
3382 
3383  // Set the titles and limits for TH2Ds
3384  for (int j = 0; j < nDraw; ++j) {
3385  TString Title = "";
3386  double Prior = 1.0, PriorError = 1.0;
3387 
3388  GetNthParameter(j, Prior, PriorError, Title);
3389  std::string HistName = Form("%s_%s_Trace", Title.Data(), BranchNames[j].Data());
3390  TraceParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nEntries, 0, nEntries);
3391  TraceParamPlots[j]->SetDirectory(nullptr);
3392  TraceParamPlots[j]->GetXaxis()->SetTitle("Step");
3393  TraceParamPlots[j]->GetYaxis()->SetTitle("Parameter Variation");
3394  }
3395 
3396  for (size_t j = 0; j < SampleName_v.size(); ++j) {
3397  std::string HistName = SampleName_v[j].Data();
3398  TraceSamplePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nEntries, 0, nEntries);
3399  TraceSamplePlots[j]->SetDirectory(nullptr);
3400  TraceSamplePlots[j]->GetXaxis()->SetTitle("Step");
3401  TraceSamplePlots[j]->GetYaxis()->SetTitle("Sample -logL");
3402  }
3403 
3404  for (size_t j = 0; j < SystName_v.size(); ++j) {
3405  std::string HistName = SystName_v[j].Data();
3406  TraceSystsPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nEntries, 0, nEntries);
3407  TraceSystsPlots[j]->SetDirectory(nullptr);
3408  TraceSystsPlots[j]->GetXaxis()->SetTitle("Step");
3409  TraceSystsPlots[j]->GetYaxis()->SetTitle("Systematic -logL");
3410  }
3411 
3412  // Have now made the empty TH1Ds, now for writing content to them!
3413  // Loop over the number of parameters to draw their traces
3414  // Each histogram
3415  #ifdef MULTITHREAD
3416  #pragma omp parallel for
3417  #endif
3418  for (int i = 0; i < nEntries; ++i) {
3419  // Set bin content for the ith bin to the parameter values
3420  for (int j = 0; j < nDraw; ++j) {
3421  TraceParamPlots[j]->SetBinContent(i, ParStep[j][i]);
3422  }
3423  for (size_t j = 0; j < SampleName_v.size(); ++j) {
3424  TraceSamplePlots[j]->SetBinContent(i, SampleValues[i][j]);
3425  }
3426  for (size_t j = 0; j < SystName_v.size(); ++j) {
3427  TraceSystsPlots[j]->SetBinContent(i, SystValues[i][j]);
3428  }
3429  }
3430 
3431  // Write the output and delete the TH2Ds
3432  TDirectory *TraceDir = OutputFile->mkdir("Trace");
3433  TraceDir->cd();
3434  for (int j = 0; j < nDraw; ++j) {
3435  // Fit a linear function to the traces
3436  auto Fitter = std::make_unique<TF1>("Fitter", "[0]", nEntries/2, nEntries);
3437  Fitter->SetLineColor(kRed);
3438  TraceParamPlots[j]->Fit("Fitter","Rq");
3439  TraceParamPlots[j]->Write();
3440  }
3441 
3442  TDirectory *LLDir = OutputFile->mkdir("LogL");
3443  LLDir->cd();
3444  for (size_t j = 0; j < SampleName_v.size(); ++j) {
3445  TraceSamplePlots[j]->Write();
3446  delete[] SampleValues[j];
3447  }
3448  delete[] SampleValues;
3449 
3450  for (size_t j = 0; j < SystName_v.size(); ++j) {
3451  TraceSystsPlots[j]->Write();
3452  delete SystValues[j];
3453  }
3454  delete[] SystValues;
3455 
3456  TraceDir->Close();
3457  delete TraceDir;
3458 
3459  OutputFile->cd();
3460 }
3461 
3462 // *********************************
3463 std::vector <double> MCMCProcessor::GetParameterSums() {
3464 // *********************************
3465  // Initialise the sums
3466  std::vector <double> ParamSums(nDraw,0);
3467 
3468  #ifdef MULTITHREAD
3469  #pragma omp parallel for
3470  #endif
3471  for (int j = 0; j < nDraw; ++j) {
3472  for (int i = 0; i < nEntries; ++i) {
3473  ParamSums[j] += ParStep[j][i];
3474  }
3475  }
3476  // Make the sums into average
3477  #ifdef MULTITHREAD
3478  #pragma omp parallel for
3479  #endif
3480  for (int i = 0; i < nDraw; ++i) {
3481  ParamSums[i] /= double(nEntries);
3482  }
3483  return ParamSums;
3484 }
3485 
3486 // *********************************
3487 // MJR: Calculate autocorrelations using the FFT algorithm.
3488 // Fast, even on CPU, and get all lags for free.
3490 // *********************************
3491  if (ParStep == nullptr) PrepareDiagMCMC();
3492 
3493  TStopwatch clock;
3494  clock.Start();
3495  const int nLags = AutoCorrLag;
3496  MACH3LOG_INFO("Making auto-correlations for nLags = {}", nLags);
3497 
3498  // Prep outputs
3499  OutputFile->cd();
3500  TDirectory* AutoCorrDir = OutputFile->mkdir("Auto_corr");
3501  std::vector<std::unique_ptr<TH1D>> LagKPlots(nDraw);
3502  std::vector<std::vector<double>> LagL(nDraw);
3503 
3504  // Arrays needed to perform FFT using ROOT
3505  std::vector<double> ACFFT(nEntries, 0.0); // Main autocorrelation array
3506  std::vector<double> ParVals(nEntries, 0.0); // Param values for full chain
3507  std::vector<double> ParValsFFTR(nEntries, 0.0); // FFT Real part
3508  std::vector<double> ParValsFFTI(nEntries, 0.0); // FFT Imaginary part
3509  std::vector<double> ParValsFFTSquare(nEntries, 0.0); // FFT Absolute square
3510  std::vector<double> ParValsComplex(nEntries, 0.0); // Input Imaginary values (0)
3511 
3512  auto ParamSums = GetParameterSums();
3513  // Create forward and reverse FFT objects. I don't love using ROOT here,
3514  // but it works so I can't complain
3515  TVirtualFFT* fftf = TVirtualFFT::FFT(1, &nEntries, "C2CFORWARD");
3516  TVirtualFFT* fftb = TVirtualFFT::FFT(1, &nEntries, "C2CBACKWARD");
3517 
3518  // Loop over all pars and calculate the full autocorrelation function using FFT
3519  for (int j = 0; j < nDraw; ++j) {
3520  // Initialize
3521  LagL[j].resize(nLags);
3522  for (int i = 0; i < nEntries; ++i) {
3523  ParVals[i] = ParStep[j][i]-ParamSums[j]; // Subtract the mean to make it numerically tractable
3524  ParValsComplex[i] = 0.; // Reset dummy array
3525  }
3526 
3527  // Transform
3528  fftf->SetPointsComplex(ParVals.data(), ParValsComplex.data());
3529  fftf->Transform();
3530  fftf->GetPointsComplex(ParValsFFTR.data(), ParValsFFTI.data());
3531 
3532  // Square the results to get the power spectrum
3533  for (int i = 0; i < nEntries; ++i) {
3534  ParValsFFTSquare[i] = ParValsFFTR[i]*ParValsFFTR[i] + ParValsFFTI[i]*ParValsFFTI[i];
3535  }
3536 
3537  // Transforming back gives the autocovariance
3538  fftb->SetPointsComplex(ParValsFFTSquare.data(), ParValsComplex.data());
3539  fftb->Transform();
3540  fftb->GetPointsComplex(ACFFT.data(), ParValsComplex.data());
3541 
3542  // Divide by norm to get autocorrelation
3543  double normAC = ACFFT[0];
3544  for (int i = 0; i < nEntries; ++i) {
3545  ACFFT[i] /= normAC;
3546  }
3547 
3548  // Get plotting info
3549  TString Title = "";
3550  double Prior = 1.0, PriorError = 1.0;
3551  GetNthParameter(j, Prior, PriorError, Title);
3552  std::string HistName = Form("%s_%s_Lag", Title.Data(), BranchNames[j].Data());
3553 
3554  // Initialize Lag plot
3555  LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3556  LagKPlots[j]->SetDirectory(nullptr);
3557  LagKPlots[j]->GetXaxis()->SetTitle("Lag");
3558  LagKPlots[j]->GetYaxis()->SetTitle("Auto-correlation function");
3559 
3560  // Fill plot
3561  for (int k = 0; k < nLags; ++k) {
3562  LagL[j][k] = ACFFT[k];
3563  LagKPlots[j]->SetBinContent(k, ACFFT[k]);
3564  }
3565 
3566  // Write and clean up
3567  AutoCorrDir->cd();
3568  LagKPlots[j]->Write();
3569  }
3570 
3571  //KS: This is different diagnostic however it relies on calculated Lag, thus we call it before we delete LagKPlots
3572  CalculateESS(nLags, LagL);
3573 
3574  AutoCorrDir->Close();
3575  delete AutoCorrDir;
3576 
3577  OutputFile->cd();
3578 
3579  clock.Stop();
3580  MACH3LOG_INFO("Making auto-correlations took {:.2f}s", clock.RealTime());
3581 }
3582 
3583 // *********************************
3584 //KS: Calculate autocorrelations supports both OpenMP and CUDA :)
3586 // *********************************
3587  if (ParStep == nullptr) PrepareDiagMCMC();
3588 
3589  TStopwatch clock;
3590  clock.Start();
3591  const int nLags = AutoCorrLag;
3592  MACH3LOG_INFO("Making auto-correlations for nLags = {}", nLags);
3593 
3594  // The sum of (Y-Ymean)^2 over all steps for each parameter
3595  std::vector<std::vector<double>> DenomSum(nDraw);
3596  std::vector<std::vector<double>> NumeratorSum(nDraw);
3597  std::vector<std::vector<double>> LagL(nDraw);
3598  auto ParamSums = GetParameterSums();
3599  for (int j = 0; j < nDraw; ++j) {
3600  DenomSum[j].resize(nLags, 0.0);
3601  NumeratorSum[j].resize(nLags, 0.0);
3602  LagL[j].resize(nLags, 0.0);
3603  }
3604  std::vector<std::unique_ptr<TH1D>> LagKPlots(nDraw);
3605  // Loop over the parameters of interest
3606  for (int j = 0; j < nDraw; ++j)
3607  {
3608  // Make TH1Ds for each parameter which hold the lag
3609  TString Title = "";
3610  double Prior = 1.0, PriorError = 1.0;
3611 
3612  GetNthParameter(j, Prior, PriorError, Title);
3613  std::string HistName = Form("%s_%s_Lag", Title.Data(), BranchNames[j].Data());
3614  LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3615  LagKPlots[j]->SetDirectory(nullptr);
3616  LagKPlots[j]->GetXaxis()->SetTitle("Lag");
3617  LagKPlots[j]->GetYaxis()->SetTitle("Auto-correlation function");
3618  }
3619 //KS: If CUDA is not enabled do calculations on CPU
3620 #ifndef MaCh3_CUDA
3621  // Loop over the lags
3622  //CW: Each lag is independent so might as well multi-thread them!
3623  #ifdef MULTITHREAD
3624  MACH3LOG_INFO("Using multi-threading...");
3625  #pragma omp parallel for collapse(2)
3626  #endif // Loop over the number of parameters
3627  for (int j = 0; j < nDraw; ++j) {
3628  for (int k = 0; k < nLags; ++k) {
3629  // Loop over the number of entries
3630  for (int i = 0; i < nEntries; ++i) {
3631  const double Diff = ParStep[j][i]-ParamSums[j];
3632 
3633  // Only sum the numerator up to i = N-k
3634  if (i < nEntries-k) {
3635  const double LagTerm = ParStep[j][i+k]-ParamSums[j];
3636  const double Product = Diff*LagTerm;
3637  NumeratorSum[j][k] += Product;
3638  }
3639  // Square the difference to form the denominator
3640  const double Denom = Diff*Diff;
3641  DenomSum[j][k] += Denom;
3642  }
3643  }
3644  }
3645 #else //NOW GPU specific code
3646  MACH3LOG_INFO("Using GPU");
3648  float* ParStep_cpu = nullptr;
3649  float* NumeratorSum_cpu = nullptr;
3650  float* ParamSums_cpu = nullptr;
3651  float* DenomSum_cpu = nullptr;
3652 
3653  //KS: This allocates memory and copy data from CPU to GPU
3654  PrepareGPU_AutoCorr(nLags, ParamSums, ParStep_cpu, NumeratorSum_cpu, ParamSums_cpu, DenomSum_cpu);
3655 
3656  //KS: This runs the main kernel and copy results back to CPU
3657  GPUProcessor->RunGPU_AutoCorr(NumeratorSum_cpu,
3658  DenomSum_cpu);
3659 
3660  #ifdef MULTITHREAD
3661  #pragma omp parallel for collapse(2)
3662  #endif
3663  //KS: Now that that we received data from GPU convert it to CPU-like format
3664  for (int j = 0; j < nDraw; ++j)
3665  {
3666  for (int k = 0; k < nLags; ++k)
3667  {
3668  const int temp_index = j*nLags+k;
3669  NumeratorSum[j][k] = NumeratorSum_cpu[temp_index];
3670  DenomSum[j][k] = DenomSum_cpu[temp_index];
3671  }
3672  }
3673  //delete auxiliary variables
3674  if(NumeratorSum_cpu) delete[] NumeratorSum_cpu;
3675  if(DenomSum_cpu) delete[] DenomSum_cpu;
3676  if(ParStep_cpu) delete[] ParStep_cpu;
3677  if(ParamSums_cpu) delete[] ParamSums_cpu;
3678 
3679  //KS: Delete stuff at GPU as well
3680  GPUProcessor->CleanupGPU_AutoCorr();
3681 
3682 //KS: End of GPU specific code
3683 #endif
3684 
3685  OutputFile->cd();
3686  TDirectory *AutoCorrDir = OutputFile->mkdir("Auto_corr");
3687  // Now fill the LagK auto-correlation plots
3688  for (int j = 0; j < nDraw; ++j) {
3689  for (int k = 0; k < nLags; ++k) {
3690  LagL[j][k] = NumeratorSum[j][k]/DenomSum[j][k];
3691  LagKPlots[j]->SetBinContent(k, NumeratorSum[j][k]/DenomSum[j][k]);
3692  }
3693  AutoCorrDir->cd();
3694  LagKPlots[j]->Write();
3695  }
3696 
3697  //KS: This is different diagnostic however it relies on calculated Lag, thus we call it before we delete LagKPlots
3698  CalculateESS(nLags, LagL);
3699 
3700  AutoCorrDir->Close();
3701  delete AutoCorrDir;
3702 
3703  OutputFile->cd();
3704 
3705  clock.Stop();
3706  MACH3LOG_INFO("Making auto-correlations took {:.2f}s", clock.RealTime());
3707 }
3708 
3709 #ifdef MaCh3_CUDA
3710 // **************************
3711 //KS: Allocates memory and copy data from CPU to GPU
3712 void MCMCProcessor::PrepareGPU_AutoCorr(const int nLags, const std::vector<double>& ParamSums, float*& ParStep_cpu,
3713  float*& NumeratorSum_cpu, float*& ParamSums_cpu, float*& DenomSum_cpu) {
3714 // **************************
3715  //KS: Create temporary arrays that will communicate with GPU code
3716  ParStep_cpu = new float[nDraw*nEntries];
3717  NumeratorSum_cpu = new float[nDraw*nLags];
3718  DenomSum_cpu = new float[nDraw*nLags];
3719  ParamSums_cpu = new float[nDraw];
3720 
3721  #ifdef MULTITHREAD
3722  //KS: Open parallel region
3723  #pragma omp parallel
3724  {
3725  #endif
3726  //KS: Operations are independent thus we are using nowait close
3727  #ifdef MULTITHREAD
3728  #pragma omp for nowait
3729  #endif
3730  for (int i = 0; i < nDraw; ++i)
3731  {
3732  //KS: We basically need this to convert from double to float for GPU
3733  ParamSums_cpu[i] = ParamSums[i];
3734  }
3735 
3736  #ifdef MULTITHREAD
3737  #pragma omp for collapse(2) nowait
3738  #endif
3739  for (int j = 0; j < nDraw; ++j)
3740  {
3741  for (int k = 0; k < nLags; ++k)
3742  {
3743  const int temp = j*nLags+k;
3744  NumeratorSum_cpu[temp] = 0.0;
3745  DenomSum_cpu[temp] = 0.0;
3746  }
3747  }
3748 
3749  #ifdef MULTITHREAD
3750  #pragma omp for collapse(2)
3751  #endif
3752  for (int j = 0; j < nDraw; ++j)
3753  {
3754  for (int i = 0; i < nEntries; ++i)
3755  {
3756  const int temp = j*nEntries+i;
3757  ParStep_cpu[temp] = ParStep[j][i];
3758  }
3759  }
3760  #ifdef MULTITHREAD
3761  //KS: End parallel region
3762  }
3763  #endif
3764 
3765  //KS: First allocate memory on GPU
3766  GPUProcessor->InitGPU_AutoCorr(nEntries,
3767  nDraw,
3768  nLags);
3769 
3770 
3771  //KS: Now copy from CPU to GPU
3772  GPUProcessor->CopyToGPU_AutoCorr(ParStep_cpu,
3773  NumeratorSum_cpu,
3774  ParamSums_cpu,
3775  DenomSum_cpu);
3776 }
3777 #endif
3778 
3779 // **************************
3780 // KS: calc Effective Sample Size Following @cite StanManual
3781 // Furthermore we calculate Sampling efficiency following @cite hanson2008mcmc
3782 // Rule of thumb is to have efficiency above 25%
3783 void MCMCProcessor::CalculateESS(const int nLags, const std::vector<std::vector<double>>& LagL) {
3784 // **************************
3785  if(LagL.size() == 0)
3786  {
3787  MACH3LOG_ERROR("Size of LagL is {}", LagL.size());
3788  throw MaCh3Exception(__FILE__ , __LINE__ );
3789  }
3790  MACH3LOG_INFO("Making ESS plots...");
3791  TVectorD EffectiveSampleSize(nDraw);
3792  TVectorD SamplingEfficiency(nDraw);
3793  std::vector<double> TempDenominator(nDraw);
3794 
3795  constexpr int Nhists = 5;
3796  constexpr double Thresholds[Nhists + 1] = {1, 0.02, 0.005, 0.001, 0.0001, 0.0};
3797  constexpr Color_t ESSColours[Nhists] = {kGreen, kGreen + 2, kYellow, kOrange, kRed};
3798 
3799  //KS: This histogram is inspired by the following: @cite gabry2024visual
3800  std::vector<std::unique_ptr<TH1D>> EffectiveSampleSizeHist(Nhists);
3801  for(int i = 0; i < Nhists; ++i)
3802  {
3803  EffectiveSampleSizeHist[i] =
3804  std::make_unique<TH1D>(Form("EffectiveSampleSizeHist_%i", i), Form("EffectiveSampleSizeHist_%i", i), nDraw, 0, nDraw);
3805  EffectiveSampleSizeHist[i]->SetDirectory(nullptr);
3806  EffectiveSampleSizeHist[i]->GetYaxis()->SetTitle("N_{eff}/N");
3807  EffectiveSampleSizeHist[i]->SetFillColor(ESSColours[i]);
3808  EffectiveSampleSizeHist[i]->SetLineColor(ESSColours[i]);
3809  EffectiveSampleSizeHist[i]->Sumw2();
3810  for (int j = 0; j < nDraw; ++j)
3811  {
3812  TString Title = "";
3813  double Prior = 1.0, PriorError = 1.0;
3814  GetNthParameter(j, Prior, PriorError, Title);
3815  EffectiveSampleSizeHist[i]->GetXaxis()->SetBinLabel(j+1, Title.Data());
3816  }
3817  }
3818 
3819  #ifdef MULTITHREAD
3820  #pragma omp parallel for
3821  #endif
3822  //KS: Calculate ESS and MCMC efficiency for each parameter
3823  for (int j = 0; j < nDraw; ++j)
3824  {
3825  EffectiveSampleSize(j) = M3::_BAD_DOUBLE_;
3826  SamplingEfficiency(j) = M3::_BAD_DOUBLE_;
3827  TempDenominator[j] = 0.;
3828  //KS: Firs sum over all Calculated autocorrelations
3829  for (int k = 0; k < nLags; ++k)
3830  {
3831  TempDenominator[j] += LagL[j][k];
3832  }
3833  TempDenominator[j] = 1+2*TempDenominator[j];
3834  EffectiveSampleSize(j) = double(nEntries)/TempDenominator[j];
3835  // 100 because we convert to percentage
3836  SamplingEfficiency(j) = 100 * 1/TempDenominator[j];
3837 
3838  for(int i = 0; i < Nhists; ++i)
3839  {
3840  EffectiveSampleSizeHist[i]->SetBinContent(j+1, 0);
3841  EffectiveSampleSizeHist[i]->SetBinError(j+1, 0);
3842 
3843  const double TempEntry = std::fabs(EffectiveSampleSize(j)) / double(nEntries);
3844  if(Thresholds[i] >= TempEntry && TempEntry > Thresholds[i+1])
3845  {
3846  if( std::isnan(EffectiveSampleSize(j)) ) continue;
3847  EffectiveSampleSizeHist[i]->SetBinContent(j+1, TempEntry);
3848  }
3849  }
3850  }
3851 
3852  //KS Write to the output tree
3853  //Save to file
3854  OutputFile->cd();
3855  EffectiveSampleSize.Write("EffectiveSampleSize");
3856  SamplingEfficiency.Write("SamplingEfficiency");
3857 
3858  EffectiveSampleSizeHist[0]->SetTitle("Effective Sample Size");
3859  EffectiveSampleSizeHist[0]->Draw();
3860  for(int i = 1; i < Nhists; ++i)
3861  {
3862  EffectiveSampleSizeHist[i]->Draw("SAME");
3863  }
3864 
3865  auto leg = std::make_unique<TLegend>(0.2, 0.7, 0.6, 0.95);
3866  SetLegendStyle(leg.get(), 0.03);
3867  for(int i = 0; i < Nhists; ++i)
3868  {
3869  leg->AddEntry(EffectiveSampleSizeHist[i].get(), Form("%.4f >= N_{eff}/N > %.4f", Thresholds[i], Thresholds[i+1]), "f");
3870  } leg->Draw("SAME");
3871 
3872  Posterior->Write("EffectiveSampleSizeCanvas");
3873 }
3874 
3875 // **************************
3876 //CW: Batched means, literally read from an array and chuck into TH1D
3878 // **************************
3879  if (BatchedAverages == nullptr) PrepareDiagMCMC();
3880  MACH3LOG_INFO("Making BatchedMeans plots...");
3881 
3882  std::vector<std::unique_ptr<TH1D>> BatchedParamPlots(nDraw);
3883  for (int j = 0; j < nDraw; ++j) {
3884  TString Title = "";
3885  double Prior = 1.0, PriorError = 1.0;
3886 
3887  GetNthParameter(j, Prior, PriorError, Title);
3888 
3889  std::string HistName = Form("%s_%s_batch", Title.Data(), BranchNames[j].Data());
3890  BatchedParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nBatches, 0, nBatches);
3891  BatchedParamPlots[j]->SetDirectory(nullptr);
3892  }
3893 
3894  #ifdef MULTITHREAD
3895  #pragma omp parallel for
3896  #endif
3897  for (int j = 0; j < nDraw; ++j) {
3898  for (int i = 0; i < nBatches; ++i) {
3899  BatchedParamPlots[j]->SetBinContent(i+1, BatchedAverages[i][j]);
3900  const int BatchRangeLow = double(i)*double(nEntries)/double(nBatches);
3901  const int BatchRangeHigh = double(i+1)*double(nEntries)/double(nBatches);
3902  std::stringstream ss;
3903  ss << BatchRangeLow << " - " << BatchRangeHigh;
3904  BatchedParamPlots[j]->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
3905  }
3906  }
3907 
3908  TDirectory *BatchDir = OutputFile->mkdir("Batched_means");
3909  BatchDir->cd();
3910  for (int j = 0; j < nDraw; ++j) {
3911  auto Fitter = std::make_unique<TF1>("Fitter", "[0]", 0, nBatches);
3912  Fitter->SetLineColor(kRed);
3913  BatchedParamPlots[j]->Fit("Fitter","Rq");
3914  BatchedParamPlots[j]->Write();
3915  }
3916 
3917  //KS: Get the batched means variance estimation and variable indicating if number of batches is sensible
3918  // We do this before deleting BatchedAverages
3919  BatchedAnalysis();
3920 
3921  for (int i = 0; i < nBatches; ++i) {
3922  delete BatchedAverages[i];
3923  }
3924  delete[] BatchedAverages;
3925 
3926  BatchDir->Close();
3927  delete BatchDir;
3928 
3929  OutputFile->cd();
3930 }
3931 
3932 // **************************
3933 // Get the batched means variance estimation and variable indicating if number of batches is sensible
3935 // **************************
3936  if(BatchedAverages == nullptr)
3937  {
3938  MACH3LOG_ERROR("BatchedAverages haven't been initialises or have been deleted something is wrong");
3939  MACH3LOG_ERROR("I need it and refuse to go further");
3940  throw MaCh3Exception(__FILE__ , __LINE__ );
3941  }
3942 
3943  // Calculate variance estimator using batched means following @cite chakraborty2019estimating see Eq. 1.2
3944  TVectorD BatchedVariance(nDraw);
3945  //KS: The hypothesis is rejected if C > z α for a given confidence level α. If the batch means do not pass the test, Correlated is reported for the half-width on the statistical reports following @cite rossetti2024batch alternatively for more old-school see Alexopoulos and Seila 1998 section 3.4.3
3946  TVectorD C_Test_Statistics(nDraw);
3947 
3948  std::vector<double> OverallBatchMean(nDraw);
3949  std::vector<double> C_Rho_Nominator(nDraw);
3950  std::vector<double> C_Rho_Denominator(nDraw);
3951  std::vector<double> C_Nominator(nDraw);
3952  std::vector<double> C_Denominator(nDraw);
3953  const int BatchLength = nEntries/nBatches+1;
3954 //KS: Start parallel region
3955 #ifdef MULTITHREAD
3956 #pragma omp parallel
3957 {
3958 #endif
3959  #ifdef MULTITHREAD
3960  #pragma omp for
3961  #endif
3962  //KS: First calculate mean of batched means for each param and Initialise everything to 0
3963  for (int j = 0; j < nDraw; ++j)
3964  {
3965  OverallBatchMean[j] = 0.0;
3966  C_Rho_Nominator[j] = 0.0;
3967  C_Rho_Denominator[j] = 0.0;
3968  C_Nominator[j] = 0.0;
3969  C_Denominator[j] = 0.0;
3970 
3971  BatchedVariance(j) = 0.0;
3972  C_Test_Statistics(j) = 0.0;
3973  for (int i = 0; i < nBatches; ++i)
3974  {
3975  OverallBatchMean[j] += BatchedAverages[i][j];
3976  }
3977  OverallBatchMean[j] /= nBatches;
3978  }
3979 
3980  #ifdef MULTITHREAD
3981  #pragma omp for nowait
3982  #endif
3983  //KS: next loop is completely independent thus nowait clause
3984  for (int j = 0; j < nDraw; ++j)
3985  {
3986  for (int i = 0; i < nBatches; ++i)
3987  {
3988  BatchedVariance(j) += (OverallBatchMean[j] - BatchedAverages[i][j])*(OverallBatchMean[j] - BatchedAverages[i][j]);
3989  }
3990  BatchedVariance(j) = (BatchLength/(nBatches-1)) * BatchedVariance(j);
3991  }
3992 
3993  //KS: Now we focus on C test statistic, again use nowait as next is calculation is independent
3994  #ifdef MULTITHREAD
3995  #pragma omp for nowait
3996  #endif
3997  for (int j = 0; j < nDraw; ++j)
3998  {
3999  C_Nominator[j] = (OverallBatchMean[j] - BatchedAverages[0][j])*(OverallBatchMean[j] - BatchedAverages[0][j]) +
4000  (OverallBatchMean[j] - BatchedAverages[nBatches-1][j])*(OverallBatchMean[j] - BatchedAverages[nBatches-1][j]);
4001  for (int i = 0; i < nBatches; ++i)
4002  {
4003  C_Denominator[j] += (OverallBatchMean[j] - BatchedAverages[i][j])*(OverallBatchMean[j] - BatchedAverages[i][j]);
4004  }
4005  C_Denominator[j] = 2*C_Denominator[j];
4006  }
4007 
4008  //KS: We still calculate C and for this we need rho wee need autocorrelations between batches
4009  #ifdef MULTITHREAD
4010  #pragma omp for
4011  #endif
4012  for (int j = 0; j < nDraw; ++j)
4013  {
4014  for (int i = 0; i < nBatches-1; ++i)
4015  {
4016  C_Rho_Nominator[j] += (OverallBatchMean[j] - BatchedAverages[i][j])*(OverallBatchMean[j] - BatchedAverages[i+1][j]);
4017  }
4018 
4019  for (int i = 0; i < nBatches; ++i)
4020  {
4021  C_Rho_Denominator[j] += (OverallBatchMean[j] - BatchedAverages[i][j])*(OverallBatchMean[j] - BatchedAverages[i][j]);
4022  }
4023  }
4024 
4025  //KS: Final calculations of C
4026  #ifdef MULTITHREAD
4027  #pragma omp for
4028  #endif
4029  for (int j = 0; j < nDraw; ++j)
4030  {
4031  C_Test_Statistics(j) = std::sqrt((nBatches*nBatches - 1)/(nBatches-2)) * ( C_Rho_Nominator[j]/C_Rho_Denominator[j] + C_Nominator[j]/ C_Denominator[j]);
4032  }
4033 #ifdef MULTITHREAD
4034 } //End parallel region
4035 #endif
4036 
4037  //Save to file
4038  OutputFile->cd();
4039  BatchedVariance.Write("BatchedMeansVariance");
4040  C_Test_Statistics.Write("C_Test_Statistics");
4041 }
4042 
4043 // **************************
4044 // RC: Perform spectral analysis of MCMC based on @cite Dunkley:2004sv
4046 // **************************
4047  TStopwatch clock;
4048  clock.Start();
4049 
4050  //KS: Store it as we go back to them at the end
4051  const double TopMargin = Posterior->GetTopMargin();
4052  const int OptTitle = gStyle->GetOptTitle();
4053 
4054  Posterior->SetTopMargin(0.1);
4055  gStyle->SetOptTitle(1);
4056 
4057  MACH3LOG_INFO("Making Power Spectrum plots...");
4058 
4059  // This is only to reduce number of computations...
4060  const int N_Coeffs = std::min(10000, nEntries);
4061  const int start = -(N_Coeffs/2-1);
4062  const int end = N_Coeffs/2-1;
4063  const int v_size = end - start;
4064 
4065  int nPrams = nDraw;
4067  nPrams = 1;
4068 
4069  std::vector<std::vector<float>> k_j(nPrams, std::vector<float>(v_size, 0.0));
4070  std::vector<std::vector<float>> P_j(nPrams, std::vector<float>(v_size, 0.0));
4071 
4072  int _N = nEntries;
4073  if (_N % 2 != 0) _N -= 1; // N must be even
4074 
4075  //This is being used a lot so calculate it once to increase performance
4076  const double two_pi_over_N = 2 * TMath::Pi() / static_cast<double>(_N);
4077 
4078  // KS: This could be moved to GPU I guess
4079  #ifdef MULTITHREAD
4080  #pragma omp parallel for collapse(2)
4081  #endif
4082  // RC: equation 11: for each value of j coef, from range -N/2 -> N/2
4083  for (int j = 0; j < nPrams; ++j)
4084  {
4085  for (int jj = start; jj < end; ++jj)
4086  {
4087  std::complex<M3::float_t> a_j = 0.0;
4088  const double two_pi_over_N_jj = two_pi_over_N * jj;
4089  for (int n = 0; n < _N; ++n)
4090  {
4091  //if(StepNumber[n] < BurnInCut) continue;
4092  std::complex<M3::float_t> exp_temp(0, two_pi_over_N_jj * n);
4093  a_j += ParStep[j][n] * std::exp(exp_temp);
4094  }
4095  a_j /= std::sqrt(float(_N));
4096  const int _c = jj - start;
4097 
4098  k_j[j][_c] = two_pi_over_N_jj;
4099  // Equation 13
4100  P_j[j][_c] = std::norm(a_j);
4101  }
4102  }
4103 
4104  TDirectory *PowerDir = OutputFile->mkdir("PowerSpectrum");
4105  PowerDir->cd();
4106 
4107  TVectorD PowerSpectrumStepSize(nPrams);
4108  for (int j = 0; j < nPrams; ++j)
4109  {
4110  auto plot = std::make_unique<TGraph>(v_size, k_j[j].data(), P_j[j].data());
4111 
4112  TString Title = "";
4113  double Prior = 1.0, PriorError = 1.0;
4114  GetNthParameter(j, Prior, PriorError, Title);
4115 
4116  std::string name = Form("Power Spectrum of %s;k;P(k)", Title.Data());
4117 
4118  plot->SetTitle(name.c_str());
4119  name = Form("%s_power_spectrum", Title.Data());
4120  plot->SetName(name.c_str());
4121  plot->SetMarkerStyle(7);
4122 
4123  // Equation 18
4124  auto func = std::make_unique<TF1>("power_template", "[0]*( ([1] / x)^[2] / (([1] / x)^[2] +1) )", 0.0, 1.0);
4125  // P0 gives the amplitude of the white noise spectrum in the k → 0 limit
4126  func->SetParameter(0, 10.0);
4127  // k* indicates the position of the turnover to a different power law behaviour
4128  func->SetParameter(1, 0.1);
4129  // alpha free parameter
4130  func->SetParameter(2, 2.0);
4131 
4132  // Set parameter limits for stability
4133  func->SetParLimits(0, 0.0, 100.0); // Amplitude should be non-negative
4134  func->SetParLimits(1, 0.001, 1.0); // k* should be within a reasonable range
4135  func->SetParLimits(2, 0.0, 5.0); // alpha should be positive
4136 
4137  plot->Fit("power_template","Rq");
4138 
4139  Posterior->SetLogx();
4140  Posterior->SetLogy();
4141  Posterior->SetGrid();
4142  plot->Draw("AL");
4143  func->Draw("SAME");
4144 
4145  //KS: I have no clue what is the reason behind this. Found this in Rick Calland code...
4146  PowerSpectrumStepSize(j) = std::sqrt(func->GetParameter(0)/float(v_size*0.5));
4147  }
4148 
4149  PowerSpectrumStepSize.Write("PowerSpectrumStepSize");
4150  PowerDir->Close();
4151  delete PowerDir;
4152 
4153  clock.Stop();
4154  MACH3LOG_INFO("Making Power Spectrum took {:.2f}s", clock.RealTime());
4155 
4156  Posterior->SetTopMargin(TopMargin);
4157  gStyle->SetOptTitle(OptTitle);
4158 }
4159 
4160 // **************************
4161 // Geweke Diagnostic based on
4162 // @cite Fang2014GewekeDiagnostics
4163 // @cite karlsbakk2011 Chapter 3.1
4165 // **************************
4166  MACH3LOG_INFO("Making Geweke Diagnostic");
4167  //KS: Up refers to upper limit we check, it stays constant, in literature it is mostly 50% thus using 0.5 for threshold
4168  std::vector<double> MeanUp(nDraw, 0.0);
4169  std::vector<double> SpectralVarianceUp(nDraw, 0.0);
4170  std::vector<int> DenomCounterUp(nDraw, 0);
4171  const double Threshold = 0.5 * nSteps;
4172 
4173  //KS: Select values between which you want to scan, for example 0 means 0% burn in and 1 100% burn in.
4174  constexpr double LowerThreshold = 0;
4175  constexpr double UpperThreshold = 1.0;
4176  // Tells how many intervals between thresholds we want to check
4177  constexpr int NChecks = 100;
4178  constexpr double Division = (UpperThreshold - LowerThreshold)/NChecks;
4179 
4180  std::vector<std::unique_ptr<TH1D>> GewekePlots(nDraw);
4181  for (int j = 0; j < nDraw; ++j)
4182  {
4183  TString Title = "";
4184  double Prior = 1.0, PriorError = 1.0;
4185  GetNthParameter(j, Prior, PriorError, Title);
4186  std::string HistName = Form("%s_%s_Geweke", Title.Data(), BranchNames[j].Data());
4187  GewekePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), NChecks, 0.0, 100 * UpperThreshold);
4188  GewekePlots[j]->SetDirectory(nullptr);
4189  GewekePlots[j]->GetXaxis()->SetTitle("Burn-In (%)");
4190  GewekePlots[j]->GetYaxis()->SetTitle("Geweke T score");
4191  }
4192 
4193 //KS: Start parallel region
4194 #ifdef MULTITHREAD
4195 #pragma omp parallel
4196 {
4197 #endif
4198  //KS: First we calculate mean and spectral variance for the upper limit, this doesn't change and in literature is most often 50%
4199  #ifdef MULTITHREAD
4200  #pragma omp for
4201  #endif
4202  for (int j = 0; j < nDraw; ++j)
4203  {
4204  for(int i = 0; i < nEntries; ++i)
4205  {
4206  if(StepNumber[i] > Threshold)
4207  {
4208  MeanUp[j] += ParStep[j][i];
4209  DenomCounterUp[j]++;
4210  }
4211  }
4212  MeanUp[j] = MeanUp[j]/DenomCounterUp[j];
4213  }
4214 
4215  //KS: now Spectral variance which in this case is sample variance
4216  #ifdef MULTITHREAD
4217  #pragma omp for collapse(2)
4218  #endif
4219  for (int j = 0; j < nDraw; ++j)
4220  {
4221  for(int i = 0; i < nEntries; ++i)
4222  {
4223  if(StepNumber[i] > Threshold)
4224  {
4225  SpectralVarianceUp[j] += (ParStep[j][i] - MeanUp[j])*(ParStep[j][i] - MeanUp[j]);
4226  }
4227  }
4228  }
4229 
4230  //Loop over how many intervals we calculate
4231  #ifdef MULTITHREAD
4232  #pragma omp for
4233  #endif
4234  for (int k = 1; k < NChecks+1; ++k)
4235  {
4236  //KS each thread has it's own
4237  std::vector<double> MeanDown(nDraw, 0.0);
4238  std::vector<double> SpectralVarianceDown(nDraw, 0.0);
4239  std::vector<int> DenomCounterDown(nDraw, 0);
4240 
4241  const unsigned int ThresholsCheck = Division*k*nSteps;
4242  //KS: First mean
4243  for (int j = 0; j < nDraw; ++j)
4244  {
4245  for(int i = 0; i < nEntries; ++i)
4246  {
4247  if(StepNumber[i] < ThresholsCheck)
4248  {
4249  MeanDown[j] += ParStep[j][i];
4250  DenomCounterDown[j]++;
4251  }
4252  }
4253  MeanDown[j] = MeanDown[j]/DenomCounterDown[j];
4254  }
4255  //Now spectral variance
4256  for (int j = 0; j < nDraw; ++j)
4257  {
4258  for(int i = 0; i < nEntries; ++i)
4259  {
4260  if(StepNumber[i] < ThresholsCheck)
4261  {
4262  SpectralVarianceDown[j] += (ParStep[j][i] - MeanDown[j])*(ParStep[j][i] - MeanDown[j]);
4263  }
4264  }
4265  }
4266  //Lastly calc T score and fill histogram entry
4267  for (int j = 0; j < nDraw; ++j)
4268  {
4269  double T_score = std::fabs((MeanDown[j] - MeanUp[j])/std::sqrt(SpectralVarianceDown[j]/DenomCounterDown[j] + SpectralVarianceUp[j]/DenomCounterUp[j]));
4270  GewekePlots[j]->SetBinContent(k, T_score);
4271  }
4272  } //end loop over intervals
4273 #ifdef MULTITHREAD
4274 } //End parallel region
4275 #endif
4276 
4277  //Finally save it to TFile
4278  OutputFile->cd();
4279  TDirectory *GewekeDir = OutputFile->mkdir("Geweke");
4280  for (int j = 0; j < nDraw; ++j)
4281  {
4282  GewekeDir->cd();
4283  GewekePlots[j]->Write();
4284  }
4285  for (int i = 0; i < nDraw; ++i) {
4286  delete[] ParStep[i];
4287  }
4288  delete[] ParStep;
4289  ParStep = nullptr;
4290 
4291  GewekeDir->Close();
4292  delete GewekeDir;
4293  OutputFile->cd();
4294 }
4295 
4296 // **************************
4297 // Acceptance Probability
4299 // **************************
4300  if (AccProbBatchedAverages == nullptr) PrepareDiagMCMC();
4301 
4302  MACH3LOG_INFO("Making AccProb plots...");
4303 
4304  // Set the titles and limits for TH1Ds
4305  auto AcceptanceProbPlot = std::make_unique<TH1D>("AcceptanceProbability", "Acceptance Probability", nEntries, 0, nEntries);
4306  AcceptanceProbPlot->SetDirectory(nullptr);
4307  AcceptanceProbPlot->GetXaxis()->SetTitle("Step");
4308  AcceptanceProbPlot->GetYaxis()->SetTitle("Acceptance Probability");
4309 
4310  auto BatchedAcceptanceProblot = std::make_unique<TH1D>("AcceptanceProbability_Batch", "AcceptanceProbability_Batch", nBatches, 0, nBatches);
4311  BatchedAcceptanceProblot->SetDirectory(nullptr);
4312  BatchedAcceptanceProblot->GetYaxis()->SetTitle("Acceptance Probability");
4313 
4314  for (int i = 0; i < nBatches; ++i) {
4315  BatchedAcceptanceProblot->SetBinContent(i+1, AccProbBatchedAverages[i]);
4316  const int BatchRangeLow = double(i)*double(nEntries)/double(nBatches);
4317  const int BatchRangeHigh = double(i+1)*double(nEntries)/double(nBatches);
4318  std::stringstream ss;
4319  ss << BatchRangeLow << " - " << BatchRangeHigh;
4320  BatchedAcceptanceProblot->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4321  }
4322 
4323  #ifdef MULTITHREAD
4324  #pragma omp parallel for
4325  #endif
4326  for (int i = 0; i < nEntries; ++i) {
4327  // Set bin content for the i-th bin to the parameter values
4328  AcceptanceProbPlot->SetBinContent(i, AccProbValues[i]);
4329  }
4330 
4331  TDirectory *probDir = OutputFile->mkdir("AccProb");
4332  probDir->cd();
4333 
4334  AcceptanceProbPlot->Write();
4335  BatchedAcceptanceProblot->Write();
4336  delete[] AccProbValues;
4337  delete[] AccProbBatchedAverages;
4338 
4339  probDir->Close();
4340  delete probDir;
4341 
4342  OutputFile->cd();
4343 }
4344 
4345 // **************************
4346 void MCMCProcessor::CheckCredibleIntervalsOrder(const std::vector<double>& CredibleIntervals, const std::vector<Color_t>& CredibleIntervalsColours) const {
4347 // **************************
4348  if (CredibleIntervals.size() != CredibleIntervalsColours.size()) {
4349  MACH3LOG_ERROR("size of CredibleIntervals is not equal to size of CredibleIntervalsColours");
4350  throw MaCh3Exception(__FILE__, __LINE__);
4351  }
4352  if (CredibleIntervals.size() > 1) {
4353  for (unsigned int i = 1; i < CredibleIntervals.size(); i++) {
4354  if (CredibleIntervals[i] > CredibleIntervals[i - 1]) {
4355  MACH3LOG_ERROR("Interval {} is smaller than {}", i, i - 1);
4356  MACH3LOG_ERROR("{:.2f} {:.2f}", CredibleIntervals[i], CredibleIntervals[i - 1]);
4357  MACH3LOG_ERROR("They should be grouped in decreasing order");
4358  throw MaCh3Exception(__FILE__, __LINE__);
4359  }
4360  }
4361  }
4362 }
4363 
4364 // **************************
4365 void MCMCProcessor::CheckCredibleRegionsOrder(const std::vector<double>& CredibleRegions,
4366  const std::vector<Style_t>& CredibleRegionStyle,
4367  const std::vector<Color_t>& CredibleRegionColor) {
4368 // **************************
4369  if ((CredibleRegions.size() != CredibleRegionStyle.size()) || (CredibleRegionStyle.size() != CredibleRegionColor.size())) {
4370  MACH3LOG_ERROR("size of CredibleRegions is not equal to size of CredibleRegionStyle or CredibleRegionColor");
4371  throw MaCh3Exception(__FILE__, __LINE__);
4372  }
4373  for (unsigned int i = 1; i < CredibleRegions.size(); i++) {
4374  if (CredibleRegions[i] > CredibleRegions[i - 1]) {
4375  MACH3LOG_ERROR("Interval {} is smaller than {}", i, i - 1);
4376  MACH3LOG_ERROR("{:.2f} {:.2f}", CredibleRegions[i], CredibleRegions[i - 1]);
4377  MACH3LOG_ERROR("They should be grouped in decreasing order");
4378  throw MaCh3Exception(__FILE__, __LINE__);
4379  }
4380  }
4381 }
4382 
4383 // **************************
4384 int MCMCProcessor::GetGroup(const std::string& name) const {
4385 // **************************
4386  // Lambda to compare strings case-insensitively
4387  auto caseInsensitiveCompare = [](const std::string& a, const std::string& b) {
4388  return std::equal(a.begin(), a.end(), b.begin(), b.end(),
4389  [](char c1, char c2) { return std::tolower(c1) == std::tolower(c2); });
4390  };
4391  int numerator = 0;
4392  for (const auto& groupName : ParameterGroup) {
4393  if (caseInsensitiveCompare(groupName, name)) {
4394  numerator++;
4395  }
4396  }
4397  return numerator;
4398 }
4399 
4400 // **************************
4402 // **************************
4403  // KS: Create a map to store the counts of unique strings
4404  std::unordered_map<std::string, int> paramCounts;
4405  std::vector<std::string> orderedKeys;
4406 
4407  for (const std::string& param : ParameterGroup) {
4408  if (paramCounts[param] == 0) {
4409  orderedKeys.push_back(param); // preserve order of first appearance
4410  }
4411  paramCounts[param]++;
4412  }
4413 
4414  MACH3LOG_INFO("************************************************");
4415  MACH3LOG_INFO("Scanning output branches...");
4416  MACH3LOG_INFO("# Useful entries in tree: \033[1;32m {} \033[0m ", nDraw);
4417  MACH3LOG_INFO("# Model params: \033[1;32m {} starting at {} \033[0m ", nParam[kModelPar], ParamTypeStartPos[kModelPar]);
4418  MACH3LOG_INFO("# With following groups: ");
4419  for (const std::string& key : orderedKeys) {
4420  MACH3LOG_INFO(" # {} params: {}", key, paramCounts[key]);
4421  }
4422  MACH3LOG_INFO("# ND params (legacy): \033[1;32m {} starting at {} \033[0m ", nParam[kNDPar], ParamTypeStartPos[kNDPar]);
4423  MACH3LOG_INFO("# FD params (legacy): \033[1;32m {} starting at {} \033[0m ", nParam[kFDDetPar], ParamTypeStartPos[kFDDetPar]);
4424  MACH3LOG_INFO("************************************************");
4425 }
4426 
4427 // **************************
4428 std::vector<double> MCMCProcessor::GetMargins(const std::unique_ptr<TCanvas>& Canv) const {
4429 // **************************
4430  return std::vector<double>{Canv->GetTopMargin(), Canv->GetBottomMargin(),
4431  Canv->GetLeftMargin(), Canv->GetRightMargin()};
4432 }
4433 
4434 // **************************
4435 void MCMCProcessor::SetMargins(std::unique_ptr<TCanvas>& Canv, const std::vector<double>& margins) {
4436 // **************************
4437  if (!Canv) {
4438  MACH3LOG_ERROR("Canv is nullptr");
4439  throw MaCh3Exception(__FILE__, __LINE__);
4440  }
4441  if (margins.size() != 4) {
4442  MACH3LOG_ERROR("Margin vector must have exactly 4 elements");
4443  throw MaCh3Exception(__FILE__, __LINE__);
4444  }
4445  Canv->SetTopMargin(margins[0]);
4446  Canv->SetBottomMargin(margins[1]);
4447  Canv->SetLeftMargin(margins[2]);
4448  Canv->SetRightMargin(margins[3]);
4449 }
4450 
4451 // **************************
4452 void MCMCProcessor::SetTLineStyle(TLine* Line, const Color_t Colour, const Width_t Width, const ELineStyle Style) const {
4453 // **************************
4454  Line->SetLineColor(Colour);
4455  Line->SetLineWidth(Width);
4456  Line->SetLineStyle(Style);
4457 }
4458 
4459 // **************************
4460 void MCMCProcessor::SetLegendStyle(TLegend* Legend, const double size) const {
4461 // **************************
4462  Legend->SetTextSize(size);
4463  Legend->SetLineColor(0);
4464  Legend->SetLineStyle(0);
4465  Legend->SetFillColor(0);
4466  Legend->SetFillStyle(0);
4467  Legend->SetBorderSize(0);
4468 }
4469 
4470 // **************************
4471 bool MCMCProcessor::GetParamFlat(const int iParam) const {
4472 // **************************
4473  ParameterEnum ParType = ParamType[iParam];
4474  int ParamTemp = iParam - ParamTypeStartPos[ParType];
4475  return ParamFlat[ParType][ParamTemp];
4476 }
#define _MaCh3_Safe_Include_Start_
KS: Avoiding warning checking for headers.
Definition: Core.h:126
#define _MaCh3_Safe_Include_End_
bool AllUnique(unsigned int *StepNumber, size_t size)
ParameterEnum
Definition: MCMCProcessor.h:45
@ kNDPar
Definition: MCMCProcessor.h:47
@ kModelPar
Definition: MCMCProcessor.h:46
@ kNParameterEnum
Definition: MCMCProcessor.h:50
@ kFDDetPar
Definition: MCMCProcessor.h:48
#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
bool isFlat(TSpline3_red *&spl)
CW: Helper function used in the constructor, tests to see if the spline is flat.
double GetSubOptimality(const std::vector< double > &EigenValues, const int TotalTarameters)
Based on .
void GetGaussian(TH1D *&hist, TF1 *gauss, double &Mean, double &Error)
CW: Fit Gaussian to posterior.
void GetCredibleIntervalSig(const std::unique_ptr< TH1D > &hist, std::unique_ptr< TH1D > &hpost_copy, const bool CredibleInSigmas, const double coverage)
KS: Get 1D histogram within credible interval, hpost_copy has to have the same binning,...
void GetHPD(TH1D *const hist, double &Mean, double &Error, double &Error_p, double &Error_m, const double coverage)
Get Highest Posterior Density (HPD)
void GetCredibleRegionSig(std::unique_ptr< TH2D > &hist2D, const bool CredibleInSigmas, const double coverage)
KS: Set 2D contour within some coverage.
void GetArithmetic(TH1D *const hist, double &Mean, double &Error)
CW: Get Arithmetic mean from posterior.
std::string GetDunneKaboth(const double BayesFactor)
Convert a Bayes factor into an approximate particle-physics significance level using the Dunne–Kaboth...
_MaCh3_Safe_Include_Start_ _MaCh3_Safe_Include_End_ std::string GetJeffreysScale(const double BayesFactor)
KS: Following H. Jeffreys .
std::unique_ptr< TH1D > GetDeltaChi2(TH1D *posterior_probability_hist)
Convert a posterior probability histogram into a distribution. Using the likelihood-ratio definition...
TMacro YAMLtoTMacro(const YAML::Node &yaml_node, const std::string &name)
Convert a YAML node to a ROOT TMacro object.
Definition: YamlHelper.h:166
YAML::Node TMacroToYAML(const TMacro &macro)
KS: Convert a ROOT TMacro object to a YAML node.
Definition: YamlHelper.h:151
bool CheckNodeExists(const YAML::Node &node, Args... args)
KS: Wrapper function to call the recursive helper.
Definition: YamlHelper.h:59
void ScanParameterOrder()
Scan order of params from a different groups.
int nBatches
Number of batches for Batched Mean.
void CheckStepCut() const
Check if step cut isn't larger than highest values of step in a chain.
void GewekeDiagnostic()
Geweke Diagnostic based on the methods described by Fang (2014) and Karlsbakk (2011)....
TMatrixDSym * Correlation
Posterior Correlation Matrix.
void MakeViolin()
Make and Draw Violin.
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 PrintInfo() const
Print info like how many params have been loaded etc.
void MakeCredibleIntervals(const std::vector< double > &CredibleIntervals={0.99, 0.90, 0.68 }, const std::vector< Color_t > &CredibleIntervalsColours={kCyan+4, kCyan-2, kCyan-10}, const bool CredibleInSigmas=false)
Make and Draw Credible intervals.
void SavePostfit()
CW: Save the postfit members.
void ReadModelFile()
Read the xsec file and get the input central values and errors.
std::vector< double > GetMargins(const std::unique_ptr< TCanvas > &Canv) const
Get TCanvas margins, to be able to reset them if particular function need different margins.
M3::float_t ** ParStep
Array holding values for all parameters.
std::unique_ptr< TF1 > Gauss
Gaussian fitter.
void Initialise()
Scan chain, what parameters we have and load information from covariance matrices.
MCMCProcessor(const std::string &InputFile)
Constructs an MCMCProcessor object with the specified input file and options.
double Post2DPlotThreshold
KS: Set Threshold when to plot 2D posterior as by default we get a LOT of plots.
void AcceptanceProbabilities()
Acceptance Probability.
std::vector< std::string > ReweightNames
Name of branch used for chain reweighting.
double ** SampleValues
Holds the sample values.
void BatchedAnalysis()
Get the batched means variance estimation and variable indicating if number of batches is sensible .
void AutoCorrelation()
KS: Calculate autocorrelations supports both OpenMP and CUDA :)
TVectorD * Means_HPD
Vector with mean values using Highest Posterior Density.
void Prepare2DHistograms()
KS: Allocate histograms for 2D plot.
std::vector< TString > SampleName_v
Vector of each sample PDF object.
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.
std::vector< std::vector< double > > ParamCentral
Parameters central values which we are going to analyse.
std::vector< std::vector< double > > ParamErrors
Uncertainty on a single parameter.
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.
std::string OutputName
Name of output files.
std::unique_ptr< TH2D > hviolin_prior
Holds prior violin plot for all dials,.
bool GetParamFlat(const int iParam) const
Get whether param has flat prior or not.
std::vector< int > nParam
Number of parameters per type.
int GetGroup(const std::string &name) const
Number of params from a given group, for example flux.
ROOT::RDF::RNode GetFilteredDataFrame() const
Build RDataFrame for MCMC Processor.
void DrawPosterior(const int i, TDirectory *PostDir, TDirectory *PostHistDir)
Perform plot of 1d marginalised posterior with HPD etc.
std::vector< std::string > CovNamePos
Covariance matrix name position.
double DrawRange
Drawrange for SetMaximum.
std::vector< std::vector< bool > > ParamFlat
Whether Param has flat prior or not.
std::vector< YAML::Node > CovConfig
Covariance matrix config.
double ** SystValues
Holds the systs values.
virtual ~MCMCProcessor()
Destroys the MCMCProcessor object.
TVectorD * Errors
Vector with errors values using RMS.
double * AccProbBatchedAverages
Holds all accProb in batches.
void MakePostfit(const std::map< std::string, std::pair< double, double >> &Edges={})
Make 1D projection for each parameter and prepare structure.
bool useFFTAutoCorrelation
MJR: Use FFT-based autocorrelation algorithm (save time & resources)?
int GetParamIndexFromName(const std::string &Name) const
Get parameter number based on name.
void MakeCredibleRegions(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, const bool Draw2DPosterior=true, const bool DrawBestFit=true)
Make and Draw Credible Regions.
std::string StepCut
BurnIn Cuts.
std::vector< std::vector< bool > > ParamCircular
Whether param has circualr prior or not, like often delta CP.
void GetPostfit_Ind(TVectorD *&Central, TVectorD *&Errors, TVectorD *&Peaks, ParameterEnum kParam)
Or the individual post-fits.
void DrawCorrelations1D()
Draw 1D correlations which might be more helpful than looking at huge 2D Corr matrix.
void GetPostfit(TVectorD *&Central, TVectorD *&Errors, TVectorD *&Central_Gauss, TVectorD *&Errors_Gauss, TVectorD *&Peaks)
Get the post-fit results (arithmetic and Gaussian)
TVectorD * Means_Gauss
Vector with mean values using Gaussian fit.
unsigned int * StepNumber
Step number for step, important if chains were merged.
int AutoCorrLag
LagL used in AutoCorrelation.
std::unique_ptr< TCanvas > Posterior
Fancy canvas used for our beautiful plots.
TFile * OutputFile
The output file.
void PlotViolins()
Simply plot produced violins.
void ReadNDFile()
Read the ND cov file and get the input central values and errors.
void ProduceChi2(const std::string &GroupName) const
Convert posterior likelihood to Delta Chi2 used for comparison with frequentists fitter.
bool ApplySmoothing
Apply smoothing for 2D histos using root algorithm.
unsigned int UpperCut
KS: Used only for SubOptimality.
int nBins
Number of bins.
TChain * Chain
Main chain storing all steps etc.
std::string MCMCFile
Name of MCMC file.
bool ReweightPosterior
Whether to apply reweighting weight or not.
void SetLegendStyle(TLegend *Legend, const double size) const
Configures the style of a TLegend object.
std::vector< std::string > ExcludedNames
std::unique_ptr< TH1D > MakePrefit()
Prepare prefit histogram for parameter overlay plot.
TVectorD * Errors_HPD_Negative
Vector with negative error (left hand side) values using Highest Posterior Density.
std::vector< std::vector< std::string > > CovPos
Covariance matrix file name position.
void DrawCorrelationsGroup(const std::unique_ptr< TH2D > &CorrMatrix) const
Produces correlation matrix but instead of giving name for each param it only give name for param gro...
void DiagMCMC()
KS: Perform MCMC diagnostic including Autocorrelation, Trace etc.
std::vector< std::string > ExcludedGroups
std::string Posterior1DCut
Cut used when making 1D Posterior distribution.
double * AccProbValues
Holds all accProb.
void FindInputFilesLegacy()
std::vector< double > GetParameterSums()
Computes the average of each parameter across all MCMC entries. Useful for autocorrelation.
void DrawCovariance()
Draw the post-fit covariances.
void SetMargins(std::unique_ptr< TCanvas > &Canv, const std::vector< double > &margins)
Set TCanvas margins to specified values.
void MakeCovariance(const bool Mute=false)
Calculate covariance by making 2D projection of each combination of parameters.
void ParamTraces()
CW: Draw trace plots of the parameters i.e. parameter vs step.
void PrepareDiagMCMC()
CW: Prepare branches etc. for DiagMCMC.
std::unique_ptr< TH2D > hviolin
Holds violin plot for all dials.
int nDraw
Number of all parameters used in the analysis.
std::string OutputSuffix
Output file suffix useful when running over same file with different settings.
void SetupOutput()
Prepare all objects used for output.
void MakeOutputFile()
prepare output root file and canvas to which we will save EVERYTHING
bool plotBinValue
If true it will print value on each bin of covariance matrix.
TVectorD * Errors_Gauss
Vector with error values using Gaussian fit.
void CheckCredibleIntervalsOrder(const std::vector< double > &CredibleIntervals, const std::vector< Color_t > &CredibleIntervalsColours) const
Checks the order and size consistency of the CredibleIntervals and CredibleIntervalsColours vectors.
void CalculateESS(const int nLags, const std::vector< std::vector< double >> &LagL)
KS: calc Effective Sample Size.
std::vector< ParameterEnum > ParamType
Make an enum for which class this parameter belongs to so we don't have to keep string comparing.
std::vector< std::string > NDSamplesNames
virtual void LoadAdditionalInfo()
allow loading additional info for example used for oscillation parameters
TVectorD * Central_Value
Vector with central value for each parameter.
std::vector< std::string > ExcludedTypes
int nSteps
KS: For merged chains number of entries will be different from nSteps.
void CheckCredibleRegionsOrder(const std::vector< double > &CredibleRegions, const std::vector< Style_t > &CredibleRegionStyle, const std::vector< Color_t > &CredibleRegionColor)
Checks the order and size consistency of the CredibleRegions, CredibleRegionStyle,...
std::vector< int > NDSamplesBins
std::vector< std::unique_ptr< TH1D > > hpost
Holds 1D Posterior Distributions.
double ** BatchedAverages
Values of batched average for every param and batch.
void DrawPostfit()
Draw the post-fit comparisons.
TString CanvasName
Name of canvas which help to save to the sample pdf.
std::vector< std::string > ParameterGroup
TVectorD * Errors_HPD
Vector with error values using Highest Posterior Density.
void AutoCorrelation_FFT()
MJR: Autocorrelation function using FFT algorithm for extra speed.
void SetTLineStyle(TLine *Line, const Color_t Colour, const Width_t Width, const ELineStyle Style) const
Configures a TLine object with the specified style parameters.
void ReadInputCovLegacy()
void GetPolarPlot(const std::vector< std::string > &ParNames)
Make funny polar plot.
void WriteCovariance(TDirectory *PostHistDir)
Write covariances to output file.
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.
TVectorD * Means
Vector with mean values using Arithmetic Mean.
std::vector< TString > SystName_v
Vector of each systematic.
std::vector< TString > BranchNames
std::vector< bool > ParamVaried
Is the ith parameter varied.
bool PlotFlatPrior
Whether we plot flat prior or not, we usually provide error even for flat prior params.
bool FancyPlotNames
Whether we want fancy plot names or not.
void SetStepCut(const std::string &Cuts)
Set the step cutting by string.
bool printToPDF
Will plot all plot to PDF not only to root file.
std::vector< std::vector< std::unique_ptr< TH2D > > > hpost2D
Holds 2D Posterior Distributions.
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.
std::pair< double, double > GetHistRange(const int iParam) const
Get Min/Max ranges for single parameter.
std::vector< std::vector< TString > > ParamNames
Name of parameters which we are going to analyse.
bool doDiagMCMC
Doing MCMC Diagnostic.
void ReadFDFile()
Read the FD cov file and get the input central values and errors.
void FindInputFiles()
Read the output MCMC file and find what inputs were used.
std::vector< int > ParamTypeStartPos
bool MadePostfit
Sanity check if Postfit is already done to not make several times.
void DrawCorrelations1DReduced(const std::vector< std::vector< double >> &CorrOfInterest, const std::vector< std::vector< std::string >> &NameCorrOfInterest)
KS: Plot only meaningful correlations.
void PowerSpectrumAnalysis()
RC: Perform spectral analysis of MCMC .
void ScanInput()
Scan Input etc.
void BatchedMeans()
CW: Batched means, literally read from an array and chuck into TH1D.
int nEntries
KS: For merged chains number of entries will be different from nSteps.
void SavageDickeyPlot(std::unique_ptr< TH1D > &PriorHist, std::unique_ptr< TH1D > &PosteriorHist, const std::string &Title, const double EvaluationPoint) const
Produce Savage Dickey plot.
int nBranches
Number of branches in a TTree.
TVectorD * Errors_HPD_Positive
Vector with positive error (right hand side) values using Highest Posterior Density.
TMatrixDSym * Covariance
Posterior Covariance Matrix.
void MakeSubOptimality(const int NIntervals=10)
Make and Draw SubOptimality .
void MakeCovarianceYAML(const std::string &OutputYAMLFile, const std::string &MeansMethod) const
Make YAML file from post-fit covariance.
bool plotRelativeToPrior
Whether we plot relative to prior or nominal, in most cases is prior.
unsigned int BurnInCut
Value of burn in cut.
void SmearChain(const std::vector< std::string > &Names, const std::vector< double > &Error, const bool &SaveBranch) const
Smear chain contours.
void ReadInputCov()
CW: Read the input Covariance matrix entries. Get stuff like parameter input errors,...
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
double Gaus(const double mean=0.0, const double sigma=1.0)
Generate a Gaussian random number.
Definition: Random.h:137
int UniformInt(const int min, const int max)
Generate a uniform random integer in [min, max].
Definition: Random.h:132
constexpr static const double _BAD_DOUBLE_
Default value used for double initialisation.
Definition: Core.h:53
double float_t
Definition: Core.h:37
bool CaseInsentiveMatch(std::string Text, std::string Pattern)
Matches a string against a simple wildcard Pattern using regex. Is not case sensitive.
void MakeCorrelationMatrix(YAML::Node &root, const std::vector< double > &Values, const std::vector< double > &Errors, const std::vector< std::vector< double >> &Correlation, const std::string &OutYAMLName, const std::vector< std::string > &FancyNames={})
KS: Replace correlation matrix and tune values in YAML covariance matrix.
constexpr static const int _BAD_INT_
Default value used for int initialisation.
Definition: Core.h:55
void AddPath(std::string &FilePath)
Prepends the MACH3 environment path to FilePath if it is not already present.
Definition: Monitor.cpp:382
TMacro * GetConfigMacroFromChain(TDirectory *CovarianceFolder)
KS: We store configuration macros inside the chain. In the past, multiple configs were stored,...