6 #include "TVirtualFFT.h"
7 #include "ROOT/RDataFrame.hxx"
16 #pragma GCC diagnostic ignored "-Wfloat-conversion"
20 Chain(nullptr), StepCut(
""), MadePostfit(false) {
94 GPUProcessor = std::make_unique<MCMCProcessorGPU>();
120 for (
int i = 0; i <
nDraw; ++i)
126 for (
int i = 0; i <
nDraw; ++i)
128 for (
int j = 0; j <
nDraw; ++j)
154 void MCMCProcessor::GetPostfit(TVectorD *&Central_PDF, TVectorD *&Errors_PDF, TVectorD *&Central_G, TVectorD *&Errors_G, TVectorD *&Peak_Values) {
175 const int ParamTypeSize = int(
ParamType.size());
177 for (
int i = 0; i < ParamTypeSize; ++i) {
179 (*PDF_Central)(ParamNumber) = (*
Means)(i);
180 (*PDF_Errors)(ParamNumber) = (*
Errors)(i);
181 (*Peak_Values)(ParamNumber) = (*
Means_HPD)(i);
191 Cov =
static_cast<TMatrixDSym*
>(
Covariance->Clone());
192 Corr =
static_cast<TMatrixDSym*
>(
Correlation->Clone());
199 auto rand = std::make_unique<TRandom3>(0);
200 const int uniform = int(rand->Uniform(0, 10000));
202 Posterior = std::make_unique<TCanvas>((
"Posterior" + std::to_string(uniform)).c_str(), (
"Posterior" + std::to_string(uniform)).c_str(), 0, 0, 1024, 1024);
204 TCandle::SetScaledViolin(
false);
207 gStyle->SetOptStat(0);
208 gStyle->SetOptTitle(0);
218 gErrorIgnoreLevel = kWarning;
232 double Prior = 1.0, PriorError = 1.0;
238 (*Central_Value)(i) = Prior;
240 double Mean, Err, Err_p, Err_m;
246 (*Means_Gauss)(i) = Mean;
247 (*Errors_Gauss)(i) = Err;
250 (*Means_HPD)(i) = Mean;
251 (*Errors_HPD)(i) = Err;
252 (*Errors_HPD_Positive)(i) = Err_p;
253 (*Errors_HPD_Negative)(i) = Err_m;
257 (*Correlation)(i,i) = 1.0;
263 hpost[i]->SetLineWidth(2);
264 hpost[i]->SetLineColor(kBlue-1);
266 hpost[i]->SetTitle(Title);
267 hpost[i]->GetXaxis()->SetTitle(
hpost[i]->GetTitle());
270 auto Asimov = std::make_unique<TLine>(Prior,
hpost[i]->GetMinimum(), Prior,
hpost[i]->GetMaximum());
273 auto leg = std::make_unique<TLegend>(0.15, 0.6, 0.6, 0.95);
275 leg->AddEntry(
hpost[i], Form(
"#splitline{PDF}{#mu = %.2f, #sigma = %.2f}",
hpost[i]->GetMean(),
hpost[i]->GetRMS()),
"l");
276 leg->AddEntry(
Gauss.get(), Form(
"#splitline{Gauss}{#mu = %.2f, #sigma = %.2f}",
Gauss->GetParameter(1),
Gauss->GetParameter(2)),
"l");
278 if(
isFlat && !
PlotFlatPrior) leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f}", Prior),
"l");
279 else leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
288 MACH3LOG_WARN(
"Found fixed parameter: {} ({}), moving on", Title, i);
291 (*Means_HPD)(i) = Prior;
292 (*Errors_HPD)(i) = PriorError;
293 (*Errors_HPD_Positive)(i) = PriorError;
294 (*Errors_HPD_Negative)(i) = PriorError;
296 (*Means_Gauss)(i) = Prior;
297 (*Errors_Gauss)(i) = PriorError;
300 (*Errors)(i) = PriorError;
310 Asimov->Draw(
"same");
319 hpost[i]->SetName(Title);
320 hpost[i]->SetTitle(Title);
329 hpost[iParam]->GetXaxis()->GetXmin(),
330 hpost[iParam]->GetXaxis()->GetXmax()
349 int originalErrorLevel = gErrorIgnoreLevel;
350 gErrorIgnoreLevel = kFatal;
353 TDirectory *PostDir =
OutputFile->mkdir(
"Post");
354 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_1d_hists");
357 std::string CutPosterior1D =
"";
360 }
else CutPosterior1D =
StepCut;
365 CutPosterior1D =
"(" + CutPosterior1D +
")*(" + name +
")";
371 for (
int i = 0; i <
nDraw; ++i)
373 if (i % (
nDraw/5) == 0) {
378 double Prior = 1.0, PriorError = 1.0;
383 if (Edges.find(Title.Data()) != Edges.end()) {
384 mini = Edges.at(Title.Data()).first;
385 maxi = Edges.at(Title.Data()).second;
390 MACH3LOG_DEBUG(
"Initialising histogram for {} with binning {:.4f}, {:.4f}", Title, mini, maxi);
395 hpost[i]->SetMinimum(0);
396 hpost[i]->GetYaxis()->SetTitle(
"Steps");
397 hpost[i]->GetYaxis()->SetNoExponent(
false);
406 TTree *SettingsBranch =
new TTree(
"Settings",
"Settings");
415 SettingsBranch->Fill();
416 SettingsBranch->Write();
417 delete SettingsBranch;
419 TDirectory *Names =
OutputFile->mkdir(
"Names");
422 TObjString((*it)).Write();
429 Means->Write(
"PDF_Means");
430 Errors->Write(
"PDF_Error");
440 PostHistDir->Close();
444 MACH3LOG_INFO(
"{} took {:.2f}s to", __func__, clock.RealTime());
447 gErrorIgnoreLevel = originalErrorLevel;
459 prefit->GetXaxis()->SetTitle(
"");
463 std::string CutPosterior1D =
"";
471 std::unique_ptr<TH1D> paramPlot = std::make_unique<TH1D>(
"paramPlot",
"paramPlot",
nDraw, 0,
nDraw);
472 paramPlot->SetDirectory(
nullptr);
473 paramPlot->SetName(
"mach3params");
474 paramPlot->SetTitle(CutPosterior1D.c_str());
475 paramPlot->SetFillStyle(3001);
476 paramPlot->SetFillColor(kBlue-1);
477 paramPlot->SetMarkerColor(paramPlot->GetFillColor());
478 paramPlot->SetMarkerStyle(20);
479 paramPlot->SetLineColor(paramPlot->GetFillColor());
480 paramPlot->SetMarkerSize(prefit->GetMarkerSize());
481 paramPlot->GetXaxis()->SetTitle(
"");
484 std::unique_ptr<TH1D> paramPlot_Gauss =
M3::Clone(paramPlot.get());
485 paramPlot_Gauss->SetMarkerColor(kOrange-5);
486 paramPlot_Gauss->SetMarkerStyle(23);
487 paramPlot_Gauss->SetLineWidth(2);
488 paramPlot_Gauss->SetMarkerSize((prefit->GetMarkerSize())*0.75);
489 paramPlot_Gauss->SetFillColor(paramPlot_Gauss->GetMarkerColor());
490 paramPlot_Gauss->SetFillStyle(3244);
491 paramPlot_Gauss->SetLineColor(paramPlot_Gauss->GetMarkerColor());
492 paramPlot_Gauss->GetXaxis()->SetTitle(
"");
495 std::unique_ptr<TH1D> paramPlot_HPD =
M3::Clone(paramPlot.get());
496 paramPlot_HPD->SetMarkerColor(kBlack);
497 paramPlot_HPD->SetMarkerStyle(25);
498 paramPlot_HPD->SetLineWidth(2);
499 paramPlot_HPD->SetMarkerSize((prefit->GetMarkerSize())*0.5);
500 paramPlot_HPD->SetFillColor(0);
501 paramPlot_HPD->SetFillStyle(0);
502 paramPlot_HPD->SetLineColor(paramPlot_HPD->GetMarkerColor());
503 paramPlot_HPD->GetXaxis()->SetTitle(
"");
506 for (
int i = 0; i <
nDraw; ++i)
514 double CentralValueTemp = 0;
515 double Central, Central_gauss, Central_HPD;
516 double Err, Err_Gauss, Err_HPD;
522 if ( CentralValueTemp != 0)
524 Central = (*Means)(i) / CentralValueTemp;
525 Err = (*Errors)(i) / CentralValueTemp;
527 Central_gauss = (*Means_Gauss)(i) / CentralValueTemp;
528 Err_Gauss = (*Errors_Gauss)(i) / CentralValueTemp;
530 Central_HPD = (*Means_HPD)(i) / CentralValueTemp;
531 Err_HPD = (*Errors_HPD)(i) / CentralValueTemp;
534 Central = 1+(*Means)(i);
537 Central_gauss = 1+(*Means_Gauss)(i);
538 Err_Gauss = (*Errors_Gauss)(i);
540 Central_HPD = 1+(*Means_HPD)(i) ;
541 Err_HPD = (*Errors_HPD)(i);
547 Central = (*Means)(i);
550 Central_gauss = (*Means_Gauss)(i);
551 Err_Gauss = (*Errors_Gauss)(i);
553 Central_HPD = (*Means_HPD)(i) ;
554 Err_HPD = (*Errors_HPD)(i);
557 paramPlot->SetBinContent(i+1, Central);
558 paramPlot->SetBinError(i+1, Err);
560 paramPlot_Gauss->SetBinContent(i+1, Central_gauss);
561 paramPlot_Gauss->SetBinError(i+1, Err_Gauss);
563 paramPlot_HPD->SetBinContent(i+1, Central_HPD);
564 paramPlot_HPD->SetBinError(i+1, Err_HPD);
566 paramPlot->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
567 paramPlot_Gauss->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
568 paramPlot_HPD->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
570 prefit->GetXaxis()->LabelsOption(
"v");
571 paramPlot->GetXaxis()->LabelsOption(
"v");\
572 paramPlot_Gauss->GetXaxis()->LabelsOption(
"v");
573 paramPlot_HPD->GetXaxis()->LabelsOption(
"v");
576 auto CompLeg = std::make_unique<TLegend>(0.33, 0.73, 0.76, 0.95);
577 CompLeg->AddEntry(prefit.get(),
"Prefit",
"fp");
578 CompLeg->AddEntry(paramPlot.get(),
"Postfit PDF",
"fp");
579 CompLeg->AddEntry(paramPlot_Gauss.get(),
"Postfit Gauss",
"fp");
580 CompLeg->AddEntry(paramPlot_HPD.get(),
"Postfit HPD",
"lfep");
581 CompLeg->SetFillColor(0);
582 CompLeg->SetFillStyle(0);
583 CompLeg->SetLineWidth(0);
584 CompLeg->SetLineStyle(0);
585 CompLeg->SetBorderSize(0);
593 prefit->Write(
"param_xsec_prefit");
594 paramPlot->Write(
"param_xsec");
595 paramPlot_Gauss->Write(
"param_xsec_gaus");
596 paramPlot_HPD->Write(
"param_xsec_HPD");
601 else prefit->GetYaxis()->SetTitle(
"Parameter Value");
602 prefit->GetYaxis()->SetRangeUser(-2.5, 2.5);
606 paramPlot->Draw(
"e2, same");
607 paramPlot_Gauss->Draw(
"e2, same");
608 paramPlot_HPD->Draw(
"e1, same");
609 CompLeg->Draw(
"same");
613 constexpr
int IntervalsSize = 20;
614 const int NIntervals =
nDraw/IntervalsSize;
616 for (
int i = 0; i < NIntervals+1; ++i)
618 int RangeMin = i*IntervalsSize;
619 int RangeMax =RangeMin + IntervalsSize;
620 if(i == NIntervals+1) {
621 RangeMin = i*IntervalsSize;
624 if(RangeMin >=
nDraw)
break;
626 double ymin = std::numeric_limits<double>::max();
627 double ymax = -std::numeric_limits<double>::max();
628 for (
int b = RangeMin; b <= RangeMax; ++b) {
631 double val = prefit->GetBinContent(b);
632 double err = prefit->GetBinError(b);
633 ymin = std::min(ymin, val - err);
634 ymax = std::max(ymax, val + err);
638 double val = paramPlot_HPD->GetBinContent(b);
639 double err = paramPlot_HPD->GetBinError(b);
640 ymin = std::min(ymin, val - err);
641 ymax = std::max(ymax, val + err);
645 double margin = 0.1 * (ymax - ymin);
646 prefit->GetYaxis()->SetRangeUser(ymin - margin, ymax + margin);
648 prefit->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
649 paramPlot->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
650 paramPlot_Gauss->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
651 paramPlot_HPD->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
655 paramPlot->Draw(
"e2, same");
656 paramPlot_Gauss->Draw(
"e2, same");
657 paramPlot_HPD->Draw(
"e1, same");
658 CompLeg->Draw(
"same");
666 int NDbinCounter = Start;
673 prefit->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
674 prefit->GetYaxis()->SetRangeUser(0.6, 1.4);
675 prefit->GetXaxis()->SetRangeUser(Start, NDbinCounter);
677 paramPlot->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
678 paramPlot->GetYaxis()->SetRangeUser(0.6, 1.4);
679 paramPlot->GetXaxis()->SetRangeUser(Start, NDbinCounter);
680 paramPlot->SetTitle(CutPosterior1D.c_str());
682 paramPlot_Gauss->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
683 paramPlot_Gauss->GetYaxis()->SetRangeUser(0.6, 1.4);
684 paramPlot_Gauss->GetXaxis()->SetRangeUser(Start, NDbinCounter);
685 paramPlot_Gauss->SetTitle(CutPosterior1D.c_str());
687 paramPlot_HPD->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
688 paramPlot_HPD->GetYaxis()->SetRangeUser(0.6, 1.4);
689 paramPlot_HPD->GetXaxis()->SetRangeUser(Start, NDbinCounter);
690 paramPlot_HPD->SetTitle(CutPosterior1D.c_str());
692 prefit->Write((
"param_"+NDname+
"_prefit").c_str());
693 paramPlot->Write((
"param_"+NDname).c_str());
694 paramPlot_Gauss->Write((
"param_"+NDname+
"_gaus").c_str());
695 paramPlot_HPD->Write((
"param_"+NDname+
"_HPD").c_str());
698 paramPlot->Draw(
"e2, same");
699 paramPlot_Gauss->Draw(
"e1, same");
700 paramPlot_HPD->Draw(
"e1, same");
701 CompLeg->Draw(
"same");
702 Posterior->Write((
"param_"+NDname+
"_canv").c_str());
715 const std::vector<Color_t>& CredibleIntervalsColours,
716 const bool CredibleInSigmas) {
721 const double LeftMargin =
Posterior->GetLeftMargin();
726 const int nCredible = int(CredibleIntervals.size());
727 std::vector<std::unique_ptr<TH1D>> hpost_copy(
nDraw);
728 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(
nDraw);
731 for (
int i = 0; i <
nDraw; ++i)
733 hpost_copy[i] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i", i));
734 hpost_cl[i].resize(nCredible);
735 for (
int j = 0; j < nCredible; ++j)
737 hpost_cl[i][j] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i_CL_%f", i, CredibleIntervals[j]));
740 hpost_cl[i][j]->Reset(
"");
741 hpost_cl[i][j]->Fill(0.0, 0.0);
746 #pragma omp parallel for
748 for (
int i = 0; i <
nDraw; ++i)
751 hpost_copy[i]->Scale(1. / hpost_copy[i]->Integral());
752 for (
int j = 0; j < nCredible; ++j)
755 hpost_cl[i][j]->Scale(1. / hpost_cl[i][j]->Integral());
758 hpost_cl[i][j]->SetFillColor(CredibleIntervalsColours[j]);
759 hpost_cl[i][j]->SetLineWidth(1);
761 hpost_copy[i]->GetYaxis()->SetTitleOffset(1.8);
762 hpost_copy[i]->SetLineWidth(1);
763 hpost_copy[i]->SetMaximum(hpost_copy[i]->GetMaximum()*1.2);
764 hpost_copy[i]->SetLineWidth(2);
765 hpost_copy[i]->SetLineColor(kBlack);
766 hpost_copy[i]->GetYaxis()->SetTitle(
"Posterior Probability");
770 TDirectory *CredibleDir =
OutputFile->mkdir(
"Credible");
772 for (
int i = 0; i <
nDraw; ++i)
778 double Prior = 1.0, PriorError = 1.0;
781 auto Asimov = std::make_unique<TLine>(Prior, hpost_copy[i]->GetMinimum(), Prior, hpost_copy[i]->GetMaximum());
784 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
786 hpost_copy[i]->Draw(
"HIST");
788 for (
int j = 0; j < nCredible; ++j)
789 hpost_cl[i][j]->Draw(
"HIST SAME");
790 for (
int j = nCredible-1; j >= 0; --j)
793 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
795 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f%% Credible Interval", CredibleIntervals[j]*100),
"f");
797 legend->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
798 legend->Draw(
"SAME");
799 Asimov->Draw(
"SAME");
810 CredibleDir->Close();
828 double maxi_y = -9999;
829 double mini_y = +9999;
830 for (
int i = 0; i <
nDraw; ++i)
833 mini_y = std::min(mini_y, range.first);
834 maxi_y = std::max(maxi_y, range.second);
837 const int vBins = (maxi_y-mini_y)*25;
838 hviolin = std::make_unique<TH2D>(
"hviolin",
"hviolin",
nDraw, 0,
nDraw, vBins, mini_y, maxi_y);
839 hviolin->SetDirectory(
nullptr);
841 constexpr
int PriorFactor = 4;
842 hviolin_prior = std::make_unique<TH2D>(
"hviolin_prior",
"hviolin_prior",
nDraw, 0,
nDraw, PriorFactor*vBins, PriorFactor*mini_y, PriorFactor*maxi_y);
845 auto rand = std::make_unique<TRandom3>(0);
846 std::vector<double> PriorVec(
nDraw);
847 std::vector<double> PriorErrorVec(
nDraw);
848 std::vector<bool> PriorFlatVec(
nDraw);
850 for (
int x = 0; x <
nDraw; ++x)
853 double Prior, PriorError;
857 hviolin->GetXaxis()->SetBinLabel(x+1, Title);
860 PriorErrorVec[x] = PriorError;
870 #pragma omp parallel for
872 for (
int x = 0; x <
nDraw; ++x)
891 const double Entry = rand->Gaus(PriorVec[x], PriorErrorVec[x]);
901 constexpr
int IntervalsSize = 10;
902 const int NIntervals =
nDraw/IntervalsSize;
904 hviolin->GetYaxis()->SetTitle(
"Parameter Value");
905 hviolin->GetXaxis()->SetTitle();
906 hviolin->GetXaxis()->LabelsOption(
"v");
923 hviolin->SetMarkerColor(kBlue);
924 hviolin->SetFillColorAlpha(kBlue, 0.35);
928 const double BottomMargin =
Posterior->GetBottomMargin();
932 hviolin->Write(
"param_violin");
935 hviolin->GetYaxis()->SetRangeUser(-1, +2);
937 for (
int i = 0; i < NIntervals+1; ++i)
939 int RangeMin = i*IntervalsSize;
940 int RangeMax = RangeMin + IntervalsSize;
941 if(i == NIntervals+1) {
942 RangeMin = i*IntervalsSize;
945 if(RangeMin >=
nDraw)
break;
947 hviolin->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
952 hviolin->Draw(
"violinX(03100300) SAME");
956 Posterior->SetBottomMargin(BottomMargin);
969 for (
int i = 0; i <
nDraw; ++i) {
971 MACH3LOG_INFO(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
980 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
982 gStyle->SetPalette(55);
986 ROOT::RDataFrame df(*
Chain);
989 ROOT::RDF::RNode dfToUse = df.Filter(
StepCut);
994 TString WeightExpression =
"1.0";
996 WeightExpression =
"(" + WeightExpression +
")*(" + name +
")";
998 dfToUse = dfToUse.Define(
"MCMC_RDF_WEIGHT", WeightExpression.Data());
1001 struct CovarianceHistogram {
1003 TString Title_i, Title_j, DrawMe;
1004 ROOT::RDF::RResultPtr<TH2D> Histogram;
1007 std::vector<CovarianceHistogram> Histograms;
1011 Histograms.reserve(nCov);
1016 for (
int i = 0; i <
nDraw; ++i)
1018 TString Title_i =
"";
1019 double Prior_i, PriorError;
1023 double xmin =
hpost[i]->GetXaxis()->GetXmin();
1024 double xmax =
hpost[i]->GetXaxis()->GetXmax();
1027 for (
int j = 0; j <= i; ++j) {
1029 if (j == i)
continue;
1033 (*Covariance)(i,j) = 0.0;
1035 (*Correlation)(i,j) = 0.0;
1040 TString Title_j =
"";
1041 double Prior_j, PriorError_j;
1045 double ymin =
hpost[j]->GetXaxis()->GetXmin();
1046 double ymax =
hpost[j]->GetXaxis()->GetXmax();
1048 ROOT::RDF::RResultPtr<TH2D> hpost_2D;
1053 hpost_2D = dfToUse.Histo2D({DrawMe.Data(), DrawMe.Data(),
1059 hpost_2D = dfToUse.Histo2D({DrawMe.Data(), DrawMe.Data(),
1063 Histograms.push_back({i, j, Title_i, Title_j, DrawMe, hpost_2D});
1066 MACH3LOG_INFO(
"Finished booking {} histograms. Now executing RDF event loop...", Histograms.size());
1072 if (!Histograms.empty()) {
1073 TH2D *dummy = Histograms[0].Histogram.GetPtr();
1079 MACH3LOG_INFO(
"RDataFrame event loop took {:.2f}s for {} entries",
1081 TStopwatch processingClock;
1082 processingClock.Start();
1084 for (
auto &Entry : Histograms)
1086 const int i = Entry.i;
1087 const int j = Entry.j;
1089 TH2D *hpost_2D = Entry.Histogram.GetPtr();
1090 hpost_2D->SetMinimum(0);
1091 hpost_2D->GetXaxis()->SetTitle(Entry.Title_i);
1092 hpost_2D->GetYaxis()->SetTitle(Entry.Title_j);
1093 hpost_2D->GetZaxis()->SetTitle(
"Steps");
1097 (*Covariance)(i,j) = hpost_2D->GetCovariance();
1099 (*Correlation)(i,j) = hpost_2D->GetCorrelationFactor();
1107 hpost_2D->Draw(
"colz");
1108 Posterior->SetName(hpost_2D->GetName());
1109 Posterior->SetTitle(hpost_2D->GetTitle());
1111 hpost_2D->Write(hpost_2D->GetTitle());
1115 processingClock.Stop();
1117 MACH3LOG_INFO(
"Processing covariance histograms took {:.2f}s", processingClock.RealTime());
1119 PostHistDir->Close();
1137 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC ");
1138 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
1151 for (
int i = 0; i <
nDraw; ++i)
1164 Chain->SetBranchStatus(
"*",
false);
1165 unsigned int stepBranch = 0;
1166 std::vector<double> ParValBranch(
nDraw);
1168 for (
int i = 0; i <
nDraw; ++i)
1173 Chain->SetBranchStatus(
"step",
true);
1174 Chain->SetBranchAddress(
"step", &stepBranch);
1176 std::vector<double> ReweightWeight(
ReweightNames.size(), 1.0);
1186 const Long64_t countwidth =
nEntries/10;
1190 for (Long64_t j = 0; j <
nEntries; ++j)
1192 if (j % countwidth == 0) {
1200 for (
int i = 0; i <
nDraw; ++i) {
1201 ParStep[i][j] = ParValBranch[i];
1205 for (
size_t i = 0; i < ReweightWeight.size(); ++i) {
1211 Chain->SetBranchStatus(
"*",
true);
1214 size_t nHistograms =
nDraw * (
nDraw + 1) / 2;
1216 MACH3LOG_INFO(
"Allocating {:.2f} MB for {} 2D Posteriors (each {}x{} bins)",
1219 for (
int i = 0; i <
nDraw; ++i)
1221 TString Title_i =
"";
1222 double Prior_i, PriorError_i;
1225 for (
int j = 0; j <= i; ++j)
1227 TString Title_j =
"";
1228 double Prior_j, PriorError_j;
1234 hpost2D[i][j] =
new TH2D((Title_i +
"_" + Title_j).Data(), (Title_i +
"_" + Title_j).Data(),
1235 nBins, range_x.first, range_x.second,
1236 nBins, range_y.first, range_y.second);
1238 hpost2D[i][j]->GetXaxis()->SetTitle(Title_i);
1239 hpost2D[i][j]->GetYaxis()->SetTitle(Title_j);
1240 hpost2D[i][j]->GetZaxis()->SetTitle(
"Steps");
1257 for (
int i = 0; i <
nDraw; ++i) {
1259 MACH3LOG_WARN(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
1266 TDirectory *PostHistDir =
nullptr;
1271 PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
1277 gStyle->SetPalette(55);
1280 #pragma omp parallel for
1282 for (
int i = 0; i <
nDraw; ++i)
1284 for (
int j = 0; j <= i; ++j)
1287 if (j == i)
continue;
1291 (*Covariance)(i,j) = 0.0;
1293 (*Correlation)(i,j) = 0.0;
1316 (*Correlation)(i,j) =
hpost2D[i][j]->GetCorrelationFactor();
1327 for (
int i = 0; i <
nDraw; ++i)
1329 for (
int j = 0; j <= i; ++j)
1332 if (j == i)
continue;
1350 PostHistDir->Close();
1364 const int DefaultUpperCut =
UpperCut;
1374 const int IntervalsSize =
nSteps/NIntervals;
1380 std::unique_ptr<TH1D> SubOptimality = std::make_unique<TH1D>(
"Suboptimality",
"Suboptimality", NIntervals, MinStep, MaxStep);
1381 SubOptimality->SetDirectory(
nullptr);
1382 SubOptimality->GetXaxis()->SetTitle(
"Step");
1383 SubOptimality->GetYaxis()->SetTitle(
"Suboptimality");
1384 SubOptimality->SetLineWidth(2);
1385 SubOptimality->SetLineColor(kBlue);
1387 for(
int i = 0; i < NIntervals; ++i)
1399 TVectorD eigen_values;
1400 eigen_values.ResizeTo(eigen.GetEigenValues());
1401 eigen_values = eigen.GetEigenValues();
1404 std::vector<double> EigenValues(eigen_values.GetNrows());
1405 for(
unsigned int j = 0; j < EigenValues.size(); j++)
1407 EigenValues[j] = eigen_values(j);
1410 SubOptimality->SetBinContent(i+1, SubOptimalityValue);
1413 MACH3LOG_INFO(
"Making Suboptimality took {:.2f}s to finish for {} steps", clock.RealTime(),
nEntries);
1419 SubOptimality->Draw(
"l");
1420 Posterior->SetName(SubOptimality->GetName());
1421 Posterior->SetTitle(SubOptimality->GetTitle());
1433 const double RightMargin =
Posterior->GetRightMargin();
1438 hCov->GetZaxis()->SetTitle(
"Covariance");
1439 hCov->SetDirectory(
nullptr);
1442 hCovSq->SetDirectory(
nullptr);
1443 hCovSq->GetZaxis()->SetTitle(
"Covariance");
1446 hCorr->SetDirectory(
nullptr);
1447 hCorr->GetZaxis()->SetTitle(
"Correlation");
1448 hCorr->SetMinimum(-1);
1449 hCorr->SetMaximum(1);
1450 hCov->GetXaxis()->SetLabelSize(0.015);
1451 hCov->GetYaxis()->SetLabelSize(0.015);
1452 hCovSq->GetXaxis()->SetLabelSize(0.015);
1453 hCovSq->GetYaxis()->SetLabelSize(0.015);
1454 hCorr->GetXaxis()->SetLabelSize(0.015);
1455 hCorr->GetYaxis()->SetLabelSize(0.015);
1458 for (
int i = 0; i <
nDraw; ++i)
1460 TString titlex =
"";
1464 hCov->GetXaxis()->SetBinLabel(i+1, titlex);
1465 hCovSq->GetXaxis()->SetBinLabel(i+1, titlex);
1466 hCorr->GetXaxis()->SetBinLabel(i+1, titlex);
1468 for (
int j = 0; j <
nDraw; ++j)
1471 const double cov = (*Covariance)(i,j);
1472 const double corr = (*Correlation)(i,j);
1474 hCov->SetBinContent(i+1, j+1, cov);
1475 hCovSq->SetBinContent(i+1, j+1, ((cov > 0) - (cov < 0))*std::sqrt(std::fabs(cov)));
1476 hCorr->SetBinContent(i+1, j+1, corr);
1478 TString titley =
"";
1479 double nom_j, err_j;
1482 hCov->GetYaxis()->SetBinLabel(j+1, titley);
1483 hCovSq->GetYaxis()->SetBinLabel(j+1, titley);
1484 hCorr->GetYaxis()->SetBinLabel(j+1, titley);
1489 gStyle->SetOptStat(0);
1492 constexpr
int NRGBs = 5;
1493 TColor::InitializeColors();
1494 Double_t stops[NRGBs] = { 0.00, 0.25, 0.50, 0.75, 1.00 };
1495 Double_t red[NRGBs] = { 0.00, 0.25, 1.00, 1.00, 0.50 };
1496 Double_t green[NRGBs] = { 0.00, 0.25, 1.00, 0.25, 0.00 };
1497 Double_t blue[NRGBs] = { 0.50, 1.00, 1.00, 0.25, 0.00 };
1498 TColor::CreateGradientColorTable(5, stops, red, green, blue, 255);
1499 gStyle->SetNumberContours(255);
1507 else hCov->Draw(
"colz");
1513 else hCorr->Draw(
"colz");
1516 hCov->Write(
"Covariance_plot");
1517 hCovSq->Write(
"Covariance_sq_plot");
1518 hCorr->Write(
"Correlation_plot");
1532 MACH3LOG_ERROR(
"Using Legacy Parameters i.e. not one from Parameter Handler Generic, this will not work");
1535 std::vector<double> MeanArray(
nDraw);
1536 std::vector<double> ErrorArray(
nDraw);
1537 std::vector<std::vector<double>> CorrelationMatrix(
nDraw, std::vector<double>(
nDraw, 0.0));
1539 TVectorD* means_vec;
1540 TVectorD* errors_vec;
1542 if (MeansMethod ==
"Arithmetic") {
1545 }
else if (MeansMethod ==
"Gaussian") {
1548 }
else if (MeansMethod ==
"HPD") {
1552 MACH3LOG_ERROR(
"Unknown means method: {}, should be either 'Arithmetic', 'Gaussian', or 'HPD'.", MeansMethod);
1557 for (
int i = 0; i <
nDraw; i++)
1559 MeanArray[i] = (*means_vec)(i);
1560 ErrorArray[i] = (*errors_vec)(i);
1561 for (
int j = 0; j <= i; j++)
1563 CorrelationMatrix[i][j] = (*Correlation)(i,j);
1564 if(i != j) CorrelationMatrix[j][i] = (*Correlation)(i,j);
1583 const double RightMargin =
Posterior->GetRightMargin();
1585 auto MatrixCopy =
M3::Clone(CorrMatrix.get());
1587 std::vector<std::string> GroupName;
1588 std::vector<int> GroupStart;
1589 std::vector<int> GroupEnd;
1592 for (
int iPar = 0; iPar <
nDraw; ++iPar)
1594 std::string GroupNameCurr;
1599 GroupNameCurr =
"Other";
1603 GroupName.push_back(GroupNameCurr);
1604 GroupStart.push_back(0);
1605 }
else if(GroupName.back() != GroupNameCurr ){
1606 GroupName.push_back(GroupNameCurr);
1607 GroupEnd.push_back(iPar);
1608 GroupStart.push_back(iPar);
1611 MatrixCopy->GetXaxis()->SetBinLabel(iPar+1,
"");
1612 MatrixCopy->GetYaxis()->SetBinLabel(iPar+1,
"");
1614 GroupEnd.push_back(
nDraw);
1616 for(
size_t iPar = 0; iPar < GroupName.size(); iPar++) {
1617 MACH3LOG_INFO(
"Group name {} from {} to {}", GroupName[iPar], GroupStart[iPar], GroupEnd[iPar]);
1621 MatrixCopy->Draw(
"colz");
1623 std::vector<std::unique_ptr<TLine>> groupLines;
1625 int nBinsX = MatrixCopy->GetNbinsX();
1626 int nBinsY = MatrixCopy->GetNbinsY();
1629 double xMin = MatrixCopy->GetXaxis()->GetBinLowEdge(1);
1630 double xMax = MatrixCopy->GetXaxis()->GetBinUpEdge(nBinsX);
1631 double yMin = MatrixCopy->GetYaxis()->GetBinLowEdge(1);
1632 double yMax = MatrixCopy->GetYaxis()->GetBinUpEdge(nBinsY);
1634 for (
size_t g = 1; g < GroupStart.size(); ++g) {
1635 const double posX = MatrixCopy->GetXaxis()->GetBinLowEdge(GroupStart[g] + 1);
1636 const double posY = MatrixCopy->GetYaxis()->GetBinLowEdge(GroupStart[g] + 1);
1639 auto vLine = std::make_unique<TLine>(posX, yMin, posX, yMax);
1640 vLine->SetLineColor(kBlack);
1641 vLine->SetLineWidth(2);
1643 groupLines.push_back(std::move(vLine));
1646 auto hLine = std::make_unique<TLine>(xMin, posY, xMax, posY);
1647 hLine->SetLineColor(kBlack);
1648 hLine->SetLineWidth(2);
1650 groupLines.push_back(std::move(hLine));
1653 std::vector<std::unique_ptr<TText>> groupLabels(GroupName.size() * 2);
1654 const double yOffsetBelow = 0.05 * (yMax - yMin);
1655 const double xOffsetRight = 0.02 * (xMax - xMin);
1657 for (
size_t g = 0; g < GroupName.size(); ++g) {
1658 const int startBin = GroupStart[g] + 1;
1659 const int endBin = GroupEnd[g];
1661 const double xStart = MatrixCopy->GetXaxis()->GetBinLowEdge(startBin);
1662 const double xEnd = MatrixCopy->GetXaxis()->GetBinUpEdge(endBin);
1663 const double xMid = 0.5 * (xStart + xEnd);
1665 const double yStart = MatrixCopy->GetYaxis()->GetBinLowEdge(startBin);
1666 const double yEnd = MatrixCopy->GetYaxis()->GetBinUpEdge(endBin);
1667 const double yMid = 0.5 * (yStart + yEnd);
1670 auto labelX = std::make_unique<TText>(xMid, yMin - yOffsetBelow, GroupName[g].c_str());
1671 labelX->SetTextAlign(23);
1672 labelX->SetTextSize(0.025);
1674 groupLabels.push_back(std::move(labelX));
1677 auto labelY = std::make_unique<TText>(xMin - xOffsetRight, yMid, GroupName[g].c_str());
1678 labelY->SetTextAlign(32);
1679 labelY->SetTextSize(0.025);
1681 groupLabels.push_back(std::move(labelY));
1694 const int OptTitle = gStyle->GetOptTitle();
1698 gStyle->SetOptTitle(1);
1700 constexpr
int Nhists = 3;
1702 constexpr
double Thresholds[Nhists+1] = {0, 0.25, 0.5, 1.0001};
1703 constexpr Color_t CorrColours[Nhists] = {kRed-10, kRed-6, kRed};
1706 std::vector<std::vector<double>> CorrOfInterest;
1707 CorrOfInterest.resize(
nDraw);
1708 std::vector<std::vector<std::string>> NameCorrOfInterest;
1709 NameCorrOfInterest.resize(
nDraw);
1711 std::vector<std::vector<std::unique_ptr<TH1D>>> Corr1DHist(
nDraw);
1713 for(
int i = 0; i <
nDraw; ++i)
1716 double Prior = 1.0, PriorError = 1.0;
1719 Corr1DHist[i].resize(Nhists);
1720 for(
int j = 0; j < Nhists; ++j)
1722 Corr1DHist[i][j] = std::make_unique<TH1D>(Form(
"Corr1DHist_%i_%i", i, j), Form(
"Corr1DHist_%i_%i", i, j),
nDraw, 0,
nDraw);
1723 Corr1DHist[i][j]->SetTitle(Form(
"%s",Title.Data()));
1724 Corr1DHist[i][j]->SetDirectory(
nullptr);
1725 Corr1DHist[i][j]->GetYaxis()->SetTitle(
"Correlation");
1726 Corr1DHist[i][j]->SetFillColor(CorrColours[j]);
1727 Corr1DHist[i][j]->SetLineColor(kBlack);
1729 for (
int k = 0; k <
nDraw; ++k)
1731 TString Title_y =
"";
1732 double Prior_y = 1.0;
1733 double PriorError_y = 1.0;
1735 Corr1DHist[i][j]->GetXaxis()->SetBinLabel(k+1, Title_y.Data());
1742 #pragma omp parallel for
1744 for(
int i = 0; i <
nDraw; ++i)
1746 for(
int j = 0; j <
nDraw; ++j)
1748 for(
int k = 0; k < Nhists; ++k)
1750 const double TempEntry = std::fabs((*
Correlation)(i,j));
1751 if(Thresholds[k+1] > TempEntry && TempEntry >= Thresholds[k])
1753 Corr1DHist[i][k]->SetBinContent(j+1, (*
Correlation)(i,j));
1759 NameCorrOfInterest[i].push_back(Corr1DHist[i][0]->GetXaxis()->GetBinLabel(j+1));
1764 TDirectory *CorrDir =
OutputFile->mkdir(
"Corr1D");
1767 for(
int i = 0; i <
nDraw; i++)
1771 Corr1DHist[i][0]->GetXaxis()->LabelsOption(
"v");
1772 Corr1DHist[i][0]->SetMaximum(+1.);
1773 Corr1DHist[i][0]->SetMinimum(-1.);
1774 Corr1DHist[i][0]->Draw();
1775 for(
int k = 1; k < Nhists; k++) {
1776 Corr1DHist[i][k]->Draw(
"SAME");
1779 auto leg = std::make_unique<TLegend>(0.3, 0.75, 0.6, 0.90);
1781 for(
int k = 0; k < Nhists; k++) {
1782 leg->AddEntry(Corr1DHist[i][k].get(), Form(
"%.2f > |Corr| >= %.2f", Thresholds[k+1], Thresholds[k]),
"f");
1786 Posterior->Write(Corr1DHist[i][0]->GetTitle());
1791 for(
int i = 0; i <
nDraw; i++)
1793 const int size = int(CorrOfInterest[i].size());
1795 if(size == 0)
continue;
1796 auto Corr1DHist_Reduced = std::make_unique<TH1D>(
"Corr1DHist_Reduced",
"Corr1DHist_Reduced", size, 0, size);
1797 Corr1DHist_Reduced->SetDirectory(
nullptr);
1798 Corr1DHist_Reduced->SetTitle(Corr1DHist[i][0]->GetTitle());
1799 Corr1DHist_Reduced->GetYaxis()->SetTitle(
"Correlation");
1800 Corr1DHist_Reduced->SetFillColor(kBlue);
1801 Corr1DHist_Reduced->SetLineColor(kBlue);
1803 for (
int j = 0; j < size; ++j)
1805 Corr1DHist_Reduced->GetXaxis()->SetBinLabel(j+1, NameCorrOfInterest[i][j].c_str());
1806 Corr1DHist_Reduced->SetBinContent(j+1, CorrOfInterest[i][j]);
1808 Corr1DHist_Reduced->GetXaxis()->LabelsOption(
"v");
1810 Corr1DHist_Reduced->SetMaximum(+1.);
1811 Corr1DHist_Reduced->SetMinimum(-1.);
1812 Corr1DHist_Reduced->Draw();
1814 Posterior->Write(Form(
"%s_Red", Corr1DHist_Reduced->GetTitle()));
1823 gStyle->SetOptTitle(OptTitle);
1831 if(GroupName ==
"")
return;
1833 TDirectory* Chi2Folder =
OutputFile->mkdir(
"DeltaChi2");
1836 for (
int iPar = 0; iPar <
nDraw; iPar++)
1838 std::string GroupNameCurr;
1843 GroupNameCurr =
"Other";
1846 if (GroupName !=
"All" && GroupNameCurr != GroupName)
continue;
1853 Chi2Folder->Close();
1861 const std::vector<Style_t>& CredibleRegionStyle,
1862 const std::vector<Color_t>& CredibleRegionColor,
1863 const bool CredibleInSigmas,
1864 const bool Draw2DPosterior,
1865 const bool DrawBestFit) {
1871 const int nCredible = int(CredibleRegions.size());
1873 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_copy(
nDraw);
1874 std::vector<std::vector<std::vector<std::unique_ptr<TH2D>>>> hpost_2D_cl(
nDraw);
1876 for (
int i = 0; i <
nDraw; ++i)
1878 hpost_2D_copy[i].resize(
nDraw);
1879 hpost_2D_cl[i].resize(
nDraw);
1880 for (
int j = 0; j <= i; ++j)
1882 hpost_2D_copy[i][j] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i", i, j));
1883 hpost_2D_cl[i][j].resize(nCredible);
1884 for (
int k = 0; k < nCredible; ++k)
1886 hpost_2D_cl[i][j][k] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i_CL_%f", i, j, CredibleRegions[k]));
1892 #pragma omp parallel for
1895 for (
int i = 0; i <
nDraw; ++i)
1897 for (
int j = 0; j <= i; ++j)
1899 for (
int k = 0; k < nCredible; ++k)
1902 hpost_2D_cl[i][j][k]->SetLineColor(CredibleRegionColor[k]);
1903 hpost_2D_cl[i][j][k]->SetLineWidth(2);
1904 hpost_2D_cl[i][j][k]->SetLineStyle(CredibleRegionStyle[k]);
1909 gStyle->SetPalette(51);
1910 for (
int i = 0; i <
nDraw; ++i)
1912 for (
int j = 0; j <= i; ++j)
1915 if (j == i)
continue;
1918 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
1919 legend->SetTextColor(kRed);
1923 auto bestfitM = std::make_unique<TGraph>(1);
1924 const int MaxBin = hpost_2D_copy[i][j]->GetMaximumBin();
1926 hpost_2D_copy[i][j]->GetBinXYZ(MaxBin, Mbx, Mby, Mbz);
1927 const double Mx = hpost_2D_copy[i][j]->GetXaxis()->GetBinCenter(Mbx);
1928 const double My = hpost_2D_copy[i][j]->GetYaxis()->GetBinCenter(Mby);
1930 bestfitM->SetPoint(0, Mx, My);
1931 bestfitM->SetMarkerStyle(22);
1932 bestfitM->SetMarkerSize(1);
1933 bestfitM->SetMarkerColor(kMagenta);
1937 if(Draw2DPosterior){
1938 hpost_2D_copy[i][j]->Draw(
"COLZ");
1940 hpost_2D_copy[i][j]->Draw(
"AXIS");
1944 for (
int k = 0; k < nCredible; ++k)
1945 hpost_2D_cl[i][j][k]->Draw(
"CONT3 SAME");
1946 for (
int k = nCredible-1; k >= 0; --k)
1948 if(CredibleInSigmas)
1949 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f#sigma Credible Interval", CredibleRegions[k]),
"l");
1951 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
1953 legend->Draw(
"SAME");
1956 legend->AddEntry(bestfitM.get(),
"Best Fit",
"p");
1957 bestfitM->Draw(
"SAME.P");
1979 const std::vector<double>& CredibleIntervals,
1980 const std::vector<Color_t>& CredibleIntervalsColours,
1982 const std::vector<double>& CredibleRegions,
1983 const std::vector<Style_t>& CredibleRegionStyle,
1984 const std::vector<Color_t>& CredibleRegionColor,
1986 const bool CredibleInSigmas) {
1990 const int nParamPlot = int(ParNames.size());
1991 std::vector<int> ParamNumber;
1992 std::string ParamInfoNames =
"Making Triangle Plot for { ";
1993 for(
int j = 0; j < nParamPlot; ++j)
1995 ParamInfoNames += fmt::format(
"{} ", ParNames[j]);
1999 MACH3LOG_WARN(
"Couldn't find param {}. Will not plot Triangle plot", ParNames[j]);
2002 ParamNumber.push_back(ParamNo);
2004 ParamInfoNames +=
"}";
2015 auto FormatHistogram = [](
auto& hist) {
2016 hist->GetXaxis()->SetTitle(
"");
2017 hist->GetYaxis()->SetTitle(
"");
2020 hist->GetXaxis()->SetLabelSize(0.1);
2021 hist->GetYaxis()->SetLabelSize(0.1);
2023 hist->GetXaxis()->SetNdivisions(4);
2024 hist->GetYaxis()->SetNdivisions(4);
2032 std::sort(ParamNumber.begin(), ParamNumber.end(), std::greater<int>());
2036 for(
int j = 1; j < nParamPlot+1; j++) Npad += j;
2042 const int nCredibleIntervals = int(CredibleIntervals.size());
2043 const int nCredibleRegions = int(CredibleRegions.size());
2046 std::vector<TPad*> TrianglePad(Npad);
2048 std::vector<std::unique_ptr<TH1D>> hpost_copy(nParamPlot);
2049 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(nParamPlot);
2050 std::vector<std::unique_ptr<TText>> TriangleText(nParamPlot * 2);
2051 std::vector<std::unique_ptr<TH2D>> hpost_2D_copy(Npad-nParamPlot);
2052 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_cl(Npad-nParamPlot);
2053 gStyle->SetPalette(51);
2056 std::vector<double> X_Min(nParamPlot);
2057 std::vector<double> X_Max(nParamPlot);
2075 const double TPm[4] = {.07,.07,.05,.05};
2076 const double Pm[2] = {.2,.1};
2079 const double TPw = 1. - TPm[0] - TPm[2];
2080 const double a_x = ( Pm[0] * TPw ) / ( 1. * nParamPlot + Pm[0] * ( 1. - 1.*nParamPlot ) );
2081 const double b_x = ( TPw - a_x ) / ( 1. * nParamPlot );
2084 X_Max[0] = X_Min[0] + a_x + b_x;
2085 for(
int i = 1; i < nParamPlot; i++)
2087 X_Min[i] = X_Max[i-1];
2088 X_Max[i] = X_Min[i]+b_x;
2091 std::vector<double> Y_Min(nParamPlot);
2092 std::vector<double> Y_Max(nParamPlot);
2095 const double TPh = 1. - TPm[1] - TPm[3];
2096 const double a_y = ( Pm[1] * TPh ) / ( 1. * nParamPlot + Pm[1] * ( 1. - 1.*nParamPlot ) );
2097 const double b_y = ( TPh - a_y ) / ( 1. * nParamPlot );
2099 Y_Min[nParamPlot-1] = TPm[1];
2100 Y_Max[nParamPlot-1] = Y_Min[nParamPlot-1] + a_y + b_y;
2101 for(
int i = nParamPlot-2; i >= 0; i--)
2103 Y_Min[i] = Y_Max[i+1];
2104 Y_Max[i] = Y_Min[i]+b_y;
2108 int counterPad = 0, counterText = 0, counterPost = 0, counter2DPost = 0;
2110 for(
int y = 0; y < nParamPlot; y++)
2113 for(
int x = 0; x <= y; x++)
2117 TrianglePad[counterPad] =
new TPad(Form(
"TPad_%i", counterPad), Form(
"TPad_%i", counterPad), X_Min[x], Y_Min[y], X_Max[x], Y_Max[y]);
2119 TrianglePad[counterPad]->SetTopMargin(0);
2120 TrianglePad[counterPad]->SetRightMargin(0);
2122 TrianglePad[counterPad]->SetGrid();
2123 TrianglePad[counterPad]->SetFrameBorderMode(0);
2124 TrianglePad[counterPad]->SetBorderMode(0);
2125 TrianglePad[counterPad]->SetBorderSize(0);
2128 TrianglePad[counterPad]->SetBottomMargin(y == (nParamPlot - 1) ? Pm[1] : 0);
2130 TrianglePad[counterPad]->SetLeftMargin(x == 0 ? Pm[0] : 0);
2132 TrianglePad[counterPad]->Draw();
2133 TrianglePad[counterPad]->cd();
2138 hpost_copy[counterPost] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i", ParamNumber[x]));
2139 hpost_cl[counterPost].resize(nCredibleIntervals);
2141 hpost_copy[counterPost]->Scale(1. / hpost_copy[counterPost]->Integral());
2142 for (
int j = 0; j < nCredibleIntervals; ++j)
2144 hpost_cl[counterPost][j] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i_CL_%f", ParamNumber[x], CredibleIntervals[j]));
2146 hpost_cl[counterPost][j]->Reset(
"");
2147 hpost_cl[counterPost][j]->Fill(0.0, 0.0);
2150 hpost_cl[counterPost][j]->Scale(1. / hpost_cl[counterPost][j]->Integral());
2151 GetCredibleIntervalSig(hpost_copy[counterPost], hpost_cl[counterPost][j], CredibleInSigmas, CredibleIntervals[j]);
2153 hpost_cl[counterPost][j]->SetFillColor(CredibleIntervalsColours[j]);
2154 hpost_cl[counterPost][j]->SetLineWidth(1);
2157 hpost_copy[counterPost]->SetMaximum(hpost_copy[counterPost]->GetMaximum()*1.2);
2158 hpost_copy[counterPost]->SetLineWidth(2);
2159 hpost_copy[counterPost]->SetLineColor(kBlack);
2162 FormatHistogram(hpost_copy[counterPost]);
2167 hpost_copy[counterPost]->GetXaxis()->SetLabelFont(133);
2168 hpost_copy[counterPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2170 hpost_copy[counterPost]->GetYaxis()->SetLabelFont(133);
2171 hpost_copy[counterPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2173 hpost_copy[counterPost]->Draw(
"HIST");
2174 for (
int j = 0; j < nCredibleIntervals; ++j){
2175 hpost_cl[counterPost][j]->Draw(
"HIST SAME");
2182 hpost_2D_copy[counter2DPost] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2183 Form(
"hpost_copy_%i_%i", ParamNumber[x], ParamNumber[y]));
2184 hpost_2D_cl[counter2DPost].resize(nCredibleRegions);
2186 for (
int k = 0; k < nCredibleRegions; ++k)
2188 hpost_2D_cl[counter2DPost][k] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2189 Form(
"hpost_copy_%i_%i_CL_%f", ParamNumber[x], ParamNumber[y], CredibleRegions[k]));
2192 hpost_2D_cl[counter2DPost][k]->SetLineColor(CredibleRegionColor[k]);
2193 hpost_2D_cl[counter2DPost][k]->SetLineWidth(2);
2194 hpost_2D_cl[counter2DPost][k]->SetLineStyle(CredibleRegionStyle[k]);
2197 FormatHistogram(hpost_2D_copy[counter2DPost]);
2202 hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelFont(133);
2203 hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2205 hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelFont(133);
2206 hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2208 hpost_2D_copy[counter2DPost]->Draw(
"COL");
2210 for (
int k = 0; k < nCredibleRegions; ++k){
2211 hpost_2D_cl[counter2DPost][k]->Draw(
"CONT3 SAME");
2216 if(y == (nParamPlot-1))
2219 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());
2222 TriangleText[counterText]->SetTextAlign(22);
2223 TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2224 TriangleText[counterText]->SetNDC(
true);
2225 TriangleText[counterText]->Draw();
2232 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());
2234 TriangleText[counterText]->SetTextAngle(90);
2237 TriangleText[counterText]->SetTextAlign(22);
2238 TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2239 TriangleText[counterText]->SetNDC(
true);
2240 TriangleText[counterText]->Draw();
2249 auto legend = std::make_unique<TLegend>(0.60, 0.7, 0.9, 0.9);
2252 for (
int j = nCredibleIntervals-1; j >= 0; --j)
2254 if(CredibleInSigmas)
2255 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
2257 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f%% Credible Interval", CredibleRegions[j]*100),
"f");
2259 for (
int k = nCredibleRegions-1; k >= 0; --k)
2261 if(CredibleInSigmas)
2262 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f#sigma Credible Region", CredibleRegions[k]),
"l");
2264 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
2266 legend->Draw(
"SAME");
2279 for(
int i = 0; i < Npad; i++)
delete TrianglePad[i];
2295 Chain =
new TChain(
"posteriors",
"posteriors");
2304 TObjArray* brlis =
Chain->GetListOfBranches();
2316 Chain->SetBranchStatus(
"*",
false);
2323 TBranch* br =
static_cast<TBranch*
>(brlis->At(i));
2328 TString bname = br->GetName();
2331 bool rejected =
false;
2340 if(rejected)
continue;
2343 Chain->SetBranchStatus(bname.Data(),
true);
2345 if (bname.BeginsWith(
"ndd_"))
2351 else if (bname.BeginsWith(
"skd_joint_"))
2359 if (bname.BeginsWith(
"LogL_sample_")) {
2362 else if (bname.BeginsWith(
"LogL_systematic_")) {
2405 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);
2406 Gauss->SetLineWidth(2);
2407 Gauss->SetLineColor(kOrange-5);
2424 #pragma omp parallel for
2426 for (
int i = 0; i <
nDraw; ++i)
2437 for (
int j = 0; j <
nDraw; ++j) {
2451 for(
unsigned int j = 0; j <
ParamType.size(); j++)
2469 auto PreFitPlot = std::make_unique<TH1D>(
"Prefit",
"Prefit",
nDraw, 0,
nDraw);
2470 PreFitPlot->SetDirectory(
nullptr);
2471 for (
int i = 0; i < PreFitPlot->GetNbinsX() + 1; ++i) {
2472 PreFitPlot->SetBinContent(i+1, 0);
2473 PreFitPlot->SetBinError(i+1, 0);
2478 double CentralValueTemp, Central, Error;
2481 for (
int i = 0; i <
nDraw; ++i)
2490 if ( CentralValueTemp != 0) {
2491 Central =
ParamCentral[ParamEnum][ParamNo] / CentralValueTemp;
2492 Error =
ParamErrors[ParamEnum][ParamNo]/CentralValueTemp;
2494 Central = CentralValueTemp + 1.0;
2500 Central = CentralValueTemp;
2507 PreFitPlot->SetBinContent(i+1, Central);
2508 PreFitPlot->SetBinError(i+1, Error);
2509 PreFitPlot->GetXaxis()->SetBinLabel(i+1,
ParamNames[ParamEnum][ParamNo]);
2511 PreFitPlot->SetDirectory(
nullptr);
2513 PreFitPlot->SetFillStyle(1001);
2514 PreFitPlot->SetFillColor(kRed-3);
2515 PreFitPlot->SetMarkerStyle(21);
2516 PreFitPlot->SetMarkerSize(2.4);
2517 PreFitPlot->SetMarkerColor(kWhite);
2518 PreFitPlot->SetLineColor(PreFitPlot->GetFillColor());
2519 PreFitPlot->GetXaxis()->LabelsOption(
"v");
2549 TDirectory* CovarianceFolder = TempFile->Get<TDirectory>(
"CovarianceFolder");
2552 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2554 if (Config ==
nullptr) {
2563 bool InputNotFound =
false;
2565 CovPos[
kXSecPar] = GetFromManager<std::vector<std::string>>(Settings[
"General"][
"Systematics"][
"XsecCovFile"], {
"none"}, __FILE__ , __LINE__);
2569 InputNotFound =
true;
2573 if (XsecConfig ==
nullptr) {
2587 TMacro *
ReweightConfig = TempFile->Get<TMacro>(
"Reweight_Config");
2588 TMacro *
UmbrellaConfig = TempFile->Get<TMacro>(
"Umbrella_Config");
2590 YAML::Node ReweightSettings;
2591 YAML::Node UmbrellaSettings;
2605 if (name ==
"umbrella_weight") {
2621 MACH3LOG_INFO(
"Enabling reweighting with configured weights.");
2633 CovarianceFolder->Close();
2634 delete CovarianceFolder;
2646 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2648 if (Config ==
nullptr) {
2656 CovPos[
kNDPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovFile"],
"none", __FILE__ , __LINE__));
2659 MACH3LOG_WARN(
"Couldn't find NDCov (legacy) branch in output");
2662 CovNamePos[
kNDPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovName"],
"none", __FILE__ , __LINE__);
2667 CovPos[
kFDDetPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovFile"],
"none", __FILE__ , __LINE__));
2670 MACH3LOG_WARN(
"Couldn't find FDCov (legacy) branch in output");
2673 CovNamePos[
kFDDetPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovName"],
"none", __FILE__ , __LINE__);
2693 auto systematics = XSecFile[
"Systematics"];
2695 for (
auto it = systematics.begin(); it != systematics.end(); ++it, ++paramIndex )
2697 auto const ¶m = *it;
2699 std::string ParName = (param[
"Systematic"][
"Names"][
"FancyName"].as<std::string>());
2700 std::string Group = param[
"Systematic"][
"ParameterGroup"].as<std::string>();
2702 bool rejected =
false;
2707 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2716 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2721 if(rejected)
continue;
2724 ParamCentral[
kXSecPar].push_back(param[
"Systematic"][
"ParameterValues"][
"PreFitValue"].as<double>());
2726 ParamFlat[
kXSecPar].push_back(GetFromManager<bool>(param[
"Systematic"][
"FlatPrior"],
false, __FILE__ , __LINE__));
2736 BranchNames.push_back(
"param_" + std::to_string(paramIndex));
2741 MACH3LOG_WARN(
"Couldn't find branch '{}', if you are not planning to draw posteriors this might be fine",
BranchNames.back());
2754 TMatrixDSym *NDdetMatrix = NDdetFile->Get<TMatrixDSym>(
CovNamePos[
kNDPar].c_str());
2755 TVectorD *NDdetNominal = NDdetFile->Get<TVectorD>(
"det_weights");
2756 TDirectory *BinningDirectory = NDdetFile->Get<TDirectory>(
"Binning");
2758 for (
int i = 0; i < NDdetNominal->GetNrows(); ++i)
2768 TIter next(BinningDirectory->GetListOfKeys());
2769 TKey *key =
nullptr;
2771 while ((key =
static_cast<TKey*
>(next())))
2773 std::string name = std::string(key->GetName());
2774 TH2Poly* RefPoly = BinningDirectory->Get<TH2Poly>((name).c_str());
2775 int size = RefPoly->GetNumberOfBins();
2794 for (
int i = 0; i < FDdetMatrix->GetNrows(); ++i)
2828 std::stringstream TempStream;
2829 TempStream <<
"step > " << Cuts;
2839 const unsigned int maxNsteps =
Chain->GetMaximum(
"step");
2864 for (
int i = 0; i <
nDraw; ++i)
2867 double Prior = 1.0, PriorError = 1.0;
2884 #pragma omp parallel for
2886 for (
int i = 0; i <
nDraw; ++i)
2888 for (
int j = 0; j <= i; ++j)
2892 hpost2D[i][j]->Fill(0.0, 0.0, 0.0);
2912 TDirectory *PolarDir =
OutputFile->mkdir(
"PolarDir");
2915 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2921 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Polar Plot", ParNames[k]);
2926 double Prior = 1.0, PriorError = 1.0;
2929 std::vector<double> x_val(
nBins);
2930 std::vector<double> y_val(
nBins);
2932 constexpr
double xmin = 0;
2933 constexpr
double xmax = 2*TMath::Pi();
2935 double Integral =
hpost[ParamNo]->Integral();
2936 for (Int_t ipt = 0; ipt <
nBins; ipt++)
2938 x_val[ipt] = ipt*(xmax-xmin)/
nBins+xmin;
2939 y_val[ipt] =
hpost[ParamNo]->GetBinContent(ipt+1)/Integral;
2942 auto PolarGraph = std::make_unique<TGraphPolar>(
nBins, x_val.data(), y_val.data());
2943 PolarGraph->SetLineWidth(2);
2944 PolarGraph->SetFillStyle(3001);
2945 PolarGraph->SetLineColor(kRed);
2946 PolarGraph->SetFillColor(kRed);
2947 PolarGraph->Draw(
"AFL");
2949 auto Text = std::make_unique<TText>(0.6, 0.1, Title);
2950 Text->SetTextSize(0.04);
2969 const std::vector<std::vector<double>>& Model1Bounds,
2970 const std::vector<std::vector<double>>& Model2Bounds,
2971 const std::vector<std::vector<std::string>>& ModelNames){
2976 if((ParNames.size() != Model1Bounds.size()) || (Model2Bounds.size() != Model1Bounds.size()) || (Model2Bounds.size() != ModelNames.size()))
2981 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2987 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Bayes Factor", ParNames[k]);
2991 const double M1_min = Model1Bounds[k][0];
2992 const double M2_min = Model2Bounds[k][0];
2993 const double M1_max = Model1Bounds[k][1];
2994 const double M2_max = Model2Bounds[k][1];
2996 long double IntegralMode1 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M1_min),
hpost[ParamNo]->FindFixBin(M1_max));
2997 long double IntegralMode2 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M2_min),
hpost[ParamNo]->FindFixBin(M2_max));
2999 double BayesFactor = 0.;
3000 std::string Name =
"";
3003 if(IntegralMode1 >= IntegralMode2)
3005 BayesFactor = IntegralMode1/IntegralMode2;
3006 Name =
"\\mathfrak{B}(" + ModelNames[k][0]+
"/" + ModelNames[k][1] +
") = " + std::to_string(BayesFactor);
3010 BayesFactor = IntegralMode2/IntegralMode1;
3011 Name =
"\\mathfrak{B}(" + ModelNames[k][1]+
"/" + ModelNames[k][0] +
") = " + std::to_string(BayesFactor);
3017 MACH3LOG_INFO(
"Following Jeffreys Scale = {}", JeffreysScale);
3018 MACH3LOG_INFO(
"Following Dunne-Kaboth Scale = {}", DunneKabothScale);
3026 const std::vector<double>& EvaluationPoint,
3027 const std::vector<std::vector<double>>& Bounds){
3029 if((ParNames.size() != EvaluationPoint.size()) || (Bounds.size() != EvaluationPoint.size()))
3038 TDirectory *SavageDickeyDir =
OutputFile->mkdir(
"SavageDickey");
3039 SavageDickeyDir->cd();
3041 for(
unsigned int k = 0; k < ParNames.size(); ++k)
3047 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate SavageDickey", ParNames[k]);
3052 double Prior = 1.0, PriorError = 1.0;
3056 auto PosteriorHist = M3::Clone<TH1D>(
hpost[ParamNo], std::string(Title));
3059 std::unique_ptr<TH1D> PriorHist;
3063 int NBins = PosteriorHist->GetNbinsX();
3064 if(Bounds[k][0] > Bounds[k][1])
3069 PriorHist = std::make_unique<TH1D>(
"PriorHist", Title, NBins, Bounds[k][0], Bounds[k][1]);
3070 PriorHist->SetDirectory(
nullptr);
3071 double FlatProb = ( Bounds[k][1] - Bounds[k][0]) / NBins;
3072 for (
int g = 0; g < NBins + 1; ++g)
3074 PriorHist->SetBinContent(g+1, FlatProb);
3079 PriorHist = M3::Clone<TH1D>(PosteriorHist.get(),
"Prior");
3080 PriorHist->Reset(
"");
3081 PriorHist->Fill(0.0, 0.0);
3083 auto rand = std::make_unique<TRandom3>(0);
3085 for(
int g = 0; g < 1000000; ++g)
3087 PriorHist->Fill(rand->Gaus(Prior, PriorError));
3090 SavageDickeyPlot(PriorHist, PosteriorHist, std::string(Title), EvaluationPoint[k]);
3093 SavageDickeyDir->Close();
3094 delete SavageDickeyDir;
3102 std::unique_ptr<TH1D>& PosteriorHist,
3103 const std::string& Title,
3104 const double EvaluationPoint)
const {
3107 PriorHist->Scale(1./PriorHist->Integral(),
"width");
3108 PosteriorHist->Scale(1./PosteriorHist->Integral(),
"width");
3110 PriorHist->SetLineColor(kRed);
3111 PriorHist->SetMarkerColor(kRed);
3112 PriorHist->SetFillColorAlpha(kRed, 0.35);
3113 PriorHist->SetFillStyle(1001);
3114 PriorHist->GetXaxis()->SetTitle(Title.c_str());
3115 PriorHist->GetYaxis()->SetTitle(
"Posterior Probability");
3116 PriorHist->SetMaximum(PosteriorHist->GetMaximum()*1.5);
3117 PriorHist->GetYaxis()->SetLabelOffset(999);
3118 PriorHist->GetYaxis()->SetLabelSize(0);
3119 PriorHist->SetLineWidth(2);
3120 PriorHist->SetLineStyle(kSolid);
3122 PosteriorHist->SetLineColor(kBlue);
3123 PosteriorHist->SetMarkerColor(kBlue);
3124 PosteriorHist->SetFillColorAlpha(kBlue, 0.35);
3125 PosteriorHist->SetFillStyle(1001);
3127 PriorHist->Draw(
"hist");
3128 PosteriorHist->Draw(
"hist same");
3130 double ProbPrior = PriorHist->GetBinContent(PriorHist->FindBin(EvaluationPoint));
3132 if(ProbPrior < 0) ProbPrior = 0.00001;
3133 double ProbPosterior = PosteriorHist->GetBinContent(PosteriorHist->FindBin(EvaluationPoint));
3134 double SavageDickey = ProbPosterior/ProbPrior;
3138 auto PostPoint = std::make_unique<TGraph>(1);
3139 PostPoint->SetPoint(0, EvaluationPoint, ProbPosterior);
3140 PostPoint->SetMarkerStyle(20);
3141 PostPoint->SetMarkerSize(1);
3142 PostPoint->Draw(
"P same");
3144 auto PriorPoint = std::make_unique<TGraph>(1);
3145 PriorPoint->SetPoint(0, EvaluationPoint, ProbPrior);
3146 PriorPoint->SetMarkerStyle(20);
3147 PriorPoint->SetMarkerSize(1);
3148 PriorPoint->Draw(
"P same");
3150 auto legend = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
3152 legend->AddEntry(PriorHist.get(),
"Prior",
"l");
3153 legend->AddEntry(PosteriorHist.get(),
"Posterior",
"l");
3154 legend->AddEntry(PostPoint.get(), Form(
"SavageDickey = %.2f, (%s)", SavageDickey, DunneKabothScale.c_str()),
"");
3155 legend->Draw(
"same");
3164 const std::vector<double>& Error,
3165 const bool& SaveBranch)
const {
3169 if( (Names.size() != Error.size()))
3171 MACH3LOG_ERROR(
"Size of passed vectors doesn't match in {}", __func__);
3174 std::vector<int> Param;
3177 for(
unsigned int k = 0; k < Names.size(); ++k)
3183 MACH3LOG_WARN(
"Couldn't find param {}. Can't Smear", Names[k]);
3188 double Prior = 1.0, PriorError = 1.0;
3191 Param.push_back(ParamNo);
3193 std::string InputFile =
MCMCFile+
".root";
3194 std::string OutputFilename =
MCMCFile +
"_smeared.root";
3197 int ret = system((
"cp " + InputFile +
" " + OutputFilename).c_str());
3199 MACH3LOG_WARN(
"Error: system call to copy file failed with code {}", ret);
3201 TFile *OutputChain =
M3::Open(OutputFilename,
"UPDATE", __FILE__, __LINE__);
3203 TTree *post = OutputChain->Get<TTree>(
"posteriors");
3204 TTree *treeNew = post->CloneTree(0);
3206 std::vector<double> NewParameter(Names.size());
3207 for(
size_t i = 0; i < Param.size(); i++) {
3208 post->SetBranchAddress(
BranchNames[Param[i]], &NewParameter[i]);
3211 std::vector<double> Unsmeared_Parameter;
3213 Unsmeared_Parameter.resize(Param.size());
3214 for(
size_t i = 0; i < Param.size(); i++) {
3215 treeNew->Branch((
BranchNames[Param[i]] +
"_unsmeared"), &Unsmeared_Parameter[i]);
3219 auto rand = std::make_unique<TRandom3>(0);
3220 Long64_t AllEntries = post->GetEntries();
3221 for (Long64_t i = 0; i < AllEntries; ++i) {
3226 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3227 Unsmeared_Parameter[iPar] = NewParameter[iPar];
3231 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3232 NewParameter[iPar] = NewParameter[iPar] + rand->Gaus(0, Error[iPar]);
3239 treeNew->Write(
"posteriors", TObject::kOverwrite);
3242 YAML::Node yaml_node;
3243 yaml_node[
"Smearing"].SetStyle(YAML::EmitterStyle::Block);
3245 for (
size_t k = 0; k < Names.size(); ++k) {
3247 entry.SetStyle(YAML::EmitterStyle::Flow);
3249 entry.push_back(Error[k]);
3250 entry.push_back(
"Gauss");
3252 yaml_node[
"Smearing"][Names[k]] = entry;
3254 TMacro ConfigSave =
YAMLtoTMacro(yaml_node,
"Smearing_Config");
3257 OutputChain->Close();
3264 const std::vector<int>& NIntervals) {
3269 for(
unsigned int k = 0; k < Names.size(); ++k)
3275 MACH3LOG_WARN(
"Couldn't find param {}. Can't reweight Prior", Names[k]);
3279 const int IntervalsSize =
nSteps/NIntervals[k];
3281 std::string filename = Names[k] +
".gif";
3282 std::ifstream f(filename);
3285 int ret = system(fmt::format(
"rm {}", filename).c_str());
3287 MACH3LOG_WARN(
"Error: system call to delete {} failed with code {}", filename, ret);
3292 for(
int i = NIntervals[k]-1; i >= 0; --i)
3297 hpost[ParamNo]->GetXaxis()->GetXmin(),
hpost[ParamNo]->GetXaxis()->GetXmax());
3298 EvePlot->SetMinimum(0);
3299 EvePlot->GetYaxis()->SetTitle(
"PDF");
3300 EvePlot->GetYaxis()->SetNoExponent(
false);
3303 std::string CutPosterior1D =
"step > " + std::to_string(i*IntervalsSize+IntervalsSize);
3313 CutPosterior1D =
"(" + CutPosterior1D +
")*(" + name +
")";
3317 std::string TextTitle =
"Steps = 0 - "+std::to_string(Counter*IntervalsSize+IntervalsSize);
3321 EvePlot->SetLineWidth(2);
3322 EvePlot->SetLineColor(kBlue-1);
3323 EvePlot->SetTitle(Names[k].c_str());
3324 EvePlot->GetXaxis()->SetTitle(EvePlot->GetTitle());
3325 EvePlot->GetYaxis()->SetLabelOffset(1000);
3328 EvePlot->Scale(1. / EvePlot->Integral());
3329 EvePlot->Draw(
"HIST");
3331 TText text(0.3, 0.8, TextTitle.c_str());
3332 text.SetTextFont (43);
3333 text.SetTextSize (40);
3337 if(i == 0)
Posterior->Print((Names[k] +
".gif++20").c_str());
3338 else Posterior->Print((Names[k] +
".gif+20").c_str());
3377 std::unordered_set<unsigned int> s(StepNumber, StepNumber + size);
3378 return s.size() == size;
3389 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC");
3390 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
3395 MACH3LOG_ERROR(
"please use SetnBatches to set other value fore example 20");
3401 for (
int j = 0; j <
nDraw; ++j) {
3403 for (
int i = 0; i <
nEntries; ++i) {
3412 for (
int i = 0; i <
nEntries; ++i) {
3419 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3431 Chain->SetBranchStatus(
"*",
false);
3434 const int countwidth =
nEntries/10;
3441 for (
int i = 0; i <
nBatches; ++i) {
3444 for (
int j = 0; j <
nDraw; ++j) {
3448 std::vector<double> ParStepBranch(
nDraw);
3449 std::vector<double> SampleValuesBranch(
SampleName_v.size());
3450 std::vector<double> SystValuesBranch(
SystName_v.size());
3451 unsigned int StepNumberBranch = 0;
3452 double AccProbValuesBranch = 0;
3454 for (
int j = 0; j <
nDraw; ++j) {
3464 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3469 Chain->SetBranchStatus(
"step",
true);
3470 Chain->SetBranchAddress(
"step", &StepNumberBranch);
3472 Chain->SetBranchStatus(
"accProb",
true);
3473 Chain->SetBranchAddress(
"accProb", &AccProbValuesBranch);
3477 for (
int i = 0; i <
nEntries; ++i) {
3481 if (i % countwidth == 0)
3485 for (
int j = 0; j <
nDraw; ++j) {
3486 ParStep[j][i] = ParStepBranch[j];
3493 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3502 int BatchNumber = -1;
3504 for (
int j = 0; j <
nBatches; ++j) {
3505 if (i < (j+1)*BatchLength) {
3511 for (
int j = 0; j <
nDraw; ++j) {
3519 MACH3LOG_INFO(
"Took {:.2f}s to finish caching statistic for Diag MCMC with {} steps", clock.RealTime(),
nEntries);
3522 MACH3LOG_ERROR(
"Found steps with duplicate StepNumber, this indicate merged chain has been passed to DiagMCMC");
3523 MACH3LOG_ERROR(
"Code hasn't been optimised to work with merged chains, results may be unintended");
3528 #pragma omp parallel for
3530 for (
int i = 0; i <
nDraw; ++i) {
3531 for (
int j = 0; j <
nBatches; ++j) {
3549 std::vector<std::unique_ptr<TH1D>> TraceParamPlots(
nDraw);
3550 std::vector<std::unique_ptr<TH1D>> TraceSamplePlots(
SampleName_v.size());
3551 std::vector<std::unique_ptr<TH1D>> TraceSystsPlots(
SystName_v.size());
3554 for (
int j = 0; j <
nDraw; ++j) {
3556 double Prior = 1.0, PriorError = 1.0;
3559 std::string HistName = Form(
"%s_%s_Trace", Title.Data(),
BranchNames[j].Data());
3560 TraceParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3561 TraceParamPlots[j]->SetDirectory(
nullptr);
3562 TraceParamPlots[j]->GetXaxis()->SetTitle(
"Step");
3563 TraceParamPlots[j]->GetYaxis()->SetTitle(
"Parameter Variation");
3568 TraceSamplePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3569 TraceSamplePlots[j]->SetDirectory(
nullptr);
3570 TraceSamplePlots[j]->GetXaxis()->SetTitle(
"Step");
3571 TraceSamplePlots[j]->GetYaxis()->SetTitle(
"Sample -logL");
3574 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3576 TraceSystsPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3577 TraceSystsPlots[j]->SetDirectory(
nullptr);
3578 TraceSystsPlots[j]->GetXaxis()->SetTitle(
"Step");
3579 TraceSystsPlots[j]->GetYaxis()->SetTitle(
"Systematic -logL");
3586 #pragma omp parallel for
3588 for (
int i = 0; i <
nEntries; ++i) {
3590 for (
int j = 0; j <
nDraw; ++j) {
3591 TraceParamPlots[j]->SetBinContent(i,
ParStep[j][i]);
3594 TraceSamplePlots[j]->SetBinContent(i,
SampleValues[i][j]);
3596 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3597 TraceSystsPlots[j]->SetBinContent(i,
SystValues[i][j]);
3602 TDirectory *TraceDir =
OutputFile->mkdir(
"Trace");
3604 for (
int j = 0; j <
nDraw; ++j) {
3606 auto Fitter = std::make_unique<TF1>(
"Fitter",
"[0]",
nEntries/2,
nEntries);
3607 Fitter->SetLineColor(kRed);
3608 TraceParamPlots[j]->Fit(
"Fitter",
"Rq");
3609 TraceParamPlots[j]->Write();
3612 TDirectory *LLDir =
OutputFile->mkdir(
"LogL");
3615 TraceSamplePlots[j]->Write();
3620 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3621 TraceSystsPlots[j]->Write();
3636 std::vector <double> ParamSums(
nDraw,0);
3639 #pragma omp parallel for
3641 for (
int j = 0; j <
nDraw; ++j) {
3642 for (
int i = 0; i <
nEntries; ++i) {
3643 ParamSums[j] +=
ParStep[j][i];
3648 #pragma omp parallel for
3650 for (
int i = 0; i <
nDraw; ++i) {
3666 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3670 TDirectory* AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3671 std::vector<std::unique_ptr<TH1D>> LagKPlots(
nDraw);
3672 std::vector<std::vector<double>> LagL(
nDraw);
3675 std::vector<double> ACFFT(
nEntries, 0.0);
3676 std::vector<double> ParVals(
nEntries, 0.0);
3677 std::vector<double> ParValsFFTR(
nEntries, 0.0);
3678 std::vector<double> ParValsFFTI(
nEntries, 0.0);
3679 std::vector<double> ParValsFFTSquare(
nEntries, 0.0);
3680 std::vector<double> ParValsComplex(
nEntries, 0.0);
3685 TVirtualFFT* fftf = TVirtualFFT::FFT(1, &
nEntries,
"C2CFORWARD");
3686 TVirtualFFT* fftb = TVirtualFFT::FFT(1, &
nEntries,
"C2CBACKWARD");
3689 for (
int j = 0; j <
nDraw; ++j) {
3691 LagL[j].resize(nLags);
3692 for (
int i = 0; i <
nEntries; ++i) {
3693 ParVals[i] =
ParStep[j][i]-ParamSums[j];
3694 ParValsComplex[i] = 0.;
3698 fftf->SetPointsComplex(ParVals.data(), ParValsComplex.data());
3700 fftf->GetPointsComplex(ParValsFFTR.data(), ParValsFFTI.data());
3703 for (
int i = 0; i <
nEntries; ++i) {
3704 ParValsFFTSquare[i] = ParValsFFTR[i]*ParValsFFTR[i] + ParValsFFTI[i]*ParValsFFTI[i];
3708 fftb->SetPointsComplex(ParValsFFTSquare.data(), ParValsComplex.data());
3710 fftb->GetPointsComplex(ACFFT.data(), ParValsComplex.data());
3713 double normAC = ACFFT[0];
3714 for (
int i = 0; i <
nEntries; ++i) {
3720 double Prior = 1.0, PriorError = 1.0;
3722 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3725 LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3726 LagKPlots[j]->SetDirectory(
nullptr);
3727 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3728 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3731 for (
int k = 0; k < nLags; ++k) {
3732 LagL[j][k] = ACFFT[k];
3733 LagKPlots[j]->SetBinContent(k, ACFFT[k]);
3738 LagKPlots[j]->Write();
3744 AutoCorrDir->Close();
3750 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3762 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3765 std::vector<std::vector<double>> DenomSum(
nDraw);
3766 std::vector<std::vector<double>> NumeratorSum(
nDraw);
3767 std::vector<std::vector<double>> LagL(
nDraw);
3769 for (
int j = 0; j <
nDraw; ++j) {
3770 DenomSum[j].resize(nLags);
3771 NumeratorSum[j].resize(nLags);
3772 LagL[j].resize(nLags);
3774 std::vector<std::unique_ptr<TH1D>> LagKPlots(
nDraw);
3776 for (
int j = 0; j <
nDraw; ++j)
3779 for (
int k = 0; k < nLags; ++k) {
3780 NumeratorSum[j][k] = 0.0;
3781 DenomSum[j][k] = 0.0;
3787 double Prior = 1.0, PriorError = 1.0;
3790 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3791 LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3792 LagKPlots[j]->SetDirectory(
nullptr);
3793 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3794 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3802 #pragma omp parallel for collapse(2)
3804 for (
int j = 0; j <
nDraw; ++j) {
3805 for (
int k = 0; k < nLags; ++k) {
3807 for (
int i = 0; i <
nEntries; ++i) {
3808 const double Diff =
ParStep[j][i]-ParamSums[j];
3812 const double LagTerm =
ParStep[j][i+k]-ParamSums[j];
3813 const double Product = Diff*LagTerm;
3814 NumeratorSum[j][k] += Product;
3817 const double Denom = Diff*Diff;
3818 DenomSum[j][k] += Denom;
3825 float* ParStep_cpu =
nullptr;
3826 float* NumeratorSum_cpu =
nullptr;
3827 float* ParamSums_cpu =
nullptr;
3828 float* DenomSum_cpu =
nullptr;
3831 PrepareGPU_AutoCorr(nLags, ParamSums, ParStep_cpu, NumeratorSum_cpu, ParamSums_cpu, DenomSum_cpu);
3834 GPUProcessor->RunGPU_AutoCorr(NumeratorSum_cpu,
3838 #pragma omp parallel for collapse(2)
3841 for (
int j = 0; j <
nDraw; ++j)
3843 for (
int k = 0; k < nLags; ++k)
3845 const int temp_index = j*nLags+k;
3846 NumeratorSum[j][k] = NumeratorSum_cpu[temp_index];
3847 DenomSum[j][k] = DenomSum_cpu[temp_index];
3851 if(NumeratorSum_cpu)
delete[] NumeratorSum_cpu;
3852 if(DenomSum_cpu)
delete[] DenomSum_cpu;
3853 if(ParStep_cpu)
delete[] ParStep_cpu;
3854 if(ParamSums_cpu)
delete[] ParamSums_cpu;
3857 GPUProcessor->CleanupGPU_AutoCorr();
3863 TDirectory *AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3865 for (
int j = 0; j <
nDraw; ++j) {
3866 for (
int k = 0; k < nLags; ++k) {
3867 LagL[j][k] = NumeratorSum[j][k]/DenomSum[j][k];
3868 LagKPlots[j]->SetBinContent(k, NumeratorSum[j][k]/DenomSum[j][k]);
3871 LagKPlots[j]->Write();
3877 AutoCorrDir->Close();
3883 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3889 void MCMCProcessor::PrepareGPU_AutoCorr(
const int nLags,
const std::vector<double>& ParamSums,
float*& ParStep_cpu,
3890 float*& NumeratorSum_cpu,
float*& ParamSums_cpu,
float*& DenomSum_cpu) {
3894 NumeratorSum_cpu =
new float[
nDraw*nLags];
3895 DenomSum_cpu =
new float[
nDraw*nLags];
3896 ParamSums_cpu =
new float[
nDraw];
3900 #pragma omp parallel
3905 #pragma omp for nowait
3907 for (
int i = 0; i <
nDraw; ++i)
3910 ParamSums_cpu[i] = ParamSums[i];
3914 #pragma omp for collapse(2) nowait
3916 for (
int j = 0; j <
nDraw; ++j)
3918 for (
int k = 0; k < nLags; ++k)
3920 const int temp = j*nLags+k;
3921 NumeratorSum_cpu[temp] = 0.0;
3922 DenomSum_cpu[temp] = 0.0;
3927 #pragma omp for collapse(2)
3929 for (
int j = 0; j <
nDraw; ++j)
3934 ParStep_cpu[temp] =
ParStep[j][i];
3943 GPUProcessor->InitGPU_AutoCorr(
nEntries,
3949 GPUProcessor->CopyToGPU_AutoCorr(ParStep_cpu,
3963 if(LagL.size() == 0)
3969 TVectorD* EffectiveSampleSize =
new TVectorD(
nDraw);
3970 TVectorD* SamplingEfficiency =
new TVectorD(
nDraw);
3971 std::vector<double> TempDenominator(
nDraw);
3973 constexpr
int Nhists = 5;
3974 constexpr
double Thresholds[Nhists + 1] = {1, 0.02, 0.005, 0.001, 0.0001, 0.0};
3975 constexpr Color_t ESSColours[Nhists] = {kGreen, kGreen + 2, kYellow, kOrange, kRed};
3978 std::vector<std::unique_ptr<TH1D>> EffectiveSampleSizeHist(Nhists);
3979 for(
int i = 0; i < Nhists; ++i)
3981 EffectiveSampleSizeHist[i] =
3982 std::make_unique<TH1D>(Form(
"EffectiveSampleSizeHist_%i", i), Form(
"EffectiveSampleSizeHist_%i", i),
nDraw, 0,
nDraw);
3983 EffectiveSampleSizeHist[i]->SetDirectory(
nullptr);
3984 EffectiveSampleSizeHist[i]->GetYaxis()->SetTitle(
"N_{eff}/N");
3985 EffectiveSampleSizeHist[i]->SetFillColor(ESSColours[i]);
3986 EffectiveSampleSizeHist[i]->SetLineColor(ESSColours[i]);
3987 EffectiveSampleSizeHist[i]->Sumw2();
3988 for (
int j = 0; j <
nDraw; ++j)
3991 double Prior = 1.0, PriorError = 1.0;
3993 EffectiveSampleSizeHist[i]->GetXaxis()->SetBinLabel(j+1, Title.Data());
3998 #pragma omp parallel for
4001 for (
int j = 0; j <
nDraw; ++j)
4005 TempDenominator[j] = 0.;
4007 for (
int k = 0; k < nLags; ++k)
4009 TempDenominator[j] += LagL[j][k];
4011 TempDenominator[j] = 1+2*TempDenominator[j];
4012 (*EffectiveSampleSize)(j) =
double(
nEntries)/TempDenominator[j];
4014 (*SamplingEfficiency)(j) = 100 * 1/TempDenominator[j];
4016 for(
int i = 0; i < Nhists; ++i)
4018 EffectiveSampleSizeHist[i]->SetBinContent(j+1, 0);
4019 EffectiveSampleSizeHist[i]->SetBinError(j+1, 0);
4021 const double TempEntry = std::fabs((*EffectiveSampleSize)(j)) / double(
nEntries);
4022 if(Thresholds[i] >= TempEntry && TempEntry > Thresholds[i+1])
4024 if( std::isnan((*EffectiveSampleSize)(j)) )
continue;
4025 EffectiveSampleSizeHist[i]->SetBinContent(j+1, TempEntry);
4033 EffectiveSampleSize->Write(
"EffectiveSampleSize");
4034 SamplingEfficiency->Write(
"SamplingEfficiency");
4036 EffectiveSampleSizeHist[0]->SetTitle(
"Effective Sample Size");
4037 EffectiveSampleSizeHist[0]->Draw();
4038 for(
int i = 1; i < Nhists; ++i)
4040 EffectiveSampleSizeHist[i]->Draw(
"SAME");
4043 auto leg = std::make_unique<TLegend>(0.2, 0.7, 0.6, 0.95);
4045 for(
int i = 0; i < Nhists; ++i)
4047 leg->AddEntry(EffectiveSampleSizeHist[i].get(), Form(
"%.4f >= N_{eff}/N > %.4f", Thresholds[i], Thresholds[i+1]),
"f");
4048 } leg->Draw(
"SAME");
4050 Posterior->Write(
"EffectiveSampleSizeCanvas");
4053 delete EffectiveSampleSize;
4054 delete SamplingEfficiency;
4064 std::vector<std::unique_ptr<TH1D>> BatchedParamPlots(
nDraw);
4065 for (
int j = 0; j <
nDraw; ++j) {
4067 double Prior = 1.0, PriorError = 1.0;
4071 std::string HistName = Form(
"%s_%s_batch", Title.Data(),
BranchNames[j].Data());
4072 BatchedParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nBatches, 0,
nBatches);
4073 BatchedParamPlots[j]->SetDirectory(
nullptr);
4077 #pragma omp parallel for
4079 for (
int j = 0; j <
nDraw; ++j) {
4080 for (
int i = 0; i <
nBatches; ++i) {
4084 std::stringstream ss;
4085 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4086 BatchedParamPlots[j]->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4090 TDirectory *BatchDir =
OutputFile->mkdir(
"Batched_means");
4092 for (
int j = 0; j <
nDraw; ++j) {
4093 auto Fitter = std::make_unique<TF1>(
"Fitter",
"[0]", 0,
nBatches);
4094 Fitter->SetLineColor(kRed);
4095 BatchedParamPlots[j]->Fit(
"Fitter",
"Rq");
4096 BatchedParamPlots[j]->Write();
4103 for (
int i = 0; i <
nBatches; ++i) {
4120 MACH3LOG_ERROR(
"BatchedAverages haven't been initialises or have been deleted something is wrong");
4126 TVectorD* BatchedVariance =
new TVectorD(
nDraw);
4128 TVectorD* C_Test_Statistics =
new TVectorD(
nDraw);
4130 std::vector<double> OverallBatchMean(
nDraw);
4131 std::vector<double> C_Rho_Nominator(
nDraw);
4132 std::vector<double> C_Rho_Denominator(
nDraw);
4133 std::vector<double> C_Nominator(
nDraw);
4134 std::vector<double> C_Denominator(
nDraw);
4138 #pragma omp parallel
4145 for (
int j = 0; j <
nDraw; ++j)
4147 OverallBatchMean[j] = 0.0;
4148 C_Rho_Nominator[j] = 0.0;
4149 C_Rho_Denominator[j] = 0.0;
4150 C_Nominator[j] = 0.0;
4151 C_Denominator[j] = 0.0;
4153 (*BatchedVariance)(j) = 0.0;
4154 (*C_Test_Statistics)(j) = 0.0;
4163 #pragma omp for nowait
4166 for (
int j = 0; j <
nDraw; ++j)
4172 (*BatchedVariance)(j) = (BatchLength/(
nBatches-1))* (*BatchedVariance)(j);
4177 #pragma omp for nowait
4179 for (
int j = 0; j <
nDraw; ++j)
4187 C_Denominator[j] = 2*C_Denominator[j];
4194 for (
int j = 0; j <
nDraw; ++j)
4196 for (
int i = 0; i <
nBatches-1; ++i)
4211 for (
int j = 0; j <
nDraw; ++j)
4213 (*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]);
4221 BatchedVariance->Write(
"BatchedMeansVariance");
4222 C_Test_Statistics->Write(
"C_Test_Statistics");
4225 delete BatchedVariance;
4226 delete C_Test_Statistics;
4237 const double TopMargin =
Posterior->GetTopMargin();
4238 const int OptTitle = gStyle->GetOptTitle();
4241 gStyle->SetOptTitle(1);
4246 const int N_Coeffs = std::min(10000,
nEntries);
4247 const int start = -(N_Coeffs/2-1);
4248 const int end = N_Coeffs/2-1;
4249 const int v_size = end - start;
4255 std::vector<std::vector<float>> k_j(nPrams, std::vector<float>(v_size, 0.0));
4256 std::vector<std::vector<float>> P_j(nPrams, std::vector<float>(v_size, 0.0));
4259 if (_N % 2 != 0) _N -= 1;
4262 const double two_pi_over_N = 2 * TMath::Pi() /
static_cast<double>(_N);
4266 #pragma omp parallel for collapse(2)
4269 for (
int j = 0; j < nPrams; ++j)
4271 for (
int jj = start; jj < end; ++jj)
4273 std::complex<M3::float_t> a_j = 0.0;
4274 const double two_pi_over_N_jj = two_pi_over_N * jj;
4275 for (
int n = 0; n < _N; ++n)
4278 std::complex<M3::float_t> exp_temp(0, two_pi_over_N_jj * n);
4279 a_j +=
ParStep[j][n] * std::exp(exp_temp);
4281 a_j /= std::sqrt(
float(_N));
4282 const int _c = jj - start;
4284 k_j[j][_c] = two_pi_over_N_jj;
4286 P_j[j][_c] = std::norm(a_j);
4290 TDirectory *PowerDir =
OutputFile->mkdir(
"PowerSpectrum");
4293 TVectorD* PowerSpectrumStepSize =
new TVectorD(nPrams);
4294 for (
int j = 0; j < nPrams; ++j)
4296 auto plot = std::make_unique<TGraph>(v_size, k_j[j].data(), P_j[j].data());
4299 double Prior = 1.0, PriorError = 1.0;
4302 std::string name = Form(
"Power Spectrum of %s;k;P(k)", Title.Data());
4304 plot->SetTitle(name.c_str());
4305 name = Form(
"%s_power_spectrum", Title.Data());
4306 plot->SetName(name.c_str());
4307 plot->SetMarkerStyle(7);
4310 auto func = std::make_unique<TF1>(
"power_template",
"[0]*( ([1] / x)^[2] / (([1] / x)^[2] +1) )", 0.0, 1.0);
4312 func->SetParameter(0, 10.0);
4314 func->SetParameter(1, 0.1);
4316 func->SetParameter(2, 2.0);
4319 func->SetParLimits(0, 0.0, 100.0);
4320 func->SetParLimits(1, 0.001, 1.0);
4321 func->SetParLimits(2, 0.0, 5.0);
4323 plot->Fit(
"power_template",
"Rq");
4332 (*PowerSpectrumStepSize)(j) = std::sqrt(func->GetParameter(0)/float(v_size*0.5));
4335 PowerSpectrumStepSize->Write(
"PowerSpectrumStepSize");
4336 delete PowerSpectrumStepSize;
4341 MACH3LOG_INFO(
"Making Power Spectrum took {:.2f}s", clock.RealTime());
4344 gStyle->SetOptTitle(OptTitle);
4355 std::vector<double> MeanUp(
nDraw, 0.0);
4356 std::vector<double> SpectralVarianceUp(
nDraw, 0.0);
4357 std::vector<int> DenomCounterUp(
nDraw, 0);
4358 const double Threshold = 0.5 *
nSteps;
4361 constexpr
double LowerThreshold = 0;
4362 constexpr
double UpperThreshold = 1.0;
4364 constexpr
int NChecks = 100;
4365 constexpr
double Division = (UpperThreshold - LowerThreshold)/NChecks;
4367 std::vector<std::unique_ptr<TH1D>> GewekePlots(
nDraw);
4368 for (
int j = 0; j <
nDraw; ++j)
4371 double Prior = 1.0, PriorError = 1.0;
4373 std::string HistName = Form(
"%s_%s_Geweke", Title.Data(),
BranchNames[j].Data());
4374 GewekePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), NChecks, 0.0, 100 * UpperThreshold);
4375 GewekePlots[j]->SetDirectory(
nullptr);
4376 GewekePlots[j]->GetXaxis()->SetTitle(
"Burn-In (%)");
4377 GewekePlots[j]->GetYaxis()->SetTitle(
"Geweke T score");
4382 #pragma omp parallel
4389 for (
int j = 0; j <
nDraw; ++j)
4396 DenomCounterUp[j]++;
4399 MeanUp[j] = MeanUp[j]/DenomCounterUp[j];
4404 #pragma omp for collapse(2)
4406 for (
int j = 0; j <
nDraw; ++j)
4412 SpectralVarianceUp[j] += (
ParStep[j][i] - MeanUp[j])*(
ParStep[j][i] - MeanUp[j]);
4421 for (
int k = 1; k < NChecks+1; ++k)
4424 std::vector<double> MeanDown(
nDraw, 0.0);
4425 std::vector<double> SpectralVarianceDown(
nDraw, 0.0);
4426 std::vector<int> DenomCounterDown(
nDraw, 0);
4428 const unsigned int ThresholsCheck = Division*k*
nSteps;
4430 for (
int j = 0; j <
nDraw; ++j)
4437 DenomCounterDown[j]++;
4440 MeanDown[j] = MeanDown[j]/DenomCounterDown[j];
4443 for (
int j = 0; j <
nDraw; ++j)
4449 SpectralVarianceDown[j] += (
ParStep[j][i] - MeanDown[j])*(
ParStep[j][i] - MeanDown[j]);
4454 for (
int j = 0; j <
nDraw; ++j)
4456 double T_score = std::fabs((MeanDown[j] - MeanUp[j])/std::sqrt(SpectralVarianceDown[j]/DenomCounterDown[j] + SpectralVarianceUp[j]/DenomCounterUp[j]));
4457 GewekePlots[j]->SetBinContent(k, T_score);
4466 TDirectory *GewekeDir =
OutputFile->mkdir(
"Geweke");
4467 for (
int j = 0; j <
nDraw; ++j)
4470 GewekePlots[j]->Write();
4472 for (
int i = 0; i <
nDraw; ++i) {
4491 auto AcceptanceProbPlot = std::make_unique<TH1D>(
"AcceptanceProbability",
"Acceptance Probability",
nEntries, 0,
nEntries);
4492 AcceptanceProbPlot->SetDirectory(
nullptr);
4493 AcceptanceProbPlot->GetXaxis()->SetTitle(
"Step");
4494 AcceptanceProbPlot->GetYaxis()->SetTitle(
"Acceptance Probability");
4496 auto BatchedAcceptanceProblot = std::make_unique<TH1D>(
"AcceptanceProbability_Batch",
"AcceptanceProbability_Batch",
nBatches, 0,
nBatches);
4497 BatchedAcceptanceProblot->SetDirectory(
nullptr);
4498 BatchedAcceptanceProblot->GetYaxis()->SetTitle(
"Acceptance Probability");
4500 for (
int i = 0; i <
nBatches; ++i) {
4504 std::stringstream ss;
4505 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4506 BatchedAcceptanceProblot->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4510 #pragma omp parallel for
4512 for (
int i = 0; i <
nEntries; ++i) {
4517 TDirectory *probDir =
OutputFile->mkdir(
"AccProb");
4520 AcceptanceProbPlot->Write();
4521 BatchedAcceptanceProblot->Write();
4534 if (CredibleIntervals.size() != CredibleIntervalsColours.size()) {
4535 MACH3LOG_ERROR(
"size of CredibleIntervals is not equal to size of CredibleIntervalsColours");
4538 if (CredibleIntervals.size() > 1) {
4539 for (
unsigned int i = 1; i < CredibleIntervals.size(); i++) {
4540 if (CredibleIntervals[i] > CredibleIntervals[i - 1]) {
4542 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleIntervals[i], CredibleIntervals[i - 1]);
4552 const std::vector<Style_t>& CredibleRegionStyle,
4553 const std::vector<Color_t>& CredibleRegionColor) {
4555 if ((CredibleRegions.size() != CredibleRegionStyle.size()) || (CredibleRegionStyle.size() != CredibleRegionColor.size())) {
4556 MACH3LOG_ERROR(
"size of CredibleRegions is not equal to size of CredibleRegionStyle or CredibleRegionColor");
4559 for (
unsigned int i = 1; i < CredibleRegions.size(); i++) {
4560 if (CredibleRegions[i] > CredibleRegions[i - 1]) {
4562 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleRegions[i], CredibleRegions[i - 1]);
4573 auto caseInsensitiveCompare = [](
const std::string& a,
const std::string& b) {
4574 return std::equal(a.begin(), a.end(), b.begin(), b.end(),
4575 [](
char c1,
char c2) { return std::tolower(c1) == std::tolower(c2); });
4579 if (caseInsensitiveCompare(groupName, name)) {
4590 std::unordered_map<std::string, int> paramCounts;
4591 std::vector<std::string> orderedKeys;
4594 if (paramCounts[param] == 0) {
4595 orderedKeys.push_back(param);
4597 paramCounts[param]++;
4600 MACH3LOG_INFO(
"************************************************");
4605 for (
const std::string& key : orderedKeys) {
4610 MACH3LOG_INFO(
"************************************************");
4616 return std::vector<double>{Canv->GetTopMargin(), Canv->GetBottomMargin(),
4617 Canv->GetLeftMargin(), Canv->GetRightMargin()};
4627 if (margins.size() != 4) {
4631 Canv->SetTopMargin(margins[0]);
4632 Canv->SetBottomMargin(margins[1]);
4633 Canv->SetLeftMargin(margins[2]);
4634 Canv->SetRightMargin(margins[3]);
4640 Line->SetLineColor(Colour);
4641 Line->SetLineWidth(Width);
4642 Line->SetLineStyle(
Style);
4648 Legend->SetTextSize(size);
4649 Legend->SetLineColor(0);
4650 Legend->SetLineStyle(0);
4651 Legend->SetFillColor(0);
4652 Legend->SetFillStyle(0);
4653 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.
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.
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.
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.