6 #include "TVirtualFFT.h"
7 #include "ROOT/RDataFrame.hxx"
16 #pragma GCC diagnostic ignored "-Wfloat-conversion"
20 Chain(nullptr), StepCut(
""), MadePostfit(false) {
95 GPUProcessor = std::make_unique<MCMCProcessorGPU>();
121 for (
int i = 0; i <
nDraw; ++i)
127 for (
int i = 0; i <
nDraw; ++i)
129 for (
int j = 0; j <
nDraw; ++j)
155 void MCMCProcessor::GetPostfit(TVectorD *&Central_PDF, TVectorD *&Errors_PDF, TVectorD *&Central_G, TVectorD *&Errors_G, TVectorD *&Peak_Values) {
176 const int ParamTypeSize = int(
ParamType.size());
178 for (
int i = 0; i < ParamTypeSize; ++i) {
180 (*PDF_Central)(ParamNumber) = (*
Means)(i);
181 (*PDF_Errors)(ParamNumber) = (*
Errors)(i);
182 (*Peak_Values)(ParamNumber) = (*
Means_HPD)(i);
192 Cov =
static_cast<TMatrixDSym*
>(
Covariance->Clone());
193 Corr =
static_cast<TMatrixDSym*
>(
Correlation->Clone());
201 std::string name =
"";
204 name =
"Posterior" + std::to_string(uniform);
205 }
while (gROOT->GetListOfCanvases()->FindObject(name.c_str()) !=
nullptr);
208 Posterior = std::make_unique<TCanvas>(name.c_str(), name.c_str(), 0, 0, 1024, 1024);
210 TCandle::SetScaledViolin(
false);
213 gStyle->SetOptStat(0);
214 gStyle->SetOptTitle(0);
224 gErrorIgnoreLevel = kWarning;
238 double Prior = 1.0, PriorError = 1.0;
244 (*Central_Value)(i) = Prior;
246 double Mean, Err, Err_p, Err_m;
252 (*Means_Gauss)(i) = Mean;
253 (*Errors_Gauss)(i) = Err;
256 (*Means_HPD)(i) = Mean;
257 (*Errors_HPD)(i) = Err;
258 (*Errors_HPD_Positive)(i) = Err_p;
259 (*Errors_HPD_Negative)(i) = Err_m;
263 (*Correlation)(i,i) = 1.0;
269 hpost[i]->SetLineWidth(2);
270 hpost[i]->SetLineColor(kBlue-1);
272 hpost[i]->SetTitle(Title);
273 hpost[i]->GetXaxis()->SetTitle(
hpost[i]->GetTitle());
276 auto Asimov = std::make_unique<TLine>(Prior,
hpost[i]->GetMinimum(), Prior,
hpost[i]->GetMaximum());
279 auto leg = std::make_unique<TLegend>(0.15, 0.6, 0.6, 0.95);
281 leg->AddEntry(
hpost[i], Form(
"#splitline{PDF}{#mu = %.2f, #sigma = %.2f}",
hpost[i]->GetMean(),
hpost[i]->GetRMS()),
"l");
282 leg->AddEntry(
Gauss.get(), Form(
"#splitline{Gauss}{#mu = %.2f, #sigma = %.2f}",
Gauss->GetParameter(1),
Gauss->GetParameter(2)),
"l");
284 if(
isFlat && !
PlotFlatPrior) leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f}", Prior),
"l");
285 else leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
294 MACH3LOG_WARN(
"Found fixed parameter: {} ({}), moving on", Title, i);
297 (*Means_HPD)(i) = Prior;
298 (*Errors_HPD)(i) = PriorError;
299 (*Errors_HPD_Positive)(i) = PriorError;
300 (*Errors_HPD_Negative)(i) = PriorError;
302 (*Means_Gauss)(i) = Prior;
303 (*Errors_Gauss)(i) = PriorError;
306 (*Errors)(i) = PriorError;
314 hpost[i]->Draw(
"hist");
316 Asimov->Draw(
"same");
325 hpost[i]->SetName(Title);
326 hpost[i]->SetTitle(Title);
335 hpost[iParam]->GetXaxis()->GetXmin(),
336 hpost[iParam]->GetXaxis()->GetXmax()
355 int originalErrorLevel = gErrorIgnoreLevel;
356 gErrorIgnoreLevel = kFatal;
359 TDirectory *PostDir =
OutputFile->mkdir(
"Post");
360 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_1d_hists");
363 std::string CutPosterior1D =
"";
366 }
else CutPosterior1D =
StepCut;
371 CutPosterior1D =
"(" + CutPosterior1D +
")*(" + name +
")";
377 for (
int i = 0; i <
nDraw; ++i)
379 if (i % (
nDraw/5) == 0) {
384 double Prior = 1.0, PriorError = 1.0;
389 if (Edges.find(Title.Data()) != Edges.end()) {
390 mini = Edges.at(Title.Data()).first;
391 maxi = Edges.at(Title.Data()).second;
396 MACH3LOG_DEBUG(
"Initialising histogram for {} with binning {:.4f}, {:.4f}", Title, mini, maxi);
401 hpost[i]->SetMinimum(0);
402 hpost[i]->GetYaxis()->SetTitle(
"Steps");
403 hpost[i]->GetYaxis()->SetNoExponent(
false);
412 TTree *SettingsBranch =
new TTree(
"Settings",
"Settings");
421 SettingsBranch->Fill();
422 SettingsBranch->Write();
423 delete SettingsBranch;
425 TDirectory *Names =
OutputFile->mkdir(
"Names");
428 TObjString((*it)).Write();
435 Means->Write(
"PDF_Means");
436 Errors->Write(
"PDF_Error");
446 PostHistDir->Close();
450 MACH3LOG_INFO(
"{} took {:.2f}s to", __func__, clock.RealTime());
453 gErrorIgnoreLevel = originalErrorLevel;
465 prefit->GetXaxis()->SetTitle(
"");
469 std::string CutPosterior1D =
"";
477 std::unique_ptr<TH1D> paramPlot = std::make_unique<TH1D>(
"paramPlot",
"paramPlot",
nDraw, 0,
nDraw);
478 paramPlot->SetDirectory(
nullptr);
479 paramPlot->SetName(
"mach3params");
480 paramPlot->SetTitle(CutPosterior1D.c_str());
481 paramPlot->SetFillStyle(3001);
482 paramPlot->SetFillColor(kBlue-1);
483 paramPlot->SetMarkerColor(paramPlot->GetFillColor());
484 paramPlot->SetMarkerStyle(20);
485 paramPlot->SetLineColor(paramPlot->GetFillColor());
486 paramPlot->SetMarkerSize(prefit->GetMarkerSize());
487 paramPlot->GetXaxis()->SetTitle(
"");
490 std::unique_ptr<TH1D> paramPlot_Gauss =
M3::Clone(paramPlot.get());
491 paramPlot_Gauss->SetMarkerColor(kOrange-5);
492 paramPlot_Gauss->SetMarkerStyle(23);
493 paramPlot_Gauss->SetLineWidth(2);
494 paramPlot_Gauss->SetMarkerSize((prefit->GetMarkerSize())*0.75);
495 paramPlot_Gauss->SetFillColor(paramPlot_Gauss->GetMarkerColor());
496 paramPlot_Gauss->SetFillStyle(3244);
497 paramPlot_Gauss->SetLineColor(paramPlot_Gauss->GetMarkerColor());
498 paramPlot_Gauss->GetXaxis()->SetTitle(
"");
501 std::unique_ptr<TH1D> paramPlot_HPD =
M3::Clone(paramPlot.get());
502 paramPlot_HPD->SetMarkerColor(kBlack);
503 paramPlot_HPD->SetMarkerStyle(25);
504 paramPlot_HPD->SetLineWidth(2);
505 paramPlot_HPD->SetMarkerSize((prefit->GetMarkerSize())*0.5);
506 paramPlot_HPD->SetFillColor(0);
507 paramPlot_HPD->SetFillStyle(0);
508 paramPlot_HPD->SetLineColor(paramPlot_HPD->GetMarkerColor());
509 paramPlot_HPD->GetXaxis()->SetTitle(
"");
512 for (
int i = 0; i <
nDraw; ++i)
520 double CentralValueTemp = 0;
521 double Central, Central_gauss, Central_HPD;
522 double Err, Err_Gauss, Err_HPD;
528 if ( CentralValueTemp != 0)
530 Central = (*Means)(i) / CentralValueTemp;
531 Err = (*Errors)(i) / CentralValueTemp;
533 Central_gauss = (*Means_Gauss)(i) / CentralValueTemp;
534 Err_Gauss = (*Errors_Gauss)(i) / CentralValueTemp;
536 Central_HPD = (*Means_HPD)(i) / CentralValueTemp;
537 Err_HPD = (*Errors_HPD)(i) / CentralValueTemp;
540 Central = 1+(*Means)(i);
543 Central_gauss = 1+(*Means_Gauss)(i);
544 Err_Gauss = (*Errors_Gauss)(i);
546 Central_HPD = 1+(*Means_HPD)(i) ;
547 Err_HPD = (*Errors_HPD)(i);
553 Central = (*Means)(i);
556 Central_gauss = (*Means_Gauss)(i);
557 Err_Gauss = (*Errors_Gauss)(i);
559 Central_HPD = (*Means_HPD)(i) ;
560 Err_HPD = (*Errors_HPD)(i);
563 paramPlot->SetBinContent(i+1, Central);
564 paramPlot->SetBinError(i+1, Err);
566 paramPlot_Gauss->SetBinContent(i+1, Central_gauss);
567 paramPlot_Gauss->SetBinError(i+1, Err_Gauss);
569 paramPlot_HPD->SetBinContent(i+1, Central_HPD);
570 paramPlot_HPD->SetBinError(i+1, Err_HPD);
572 paramPlot->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
573 paramPlot_Gauss->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
574 paramPlot_HPD->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
576 prefit->GetXaxis()->LabelsOption(
"v");
577 paramPlot->GetXaxis()->LabelsOption(
"v");\
578 paramPlot_Gauss->GetXaxis()->LabelsOption(
"v");
579 paramPlot_HPD->GetXaxis()->LabelsOption(
"v");
582 auto CompLeg = std::make_unique<TLegend>(0.33, 0.73, 0.76, 0.95);
583 CompLeg->AddEntry(prefit.get(),
"Prefit",
"fp");
584 CompLeg->AddEntry(paramPlot.get(),
"Postfit PDF",
"fp");
585 CompLeg->AddEntry(paramPlot_Gauss.get(),
"Postfit Gauss",
"fp");
586 CompLeg->AddEntry(paramPlot_HPD.get(),
"Postfit HPD",
"lfep");
587 CompLeg->SetFillColor(0);
588 CompLeg->SetFillStyle(0);
589 CompLeg->SetLineWidth(0);
590 CompLeg->SetLineStyle(0);
591 CompLeg->SetBorderSize(0);
599 prefit->Write(
"param_xsec_prefit");
600 paramPlot->Write(
"param_xsec");
601 paramPlot_Gauss->Write(
"param_xsec_gaus");
602 paramPlot_HPD->Write(
"param_xsec_HPD");
607 else prefit->GetYaxis()->SetTitle(
"Parameter Value");
608 prefit->GetYaxis()->SetRangeUser(-2.5, 2.5);
612 paramPlot->Draw(
"e2, same");
613 paramPlot_Gauss->Draw(
"e2, same");
614 paramPlot_HPD->Draw(
"e1, same");
615 CompLeg->Draw(
"same");
619 constexpr
int IntervalsSize = 20;
620 const int NIntervals =
nDraw/IntervalsSize;
622 for (
int i = 0; i < NIntervals+1; ++i)
624 int RangeMin = i*IntervalsSize;
625 int RangeMax =RangeMin + IntervalsSize;
626 if(i == NIntervals+1) {
627 RangeMin = i*IntervalsSize;
630 if(RangeMin >=
nDraw)
break;
632 double ymin = std::numeric_limits<double>::max();
633 double ymax = -std::numeric_limits<double>::max();
634 for (
int b = RangeMin; b <= RangeMax; ++b) {
637 double val = prefit->GetBinContent(b);
638 double err = prefit->GetBinError(b);
639 ymin = std::min(ymin, val - err);
640 ymax = std::max(ymax, val + err);
644 double val = paramPlot_HPD->GetBinContent(b);
645 double err = paramPlot_HPD->GetBinError(b);
646 ymin = std::min(ymin, val - err);
647 ymax = std::max(ymax, val + err);
651 double margin = 0.1 * (ymax - ymin);
652 prefit->GetYaxis()->SetRangeUser(ymin - margin, ymax + margin);
654 prefit->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
655 paramPlot->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
656 paramPlot_Gauss->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
657 paramPlot_HPD->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
661 paramPlot->Draw(
"e2, same");
662 paramPlot_Gauss->Draw(
"e2, same");
663 paramPlot_HPD->Draw(
"e1, same");
664 CompLeg->Draw(
"same");
672 int NDbinCounter = Start;
679 prefit->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
680 prefit->GetYaxis()->SetRangeUser(0.6, 1.4);
681 prefit->GetXaxis()->SetRangeUser(Start, NDbinCounter);
683 paramPlot->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
684 paramPlot->GetYaxis()->SetRangeUser(0.6, 1.4);
685 paramPlot->GetXaxis()->SetRangeUser(Start, NDbinCounter);
686 paramPlot->SetTitle(CutPosterior1D.c_str());
688 paramPlot_Gauss->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
689 paramPlot_Gauss->GetYaxis()->SetRangeUser(0.6, 1.4);
690 paramPlot_Gauss->GetXaxis()->SetRangeUser(Start, NDbinCounter);
691 paramPlot_Gauss->SetTitle(CutPosterior1D.c_str());
693 paramPlot_HPD->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
694 paramPlot_HPD->GetYaxis()->SetRangeUser(0.6, 1.4);
695 paramPlot_HPD->GetXaxis()->SetRangeUser(Start, NDbinCounter);
696 paramPlot_HPD->SetTitle(CutPosterior1D.c_str());
698 prefit->Write((
"param_"+NDname+
"_prefit").c_str());
699 paramPlot->Write((
"param_"+NDname).c_str());
700 paramPlot_Gauss->Write((
"param_"+NDname+
"_gaus").c_str());
701 paramPlot_HPD->Write((
"param_"+NDname+
"_HPD").c_str());
704 paramPlot->Draw(
"e2, same");
705 paramPlot_Gauss->Draw(
"e1, same");
706 paramPlot_HPD->Draw(
"e1, same");
707 CompLeg->Draw(
"same");
708 Posterior->Write((
"param_"+NDname+
"_canv").c_str());
721 const std::vector<Color_t>& CredibleIntervalsColours,
722 const bool CredibleInSigmas) {
727 const double LeftMargin =
Posterior->GetLeftMargin();
732 const int nCredible = int(CredibleIntervals.size());
733 std::vector<std::unique_ptr<TH1D>> hpost_copy(
nDraw);
734 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(
nDraw);
737 for (
int i = 0; i <
nDraw; ++i)
739 hpost_copy[i] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i", i));
740 hpost_cl[i].resize(nCredible);
741 for (
int j = 0; j < nCredible; ++j)
743 hpost_cl[i][j] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i_CL_%f", i, CredibleIntervals[j]));
746 hpost_cl[i][j]->Reset(
"");
747 hpost_cl[i][j]->Fill(0.0, 0.0);
752 #pragma omp parallel for
754 for (
int i = 0; i <
nDraw; ++i)
757 hpost_copy[i]->Scale(1. / hpost_copy[i]->Integral());
758 for (
int j = 0; j < nCredible; ++j)
761 hpost_cl[i][j]->Scale(1. / hpost_cl[i][j]->Integral());
764 hpost_cl[i][j]->SetFillColor(CredibleIntervalsColours[j]);
765 hpost_cl[i][j]->SetLineWidth(1);
767 hpost_copy[i]->GetYaxis()->SetTitleOffset(1.8);
768 hpost_copy[i]->SetLineWidth(1);
769 hpost_copy[i]->SetMaximum(hpost_copy[i]->GetMaximum()*1.2);
770 hpost_copy[i]->SetLineWidth(2);
771 hpost_copy[i]->SetLineColor(kBlack);
772 hpost_copy[i]->GetYaxis()->SetTitle(
"Posterior Probability");
776 TDirectory *CredibleDir =
OutputFile->mkdir(
"Credible");
778 for (
int i = 0; i <
nDraw; ++i)
784 double Prior = 1.0, PriorError = 1.0;
787 auto Asimov = std::make_unique<TLine>(Prior, hpost_copy[i]->GetMinimum(), Prior, hpost_copy[i]->GetMaximum());
790 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
792 hpost_copy[i]->Draw(
"HIST");
794 for (
int j = 0; j < nCredible; ++j)
795 hpost_cl[i][j]->Draw(
"HIST SAME");
796 for (
int j = nCredible-1; j >= 0; --j)
799 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
801 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f%% Credible Interval", CredibleIntervals[j]*100),
"f");
803 legend->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
804 legend->Draw(
"SAME");
805 Asimov->Draw(
"SAME");
816 CredibleDir->Close();
834 double maxi_y = -9999;
835 double mini_y = +9999;
836 for (
int i = 0; i <
nDraw; ++i)
839 mini_y = std::min(mini_y, range.first);
840 maxi_y = std::max(maxi_y, range.second);
843 const int vBins = (maxi_y-mini_y)*25;
844 hviolin = std::make_unique<TH2D>(
"hviolin",
"hviolin",
nDraw, 0,
nDraw, vBins, mini_y, maxi_y);
845 hviolin->SetDirectory(
nullptr);
847 constexpr
int PriorFactor = 4;
848 hviolin_prior = std::make_unique<TH2D>(
"hviolin_prior",
"hviolin_prior",
nDraw, 0,
nDraw, PriorFactor*vBins, PriorFactor*mini_y, PriorFactor*maxi_y);
851 std::vector<double> PriorVec(
nDraw);
852 std::vector<double> PriorErrorVec(
nDraw);
853 std::vector<bool> PriorFlatVec(
nDraw);
855 for (
int x = 0; x <
nDraw; ++x)
858 double Prior, PriorError;
862 hviolin->GetXaxis()->SetBinLabel(x+1, Title);
865 PriorErrorVec[x] = PriorError;
875 #pragma omp parallel for
877 for (
int x = 0; x <
nDraw; ++x)
896 const double Entry =
M3::rand::Gaus(PriorVec[x], PriorErrorVec[x]);
906 constexpr
int IntervalsSize = 10;
907 const int NIntervals =
nDraw/IntervalsSize;
909 hviolin->GetYaxis()->SetTitle(
"Parameter Value");
910 hviolin->GetXaxis()->SetTitle();
911 hviolin->GetXaxis()->LabelsOption(
"v");
928 hviolin->SetMarkerColor(kBlue);
929 hviolin->SetFillColorAlpha(kBlue, 0.35);
933 const double BottomMargin =
Posterior->GetBottomMargin();
937 hviolin->Write(
"param_violin");
940 hviolin->GetYaxis()->SetRangeUser(-1, +2);
942 for (
int i = 0; i < NIntervals+1; ++i)
944 int RangeMin = i*IntervalsSize;
945 int RangeMax = RangeMin + IntervalsSize;
946 if(i == NIntervals+1) {
947 RangeMin = i*IntervalsSize;
950 if(RangeMin >=
nDraw)
break;
952 hviolin->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
957 hviolin->Draw(
"violinX(03100300) SAME");
961 Posterior->SetBottomMargin(BottomMargin);
974 for (
int i = 0; i <
nDraw; ++i) {
976 MACH3LOG_INFO(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
985 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
987 gStyle->SetPalette(55);
991 ROOT::RDataFrame df(*
Chain);
994 ROOT::RDF::RNode dfToUse = df.Filter(
StepCut);
999 TString WeightExpression =
"1.0";
1001 WeightExpression =
"(" + WeightExpression +
")*(" + name +
")";
1003 dfToUse = dfToUse.Define(
"MCMC_RDF_WEIGHT", WeightExpression.Data());
1006 struct CovarianceHistogram {
1008 TString Title_i, Title_j, DrawMe;
1009 ROOT::RDF::RResultPtr<TH2D> Histogram;
1012 std::vector<CovarianceHistogram> Histograms;
1016 Histograms.reserve(nCov);
1021 for (
int i = 0; i <
nDraw; ++i)
1023 TString Title_i =
"";
1024 double Prior_i, PriorError;
1028 double xmin =
hpost[i]->GetXaxis()->GetXmin();
1029 double xmax =
hpost[i]->GetXaxis()->GetXmax();
1032 for (
int j = 0; j <= i; ++j) {
1034 if (j == i)
continue;
1038 (*Covariance)(i,j) = 0.0;
1040 (*Correlation)(i,j) = 0.0;
1045 TString Title_j =
"";
1046 double Prior_j, PriorError_j;
1050 double ymin =
hpost[j]->GetXaxis()->GetXmin();
1051 double ymax =
hpost[j]->GetXaxis()->GetXmax();
1053 ROOT::RDF::RResultPtr<TH2D> hpost_2D;
1058 hpost_2D = dfToUse.Histo2D({DrawMe.Data(), DrawMe.Data(),
1064 hpost_2D = dfToUse.Histo2D({DrawMe.Data(), DrawMe.Data(),
1068 Histograms.push_back({i, j, Title_i, Title_j, DrawMe, hpost_2D});
1071 MACH3LOG_INFO(
"Finished booking {} histograms. Now executing RDF event loop...", Histograms.size());
1077 if (!Histograms.empty()) {
1078 TH2D *dummy = Histograms[0].Histogram.GetPtr();
1084 MACH3LOG_INFO(
"RDataFrame event loop took {:.2f}s for {} entries",
1086 TStopwatch processingClock;
1087 processingClock.Start();
1089 for (
auto &Entry : Histograms)
1091 const int i = Entry.i;
1092 const int j = Entry.j;
1094 TH2D *hpost_2D = Entry.Histogram.GetPtr();
1095 hpost_2D->SetMinimum(0);
1096 hpost_2D->GetXaxis()->SetTitle(Entry.Title_i);
1097 hpost_2D->GetYaxis()->SetTitle(Entry.Title_j);
1098 hpost_2D->GetZaxis()->SetTitle(
"Steps");
1102 (*Covariance)(i,j) = hpost_2D->GetCovariance();
1104 (*Correlation)(i,j) = hpost_2D->GetCorrelationFactor();
1112 hpost_2D->Draw(
"colz");
1113 Posterior->SetName(hpost_2D->GetName());
1114 Posterior->SetTitle(hpost_2D->GetTitle());
1116 hpost_2D->Write(hpost_2D->GetTitle());
1120 processingClock.Stop();
1122 MACH3LOG_INFO(
"Processing covariance histograms took {:.2f}s", processingClock.RealTime());
1124 PostHistDir->Close();
1142 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC ");
1143 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
1156 for (
int i = 0; i <
nDraw; ++i)
1169 Chain->SetBranchStatus(
"*",
false);
1170 unsigned int stepBranch = 0;
1171 std::vector<double> ParValBranch(
nDraw);
1173 for (
int i = 0; i <
nDraw; ++i)
1178 Chain->SetBranchStatus(
"step",
true);
1179 Chain->SetBranchAddress(
"step", &stepBranch);
1181 std::vector<double> ReweightWeight(
ReweightNames.size(), 1.0);
1191 const Long64_t countwidth =
nEntries/10;
1195 for (Long64_t j = 0; j <
nEntries; ++j)
1197 if (j % countwidth == 0) {
1205 for (
int i = 0; i <
nDraw; ++i) {
1206 ParStep[i][j] = ParValBranch[i];
1210 for (
size_t i = 0; i < ReweightWeight.size(); ++i) {
1216 Chain->SetBranchStatus(
"*",
true);
1219 size_t nHistograms =
nDraw * (
nDraw + 1) / 2;
1221 MACH3LOG_INFO(
"Allocating {:.2f} MB for {} 2D Posteriors (each {}x{} bins)",
1224 for (
int i = 0; i <
nDraw; ++i)
1226 TString Title_i =
"";
1227 double Prior_i, PriorError_i;
1230 for (
int j = 0; j <= i; ++j)
1232 TString Title_j =
"";
1233 double Prior_j, PriorError_j;
1239 hpost2D[i][j] =
new TH2D((Title_i +
"_" + Title_j).Data(), (Title_i +
"_" + Title_j).Data(),
1240 nBins, range_x.first, range_x.second,
1241 nBins, range_y.first, range_y.second);
1243 hpost2D[i][j]->GetXaxis()->SetTitle(Title_i);
1244 hpost2D[i][j]->GetYaxis()->SetTitle(Title_j);
1245 hpost2D[i][j]->GetZaxis()->SetTitle(
"Steps");
1262 for (
int i = 0; i <
nDraw; ++i) {
1264 MACH3LOG_WARN(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
1271 TDirectory *PostHistDir =
nullptr;
1276 PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
1282 gStyle->SetPalette(55);
1285 #pragma omp parallel for
1287 for (
int i = 0; i <
nDraw; ++i)
1289 for (
int j = 0; j <= i; ++j)
1292 if (j == i)
continue;
1296 (*Covariance)(i,j) = 0.0;
1298 (*Correlation)(i,j) = 0.0;
1321 (*Correlation)(i,j) =
hpost2D[i][j]->GetCorrelationFactor();
1332 for (
int i = 0; i <
nDraw; ++i)
1334 for (
int j = 0; j <= i; ++j)
1337 if (j == i)
continue;
1355 PostHistDir->Close();
1369 const int DefaultUpperCut =
UpperCut;
1379 const int IntervalsSize =
nSteps/NIntervals;
1385 std::unique_ptr<TH1D> SubOptimality = std::make_unique<TH1D>(
"Suboptimality",
"Suboptimality", NIntervals, MinStep, MaxStep);
1386 SubOptimality->SetDirectory(
nullptr);
1387 SubOptimality->GetXaxis()->SetTitle(
"Step");
1388 SubOptimality->GetYaxis()->SetTitle(
"Suboptimality");
1389 SubOptimality->SetLineWidth(2);
1390 SubOptimality->SetLineColor(kBlue);
1392 for(
int i = 0; i < NIntervals; ++i)
1404 TVectorD eigen_values;
1405 eigen_values.ResizeTo(eigen.GetEigenValues());
1406 eigen_values = eigen.GetEigenValues();
1409 std::vector<double> EigenValues(eigen_values.GetNrows());
1410 for(
unsigned int j = 0; j < EigenValues.size(); j++)
1412 EigenValues[j] = eigen_values(j);
1415 SubOptimality->SetBinContent(i+1, SubOptimalityValue);
1418 MACH3LOG_INFO(
"Making Suboptimality took {:.2f}s to finish for {} steps", clock.RealTime(),
nEntries);
1424 SubOptimality->Draw(
"l");
1425 Posterior->SetName(SubOptimality->GetName());
1426 Posterior->SetTitle(SubOptimality->GetTitle());
1438 const double RightMargin =
Posterior->GetRightMargin();
1443 hCov->GetZaxis()->SetTitle(
"Covariance");
1444 hCov->SetDirectory(
nullptr);
1447 hCovSq->SetDirectory(
nullptr);
1448 hCovSq->GetZaxis()->SetTitle(
"Covariance");
1451 hCorr->SetDirectory(
nullptr);
1452 hCorr->GetZaxis()->SetTitle(
"Correlation");
1453 hCorr->SetMinimum(-1);
1454 hCorr->SetMaximum(1);
1455 hCov->GetXaxis()->SetLabelSize(0.015);
1456 hCov->GetYaxis()->SetLabelSize(0.015);
1457 hCovSq->GetXaxis()->SetLabelSize(0.015);
1458 hCovSq->GetYaxis()->SetLabelSize(0.015);
1459 hCorr->GetXaxis()->SetLabelSize(0.015);
1460 hCorr->GetYaxis()->SetLabelSize(0.015);
1463 for (
int i = 0; i <
nDraw; ++i)
1465 TString titlex =
"";
1469 hCov->GetXaxis()->SetBinLabel(i+1, titlex);
1470 hCovSq->GetXaxis()->SetBinLabel(i+1, titlex);
1471 hCorr->GetXaxis()->SetBinLabel(i+1, titlex);
1473 for (
int j = 0; j <
nDraw; ++j)
1476 const double cov = (*Covariance)(i,j);
1477 const double corr = (*Correlation)(i,j);
1479 hCov->SetBinContent(i+1, j+1, cov);
1480 hCovSq->SetBinContent(i+1, j+1, ((cov > 0) - (cov < 0))*std::sqrt(std::fabs(cov)));
1481 hCorr->SetBinContent(i+1, j+1, corr);
1483 TString titley =
"";
1484 double nom_j, err_j;
1487 hCov->GetYaxis()->SetBinLabel(j+1, titley);
1488 hCovSq->GetYaxis()->SetBinLabel(j+1, titley);
1489 hCorr->GetYaxis()->SetBinLabel(j+1, titley);
1494 gStyle->SetOptStat(0);
1497 constexpr
int NRGBs = 5;
1498 TColor::InitializeColors();
1499 Double_t stops[NRGBs] = { 0.00, 0.25, 0.50, 0.75, 1.00 };
1500 Double_t red[NRGBs] = { 0.00, 0.25, 1.00, 1.00, 0.50 };
1501 Double_t green[NRGBs] = { 0.00, 0.25, 1.00, 0.25, 0.00 };
1502 Double_t blue[NRGBs] = { 0.50, 1.00, 1.00, 0.25, 0.00 };
1503 TColor::CreateGradientColorTable(5, stops, red, green, blue, 255);
1504 gStyle->SetNumberContours(255);
1512 else hCov->Draw(
"colz");
1518 else hCorr->Draw(
"colz");
1521 hCov->Write(
"Covariance_plot");
1522 hCovSq->Write(
"Covariance_sq_plot");
1523 hCorr->Write(
"Correlation_plot");
1537 MACH3LOG_ERROR(
"Using Legacy Parameters i.e. not one from Parameter Handler Generic, this will not work");
1540 std::vector<double> MeanArray(
nDraw);
1541 std::vector<double> ErrorArray(
nDraw);
1542 std::vector<std::vector<double>> CorrelationMatrix(
nDraw, std::vector<double>(
nDraw, 0.0));
1544 TVectorD* means_vec;
1545 TVectorD* errors_vec;
1547 if (MeansMethod ==
"Arithmetic") {
1550 }
else if (MeansMethod ==
"Gaussian") {
1553 }
else if (MeansMethod ==
"HPD") {
1557 MACH3LOG_ERROR(
"Unknown means method: {}, should be either 'Arithmetic', 'Gaussian', or 'HPD'.", MeansMethod);
1562 for (
int i = 0; i <
nDraw; i++)
1564 MeanArray[i] = (*means_vec)(i);
1565 ErrorArray[i] = (*errors_vec)(i);
1566 for (
int j = 0; j <= i; j++)
1568 CorrelationMatrix[i][j] = (*Correlation)(i,j);
1569 if(i != j) CorrelationMatrix[j][i] = (*Correlation)(i,j);
1588 const double RightMargin =
Posterior->GetRightMargin();
1590 auto MatrixCopy =
M3::Clone(CorrMatrix.get());
1592 std::vector<std::string> GroupName;
1593 std::vector<int> GroupStart;
1594 std::vector<int> GroupEnd;
1597 for (
int iPar = 0; iPar <
nDraw; ++iPar)
1599 std::string GroupNameCurr;
1604 GroupNameCurr =
"Other";
1608 GroupName.push_back(GroupNameCurr);
1609 GroupStart.push_back(0);
1610 }
else if(GroupName.back() != GroupNameCurr ){
1611 GroupName.push_back(GroupNameCurr);
1612 GroupEnd.push_back(iPar);
1613 GroupStart.push_back(iPar);
1616 MatrixCopy->GetXaxis()->SetBinLabel(iPar+1,
"");
1617 MatrixCopy->GetYaxis()->SetBinLabel(iPar+1,
"");
1619 GroupEnd.push_back(
nDraw);
1621 for(
size_t iPar = 0; iPar < GroupName.size(); iPar++) {
1622 MACH3LOG_INFO(
"Group name {} from {} to {}", GroupName[iPar], GroupStart[iPar], GroupEnd[iPar]);
1626 MatrixCopy->Draw(
"colz");
1628 std::vector<std::unique_ptr<TLine>> groupLines;
1630 int nBinsX = MatrixCopy->GetNbinsX();
1631 int nBinsY = MatrixCopy->GetNbinsY();
1634 double xMin = MatrixCopy->GetXaxis()->GetBinLowEdge(1);
1635 double xMax = MatrixCopy->GetXaxis()->GetBinUpEdge(nBinsX);
1636 double yMin = MatrixCopy->GetYaxis()->GetBinLowEdge(1);
1637 double yMax = MatrixCopy->GetYaxis()->GetBinUpEdge(nBinsY);
1639 for (
size_t g = 1; g < GroupStart.size(); ++g) {
1640 const double posX = MatrixCopy->GetXaxis()->GetBinLowEdge(GroupStart[g] + 1);
1641 const double posY = MatrixCopy->GetYaxis()->GetBinLowEdge(GroupStart[g] + 1);
1644 auto vLine = std::make_unique<TLine>(posX, yMin, posX, yMax);
1645 vLine->SetLineColor(kBlack);
1646 vLine->SetLineWidth(2);
1648 groupLines.push_back(std::move(vLine));
1651 auto hLine = std::make_unique<TLine>(xMin, posY, xMax, posY);
1652 hLine->SetLineColor(kBlack);
1653 hLine->SetLineWidth(2);
1655 groupLines.push_back(std::move(hLine));
1658 std::vector<std::unique_ptr<TText>> groupLabels(GroupName.size() * 2);
1659 const double yOffsetBelow = 0.05 * (yMax - yMin);
1660 const double xOffsetRight = 0.02 * (xMax - xMin);
1662 for (
size_t g = 0; g < GroupName.size(); ++g) {
1663 const int startBin = GroupStart[g] + 1;
1664 const int endBin = GroupEnd[g];
1666 const double xStart = MatrixCopy->GetXaxis()->GetBinLowEdge(startBin);
1667 const double xEnd = MatrixCopy->GetXaxis()->GetBinUpEdge(endBin);
1668 const double xMid = 0.5 * (xStart + xEnd);
1670 const double yStart = MatrixCopy->GetYaxis()->GetBinLowEdge(startBin);
1671 const double yEnd = MatrixCopy->GetYaxis()->GetBinUpEdge(endBin);
1672 const double yMid = 0.5 * (yStart + yEnd);
1675 auto labelX = std::make_unique<TText>(xMid, yMin - yOffsetBelow, GroupName[g].c_str());
1676 labelX->SetTextAlign(23);
1677 labelX->SetTextSize(0.025);
1679 groupLabels.push_back(std::move(labelX));
1682 auto labelY = std::make_unique<TText>(xMin - xOffsetRight, yMid, GroupName[g].c_str());
1683 labelY->SetTextAlign(32);
1684 labelY->SetTextSize(0.025);
1686 groupLabels.push_back(std::move(labelY));
1699 const int OptTitle = gStyle->GetOptTitle();
1703 gStyle->SetOptTitle(1);
1705 constexpr
int Nhists = 3;
1707 constexpr
double Thresholds[Nhists+1] = {0, 0.25, 0.5, 1.0001};
1708 constexpr Color_t CorrColours[Nhists] = {kRed-10, kRed-6, kRed};
1711 std::vector<std::vector<double>> CorrOfInterest;
1712 CorrOfInterest.resize(
nDraw);
1713 std::vector<std::vector<std::string>> NameCorrOfInterest;
1714 NameCorrOfInterest.resize(
nDraw);
1716 std::vector<std::vector<std::unique_ptr<TH1D>>> Corr1DHist(
nDraw);
1718 for(
int i = 0; i <
nDraw; ++i)
1721 double Prior = 1.0, PriorError = 1.0;
1724 Corr1DHist[i].resize(Nhists);
1725 for(
int j = 0; j < Nhists; ++j)
1727 Corr1DHist[i][j] = std::make_unique<TH1D>(Form(
"Corr1DHist_%i_%i", i, j), Form(
"Corr1DHist_%i_%i", i, j),
nDraw, 0,
nDraw);
1728 Corr1DHist[i][j]->SetTitle(Form(
"%s",Title.Data()));
1729 Corr1DHist[i][j]->SetDirectory(
nullptr);
1730 Corr1DHist[i][j]->GetYaxis()->SetTitle(
"Correlation");
1731 Corr1DHist[i][j]->SetFillColor(CorrColours[j]);
1732 Corr1DHist[i][j]->SetLineColor(kBlack);
1734 for (
int k = 0; k <
nDraw; ++k)
1736 TString Title_y =
"";
1737 double Prior_y = 1.0;
1738 double PriorError_y = 1.0;
1740 Corr1DHist[i][j]->GetXaxis()->SetBinLabel(k+1, Title_y.Data());
1747 #pragma omp parallel for
1749 for(
int i = 0; i <
nDraw; ++i)
1751 for(
int j = 0; j <
nDraw; ++j)
1753 for(
int k = 0; k < Nhists; ++k)
1755 const double TempEntry = std::fabs((*
Correlation)(i,j));
1756 if(Thresholds[k+1] > TempEntry && TempEntry >= Thresholds[k])
1758 Corr1DHist[i][k]->SetBinContent(j+1, (*
Correlation)(i,j));
1764 NameCorrOfInterest[i].push_back(Corr1DHist[i][0]->GetXaxis()->GetBinLabel(j+1));
1769 TDirectory *CorrDir =
OutputFile->mkdir(
"Corr1D");
1772 for(
int i = 0; i <
nDraw; i++)
1776 Corr1DHist[i][0]->GetXaxis()->LabelsOption(
"v");
1777 Corr1DHist[i][0]->SetMaximum(+1.);
1778 Corr1DHist[i][0]->SetMinimum(-1.);
1779 Corr1DHist[i][0]->Draw();
1780 for(
int k = 1; k < Nhists; k++) {
1781 Corr1DHist[i][k]->Draw(
"SAME");
1784 auto leg = std::make_unique<TLegend>(0.3, 0.75, 0.6, 0.90);
1786 for(
int k = 0; k < Nhists; k++) {
1787 leg->AddEntry(Corr1DHist[i][k].get(), Form(
"%.2f > |Corr| >= %.2f", Thresholds[k+1], Thresholds[k]),
"f");
1791 Posterior->Write(Corr1DHist[i][0]->GetTitle());
1796 for(
int i = 0; i <
nDraw; i++)
1798 const int size = int(CorrOfInterest[i].size());
1800 if(size == 0)
continue;
1801 auto Corr1DHist_Reduced = std::make_unique<TH1D>(
"Corr1DHist_Reduced",
"Corr1DHist_Reduced", size, 0, size);
1802 Corr1DHist_Reduced->SetDirectory(
nullptr);
1803 Corr1DHist_Reduced->SetTitle(Corr1DHist[i][0]->GetTitle());
1804 Corr1DHist_Reduced->GetYaxis()->SetTitle(
"Correlation");
1805 Corr1DHist_Reduced->SetFillColor(kBlue);
1806 Corr1DHist_Reduced->SetLineColor(kBlue);
1808 for (
int j = 0; j < size; ++j)
1810 Corr1DHist_Reduced->GetXaxis()->SetBinLabel(j+1, NameCorrOfInterest[i][j].c_str());
1811 Corr1DHist_Reduced->SetBinContent(j+1, CorrOfInterest[i][j]);
1813 Corr1DHist_Reduced->GetXaxis()->LabelsOption(
"v");
1815 Corr1DHist_Reduced->SetMaximum(+1.);
1816 Corr1DHist_Reduced->SetMinimum(-1.);
1817 Corr1DHist_Reduced->Draw();
1819 Posterior->Write(Form(
"%s_Red", Corr1DHist_Reduced->GetTitle()));
1828 gStyle->SetOptTitle(OptTitle);
1836 if(GroupName ==
"")
return;
1838 TDirectory* Chi2Folder =
OutputFile->mkdir(
"DeltaChi2");
1841 for (
int iPar = 0; iPar <
nDraw; iPar++)
1843 std::string GroupNameCurr;
1848 GroupNameCurr =
"Other";
1851 if (GroupName !=
"All" && GroupNameCurr != GroupName)
continue;
1858 Chi2Folder->Close();
1866 const std::vector<Style_t>& CredibleRegionStyle,
1867 const std::vector<Color_t>& CredibleRegionColor,
1868 const bool CredibleInSigmas,
1869 const bool Draw2DPosterior,
1870 const bool DrawBestFit) {
1876 const int nCredible = int(CredibleRegions.size());
1878 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_copy(
nDraw);
1879 std::vector<std::vector<std::vector<std::unique_ptr<TH2D>>>> hpost_2D_cl(
nDraw);
1881 for (
int i = 0; i <
nDraw; ++i)
1883 hpost_2D_copy[i].resize(
nDraw);
1884 hpost_2D_cl[i].resize(
nDraw);
1885 for (
int j = 0; j <= i; ++j)
1887 hpost_2D_copy[i][j] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i", i, j));
1888 hpost_2D_cl[i][j].resize(nCredible);
1889 for (
int k = 0; k < nCredible; ++k)
1891 hpost_2D_cl[i][j][k] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i_CL_%f", i, j, CredibleRegions[k]));
1897 #pragma omp parallel for
1900 for (
int i = 0; i <
nDraw; ++i)
1902 for (
int j = 0; j <= i; ++j)
1904 for (
int k = 0; k < nCredible; ++k)
1907 hpost_2D_cl[i][j][k]->SetLineColor(CredibleRegionColor[k]);
1908 hpost_2D_cl[i][j][k]->SetLineWidth(2);
1909 hpost_2D_cl[i][j][k]->SetLineStyle(CredibleRegionStyle[k]);
1914 gStyle->SetPalette(51);
1915 for (
int i = 0; i <
nDraw; ++i)
1917 for (
int j = 0; j <= i; ++j)
1920 if (j == i)
continue;
1923 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
1924 legend->SetTextColor(kRed);
1928 auto bestfitM = std::make_unique<TGraph>(1);
1929 const int MaxBin = hpost_2D_copy[i][j]->GetMaximumBin();
1931 hpost_2D_copy[i][j]->GetBinXYZ(MaxBin, Mbx, Mby, Mbz);
1932 const double Mx = hpost_2D_copy[i][j]->GetXaxis()->GetBinCenter(Mbx);
1933 const double My = hpost_2D_copy[i][j]->GetYaxis()->GetBinCenter(Mby);
1935 bestfitM->SetPoint(0, Mx, My);
1936 bestfitM->SetMarkerStyle(22);
1937 bestfitM->SetMarkerSize(1);
1938 bestfitM->SetMarkerColor(kMagenta);
1942 if(Draw2DPosterior){
1943 hpost_2D_copy[i][j]->Draw(
"COLZ");
1945 hpost_2D_copy[i][j]->Draw(
"AXIS");
1949 for (
int k = 0; k < nCredible; ++k)
1950 hpost_2D_cl[i][j][k]->Draw(
"CONT3 SAME");
1951 for (
int k = nCredible-1; k >= 0; --k)
1953 if(CredibleInSigmas)
1954 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f#sigma Credible Interval", CredibleRegions[k]),
"l");
1956 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
1958 legend->Draw(
"SAME");
1961 legend->AddEntry(bestfitM.get(),
"Best Fit",
"p");
1962 bestfitM->Draw(
"SAME.P");
1984 const std::vector<double>& CredibleIntervals,
1985 const std::vector<Color_t>& CredibleIntervalsColours,
1987 const std::vector<double>& CredibleRegions,
1988 const std::vector<Style_t>& CredibleRegionStyle,
1989 const std::vector<Color_t>& CredibleRegionColor,
1991 const bool CredibleInSigmas) {
1995 const int nParamPlot = int(ParNames.size());
1996 std::vector<int> ParamNumber;
1997 std::string ParamInfoNames =
"Making Triangle Plot for { ";
1998 for(
int j = 0; j < nParamPlot; ++j)
2000 ParamInfoNames += fmt::format(
"{} ", ParNames[j]);
2004 MACH3LOG_WARN(
"Couldn't find param {}. Will not plot Triangle plot", ParNames[j]);
2007 ParamNumber.push_back(ParamNo);
2009 ParamInfoNames +=
"}";
2020 auto FormatHistogram = [](
auto& hist) {
2021 hist->GetXaxis()->SetTitle(
"");
2022 hist->GetYaxis()->SetTitle(
"");
2025 hist->GetXaxis()->SetLabelSize(0.1);
2026 hist->GetYaxis()->SetLabelSize(0.1);
2028 hist->GetXaxis()->SetNdivisions(4);
2029 hist->GetYaxis()->SetNdivisions(4);
2037 std::sort(ParamNumber.begin(), ParamNumber.end(), std::greater<int>());
2041 for(
int j = 1; j < nParamPlot+1; j++) Npad += j;
2047 const int nCredibleIntervals = int(CredibleIntervals.size());
2048 const int nCredibleRegions = int(CredibleRegions.size());
2051 std::vector<TPad*> TrianglePad(Npad);
2053 std::vector<std::unique_ptr<TH1D>> hpost_copy(nParamPlot);
2054 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(nParamPlot);
2055 std::vector<std::unique_ptr<TText>> TriangleText(nParamPlot * 2);
2056 std::vector<std::unique_ptr<TH2D>> hpost_2D_copy(Npad-nParamPlot);
2057 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_cl(Npad-nParamPlot);
2058 gStyle->SetPalette(51);
2061 std::vector<double> X_Min(nParamPlot);
2062 std::vector<double> X_Max(nParamPlot);
2080 const double TPm[4] = {.07,.07,.05,.05};
2081 const double Pm[2] = {.2,.1};
2084 const double TPw = 1. - TPm[0] - TPm[2];
2085 const double a_x = ( Pm[0] * TPw ) / ( 1. * nParamPlot + Pm[0] * ( 1. - 1.*nParamPlot ) );
2086 const double b_x = ( TPw - a_x ) / ( 1. * nParamPlot );
2089 X_Max[0] = X_Min[0] + a_x + b_x;
2090 for(
int i = 1; i < nParamPlot; i++)
2092 X_Min[i] = X_Max[i-1];
2093 X_Max[i] = X_Min[i]+b_x;
2096 std::vector<double> Y_Min(nParamPlot);
2097 std::vector<double> Y_Max(nParamPlot);
2100 const double TPh = 1. - TPm[1] - TPm[3];
2101 const double a_y = ( Pm[1] * TPh ) / ( 1. * nParamPlot + Pm[1] * ( 1. - 1.*nParamPlot ) );
2102 const double b_y = ( TPh - a_y ) / ( 1. * nParamPlot );
2104 Y_Min[nParamPlot-1] = TPm[1];
2105 Y_Max[nParamPlot-1] = Y_Min[nParamPlot-1] + a_y + b_y;
2106 for(
int i = nParamPlot-2; i >= 0; i--)
2108 Y_Min[i] = Y_Max[i+1];
2109 Y_Max[i] = Y_Min[i]+b_y;
2113 int counterPad = 0, counterText = 0, counterPost = 0, counter2DPost = 0;
2115 for(
int y = 0; y < nParamPlot; y++)
2118 for(
int x = 0; x <= y; x++)
2122 TrianglePad[counterPad] =
new TPad(Form(
"TPad_%i", counterPad), Form(
"TPad_%i", counterPad), X_Min[x], Y_Min[y], X_Max[x], Y_Max[y]);
2124 TrianglePad[counterPad]->SetTopMargin(0);
2125 TrianglePad[counterPad]->SetRightMargin(0);
2127 TrianglePad[counterPad]->SetGrid();
2128 TrianglePad[counterPad]->SetFrameBorderMode(0);
2129 TrianglePad[counterPad]->SetBorderMode(0);
2130 TrianglePad[counterPad]->SetBorderSize(0);
2133 TrianglePad[counterPad]->SetBottomMargin(y == (nParamPlot - 1) ? Pm[1] : 0);
2135 TrianglePad[counterPad]->SetLeftMargin(x == 0 ? Pm[0] : 0);
2137 TrianglePad[counterPad]->Draw();
2138 TrianglePad[counterPad]->cd();
2143 hpost_copy[counterPost] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i", ParamNumber[x]));
2144 hpost_cl[counterPost].resize(nCredibleIntervals);
2146 hpost_copy[counterPost]->Scale(1. / hpost_copy[counterPost]->Integral());
2147 for (
int j = 0; j < nCredibleIntervals; ++j)
2149 hpost_cl[counterPost][j] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i_CL_%f", ParamNumber[x], CredibleIntervals[j]));
2151 hpost_cl[counterPost][j]->Reset(
"");
2152 hpost_cl[counterPost][j]->Fill(0.0, 0.0);
2155 hpost_cl[counterPost][j]->Scale(1. / hpost_cl[counterPost][j]->Integral());
2156 GetCredibleIntervalSig(hpost_copy[counterPost], hpost_cl[counterPost][j], CredibleInSigmas, CredibleIntervals[j]);
2158 hpost_cl[counterPost][j]->SetFillColor(CredibleIntervalsColours[j]);
2159 hpost_cl[counterPost][j]->SetLineWidth(1);
2162 hpost_copy[counterPost]->SetMaximum(hpost_copy[counterPost]->GetMaximum()*1.2);
2163 hpost_copy[counterPost]->SetLineWidth(2);
2164 hpost_copy[counterPost]->SetLineColor(kBlack);
2167 FormatHistogram(hpost_copy[counterPost]);
2172 hpost_copy[counterPost]->GetXaxis()->SetLabelFont(133);
2173 hpost_copy[counterPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2175 hpost_copy[counterPost]->GetYaxis()->SetLabelFont(133);
2176 hpost_copy[counterPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2178 hpost_copy[counterPost]->Draw(
"HIST");
2179 for (
int j = 0; j < nCredibleIntervals; ++j){
2180 hpost_cl[counterPost][j]->Draw(
"HIST SAME");
2187 hpost_2D_copy[counter2DPost] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2188 Form(
"hpost_copy_%i_%i", ParamNumber[x], ParamNumber[y]));
2189 hpost_2D_cl[counter2DPost].resize(nCredibleRegions);
2191 for (
int k = 0; k < nCredibleRegions; ++k)
2193 hpost_2D_cl[counter2DPost][k] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2194 Form(
"hpost_copy_%i_%i_CL_%f", ParamNumber[x], ParamNumber[y], CredibleRegions[k]));
2197 hpost_2D_cl[counter2DPost][k]->SetLineColor(CredibleRegionColor[k]);
2198 hpost_2D_cl[counter2DPost][k]->SetLineWidth(2);
2199 hpost_2D_cl[counter2DPost][k]->SetLineStyle(CredibleRegionStyle[k]);
2202 FormatHistogram(hpost_2D_copy[counter2DPost]);
2207 hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelFont(133);
2208 hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2210 hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelFont(133);
2211 hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2213 hpost_2D_copy[counter2DPost]->Draw(
"COL");
2215 for (
int k = 0; k < nCredibleRegions; ++k){
2216 hpost_2D_cl[counter2DPost][k]->Draw(
"CONT3 SAME");
2221 if(y == (nParamPlot-1))
2224 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());
2227 TriangleText[counterText]->SetTextAlign(22);
2228 TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2229 TriangleText[counterText]->SetNDC(
true);
2230 TriangleText[counterText]->Draw();
2237 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());
2239 TriangleText[counterText]->SetTextAngle(90);
2242 TriangleText[counterText]->SetTextAlign(22);
2243 TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2244 TriangleText[counterText]->SetNDC(
true);
2245 TriangleText[counterText]->Draw();
2254 auto legend = std::make_unique<TLegend>(0.60, 0.7, 0.9, 0.9);
2257 for (
int j = nCredibleIntervals-1; j >= 0; --j)
2259 if(CredibleInSigmas)
2260 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
2262 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f%% Credible Interval", CredibleRegions[j]*100),
"f");
2264 for (
int k = nCredibleRegions-1; k >= 0; --k)
2266 if(CredibleInSigmas)
2267 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f#sigma Credible Region", CredibleRegions[k]),
"l");
2269 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
2271 legend->Draw(
"SAME");
2284 for(
int i = 0; i < Npad; i++)
delete TrianglePad[i];
2300 Chain =
new TChain(
"posteriors",
"posteriors");
2309 TObjArray* brlis =
Chain->GetListOfBranches();
2321 Chain->SetBranchStatus(
"*",
false);
2328 TBranch* br =
static_cast<TBranch*
>(brlis->At(i));
2333 TString bname = br->GetName();
2336 bool rejected =
false;
2345 if(rejected)
continue;
2348 Chain->SetBranchStatus(bname.Data(),
true);
2350 if (bname.BeginsWith(
"ndd_"))
2356 else if (bname.BeginsWith(
"skd_joint_"))
2364 if (bname.BeginsWith(
"LogL_sample_")) {
2367 else if (bname.BeginsWith(
"LogL_systematic_")) {
2410 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);
2411 Gauss->SetLineWidth(2);
2412 Gauss->SetLineColor(kOrange-5);
2429 #pragma omp parallel for
2431 for (
int i = 0; i <
nDraw; ++i)
2442 for (
int j = 0; j <
nDraw; ++j) {
2456 for(
unsigned int j = 0; j <
ParamType.size(); j++)
2474 auto PreFitPlot = std::make_unique<TH1D>(
"Prefit",
"Prefit",
nDraw, 0,
nDraw);
2475 PreFitPlot->SetDirectory(
nullptr);
2476 for (
int i = 0; i < PreFitPlot->GetNbinsX() + 1; ++i) {
2477 PreFitPlot->SetBinContent(i+1, 0);
2478 PreFitPlot->SetBinError(i+1, 0);
2483 double CentralValueTemp, Central, Error;
2486 for (
int i = 0; i <
nDraw; ++i)
2495 if ( CentralValueTemp != 0) {
2496 Central =
ParamCentral[ParamEnum][ParamNo] / CentralValueTemp;
2497 Error =
ParamErrors[ParamEnum][ParamNo]/CentralValueTemp;
2499 Central = CentralValueTemp + 1.0;
2505 Central = CentralValueTemp;
2512 PreFitPlot->SetBinContent(i+1, Central);
2513 PreFitPlot->SetBinError(i+1, Error);
2514 PreFitPlot->GetXaxis()->SetBinLabel(i+1,
ParamNames[ParamEnum][ParamNo]);
2516 PreFitPlot->SetDirectory(
nullptr);
2518 PreFitPlot->SetFillStyle(1001);
2519 PreFitPlot->SetFillColor(kRed-3);
2520 PreFitPlot->SetMarkerStyle(21);
2521 PreFitPlot->SetMarkerSize(2.4);
2522 PreFitPlot->SetMarkerColor(kWhite);
2523 PreFitPlot->SetLineColor(PreFitPlot->GetFillColor());
2524 PreFitPlot->GetXaxis()->LabelsOption(
"v");
2554 TDirectory* CovarianceFolder = TempFile->Get<TDirectory>(
"CovarianceFolder");
2557 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2559 if (Config ==
nullptr) {
2568 bool InputNotFound =
false;
2570 CovPos[
kXSecPar] = GetFromManager<std::vector<std::string>>(Settings[
"General"][
"Systematics"][
"XsecCovFile"], {
"none"}, __FILE__ , __LINE__);
2574 InputNotFound =
true;
2578 if (XsecConfig ==
nullptr) {
2592 TMacro *
ReweightConfig = TempFile->Get<TMacro>(
"Reweight_Config");
2593 TMacro *
UmbrellaConfig = TempFile->Get<TMacro>(
"Umbrella_Config");
2595 YAML::Node ReweightSettings;
2596 YAML::Node UmbrellaSettings;
2610 if (name ==
"umbrella_weight") {
2626 MACH3LOG_INFO(
"Enabling reweighting with configured weights.");
2638 CovarianceFolder->Close();
2639 delete CovarianceFolder;
2651 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2653 if (Config ==
nullptr) {
2661 CovPos[
kNDPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovFile"],
"none", __FILE__ , __LINE__));
2664 MACH3LOG_WARN(
"Couldn't find NDCov (legacy) branch in output");
2667 CovNamePos[
kNDPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovName"],
"none", __FILE__ , __LINE__);
2672 CovPos[
kFDDetPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovFile"],
"none", __FILE__ , __LINE__));
2675 MACH3LOG_WARN(
"Couldn't find FDCov (legacy) branch in output");
2678 CovNamePos[
kFDDetPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovName"],
"none", __FILE__ , __LINE__);
2698 auto systematics = XSecFile[
"Systematics"];
2700 for (
auto it = systematics.begin(); it != systematics.end(); ++it, ++paramIndex )
2702 auto const ¶m = *it;
2704 std::string ParName = (param[
"Systematic"][
"Names"][
"FancyName"].as<std::string>());
2705 std::string Group = param[
"Systematic"][
"ParameterGroup"].as<std::string>();
2707 bool rejected =
false;
2712 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2721 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2726 if(rejected)
continue;
2729 ParamCentral[
kXSecPar].push_back(param[
"Systematic"][
"ParameterValues"][
"PreFitValue"].as<double>());
2731 ParamFlat[
kXSecPar].push_back(GetFromManager<bool>(param[
"Systematic"][
"FlatPrior"],
false, __FILE__ , __LINE__));
2733 if(
CheckNodeExists(param[
"Systematic"],
"SpecialProposal",
"CircularBounds")) {
2746 BranchNames.push_back(
"param_" + std::to_string(paramIndex));
2751 MACH3LOG_WARN(
"Couldn't find branch '{}', if you are not planning to draw posteriors this might be fine",
BranchNames.back());
2764 TMatrixDSym *NDdetMatrix = NDdetFile->Get<TMatrixDSym>(
CovNamePos[
kNDPar].c_str());
2765 TVectorD *NDdetNominal = NDdetFile->Get<TVectorD>(
"det_weights");
2766 TDirectory *BinningDirectory = NDdetFile->Get<TDirectory>(
"Binning");
2768 for (
int i = 0; i < NDdetNominal->GetNrows(); ++i)
2779 TIter next(BinningDirectory->GetListOfKeys());
2780 TKey *key =
nullptr;
2782 while ((key =
static_cast<TKey*
>(next())))
2784 std::string name = std::string(key->GetName());
2785 TH2Poly* RefPoly = BinningDirectory->Get<TH2Poly>((name).c_str());
2786 int size = RefPoly->GetNumberOfBins();
2805 for (
int i = 0; i < FDdetMatrix->GetNrows(); ++i)
2840 std::stringstream TempStream;
2841 TempStream <<
"step > " << Cuts;
2851 const unsigned int maxNsteps =
Chain->GetMaximum(
"step");
2876 for (
int i = 0; i <
nDraw; ++i)
2879 double Prior = 1.0, PriorError = 1.0;
2896 #pragma omp parallel for
2898 for (
int i = 0; i <
nDraw; ++i)
2900 for (
int j = 0; j <= i; ++j)
2904 hpost2D[i][j]->Fill(0.0, 0.0, 0.0);
2924 TDirectory *PolarDir =
OutputFile->mkdir(
"PolarDir");
2927 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2933 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Polar Plot", ParNames[k]);
2938 double Prior = 1.0, PriorError = 1.0;
2941 std::vector<double> x_val(
nBins);
2942 std::vector<double> y_val(
nBins);
2944 constexpr
double xmin = 0;
2945 constexpr
double xmax = 2*TMath::Pi();
2947 double Integral =
hpost[ParamNo]->Integral();
2948 for (Int_t ipt = 0; ipt <
nBins; ipt++)
2950 x_val[ipt] = ipt*(xmax-xmin)/
nBins+xmin;
2951 y_val[ipt] =
hpost[ParamNo]->GetBinContent(ipt+1)/Integral;
2954 auto PolarGraph = std::make_unique<TGraphPolar>(
nBins, x_val.data(), y_val.data());
2955 PolarGraph->SetLineWidth(2);
2956 PolarGraph->SetFillStyle(3001);
2957 PolarGraph->SetLineColor(kRed);
2958 PolarGraph->SetFillColor(kRed);
2959 PolarGraph->Draw(
"AFL");
2961 auto Text = std::make_unique<TText>(0.6, 0.1, Title);
2962 Text->SetTextSize(0.04);
2981 const std::vector<std::vector<double>>& Model1Bounds,
2982 const std::vector<std::vector<double>>& Model2Bounds,
2983 const std::vector<std::vector<std::string>>& ModelNames){
2988 if((ParNames.size() != Model1Bounds.size()) || (Model2Bounds.size() != Model1Bounds.size()) || (Model2Bounds.size() != ModelNames.size()))
2993 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2999 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Bayes Factor", ParNames[k]);
3003 const double M1_min = Model1Bounds[k][0];
3004 const double M2_min = Model2Bounds[k][0];
3005 const double M1_max = Model1Bounds[k][1];
3006 const double M2_max = Model2Bounds[k][1];
3008 long double IntegralMode1 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M1_min),
hpost[ParamNo]->FindFixBin(M1_max));
3009 long double IntegralMode2 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M2_min),
hpost[ParamNo]->FindFixBin(M2_max));
3011 double BayesFactor = 0.;
3012 std::string Name =
"";
3015 if(IntegralMode1 >= IntegralMode2)
3017 BayesFactor = IntegralMode1/IntegralMode2;
3018 Name =
"\\mathfrak{B}(" + ModelNames[k][0]+
"/" + ModelNames[k][1] +
") = " + std::to_string(BayesFactor);
3022 BayesFactor = IntegralMode2/IntegralMode1;
3023 Name =
"\\mathfrak{B}(" + ModelNames[k][1]+
"/" + ModelNames[k][0] +
") = " + std::to_string(BayesFactor);
3029 MACH3LOG_INFO(
"Following Jeffreys Scale = {}", JeffreysScale);
3030 MACH3LOG_INFO(
"Following Dunne-Kaboth Scale = {}", DunneKabothScale);
3038 const std::vector<double>& EvaluationPoint,
3039 const std::vector<std::vector<double>>& Bounds){
3041 if((ParNames.size() != EvaluationPoint.size()) || (Bounds.size() != EvaluationPoint.size()))
3050 TDirectory *SavageDickeyDir =
OutputFile->mkdir(
"SavageDickey");
3051 SavageDickeyDir->cd();
3053 for(
unsigned int k = 0; k < ParNames.size(); ++k)
3059 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate SavageDickey", ParNames[k]);
3064 double Prior = 1.0, PriorError = 1.0;
3068 auto PosteriorHist = M3::Clone<TH1D>(
hpost[ParamNo], std::string(Title));
3071 std::unique_ptr<TH1D> PriorHist;
3075 int NBins = PosteriorHist->GetNbinsX();
3076 if(Bounds[k][0] > Bounds[k][1])
3081 PriorHist = std::make_unique<TH1D>(
"PriorHist", Title, NBins, Bounds[k][0], Bounds[k][1]);
3082 PriorHist->SetDirectory(
nullptr);
3083 double FlatProb = ( Bounds[k][1] - Bounds[k][0]) / NBins;
3084 for (
int g = 0; g < NBins + 1; ++g)
3086 PriorHist->SetBinContent(g+1, FlatProb);
3091 PriorHist = M3::Clone<TH1D>(PosteriorHist.get(),
"Prior");
3092 PriorHist->Reset(
"");
3093 PriorHist->Fill(0.0, 0.0);
3096 for(
int g = 0; g < 1000000; ++g)
3101 SavageDickeyPlot(PriorHist, PosteriorHist, std::string(Title), EvaluationPoint[k]);
3104 SavageDickeyDir->Close();
3105 delete SavageDickeyDir;
3113 std::unique_ptr<TH1D>& PosteriorHist,
3114 const std::string& Title,
3115 const double EvaluationPoint)
const {
3118 PriorHist->Scale(1./PriorHist->Integral(),
"width");
3119 PosteriorHist->Scale(1./PosteriorHist->Integral(),
"width");
3121 PriorHist->SetLineColor(kRed);
3122 PriorHist->SetMarkerColor(kRed);
3123 PriorHist->SetFillColorAlpha(kRed, 0.35);
3124 PriorHist->SetFillStyle(1001);
3125 PriorHist->GetXaxis()->SetTitle(Title.c_str());
3126 PriorHist->GetYaxis()->SetTitle(
"Posterior Probability");
3127 PriorHist->SetMaximum(PosteriorHist->GetMaximum()*1.5);
3128 PriorHist->GetYaxis()->SetLabelOffset(999);
3129 PriorHist->GetYaxis()->SetLabelSize(0);
3130 PriorHist->SetLineWidth(2);
3131 PriorHist->SetLineStyle(kSolid);
3133 PosteriorHist->SetLineColor(kBlue);
3134 PosteriorHist->SetMarkerColor(kBlue);
3135 PosteriorHist->SetFillColorAlpha(kBlue, 0.35);
3136 PosteriorHist->SetFillStyle(1001);
3138 PriorHist->Draw(
"hist");
3139 PosteriorHist->Draw(
"hist same");
3141 double ProbPrior = PriorHist->GetBinContent(PriorHist->FindBin(EvaluationPoint));
3143 if(ProbPrior < 0) ProbPrior = 0.00001;
3144 double ProbPosterior = PosteriorHist->GetBinContent(PosteriorHist->FindBin(EvaluationPoint));
3145 double SavageDickey = ProbPosterior/ProbPrior;
3149 auto PostPoint = std::make_unique<TGraph>(1);
3150 PostPoint->SetPoint(0, EvaluationPoint, ProbPosterior);
3151 PostPoint->SetMarkerStyle(20);
3152 PostPoint->SetMarkerSize(1);
3153 PostPoint->Draw(
"P same");
3155 auto PriorPoint = std::make_unique<TGraph>(1);
3156 PriorPoint->SetPoint(0, EvaluationPoint, ProbPrior);
3157 PriorPoint->SetMarkerStyle(20);
3158 PriorPoint->SetMarkerSize(1);
3159 PriorPoint->Draw(
"P same");
3161 auto legend = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
3163 legend->AddEntry(PriorHist.get(),
"Prior",
"l");
3164 legend->AddEntry(PosteriorHist.get(),
"Posterior",
"l");
3165 legend->AddEntry(PostPoint.get(), Form(
"SavageDickey = %.2f, (%s)", SavageDickey, DunneKabothScale.c_str()),
"");
3166 legend->Draw(
"same");
3175 const std::vector<double>& Error,
3176 const bool& SaveBranch)
const {
3180 if( (Names.size() != Error.size()))
3182 MACH3LOG_ERROR(
"Size of passed vectors doesn't match in {}", __func__);
3185 std::vector<int> Param;
3188 for(
unsigned int k = 0; k < Names.size(); ++k)
3194 MACH3LOG_WARN(
"Couldn't find param {}. Can't Smear", Names[k]);
3199 double Prior = 1.0, PriorError = 1.0;
3206 MACH3LOG_ERROR(
"Trying to apply smearing for param {}, which has circular prior", Names[k]);
3211 Param.push_back(ParamNo);
3213 std::string InputFile =
MCMCFile+
".root";
3214 std::string OutputFilename =
MCMCFile +
"_smeared.root";
3217 int ret = system((
"cp " + InputFile +
" " + OutputFilename).c_str());
3219 MACH3LOG_WARN(
"Error: system call to copy file failed with code {}", ret);
3221 TFile *OutputChain =
M3::Open(OutputFilename,
"UPDATE", __FILE__, __LINE__);
3223 TTree *post = OutputChain->Get<TTree>(
"posteriors");
3224 TTree *treeNew = post->CloneTree(0);
3226 std::vector<double> NewParameter(Names.size());
3227 for(
size_t i = 0; i < Param.size(); i++) {
3228 post->SetBranchAddress(
BranchNames[Param[i]], &NewParameter[i]);
3231 std::vector<double> Unsmeared_Parameter;
3233 Unsmeared_Parameter.resize(Param.size());
3234 for(
size_t i = 0; i < Param.size(); i++) {
3235 treeNew->Branch((
BranchNames[Param[i]] +
"_unsmeared"), &Unsmeared_Parameter[i]);
3239 Long64_t AllEntries = post->GetEntries();
3240 for (Long64_t i = 0; i < AllEntries; ++i) {
3245 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3246 Unsmeared_Parameter[iPar] = NewParameter[iPar];
3250 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3258 treeNew->Write(
"posteriors", TObject::kOverwrite);
3261 YAML::Node yaml_node;
3262 yaml_node[
"Smearing"].SetStyle(YAML::EmitterStyle::Block);
3264 for (
size_t k = 0; k < Names.size(); ++k) {
3266 entry.SetStyle(YAML::EmitterStyle::Flow);
3268 entry.push_back(Error[k]);
3269 entry.push_back(
"Gauss");
3271 yaml_node[
"Smearing"][Names[k]] = entry;
3273 TMacro ConfigSave =
YAMLtoTMacro(yaml_node,
"Smearing_Config");
3276 OutputChain->Close();
3283 const std::vector<int>& NIntervals) {
3288 for(
unsigned int k = 0; k < Names.size(); ++k)
3294 MACH3LOG_WARN(
"Couldn't find param {}. Can't reweight Prior", Names[k]);
3298 const int IntervalsSize =
nSteps/NIntervals[k];
3300 std::string filename = Names[k] +
".gif";
3301 std::ifstream f(filename);
3304 int ret = system(fmt::format(
"rm {}", filename).c_str());
3306 MACH3LOG_WARN(
"Error: system call to delete {} failed with code {}", filename, ret);
3311 for(
int i = NIntervals[k]-1; i >= 0; --i)
3316 hpost[ParamNo]->GetXaxis()->GetXmin(),
hpost[ParamNo]->GetXaxis()->GetXmax());
3317 EvePlot->SetMinimum(0);
3318 EvePlot->GetYaxis()->SetTitle(
"PDF");
3319 EvePlot->GetYaxis()->SetNoExponent(
false);
3322 std::string CutPosterior1D =
"step > " + std::to_string(i*IntervalsSize+IntervalsSize);
3332 CutPosterior1D =
"(" + CutPosterior1D +
")*(" + name +
")";
3336 std::string TextTitle =
"Steps = 0 - "+std::to_string(Counter*IntervalsSize+IntervalsSize);
3340 EvePlot->SetLineWidth(2);
3341 EvePlot->SetLineColor(kBlue-1);
3342 EvePlot->SetTitle(Names[k].c_str());
3343 EvePlot->GetXaxis()->SetTitle(EvePlot->GetTitle());
3344 EvePlot->GetYaxis()->SetLabelOffset(1000);
3347 EvePlot->Scale(1. / EvePlot->Integral());
3348 EvePlot->Draw(
"HIST");
3350 TText text(0.3, 0.8, TextTitle.c_str());
3351 text.SetTextFont (43);
3352 text.SetTextSize (40);
3356 if(i == 0)
Posterior->Print((Names[k] +
".gif++20").c_str());
3357 else Posterior->Print((Names[k] +
".gif+20").c_str());
3396 std::unordered_set<unsigned int> s(StepNumber, StepNumber + size);
3397 return s.size() == size;
3408 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC");
3409 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
3414 MACH3LOG_ERROR(
"please use SetnBatches to set other value fore example 20");
3420 for (
int j = 0; j <
nDraw; ++j) {
3422 for (
int i = 0; i <
nEntries; ++i) {
3431 for (
int i = 0; i <
nEntries; ++i) {
3438 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3450 Chain->SetBranchStatus(
"*",
false);
3453 const int countwidth =
nEntries/10;
3460 for (
int i = 0; i <
nBatches; ++i) {
3463 for (
int j = 0; j <
nDraw; ++j) {
3467 std::vector<double> ParStepBranch(
nDraw);
3468 std::vector<double> SampleValuesBranch(
SampleName_v.size());
3469 std::vector<double> SystValuesBranch(
SystName_v.size());
3470 unsigned int StepNumberBranch = 0;
3471 double AccProbValuesBranch = 0;
3473 for (
int j = 0; j <
nDraw; ++j) {
3483 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3488 Chain->SetBranchStatus(
"step",
true);
3489 Chain->SetBranchAddress(
"step", &StepNumberBranch);
3491 Chain->SetBranchStatus(
"accProb",
true);
3492 Chain->SetBranchAddress(
"accProb", &AccProbValuesBranch);
3496 for (
int i = 0; i <
nEntries; ++i) {
3500 if (i % countwidth == 0)
3504 for (
int j = 0; j <
nDraw; ++j) {
3505 ParStep[j][i] = ParStepBranch[j];
3512 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3521 int BatchNumber = -1;
3523 for (
int j = 0; j <
nBatches; ++j) {
3524 if (i < (j+1)*BatchLength) {
3530 for (
int j = 0; j <
nDraw; ++j) {
3538 MACH3LOG_INFO(
"Took {:.2f}s to finish caching statistic for Diag MCMC with {} steps", clock.RealTime(),
nEntries);
3541 MACH3LOG_ERROR(
"Found steps with duplicate StepNumber, this indicate merged chain has been passed to DiagMCMC");
3542 MACH3LOG_ERROR(
"Code hasn't been optimised to work with merged chains, results may be unintended");
3547 #pragma omp parallel for
3549 for (
int i = 0; i <
nDraw; ++i) {
3550 for (
int j = 0; j <
nBatches; ++j) {
3568 std::vector<std::unique_ptr<TH1D>> TraceParamPlots(
nDraw);
3569 std::vector<std::unique_ptr<TH1D>> TraceSamplePlots(
SampleName_v.size());
3570 std::vector<std::unique_ptr<TH1D>> TraceSystsPlots(
SystName_v.size());
3573 for (
int j = 0; j <
nDraw; ++j) {
3575 double Prior = 1.0, PriorError = 1.0;
3578 std::string HistName = Form(
"%s_%s_Trace", Title.Data(),
BranchNames[j].Data());
3579 TraceParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3580 TraceParamPlots[j]->SetDirectory(
nullptr);
3581 TraceParamPlots[j]->GetXaxis()->SetTitle(
"Step");
3582 TraceParamPlots[j]->GetYaxis()->SetTitle(
"Parameter Variation");
3587 TraceSamplePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3588 TraceSamplePlots[j]->SetDirectory(
nullptr);
3589 TraceSamplePlots[j]->GetXaxis()->SetTitle(
"Step");
3590 TraceSamplePlots[j]->GetYaxis()->SetTitle(
"Sample -logL");
3593 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3595 TraceSystsPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3596 TraceSystsPlots[j]->SetDirectory(
nullptr);
3597 TraceSystsPlots[j]->GetXaxis()->SetTitle(
"Step");
3598 TraceSystsPlots[j]->GetYaxis()->SetTitle(
"Systematic -logL");
3605 #pragma omp parallel for
3607 for (
int i = 0; i <
nEntries; ++i) {
3609 for (
int j = 0; j <
nDraw; ++j) {
3610 TraceParamPlots[j]->SetBinContent(i,
ParStep[j][i]);
3613 TraceSamplePlots[j]->SetBinContent(i,
SampleValues[i][j]);
3615 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3616 TraceSystsPlots[j]->SetBinContent(i,
SystValues[i][j]);
3621 TDirectory *TraceDir =
OutputFile->mkdir(
"Trace");
3623 for (
int j = 0; j <
nDraw; ++j) {
3625 auto Fitter = std::make_unique<TF1>(
"Fitter",
"[0]",
nEntries/2,
nEntries);
3626 Fitter->SetLineColor(kRed);
3627 TraceParamPlots[j]->Fit(
"Fitter",
"Rq");
3628 TraceParamPlots[j]->Write();
3631 TDirectory *LLDir =
OutputFile->mkdir(
"LogL");
3634 TraceSamplePlots[j]->Write();
3639 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3640 TraceSystsPlots[j]->Write();
3655 std::vector <double> ParamSums(
nDraw,0);
3658 #pragma omp parallel for
3660 for (
int j = 0; j <
nDraw; ++j) {
3661 for (
int i = 0; i <
nEntries; ++i) {
3662 ParamSums[j] +=
ParStep[j][i];
3667 #pragma omp parallel for
3669 for (
int i = 0; i <
nDraw; ++i) {
3685 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3689 TDirectory* AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3690 std::vector<std::unique_ptr<TH1D>> LagKPlots(
nDraw);
3691 std::vector<std::vector<double>> LagL(
nDraw);
3694 std::vector<double> ACFFT(
nEntries, 0.0);
3695 std::vector<double> ParVals(
nEntries, 0.0);
3696 std::vector<double> ParValsFFTR(
nEntries, 0.0);
3697 std::vector<double> ParValsFFTI(
nEntries, 0.0);
3698 std::vector<double> ParValsFFTSquare(
nEntries, 0.0);
3699 std::vector<double> ParValsComplex(
nEntries, 0.0);
3704 TVirtualFFT* fftf = TVirtualFFT::FFT(1, &
nEntries,
"C2CFORWARD");
3705 TVirtualFFT* fftb = TVirtualFFT::FFT(1, &
nEntries,
"C2CBACKWARD");
3708 for (
int j = 0; j <
nDraw; ++j) {
3710 LagL[j].resize(nLags);
3711 for (
int i = 0; i <
nEntries; ++i) {
3712 ParVals[i] =
ParStep[j][i]-ParamSums[j];
3713 ParValsComplex[i] = 0.;
3717 fftf->SetPointsComplex(ParVals.data(), ParValsComplex.data());
3719 fftf->GetPointsComplex(ParValsFFTR.data(), ParValsFFTI.data());
3722 for (
int i = 0; i <
nEntries; ++i) {
3723 ParValsFFTSquare[i] = ParValsFFTR[i]*ParValsFFTR[i] + ParValsFFTI[i]*ParValsFFTI[i];
3727 fftb->SetPointsComplex(ParValsFFTSquare.data(), ParValsComplex.data());
3729 fftb->GetPointsComplex(ACFFT.data(), ParValsComplex.data());
3732 double normAC = ACFFT[0];
3733 for (
int i = 0; i <
nEntries; ++i) {
3739 double Prior = 1.0, PriorError = 1.0;
3741 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3744 LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3745 LagKPlots[j]->SetDirectory(
nullptr);
3746 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3747 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3750 for (
int k = 0; k < nLags; ++k) {
3751 LagL[j][k] = ACFFT[k];
3752 LagKPlots[j]->SetBinContent(k, ACFFT[k]);
3757 LagKPlots[j]->Write();
3763 AutoCorrDir->Close();
3769 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3781 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3784 std::vector<std::vector<double>> DenomSum(
nDraw);
3785 std::vector<std::vector<double>> NumeratorSum(
nDraw);
3786 std::vector<std::vector<double>> LagL(
nDraw);
3788 for (
int j = 0; j <
nDraw; ++j) {
3789 DenomSum[j].resize(nLags);
3790 NumeratorSum[j].resize(nLags);
3791 LagL[j].resize(nLags);
3793 std::vector<std::unique_ptr<TH1D>> LagKPlots(
nDraw);
3795 for (
int j = 0; j <
nDraw; ++j)
3798 for (
int k = 0; k < nLags; ++k) {
3799 NumeratorSum[j][k] = 0.0;
3800 DenomSum[j][k] = 0.0;
3806 double Prior = 1.0, PriorError = 1.0;
3809 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3810 LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3811 LagKPlots[j]->SetDirectory(
nullptr);
3812 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3813 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3821 #pragma omp parallel for collapse(2)
3823 for (
int j = 0; j <
nDraw; ++j) {
3824 for (
int k = 0; k < nLags; ++k) {
3826 for (
int i = 0; i <
nEntries; ++i) {
3827 const double Diff =
ParStep[j][i]-ParamSums[j];
3831 const double LagTerm =
ParStep[j][i+k]-ParamSums[j];
3832 const double Product = Diff*LagTerm;
3833 NumeratorSum[j][k] += Product;
3836 const double Denom = Diff*Diff;
3837 DenomSum[j][k] += Denom;
3844 float* ParStep_cpu =
nullptr;
3845 float* NumeratorSum_cpu =
nullptr;
3846 float* ParamSums_cpu =
nullptr;
3847 float* DenomSum_cpu =
nullptr;
3850 PrepareGPU_AutoCorr(nLags, ParamSums, ParStep_cpu, NumeratorSum_cpu, ParamSums_cpu, DenomSum_cpu);
3853 GPUProcessor->RunGPU_AutoCorr(NumeratorSum_cpu,
3857 #pragma omp parallel for collapse(2)
3860 for (
int j = 0; j <
nDraw; ++j)
3862 for (
int k = 0; k < nLags; ++k)
3864 const int temp_index = j*nLags+k;
3865 NumeratorSum[j][k] = NumeratorSum_cpu[temp_index];
3866 DenomSum[j][k] = DenomSum_cpu[temp_index];
3870 if(NumeratorSum_cpu)
delete[] NumeratorSum_cpu;
3871 if(DenomSum_cpu)
delete[] DenomSum_cpu;
3872 if(ParStep_cpu)
delete[] ParStep_cpu;
3873 if(ParamSums_cpu)
delete[] ParamSums_cpu;
3876 GPUProcessor->CleanupGPU_AutoCorr();
3882 TDirectory *AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3884 for (
int j = 0; j <
nDraw; ++j) {
3885 for (
int k = 0; k < nLags; ++k) {
3886 LagL[j][k] = NumeratorSum[j][k]/DenomSum[j][k];
3887 LagKPlots[j]->SetBinContent(k, NumeratorSum[j][k]/DenomSum[j][k]);
3890 LagKPlots[j]->Write();
3896 AutoCorrDir->Close();
3902 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3908 void MCMCProcessor::PrepareGPU_AutoCorr(
const int nLags,
const std::vector<double>& ParamSums,
float*& ParStep_cpu,
3909 float*& NumeratorSum_cpu,
float*& ParamSums_cpu,
float*& DenomSum_cpu) {
3913 NumeratorSum_cpu =
new float[
nDraw*nLags];
3914 DenomSum_cpu =
new float[
nDraw*nLags];
3915 ParamSums_cpu =
new float[
nDraw];
3919 #pragma omp parallel
3924 #pragma omp for nowait
3926 for (
int i = 0; i <
nDraw; ++i)
3929 ParamSums_cpu[i] = ParamSums[i];
3933 #pragma omp for collapse(2) nowait
3935 for (
int j = 0; j <
nDraw; ++j)
3937 for (
int k = 0; k < nLags; ++k)
3939 const int temp = j*nLags+k;
3940 NumeratorSum_cpu[temp] = 0.0;
3941 DenomSum_cpu[temp] = 0.0;
3946 #pragma omp for collapse(2)
3948 for (
int j = 0; j <
nDraw; ++j)
3953 ParStep_cpu[temp] =
ParStep[j][i];
3962 GPUProcessor->InitGPU_AutoCorr(
nEntries,
3968 GPUProcessor->CopyToGPU_AutoCorr(ParStep_cpu,
3982 if(LagL.size() == 0)
3988 TVectorD* EffectiveSampleSize =
new TVectorD(
nDraw);
3989 TVectorD* SamplingEfficiency =
new TVectorD(
nDraw);
3990 std::vector<double> TempDenominator(
nDraw);
3992 constexpr
int Nhists = 5;
3993 constexpr
double Thresholds[Nhists + 1] = {1, 0.02, 0.005, 0.001, 0.0001, 0.0};
3994 constexpr Color_t ESSColours[Nhists] = {kGreen, kGreen + 2, kYellow, kOrange, kRed};
3997 std::vector<std::unique_ptr<TH1D>> EffectiveSampleSizeHist(Nhists);
3998 for(
int i = 0; i < Nhists; ++i)
4000 EffectiveSampleSizeHist[i] =
4001 std::make_unique<TH1D>(Form(
"EffectiveSampleSizeHist_%i", i), Form(
"EffectiveSampleSizeHist_%i", i),
nDraw, 0,
nDraw);
4002 EffectiveSampleSizeHist[i]->SetDirectory(
nullptr);
4003 EffectiveSampleSizeHist[i]->GetYaxis()->SetTitle(
"N_{eff}/N");
4004 EffectiveSampleSizeHist[i]->SetFillColor(ESSColours[i]);
4005 EffectiveSampleSizeHist[i]->SetLineColor(ESSColours[i]);
4006 EffectiveSampleSizeHist[i]->Sumw2();
4007 for (
int j = 0; j <
nDraw; ++j)
4010 double Prior = 1.0, PriorError = 1.0;
4012 EffectiveSampleSizeHist[i]->GetXaxis()->SetBinLabel(j+1, Title.Data());
4017 #pragma omp parallel for
4020 for (
int j = 0; j <
nDraw; ++j)
4024 TempDenominator[j] = 0.;
4026 for (
int k = 0; k < nLags; ++k)
4028 TempDenominator[j] += LagL[j][k];
4030 TempDenominator[j] = 1+2*TempDenominator[j];
4031 (*EffectiveSampleSize)(j) =
double(
nEntries)/TempDenominator[j];
4033 (*SamplingEfficiency)(j) = 100 * 1/TempDenominator[j];
4035 for(
int i = 0; i < Nhists; ++i)
4037 EffectiveSampleSizeHist[i]->SetBinContent(j+1, 0);
4038 EffectiveSampleSizeHist[i]->SetBinError(j+1, 0);
4040 const double TempEntry = std::fabs((*EffectiveSampleSize)(j)) / double(
nEntries);
4041 if(Thresholds[i] >= TempEntry && TempEntry > Thresholds[i+1])
4043 if( std::isnan((*EffectiveSampleSize)(j)) )
continue;
4044 EffectiveSampleSizeHist[i]->SetBinContent(j+1, TempEntry);
4052 EffectiveSampleSize->Write(
"EffectiveSampleSize");
4053 SamplingEfficiency->Write(
"SamplingEfficiency");
4055 EffectiveSampleSizeHist[0]->SetTitle(
"Effective Sample Size");
4056 EffectiveSampleSizeHist[0]->Draw();
4057 for(
int i = 1; i < Nhists; ++i)
4059 EffectiveSampleSizeHist[i]->Draw(
"SAME");
4062 auto leg = std::make_unique<TLegend>(0.2, 0.7, 0.6, 0.95);
4064 for(
int i = 0; i < Nhists; ++i)
4066 leg->AddEntry(EffectiveSampleSizeHist[i].get(), Form(
"%.4f >= N_{eff}/N > %.4f", Thresholds[i], Thresholds[i+1]),
"f");
4067 } leg->Draw(
"SAME");
4069 Posterior->Write(
"EffectiveSampleSizeCanvas");
4072 delete EffectiveSampleSize;
4073 delete SamplingEfficiency;
4083 std::vector<std::unique_ptr<TH1D>> BatchedParamPlots(
nDraw);
4084 for (
int j = 0; j <
nDraw; ++j) {
4086 double Prior = 1.0, PriorError = 1.0;
4090 std::string HistName = Form(
"%s_%s_batch", Title.Data(),
BranchNames[j].Data());
4091 BatchedParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nBatches, 0,
nBatches);
4092 BatchedParamPlots[j]->SetDirectory(
nullptr);
4096 #pragma omp parallel for
4098 for (
int j = 0; j <
nDraw; ++j) {
4099 for (
int i = 0; i <
nBatches; ++i) {
4103 std::stringstream ss;
4104 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4105 BatchedParamPlots[j]->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4109 TDirectory *BatchDir =
OutputFile->mkdir(
"Batched_means");
4111 for (
int j = 0; j <
nDraw; ++j) {
4112 auto Fitter = std::make_unique<TF1>(
"Fitter",
"[0]", 0,
nBatches);
4113 Fitter->SetLineColor(kRed);
4114 BatchedParamPlots[j]->Fit(
"Fitter",
"Rq");
4115 BatchedParamPlots[j]->Write();
4122 for (
int i = 0; i <
nBatches; ++i) {
4139 MACH3LOG_ERROR(
"BatchedAverages haven't been initialises or have been deleted something is wrong");
4145 TVectorD* BatchedVariance =
new TVectorD(
nDraw);
4147 TVectorD* C_Test_Statistics =
new TVectorD(
nDraw);
4149 std::vector<double> OverallBatchMean(
nDraw);
4150 std::vector<double> C_Rho_Nominator(
nDraw);
4151 std::vector<double> C_Rho_Denominator(
nDraw);
4152 std::vector<double> C_Nominator(
nDraw);
4153 std::vector<double> C_Denominator(
nDraw);
4157 #pragma omp parallel
4164 for (
int j = 0; j <
nDraw; ++j)
4166 OverallBatchMean[j] = 0.0;
4167 C_Rho_Nominator[j] = 0.0;
4168 C_Rho_Denominator[j] = 0.0;
4169 C_Nominator[j] = 0.0;
4170 C_Denominator[j] = 0.0;
4172 (*BatchedVariance)(j) = 0.0;
4173 (*C_Test_Statistics)(j) = 0.0;
4182 #pragma omp for nowait
4185 for (
int j = 0; j <
nDraw; ++j)
4191 (*BatchedVariance)(j) = (BatchLength/(
nBatches-1))* (*BatchedVariance)(j);
4196 #pragma omp for nowait
4198 for (
int j = 0; j <
nDraw; ++j)
4206 C_Denominator[j] = 2*C_Denominator[j];
4213 for (
int j = 0; j <
nDraw; ++j)
4215 for (
int i = 0; i <
nBatches-1; ++i)
4230 for (
int j = 0; j <
nDraw; ++j)
4232 (*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]);
4240 BatchedVariance->Write(
"BatchedMeansVariance");
4241 C_Test_Statistics->Write(
"C_Test_Statistics");
4244 delete BatchedVariance;
4245 delete C_Test_Statistics;
4256 const double TopMargin =
Posterior->GetTopMargin();
4257 const int OptTitle = gStyle->GetOptTitle();
4260 gStyle->SetOptTitle(1);
4265 const int N_Coeffs = std::min(10000,
nEntries);
4266 const int start = -(N_Coeffs/2-1);
4267 const int end = N_Coeffs/2-1;
4268 const int v_size = end - start;
4274 std::vector<std::vector<float>> k_j(nPrams, std::vector<float>(v_size, 0.0));
4275 std::vector<std::vector<float>> P_j(nPrams, std::vector<float>(v_size, 0.0));
4278 if (_N % 2 != 0) _N -= 1;
4281 const double two_pi_over_N = 2 * TMath::Pi() /
static_cast<double>(_N);
4285 #pragma omp parallel for collapse(2)
4288 for (
int j = 0; j < nPrams; ++j)
4290 for (
int jj = start; jj < end; ++jj)
4292 std::complex<M3::float_t> a_j = 0.0;
4293 const double two_pi_over_N_jj = two_pi_over_N * jj;
4294 for (
int n = 0; n < _N; ++n)
4297 std::complex<M3::float_t> exp_temp(0, two_pi_over_N_jj * n);
4298 a_j +=
ParStep[j][n] * std::exp(exp_temp);
4300 a_j /= std::sqrt(
float(_N));
4301 const int _c = jj - start;
4303 k_j[j][_c] = two_pi_over_N_jj;
4305 P_j[j][_c] = std::norm(a_j);
4309 TDirectory *PowerDir =
OutputFile->mkdir(
"PowerSpectrum");
4312 TVectorD* PowerSpectrumStepSize =
new TVectorD(nPrams);
4313 for (
int j = 0; j < nPrams; ++j)
4315 auto plot = std::make_unique<TGraph>(v_size, k_j[j].data(), P_j[j].data());
4318 double Prior = 1.0, PriorError = 1.0;
4321 std::string name = Form(
"Power Spectrum of %s;k;P(k)", Title.Data());
4323 plot->SetTitle(name.c_str());
4324 name = Form(
"%s_power_spectrum", Title.Data());
4325 plot->SetName(name.c_str());
4326 plot->SetMarkerStyle(7);
4329 auto func = std::make_unique<TF1>(
"power_template",
"[0]*( ([1] / x)^[2] / (([1] / x)^[2] +1) )", 0.0, 1.0);
4331 func->SetParameter(0, 10.0);
4333 func->SetParameter(1, 0.1);
4335 func->SetParameter(2, 2.0);
4338 func->SetParLimits(0, 0.0, 100.0);
4339 func->SetParLimits(1, 0.001, 1.0);
4340 func->SetParLimits(2, 0.0, 5.0);
4342 plot->Fit(
"power_template",
"Rq");
4351 (*PowerSpectrumStepSize)(j) = std::sqrt(func->GetParameter(0)/float(v_size*0.5));
4354 PowerSpectrumStepSize->Write(
"PowerSpectrumStepSize");
4355 delete PowerSpectrumStepSize;
4360 MACH3LOG_INFO(
"Making Power Spectrum took {:.2f}s", clock.RealTime());
4363 gStyle->SetOptTitle(OptTitle);
4374 std::vector<double> MeanUp(
nDraw, 0.0);
4375 std::vector<double> SpectralVarianceUp(
nDraw, 0.0);
4376 std::vector<int> DenomCounterUp(
nDraw, 0);
4377 const double Threshold = 0.5 *
nSteps;
4380 constexpr
double LowerThreshold = 0;
4381 constexpr
double UpperThreshold = 1.0;
4383 constexpr
int NChecks = 100;
4384 constexpr
double Division = (UpperThreshold - LowerThreshold)/NChecks;
4386 std::vector<std::unique_ptr<TH1D>> GewekePlots(
nDraw);
4387 for (
int j = 0; j <
nDraw; ++j)
4390 double Prior = 1.0, PriorError = 1.0;
4392 std::string HistName = Form(
"%s_%s_Geweke", Title.Data(),
BranchNames[j].Data());
4393 GewekePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), NChecks, 0.0, 100 * UpperThreshold);
4394 GewekePlots[j]->SetDirectory(
nullptr);
4395 GewekePlots[j]->GetXaxis()->SetTitle(
"Burn-In (%)");
4396 GewekePlots[j]->GetYaxis()->SetTitle(
"Geweke T score");
4401 #pragma omp parallel
4408 for (
int j = 0; j <
nDraw; ++j)
4415 DenomCounterUp[j]++;
4418 MeanUp[j] = MeanUp[j]/DenomCounterUp[j];
4423 #pragma omp for collapse(2)
4425 for (
int j = 0; j <
nDraw; ++j)
4431 SpectralVarianceUp[j] += (
ParStep[j][i] - MeanUp[j])*(
ParStep[j][i] - MeanUp[j]);
4440 for (
int k = 1; k < NChecks+1; ++k)
4443 std::vector<double> MeanDown(
nDraw, 0.0);
4444 std::vector<double> SpectralVarianceDown(
nDraw, 0.0);
4445 std::vector<int> DenomCounterDown(
nDraw, 0);
4447 const unsigned int ThresholsCheck = Division*k*
nSteps;
4449 for (
int j = 0; j <
nDraw; ++j)
4456 DenomCounterDown[j]++;
4459 MeanDown[j] = MeanDown[j]/DenomCounterDown[j];
4462 for (
int j = 0; j <
nDraw; ++j)
4468 SpectralVarianceDown[j] += (
ParStep[j][i] - MeanDown[j])*(
ParStep[j][i] - MeanDown[j]);
4473 for (
int j = 0; j <
nDraw; ++j)
4475 double T_score = std::fabs((MeanDown[j] - MeanUp[j])/std::sqrt(SpectralVarianceDown[j]/DenomCounterDown[j] + SpectralVarianceUp[j]/DenomCounterUp[j]));
4476 GewekePlots[j]->SetBinContent(k, T_score);
4485 TDirectory *GewekeDir =
OutputFile->mkdir(
"Geweke");
4486 for (
int j = 0; j <
nDraw; ++j)
4489 GewekePlots[j]->Write();
4491 for (
int i = 0; i <
nDraw; ++i) {
4510 auto AcceptanceProbPlot = std::make_unique<TH1D>(
"AcceptanceProbability",
"Acceptance Probability",
nEntries, 0,
nEntries);
4511 AcceptanceProbPlot->SetDirectory(
nullptr);
4512 AcceptanceProbPlot->GetXaxis()->SetTitle(
"Step");
4513 AcceptanceProbPlot->GetYaxis()->SetTitle(
"Acceptance Probability");
4515 auto BatchedAcceptanceProblot = std::make_unique<TH1D>(
"AcceptanceProbability_Batch",
"AcceptanceProbability_Batch",
nBatches, 0,
nBatches);
4516 BatchedAcceptanceProblot->SetDirectory(
nullptr);
4517 BatchedAcceptanceProblot->GetYaxis()->SetTitle(
"Acceptance Probability");
4519 for (
int i = 0; i <
nBatches; ++i) {
4523 std::stringstream ss;
4524 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4525 BatchedAcceptanceProblot->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4529 #pragma omp parallel for
4531 for (
int i = 0; i <
nEntries; ++i) {
4536 TDirectory *probDir =
OutputFile->mkdir(
"AccProb");
4539 AcceptanceProbPlot->Write();
4540 BatchedAcceptanceProblot->Write();
4553 if (CredibleIntervals.size() != CredibleIntervalsColours.size()) {
4554 MACH3LOG_ERROR(
"size of CredibleIntervals is not equal to size of CredibleIntervalsColours");
4557 if (CredibleIntervals.size() > 1) {
4558 for (
unsigned int i = 1; i < CredibleIntervals.size(); i++) {
4559 if (CredibleIntervals[i] > CredibleIntervals[i - 1]) {
4561 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleIntervals[i], CredibleIntervals[i - 1]);
4571 const std::vector<Style_t>& CredibleRegionStyle,
4572 const std::vector<Color_t>& CredibleRegionColor) {
4574 if ((CredibleRegions.size() != CredibleRegionStyle.size()) || (CredibleRegionStyle.size() != CredibleRegionColor.size())) {
4575 MACH3LOG_ERROR(
"size of CredibleRegions is not equal to size of CredibleRegionStyle or CredibleRegionColor");
4578 for (
unsigned int i = 1; i < CredibleRegions.size(); i++) {
4579 if (CredibleRegions[i] > CredibleRegions[i - 1]) {
4581 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleRegions[i], CredibleRegions[i - 1]);
4592 auto caseInsensitiveCompare = [](
const std::string& a,
const std::string& b) {
4593 return std::equal(a.begin(), a.end(), b.begin(), b.end(),
4594 [](
char c1,
char c2) { return std::tolower(c1) == std::tolower(c2); });
4598 if (caseInsensitiveCompare(groupName, name)) {
4609 std::unordered_map<std::string, int> paramCounts;
4610 std::vector<std::string> orderedKeys;
4613 if (paramCounts[param] == 0) {
4614 orderedKeys.push_back(param);
4616 paramCounts[param]++;
4619 MACH3LOG_INFO(
"************************************************");
4624 for (
const std::string& key : orderedKeys) {
4629 MACH3LOG_INFO(
"************************************************");
4635 return std::vector<double>{Canv->GetTopMargin(), Canv->GetBottomMargin(),
4636 Canv->GetLeftMargin(), Canv->GetRightMargin()};
4646 if (margins.size() != 4) {
4650 Canv->SetTopMargin(margins[0]);
4651 Canv->SetBottomMargin(margins[1]);
4652 Canv->SetLeftMargin(margins[2]);
4653 Canv->SetRightMargin(margins[3]);
4659 Line->SetLineColor(Colour);
4660 Line->SetLineWidth(Width);
4661 Line->SetLineStyle(
Style);
4667 Legend->SetTextSize(size);
4668 Legend->SetLineColor(0);
4669 Legend->SetLineStyle(0);
4670 Legend->SetFillColor(0);
4671 Legend->SetFillStyle(0);
4672 Legend->SetBorderSize(0);
#define _MaCh3_Safe_Include_Start_
KS: Avoiding warning checking for headers.
#define _MaCh3_Safe_Include_End_
int NDParametersStartingPos
void RemoveFitter(TH1D *hist, const std::string &name)
KS: Remove fitted TF1 from hist to make comparison easier.
bool AllUnique(unsigned int *StepNumber, size_t size)
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
constexpr ELineStyle Style[NVars]
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.
YAML::Node TMacroToYAML(const TMacro ¯o)
KS: Convert a ROOT TMacro object to a YAML node.
bool CheckNodeExists(const YAML::Node &node, Args... args)
KS: Wrapper function to call the recursive helper.
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 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.
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.
double * WeightValue
Stores value of weight for each step.
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.
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 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.
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.
std::vector< TH1D * > hpost
Holds 1D Posterior Distributions.
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 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
void MakeCovariance_MP(const bool Mute=false)
Calculate covariance by making 2D projection of each combination of parameters using multithreading.
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.
std::vector< std::vector< TH2D * > > hpost2D
Holds 2D Posterior Distributions.
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.
void CacheSteps()
KS:By caching each step we use multithreading.
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.
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.
bool CacheMCMC
MCMC Chain has been cached.
std::vector< int > ParamTypeStartPos
bool MadePostfit
Sanity check if Postfit is already done to not make several times.
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.
void MakeCovariance()
Calculate covariance by making 2D projection of each combination of parameters.
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 EstimateDataTransferRate(TChain *chain, const Long64_t entry)
KS: Check what CPU you are using.
void PrintConfig(const YAML::Node &node)
KS: Print Yaml config using logger.
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
void MaCh3Welcome()
KS: Prints welcome message with MaCh3 logo.
double Gaus(const double mean=0.0, const double sigma=1.0)
Generate a Gaussian random number.
int UniformInt(const int min, const int max)
Generate a uniform random integer in [min, max].
std::unique_ptr< ObjectType > Clone(const ObjectType *obj, const std::string &name="")
KS: Creates a copy of a ROOT-like object and wraps it in a smart pointer.
constexpr static const double _BAD_DOUBLE_
Default value used for double initialisation.
bool CaseInsentiveMatch(std::string Text, std::string Pattern)
Matches a string against a simple wildcard Pattern using regex. Is not case sensitive.
TFile * Open(const std::string &Name, const std::string &Type, const std::string &File, const int Line)
Opens a ROOT file with the given name and mode.
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.
void AddPath(std::string &FilePath)
Prepends the MACH3 environment path to FilePath if it is not already present.
TMacro * GetConfigMacroFromChain(TDirectory *CovarianceFolder)
KS: We store configuration macros inside the chain. In the past, multiple configs were stored,...
Structure to hold reweight configuration.