6 #include "TVirtualFFT.h"
15 #pragma GCC diagnostic ignored "-Wfloat-conversion"
19 Chain(nullptr), StepCut(
""), MadePostfit(false) {
92 GPUProcessor = std::make_unique<MCMCProcessorGPU>();
118 for (
int i = 0; i <
nDraw; ++i)
124 for (
int i = 0; i <
nDraw; ++i)
126 for (
int j = 0; j <
nDraw; ++j)
152 void MCMCProcessor::GetPostfit(TVectorD *&Central_PDF, TVectorD *&Errors_PDF, TVectorD *&Central_G, TVectorD *&Errors_G, TVectorD *&Peak_Values) {
173 const int ParamTypeSize = int(
ParamType.size());
175 for (
int i = 0; i < ParamTypeSize; ++i) {
177 (*PDF_Central)(ParamNumber) = (*
Means)(i);
178 (*PDF_Errors)(ParamNumber) = (*
Errors)(i);
179 (*Peak_Values)(ParamNumber) = (*
Means_HPD)(i);
189 Cov =
static_cast<TMatrixDSym*
>(
Covariance->Clone());
190 Corr =
static_cast<TMatrixDSym*
>(
Correlation->Clone());
197 auto rand = std::make_unique<TRandom3>(0);
198 const int uniform = int(rand->Uniform(0, 10000));
200 Posterior = std::make_unique<TCanvas>((
"Posterior" + std::to_string(uniform)).c_str(), (
"Posterior" + std::to_string(uniform)).c_str(), 0, 0, 1024, 1024);
202 TCandle::SetScaledViolin(
false);
205 gStyle->SetOptStat(0);
206 gStyle->SetOptTitle(0);
216 gErrorIgnoreLevel = kWarning;
239 int originalErrorLevel = gErrorIgnoreLevel;
240 gErrorIgnoreLevel = kFatal;
243 TDirectory *PostDir =
OutputFile->mkdir(
"Post");
244 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_1d_hists");
247 std::string CutPosterior1D =
"";
250 }
else CutPosterior1D =
StepCut;
254 CutPosterior1D =
"(" + CutPosterior1D +
")*(" +
ReweightName +
")";
259 for (
int i = 0; i <
nDraw; ++i)
261 if (i % (
nDraw/5) == 0) {
266 double Prior = 1.0, PriorError = 1.0;
275 if (Edges.find(Title.Data()) != Edges.end()) {
276 mini = Edges.at(Title.Data()).first;
277 maxi = Edges.at(Title.Data()).second;
282 MACH3LOG_DEBUG(
"Initialising histogram for {} with binning {:.4f}, {:.4f}", Title, mini, maxi);
287 hpost[i]->SetMinimum(0);
288 hpost[i]->GetYaxis()->SetTitle(
"Steps");
289 hpost[i]->GetYaxis()->SetNoExponent(
false);
296 (*Central_Value)(i) = Prior;
298 double Mean, Err, Err_p, Err_m;
304 (*Means_Gauss)(i) =
Mean;
305 (*Errors_Gauss)(i) = Err;
308 (*Means_HPD)(i) =
Mean;
309 (*Errors_HPD)(i) = Err;
310 (*Errors_HPD_Positive)(i) = Err_p;
311 (*Errors_HPD_Negative)(i) = Err_m;
315 (*Correlation)(i,i) = 1.0;
321 hpost[i]->SetLineWidth(2);
322 hpost[i]->SetLineColor(kBlue-1);
324 hpost[i]->SetTitle(Title);
325 hpost[i]->GetXaxis()->SetTitle(
hpost[i]->GetTitle());
328 auto Asimov = std::make_unique<TLine>(Prior,
hpost[i]->GetMinimum(), Prior,
hpost[i]->GetMaximum());
331 auto leg = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
333 leg->AddEntry(
hpost[i], Form(
"#splitline{PDF}{#mu = %.2f, #sigma = %.2f}",
hpost[i]->GetMean(),
hpost[i]->GetRMS()),
"l");
334 leg->AddEntry(
Gauss.get(), Form(
"#splitline{Gauss}{#mu = %.2f, #sigma = %.2f}",
Gauss->GetParameter(1),
Gauss->GetParameter(2)),
"l");
336 if(
isFlat && !
PlotFlatPrior) leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f}", Prior),
"l");
337 else leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
346 MACH3LOG_WARN(
"Found fixed parameter: {} ({}), moving on", Title, i);
349 (*Means_HPD)(i) = Prior;
350 (*Errors_HPD)(i) = PriorError;
351 (*Errors_HPD_Positive)(i) = PriorError;
352 (*Errors_HPD_Negative)(i) = PriorError;
354 (*Means_Gauss)(i) = Prior;
355 (*Errors_Gauss)(i) = PriorError;
358 (*Errors)(i) = PriorError;
368 Asimov->Draw(
"same");
377 hpost[i]->SetName(Title);
378 hpost[i]->SetTitle(Title);
384 TTree *SettingsBranch =
new TTree(
"Settings",
"Settings");
393 SettingsBranch->Fill();
394 SettingsBranch->Write();
395 delete SettingsBranch;
397 TDirectory *Names =
OutputFile->mkdir(
"Names");
400 TObjString((*it)).Write();
407 Means->Write(
"PDF_Means");
408 Errors->Write(
"PDF_Error");
418 PostHistDir->Close();
422 gErrorIgnoreLevel = originalErrorLevel;
434 prefit->GetXaxis()->SetTitle(
"");
438 std::string CutPosterior1D =
"";
446 std::unique_ptr<TH1D> paramPlot = std::make_unique<TH1D>(
"paramPlot",
"paramPlot",
nDraw, 0,
nDraw);
447 paramPlot->SetDirectory(
nullptr);
448 paramPlot->SetName(
"mach3params");
449 paramPlot->SetTitle(CutPosterior1D.c_str());
450 paramPlot->SetFillStyle(3001);
451 paramPlot->SetFillColor(kBlue-1);
452 paramPlot->SetMarkerColor(paramPlot->GetFillColor());
453 paramPlot->SetMarkerStyle(20);
454 paramPlot->SetLineColor(paramPlot->GetFillColor());
455 paramPlot->SetMarkerSize(prefit->GetMarkerSize());
456 paramPlot->GetXaxis()->SetTitle(
"");
459 std::unique_ptr<TH1D> paramPlot_Gauss =
M3::Clone(paramPlot.get());
460 paramPlot_Gauss->SetMarkerColor(kOrange-5);
461 paramPlot_Gauss->SetMarkerStyle(23);
462 paramPlot_Gauss->SetLineWidth(2);
463 paramPlot_Gauss->SetMarkerSize((prefit->GetMarkerSize())*0.75);
464 paramPlot_Gauss->SetFillColor(paramPlot_Gauss->GetMarkerColor());
465 paramPlot_Gauss->SetFillStyle(3244);
466 paramPlot_Gauss->SetLineColor(paramPlot_Gauss->GetMarkerColor());
467 paramPlot_Gauss->GetXaxis()->SetTitle(
"");
470 std::unique_ptr<TH1D> paramPlot_HPD =
M3::Clone(paramPlot.get());
471 paramPlot_HPD->SetMarkerColor(kBlack);
472 paramPlot_HPD->SetMarkerStyle(25);
473 paramPlot_HPD->SetLineWidth(2);
474 paramPlot_HPD->SetMarkerSize((prefit->GetMarkerSize())*0.5);
475 paramPlot_HPD->SetFillColor(0);
476 paramPlot_HPD->SetFillStyle(0);
477 paramPlot_HPD->SetLineColor(paramPlot_HPD->GetMarkerColor());
478 paramPlot_HPD->GetXaxis()->SetTitle(
"");
481 for (
int i = 0; i <
nDraw; ++i)
489 double CentralValueTemp = 0;
490 double Central, Central_gauss, Central_HPD;
491 double Err, Err_Gauss, Err_HPD;
497 if ( CentralValueTemp != 0)
499 Central = (*Means)(i) / CentralValueTemp;
500 Err = (*Errors)(i) / CentralValueTemp;
502 Central_gauss = (*Means_Gauss)(i) / CentralValueTemp;
503 Err_Gauss = (*Errors_Gauss)(i) / CentralValueTemp;
505 Central_HPD = (*Means_HPD)(i) / CentralValueTemp;
506 Err_HPD = (*Errors_HPD)(i) / CentralValueTemp;
509 Central = 1+(*Means)(i);
512 Central_gauss = 1+(*Means_Gauss)(i);
513 Err_Gauss = (*Errors_Gauss)(i);
515 Central_HPD = 1+(*Means_HPD)(i) ;
516 Err_HPD = (*Errors_HPD)(i);
522 Central = (*Means)(i);
525 Central_gauss = (*Means_Gauss)(i);
526 Err_Gauss = (*Errors_Gauss)(i);
528 Central_HPD = (*Means_HPD)(i) ;
529 Err_HPD = (*Errors_HPD)(i);
532 paramPlot->SetBinContent(i+1, Central);
533 paramPlot->SetBinError(i+1, Err);
535 paramPlot_Gauss->SetBinContent(i+1, Central_gauss);
536 paramPlot_Gauss->SetBinError(i+1, Err_Gauss);
538 paramPlot_HPD->SetBinContent(i+1, Central_HPD);
539 paramPlot_HPD->SetBinError(i+1, Err_HPD);
541 paramPlot->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
542 paramPlot_Gauss->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
543 paramPlot_HPD->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
545 prefit->GetXaxis()->LabelsOption(
"v");
546 paramPlot->GetXaxis()->LabelsOption(
"v");\
547 paramPlot_Gauss->GetXaxis()->LabelsOption(
"v");
548 paramPlot_HPD->GetXaxis()->LabelsOption(
"v");
551 auto CompLeg = std::make_unique<TLegend>(0.33, 0.73, 0.76, 0.95);
552 CompLeg->AddEntry(prefit.get(),
"Prefit",
"fp");
553 CompLeg->AddEntry(paramPlot.get(),
"Postfit PDF",
"fp");
554 CompLeg->AddEntry(paramPlot_Gauss.get(),
"Postfit Gauss",
"fp");
555 CompLeg->AddEntry(paramPlot_HPD.get(),
"Postfit HPD",
"lfep");
556 CompLeg->SetFillColor(0);
557 CompLeg->SetFillStyle(0);
558 CompLeg->SetLineWidth(0);
559 CompLeg->SetLineStyle(0);
560 CompLeg->SetBorderSize(0);
568 prefit->Write(
"param_xsec_prefit");
569 paramPlot->Write(
"param_xsec");
570 paramPlot_Gauss->Write(
"param_xsec_gaus");
571 paramPlot_HPD->Write(
"param_xsec_HPD");
576 else prefit->GetYaxis()->SetTitle(
"Parameter Value");
577 prefit->GetYaxis()->SetRangeUser(-2.5, 2.5);
581 paramPlot->Draw(
"e2, same");
582 paramPlot_Gauss->Draw(
"e2, same");
583 paramPlot_HPD->Draw(
"e1, same");
584 CompLeg->Draw(
"same");
588 constexpr
int IntervalsSize = 20;
589 const int NIntervals =
nDraw/IntervalsSize;
591 for (
int i = 0; i < NIntervals+1; ++i)
593 int RangeMin = i*IntervalsSize;
594 int RangeMax =RangeMin + IntervalsSize;
595 if(i == NIntervals+1) {
596 RangeMin = i*IntervalsSize;
599 if(RangeMin >=
nDraw)
break;
601 double ymin = std::numeric_limits<double>::max();
602 double ymax = -std::numeric_limits<double>::max();
603 for (
int b = RangeMin; b <= RangeMax; ++b) {
606 double val = prefit->GetBinContent(b);
607 double err = prefit->GetBinError(b);
608 ymin = std::min(ymin, val - err);
609 ymax = std::max(ymax, val + err);
613 double val = paramPlot_HPD->GetBinContent(b);
614 double err = paramPlot_HPD->GetBinError(b);
615 ymin = std::min(ymin, val - err);
616 ymax = std::max(ymax, val + err);
620 double margin = 0.1 * (ymax - ymin);
621 prefit->GetYaxis()->SetRangeUser(ymin - margin, ymax + margin);
623 prefit->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
624 paramPlot->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
625 paramPlot_Gauss->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
626 paramPlot_HPD->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
630 paramPlot->Draw(
"e2, same");
631 paramPlot_Gauss->Draw(
"e2, same");
632 paramPlot_HPD->Draw(
"e1, same");
633 CompLeg->Draw(
"same");
641 int NDbinCounter = Start;
648 prefit->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
649 prefit->GetYaxis()->SetRangeUser(0.6, 1.4);
650 prefit->GetXaxis()->SetRangeUser(Start, NDbinCounter);
652 paramPlot->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
653 paramPlot->GetYaxis()->SetRangeUser(0.6, 1.4);
654 paramPlot->GetXaxis()->SetRangeUser(Start, NDbinCounter);
655 paramPlot->SetTitle(CutPosterior1D.c_str());
657 paramPlot_Gauss->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
658 paramPlot_Gauss->GetYaxis()->SetRangeUser(0.6, 1.4);
659 paramPlot_Gauss->GetXaxis()->SetRangeUser(Start, NDbinCounter);
660 paramPlot_Gauss->SetTitle(CutPosterior1D.c_str());
662 paramPlot_HPD->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
663 paramPlot_HPD->GetYaxis()->SetRangeUser(0.6, 1.4);
664 paramPlot_HPD->GetXaxis()->SetRangeUser(Start, NDbinCounter);
665 paramPlot_HPD->SetTitle(CutPosterior1D.c_str());
667 prefit->Write((
"param_"+NDname+
"_prefit").c_str());
668 paramPlot->Write((
"param_"+NDname).c_str());
669 paramPlot_Gauss->Write((
"param_"+NDname+
"_gaus").c_str());
670 paramPlot_HPD->Write((
"param_"+NDname+
"_HPD").c_str());
673 paramPlot->Draw(
"e2, same");
674 paramPlot_Gauss->Draw(
"e1, same");
675 paramPlot_HPD->Draw(
"e1, same");
676 CompLeg->Draw(
"same");
677 Posterior->Write((
"param_"+NDname+
"_canv").c_str());
690 const std::vector<Color_t>& CredibleIntervalsColours,
691 const bool CredibleInSigmas) {
696 const double LeftMargin =
Posterior->GetLeftMargin();
701 const int nCredible = int(CredibleIntervals.size());
702 std::vector<std::unique_ptr<TH1D>> hpost_copy(
nDraw);
703 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(
nDraw);
706 for (
int i = 0; i <
nDraw; ++i)
708 hpost_copy[i] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i", i));
709 hpost_cl[i].resize(nCredible);
710 for (
int j = 0; j < nCredible; ++j)
712 hpost_cl[i][j] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i_CL_%f", i, CredibleIntervals[j]));
715 hpost_cl[i][j]->Reset(
"");
716 hpost_cl[i][j]->Fill(0.0, 0.0);
721 #pragma omp parallel for
723 for (
int i = 0; i <
nDraw; ++i)
726 hpost_copy[i]->Scale(1. / hpost_copy[i]->Integral());
727 for (
int j = 0; j < nCredible; ++j)
730 hpost_cl[i][j]->Scale(1. / hpost_cl[i][j]->Integral());
733 hpost_cl[i][j]->SetFillColor(CredibleIntervalsColours[j]);
734 hpost_cl[i][j]->SetLineWidth(1);
736 hpost_copy[i]->GetYaxis()->SetTitleOffset(1.8);
737 hpost_copy[i]->SetLineWidth(1);
738 hpost_copy[i]->SetMaximum(hpost_copy[i]->GetMaximum()*1.2);
739 hpost_copy[i]->SetLineWidth(2);
740 hpost_copy[i]->SetLineColor(kBlack);
741 hpost_copy[i]->GetYaxis()->SetTitle(
"Posterior Probability");
745 TDirectory *CredibleDir =
OutputFile->mkdir(
"Credible");
747 for (
int i = 0; i <
nDraw; ++i)
753 double Prior = 1.0, PriorError = 1.0;
756 auto Asimov = std::make_unique<TLine>(Prior, hpost_copy[i]->GetMinimum(), Prior, hpost_copy[i]->GetMaximum());
759 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
761 hpost_copy[i]->Draw(
"HIST");
763 for (
int j = 0; j < nCredible; ++j)
764 hpost_cl[i][j]->Draw(
"HIST SAME");
765 for (
int j = nCredible-1; j >= 0; --j)
768 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
770 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f%% Credible Interval", CredibleIntervals[j]*100),
"f");
772 legend->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
773 legend->Draw(
"SAME");
774 Asimov->Draw(
"SAME");
785 CredibleDir->Close();
803 double tempVal = 0.0;
805 double maxi_y = -9999;
806 double mini_y = +9999;
807 for (
int i = 0; i <
nDraw; ++i)
813 maxi_y = std::max(maxi_y, max_val);
814 mini_y = std::min(mini_y, min_val);
817 const int vBins = (maxi_y-mini_y)*25;
818 hviolin = std::make_unique<TH2D>(
"hviolin",
"hviolin",
nDraw, 0,
nDraw, vBins, mini_y, maxi_y);
819 hviolin->SetDirectory(
nullptr);
821 constexpr
int PriorFactor = 4;
822 hviolin_prior = std::make_unique<TH2D>(
"hviolin_prior",
"hviolin_prior",
nDraw, 0,
nDraw, PriorFactor*vBins, PriorFactor*mini_y, PriorFactor*maxi_y);
825 auto rand = std::make_unique<TRandom3>(0);
826 std::vector<double> PriorVec(
nDraw);
827 std::vector<double> PriorErrorVec(
nDraw);
828 std::vector<bool> PriorFlatVec(
nDraw);
830 for (
int x = 0; x <
nDraw; ++x)
833 double Prior, PriorError;
837 hviolin->GetXaxis()->SetBinLabel(x+1, Title);
840 PriorErrorVec[x] = PriorError;
844 PriorFlatVec[x] =
ParamFlat[ParType][ParamTemp];
852 #pragma omp parallel for
854 for (
int x = 0; x <
nDraw; ++x)
876 const double Entry = rand->Gaus(PriorVec[x], PriorErrorVec[x]);
886 constexpr
int IntervalsSize = 10;
887 const int NIntervals =
nDraw/IntervalsSize;
889 hviolin->GetYaxis()->SetTitle(
"Parameter Value");
890 hviolin->GetXaxis()->SetTitle();
891 hviolin->GetXaxis()->LabelsOption(
"v");
908 hviolin->SetMarkerColor(kBlue);
909 hviolin->SetFillColorAlpha(kBlue, 0.35);
913 const double BottomMargin =
Posterior->GetBottomMargin();
917 hviolin->Write(
"param_violin");
920 hviolin->GetYaxis()->SetRangeUser(-1, +2);
922 for (
int i = 0; i < NIntervals+1; ++i)
924 int RangeMin = i*IntervalsSize;
925 int RangeMax =RangeMin + IntervalsSize;
926 if(i == NIntervals+1) {
927 RangeMin = i*IntervalsSize;
930 if(RangeMin >=
nDraw)
break;
932 hviolin->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
937 hviolin->Draw(
"violinX(03100300) SAME");
941 Posterior->SetBottomMargin(BottomMargin);
950 bool HaveMadeDiagonal =
false;
954 for (
int i = 0; i <
nDraw; ++i) {
956 HaveMadeDiagonal =
false;
957 MACH3LOG_INFO(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
960 HaveMadeDiagonal =
true;
964 if (HaveMadeDiagonal ==
false) {
968 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
970 gStyle->SetPalette(55);
972 for (
int i = 0; i <
nDraw; ++i)
974 if (i % (
nDraw/5) == 0)
977 TString Title_i =
"";
978 double Prior_i, PriorError;
983 for (
int j = 0; j <= i; ++j) {
985 if (j == i)
continue;
989 (*Covariance)(i,j) = 0.0;
991 (*Correlation)(i,j) = 0.0;
996 TString Title_j =
"";
997 double Prior_j, PriorError_j;
1006 auto hpost_2D =
new TH2D(DrawMe, DrawMe,
1007 nBins,
hpost[i]->GetXaxis()->GetXmin(),
hpost[i]->GetXaxis()->GetXmax(),
1008 nBins,
hpost[j]->GetXaxis()->GetXmin(),
hpost[j]->GetXaxis()->GetXmax());
1009 hpost_2D->SetMinimum(0);
1010 hpost_2D->GetXaxis()->SetTitle(Title_i);
1011 hpost_2D->GetYaxis()->SetTitle(Title_j);
1012 hpost_2D->GetZaxis()->SetTitle(
"Steps");
1014 std::string SelectionStr =
StepCut;
1019 Chain->Project(DrawMe, DrawMe, SelectionStr.c_str());
1023 (*Covariance)(i,j) = hpost_2D->GetCovariance();
1026 (*Correlation)(i,j) = hpost_2D->GetCorrelationFactor();
1037 hpost_2D->Draw(
"colz");
1038 Posterior->SetName(hpost_2D->GetName());
1039 Posterior->SetTitle(hpost_2D->GetTitle());
1051 PostHistDir->Close();
1069 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC ");
1070 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
1083 for (
int i = 0; i <
nDraw; ++i)
1096 Chain->SetBranchStatus(
"*",
false);
1097 unsigned int stepBranch = 0;
1098 std::vector<double> ParValBranch(
nDraw);
1100 for (
int i = 0; i <
nDraw; ++i)
1105 Chain->SetBranchStatus(
"step",
true);
1106 Chain->SetBranchAddress(
"step", &stepBranch);
1108 double ReweightWeight = 1.;
1116 const Long64_t countwidth =
nEntries/10;
1120 for (Long64_t j = 0; j <
nEntries; ++j)
1122 if (j % countwidth == 0) {
1130 for (
int i = 0; i <
nDraw; ++i) {
1131 ParStep[i][j] = ParValBranch[i];
1139 Chain->SetBranchStatus(
"*",
true);
1142 double tempVal = 0.0;
1143 std::vector<double> Min_Chain(
nDraw);
1144 std::vector<double> Max_Chain(
nDraw);
1145 for (
int i = 0; i <
nDraw; ++i)
1153 size_t nHistograms =
nDraw * (
nDraw + 1) / 2;
1155 MACH3LOG_INFO(
"Allocating {:.2f} MB for {} 2D Posteriors (each {}x{} bins)",
1158 for (
int i = 0; i <
nDraw; ++i)
1160 TString Title_i =
"";
1161 double Prior_i, PriorError_i;
1164 for (
int j = 0; j <= i; ++j)
1166 TString Title_j =
"";
1167 double Prior_j, PriorError_j;
1171 hpost2D[i][j] =
new TH2D((Title_i +
"_" + Title_j).Data(), (Title_i +
"_" + Title_j).Data(),
1172 nBins,
hpost[i]->GetXaxis()->GetXmin(),
hpost[i]->GetXaxis()->GetXmax(),
1173 nBins,
hpost[j]->GetXaxis()->GetXmin(),
hpost[j]->GetXaxis()->GetXmax());
1175 hpost2D[i][j]->GetXaxis()->SetTitle(Title_i);
1176 hpost2D[i][j]->GetYaxis()->SetTitle(Title_j);
1177 hpost2D[i][j]->GetZaxis()->SetTitle(
"Steps");
1192 bool HaveMadeDiagonal =
false;
1195 for (
int i = 0; i <
nDraw; ++i) {
1197 HaveMadeDiagonal =
false;
1198 MACH3LOG_WARN(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
1201 HaveMadeDiagonal =
true;
1207 TDirectory *PostHistDir =
nullptr;
1212 PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
1218 gStyle->SetPalette(55);
1221 #pragma omp parallel for
1223 for (
int i = 0; i <
nDraw; ++i)
1225 for (
int j = 0; j <= i; ++j)
1228 if (j == i)
continue;
1232 (*Covariance)(i,j) = 0.0;
1234 (*Correlation)(i,j) = 0.0;
1257 (*Correlation)(i,j) =
hpost2D[i][j]->GetCorrelationFactor();
1268 for (
int i = 0; i <
nDraw; ++i)
1270 for (
int j = 0; j <= i; ++j)
1273 if (j == i)
continue;
1291 PostHistDir->Close();
1305 const int DefaultUpperCut =
UpperCut;
1315 const int IntervalsSize =
nSteps/NIntervals;
1321 std::unique_ptr<TH1D> SubOptimality = std::make_unique<TH1D>(
"Suboptimality",
"Suboptimality", NIntervals, MinStep, MaxStep);
1322 SubOptimality->SetDirectory(
nullptr);
1323 SubOptimality->GetXaxis()->SetTitle(
"Step");
1324 SubOptimality->GetYaxis()->SetTitle(
"Suboptimality");
1325 SubOptimality->SetLineWidth(2);
1326 SubOptimality->SetLineColor(kBlue);
1328 for(
int i = 0; i < NIntervals; ++i)
1340 TVectorD eigen_values;
1341 eigen_values.ResizeTo(eigen.GetEigenValues());
1342 eigen_values = eigen.GetEigenValues();
1345 std::vector<double> EigenValues(eigen_values.GetNrows());
1346 for(
unsigned int j = 0; j < EigenValues.size(); j++)
1348 EigenValues[j] = eigen_values(j);
1351 SubOptimality->SetBinContent(i+1, SubOptimalityValue);
1354 MACH3LOG_INFO(
"Making Suboptimality took {:.2f}s to finish for {} steps", clock.RealTime(),
nEntries);
1360 SubOptimality->Draw(
"l");
1361 Posterior->SetName(SubOptimality->GetName());
1362 Posterior->SetTitle(SubOptimality->GetTitle());
1374 const double RightMargin =
Posterior->GetRightMargin();
1379 hCov->GetZaxis()->SetTitle(
"Covariance");
1380 hCov->SetDirectory(
nullptr);
1383 hCovSq->SetDirectory(
nullptr);
1384 hCovSq->GetZaxis()->SetTitle(
"Covariance");
1387 hCorr->SetDirectory(
nullptr);
1388 hCorr->GetZaxis()->SetTitle(
"Correlation");
1389 hCorr->SetMinimum(-1);
1390 hCorr->SetMaximum(1);
1391 hCov->GetXaxis()->SetLabelSize(0.015);
1392 hCov->GetYaxis()->SetLabelSize(0.015);
1393 hCovSq->GetXaxis()->SetLabelSize(0.015);
1394 hCovSq->GetYaxis()->SetLabelSize(0.015);
1395 hCorr->GetXaxis()->SetLabelSize(0.015);
1396 hCorr->GetYaxis()->SetLabelSize(0.015);
1399 for (
int i = 0; i <
nDraw; ++i)
1401 TString titlex =
"";
1405 hCov->GetXaxis()->SetBinLabel(i+1, titlex);
1406 hCovSq->GetXaxis()->SetBinLabel(i+1, titlex);
1407 hCorr->GetXaxis()->SetBinLabel(i+1, titlex);
1409 for (
int j = 0; j <
nDraw; ++j)
1412 const double cov = (*Covariance)(i,j);
1413 const double corr = (*Correlation)(i,j);
1415 hCov->SetBinContent(i+1, j+1, cov);
1416 hCovSq->SetBinContent(i+1, j+1, ((cov > 0) - (cov < 0))*std::sqrt(std::fabs(cov)));
1417 hCorr->SetBinContent(i+1, j+1, corr);
1419 TString titley =
"";
1420 double nom_j, err_j;
1423 hCov->GetYaxis()->SetBinLabel(j+1, titley);
1424 hCovSq->GetYaxis()->SetBinLabel(j+1, titley);
1425 hCorr->GetYaxis()->SetBinLabel(j+1, titley);
1430 gStyle->SetOptStat(0);
1433 constexpr
int NRGBs = 5;
1434 TColor::InitializeColors();
1435 Double_t stops[NRGBs] = { 0.00, 0.25, 0.50, 0.75, 1.00 };
1436 Double_t red[NRGBs] = { 0.00, 0.25, 1.00, 1.00, 0.50 };
1437 Double_t green[NRGBs] = { 0.00, 0.25, 1.00, 0.25, 0.00 };
1438 Double_t blue[NRGBs] = { 0.50, 1.00, 1.00, 0.25, 0.00 };
1439 TColor::CreateGradientColorTable(5, stops, red, green, blue, 255);
1440 gStyle->SetNumberContours(255);
1448 else hCov->Draw(
"colz");
1454 else hCorr->Draw(
"colz");
1457 hCov->Write(
"Covariance_plot");
1458 hCovSq->Write(
"Covariance_sq_plot");
1459 hCorr->Write(
"Correlation_plot");
1473 MACH3LOG_ERROR(
"Using Legacy Parameters i.e. not one from Parameter Handler Generic, this will not work");
1476 std::vector<double> MeanArray(
nDraw);
1477 std::vector<double> ErrorArray(
nDraw);
1478 std::vector<std::vector<double>> CorrelationMatrix(
nDraw, std::vector<double>(
nDraw, 0.0));
1480 TVectorD* means_vec;
1481 TVectorD* errors_vec;
1483 if (MeansMethod ==
"Arithmetic") {
1486 }
else if (MeansMethod ==
"Gaussian") {
1489 }
else if (MeansMethod ==
"HPD") {
1493 MACH3LOG_ERROR(
"Unknown means method: {}, should be either 'Arithmetic', 'Gaussian', or 'HPD'.", MeansMethod);
1498 for (
int i = 0; i <
nDraw; i++)
1500 MeanArray[i] = (*means_vec)(i);
1501 ErrorArray[i] = (*errors_vec)(i);
1502 for (
int j = 0; j <= i; j++)
1504 CorrelationMatrix[i][j] = (*Correlation)(i,j);
1505 if(i != j) CorrelationMatrix[j][i] = (*Correlation)(i,j);
1524 const double RightMargin =
Posterior->GetRightMargin();
1526 auto MatrixCopy =
M3::Clone(CorrMatrix.get());
1528 std::vector<std::string> GroupName;
1529 std::vector<int> GroupStart;
1530 std::vector<int> GroupEnd;
1533 for (
int iPar = 0; iPar <
nDraw; ++iPar)
1535 std::string GroupNameCurr;
1540 GroupNameCurr =
"Other";
1544 GroupName.push_back(GroupNameCurr);
1545 GroupStart.push_back(0);
1546 }
else if(GroupName.back() != GroupNameCurr ){
1547 GroupName.push_back(GroupNameCurr);
1548 GroupEnd.push_back(iPar);
1549 GroupStart.push_back(iPar);
1552 MatrixCopy->GetXaxis()->SetBinLabel(iPar+1,
"");
1553 MatrixCopy->GetYaxis()->SetBinLabel(iPar+1,
"");
1555 GroupEnd.push_back(
nDraw);
1557 for(
size_t iPar = 0; iPar < GroupName.size(); iPar++) {
1558 MACH3LOG_INFO(
"Group name {} from {} to {}", GroupName[iPar], GroupStart[iPar], GroupEnd[iPar]);
1562 MatrixCopy->Draw(
"colz");
1564 std::vector<std::unique_ptr<TLine>> groupLines;
1566 int nBinsX = MatrixCopy->GetNbinsX();
1567 int nBinsY = MatrixCopy->GetNbinsY();
1570 double xMin = MatrixCopy->GetXaxis()->GetBinLowEdge(1);
1571 double xMax = MatrixCopy->GetXaxis()->GetBinUpEdge(nBinsX);
1572 double yMin = MatrixCopy->GetYaxis()->GetBinLowEdge(1);
1573 double yMax = MatrixCopy->GetYaxis()->GetBinUpEdge(nBinsY);
1575 for (
size_t g = 1; g < GroupStart.size(); ++g) {
1576 const double posX = MatrixCopy->GetXaxis()->GetBinLowEdge(GroupStart[g] + 1);
1577 const double posY = MatrixCopy->GetYaxis()->GetBinLowEdge(GroupStart[g] + 1);
1580 auto vLine = std::make_unique<TLine>(posX, yMin, posX, yMax);
1581 vLine->SetLineColor(kBlack);
1582 vLine->SetLineWidth(2);
1584 groupLines.push_back(std::move(vLine));
1587 auto hLine = std::make_unique<TLine>(xMin, posY, xMax, posY);
1588 hLine->SetLineColor(kBlack);
1589 hLine->SetLineWidth(2);
1591 groupLines.push_back(std::move(hLine));
1594 std::vector<std::unique_ptr<TText>> groupLabels(GroupName.size() * 2);
1595 const double yOffsetBelow = 0.05 * (yMax - yMin);
1596 const double xOffsetRight = 0.02 * (xMax - xMin);
1598 for (
size_t g = 0; g < GroupName.size(); ++g) {
1599 const int startBin = GroupStart[g] + 1;
1600 const int endBin = GroupEnd[g];
1602 const double xStart = MatrixCopy->GetXaxis()->GetBinLowEdge(startBin);
1603 const double xEnd = MatrixCopy->GetXaxis()->GetBinUpEdge(endBin);
1604 const double xMid = 0.5 * (xStart + xEnd);
1606 const double yStart = MatrixCopy->GetYaxis()->GetBinLowEdge(startBin);
1607 const double yEnd = MatrixCopy->GetYaxis()->GetBinUpEdge(endBin);
1608 const double yMid = 0.5 * (yStart + yEnd);
1611 auto labelX = std::make_unique<TText>(xMid, yMin - yOffsetBelow, GroupName[g].c_str());
1612 labelX->SetTextAlign(23);
1613 labelX->SetTextSize(0.025);
1615 groupLabels.push_back(std::move(labelX));
1618 auto labelY = std::make_unique<TText>(xMin - xOffsetRight, yMid, GroupName[g].c_str());
1619 labelY->SetTextAlign(32);
1620 labelY->SetTextSize(0.025);
1622 groupLabels.push_back(std::move(labelY));
1635 const int OptTitle = gStyle->GetOptTitle();
1639 gStyle->SetOptTitle(1);
1641 constexpr
int Nhists = 3;
1643 constexpr
double Thresholds[Nhists+1] = {0, 0.25, 0.5, 1.0001};
1644 constexpr Color_t CorrColours[Nhists] = {kRed-10, kRed-6, kRed};
1647 std::vector<std::vector<double>> CorrOfInterest;
1648 CorrOfInterest.resize(
nDraw);
1649 std::vector<std::vector<std::string>> NameCorrOfInterest;
1650 NameCorrOfInterest.resize(
nDraw);
1652 std::vector<std::vector<std::unique_ptr<TH1D>>> Corr1DHist(
nDraw);
1654 for(
int i = 0; i <
nDraw; ++i)
1657 double Prior = 1.0, PriorError = 1.0;
1660 Corr1DHist[i].resize(Nhists);
1661 for(
int j = 0; j < Nhists; ++j)
1663 Corr1DHist[i][j] = std::make_unique<TH1D>(Form(
"Corr1DHist_%i_%i", i, j), Form(
"Corr1DHist_%i_%i", i, j),
nDraw, 0,
nDraw);
1664 Corr1DHist[i][j]->SetTitle(Form(
"%s",Title.Data()));
1665 Corr1DHist[i][j]->SetDirectory(
nullptr);
1666 Corr1DHist[i][j]->GetYaxis()->SetTitle(
"Correlation");
1667 Corr1DHist[i][j]->SetFillColor(CorrColours[j]);
1668 Corr1DHist[i][j]->SetLineColor(kBlack);
1670 for (
int k = 0; k <
nDraw; ++k)
1672 TString Title_y =
"";
1673 double Prior_y = 1.0;
1674 double PriorError_y = 1.0;
1676 Corr1DHist[i][j]->GetXaxis()->SetBinLabel(k+1, Title_y.Data());
1683 #pragma omp parallel for
1685 for(
int i = 0; i <
nDraw; ++i)
1687 for(
int j = 0; j <
nDraw; ++j)
1689 for(
int k = 0; k < Nhists; ++k)
1691 const double TempEntry = std::fabs((*
Correlation)(i,j));
1692 if(Thresholds[k+1] > TempEntry && TempEntry >= Thresholds[k])
1694 Corr1DHist[i][k]->SetBinContent(j+1, (*
Correlation)(i,j));
1700 NameCorrOfInterest[i].push_back(Corr1DHist[i][0]->GetXaxis()->GetBinLabel(j+1));
1705 TDirectory *CorrDir =
OutputFile->mkdir(
"Corr1D");
1708 for(
int i = 0; i <
nDraw; i++)
1712 Corr1DHist[i][0]->GetXaxis()->LabelsOption(
"v");
1713 Corr1DHist[i][0]->SetMaximum(+1.);
1714 Corr1DHist[i][0]->SetMinimum(-1.);
1715 Corr1DHist[i][0]->Draw();
1716 for(
int k = 1; k < Nhists; k++) {
1717 Corr1DHist[i][k]->Draw(
"SAME");
1720 auto leg = std::make_unique<TLegend>(0.3, 0.75, 0.6, 0.90);
1722 for(
int k = 0; k < Nhists; k++) {
1723 leg->AddEntry(Corr1DHist[i][k].get(), Form(
"%.2f > |Corr| >= %.2f", Thresholds[k+1], Thresholds[k]),
"f");
1727 Posterior->Write(Corr1DHist[i][0]->GetTitle());
1732 for(
int i = 0; i <
nDraw; i++)
1734 const int size = int(CorrOfInterest[i].size());
1736 if(size == 0)
continue;
1737 auto Corr1DHist_Reduced = std::make_unique<TH1D>(
"Corr1DHist_Reduced",
"Corr1DHist_Reduced", size, 0, size);
1738 Corr1DHist_Reduced->SetDirectory(
nullptr);
1739 Corr1DHist_Reduced->SetTitle(Corr1DHist[i][0]->GetTitle());
1740 Corr1DHist_Reduced->GetYaxis()->SetTitle(
"Correlation");
1741 Corr1DHist_Reduced->SetFillColor(kBlue);
1742 Corr1DHist_Reduced->SetLineColor(kBlue);
1744 for (
int j = 0; j < size; ++j)
1746 Corr1DHist_Reduced->GetXaxis()->SetBinLabel(j+1, NameCorrOfInterest[i][j].c_str());
1747 Corr1DHist_Reduced->SetBinContent(j+1, CorrOfInterest[i][j]);
1749 Corr1DHist_Reduced->GetXaxis()->LabelsOption(
"v");
1751 Corr1DHist_Reduced->SetMaximum(+1.);
1752 Corr1DHist_Reduced->SetMinimum(-1.);
1753 Corr1DHist_Reduced->Draw();
1755 Posterior->Write(Form(
"%s_Red", Corr1DHist_Reduced->GetTitle()));
1764 gStyle->SetOptTitle(OptTitle);
1772 if(GroupName ==
"")
return;
1774 TDirectory* Chi2Folder =
OutputFile->mkdir(
"DeltaChi2");
1777 for (
int iPar = 0; iPar <
nDraw; iPar++)
1779 std::string GroupNameCurr;
1784 GroupNameCurr =
"Other";
1787 if (GroupName !=
"All" && GroupNameCurr != GroupName)
continue;
1794 Chi2Folder->Close();
1802 const std::vector<Style_t>& CredibleRegionStyle,
1803 const std::vector<Color_t>& CredibleRegionColor,
1804 const bool CredibleInSigmas,
1805 const bool Draw2DPosterior,
1806 const bool DrawBestFit) {
1812 const int nCredible = int(CredibleRegions.size());
1814 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_copy(
nDraw);
1815 std::vector<std::vector<std::vector<std::unique_ptr<TH2D>>>> hpost_2D_cl(
nDraw);
1817 for (
int i = 0; i <
nDraw; ++i)
1819 hpost_2D_copy[i].resize(
nDraw);
1820 hpost_2D_cl[i].resize(
nDraw);
1821 for (
int j = 0; j <= i; ++j)
1823 hpost_2D_copy[i][j] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i", i, j));
1824 hpost_2D_cl[i][j].resize(nCredible);
1825 for (
int k = 0; k < nCredible; ++k)
1827 hpost_2D_cl[i][j][k] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i_CL_%f", i, j, CredibleRegions[k]));
1833 #pragma omp parallel for
1836 for (
int i = 0; i <
nDraw; ++i)
1838 for (
int j = 0; j <= i; ++j)
1840 for (
int k = 0; k < nCredible; ++k)
1843 hpost_2D_cl[i][j][k]->SetLineColor(CredibleRegionColor[k]);
1844 hpost_2D_cl[i][j][k]->SetLineWidth(2);
1845 hpost_2D_cl[i][j][k]->SetLineStyle(CredibleRegionStyle[k]);
1850 gStyle->SetPalette(51);
1851 for (
int i = 0; i <
nDraw; ++i)
1853 for (
int j = 0; j <= i; ++j)
1856 if (j == i)
continue;
1859 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
1860 legend->SetTextColor(kRed);
1864 auto bestfitM = std::make_unique<TGraph>(1);
1865 const int MaxBin = hpost_2D_copy[i][j]->GetMaximumBin();
1867 hpost_2D_copy[i][j]->GetBinXYZ(MaxBin, Mbx, Mby, Mbz);
1868 const double Mx = hpost_2D_copy[i][j]->GetXaxis()->GetBinCenter(Mbx);
1869 const double My = hpost_2D_copy[i][j]->GetYaxis()->GetBinCenter(Mby);
1871 bestfitM->SetPoint(0, Mx, My);
1872 bestfitM->SetMarkerStyle(22);
1873 bestfitM->SetMarkerSize(1);
1874 bestfitM->SetMarkerColor(kMagenta);
1878 if(Draw2DPosterior){
1879 hpost_2D_copy[i][j]->Draw(
"COLZ");
1881 hpost_2D_copy[i][j]->Draw(
"AXIS");
1885 for (
int k = 0; k < nCredible; ++k)
1886 hpost_2D_cl[i][j][k]->Draw(
"CONT3 SAME");
1887 for (
int k = nCredible-1; k >= 0; --k)
1889 if(CredibleInSigmas)
1890 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f#sigma Credible Interval", CredibleRegions[k]),
"l");
1892 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
1894 legend->Draw(
"SAME");
1897 legend->AddEntry(bestfitM.get(),
"Best Fit",
"p");
1898 bestfitM->Draw(
"SAME.P");
1920 const std::vector<double>& CredibleIntervals,
1921 const std::vector<Color_t>& CredibleIntervalsColours,
1923 const std::vector<double>& CredibleRegions,
1924 const std::vector<Style_t>& CredibleRegionStyle,
1925 const std::vector<Color_t>& CredibleRegionColor,
1927 const bool CredibleInSigmas) {
1931 const int nParamPlot = int(ParNames.size());
1932 std::vector<int> ParamNumber;
1933 std::string ParamInfoNames =
"Making Triangle Plot for { ";
1934 for(
int j = 0; j < nParamPlot; ++j)
1936 ParamInfoNames += fmt::format(
"{} ", ParNames[j]);
1940 MACH3LOG_WARN(
"Couldn't find param {}. Will not plot Triangle plot", ParNames[j]);
1943 ParamNumber.push_back(ParamNo);
1945 ParamInfoNames +=
"}";
1956 auto FormatHistogram = [](
auto& hist) {
1957 hist->GetXaxis()->SetTitle(
"");
1958 hist->GetYaxis()->SetTitle(
"");
1961 hist->GetXaxis()->SetLabelSize(0.1);
1962 hist->GetYaxis()->SetLabelSize(0.1);
1964 hist->GetXaxis()->SetNdivisions(4);
1965 hist->GetYaxis()->SetNdivisions(4);
1973 std::sort(ParamNumber.begin(), ParamNumber.end(), std::greater<int>());
1977 for(
int j = 1; j < nParamPlot+1; j++) Npad += j;
1983 const int nCredibleIntervals = int(CredibleIntervals.size());
1984 const int nCredibleRegions = int(CredibleRegions.size());
1987 std::vector<TPad*> TrianglePad(Npad);
1989 std::vector<std::unique_ptr<TH1D>> hpost_copy(nParamPlot);
1990 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(nParamPlot);
1991 std::vector<std::unique_ptr<TText>> TriangleText(nParamPlot * 2);
1992 std::vector<std::unique_ptr<TH2D>> hpost_2D_copy(Npad-nParamPlot);
1993 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_cl(Npad-nParamPlot);
1994 gStyle->SetPalette(51);
1997 std::vector<double> X_Min(nParamPlot);
1998 std::vector<double> X_Max(nParamPlot);
2016 const double TPm[4] = {.07,.07,.05,.05};
2017 const double Pm[2] = {.2,.1};
2020 const double TPw = 1. - TPm[0] - TPm[2];
2021 const double a_x = ( Pm[0] * TPw ) / ( 1. * nParamPlot + Pm[0] * ( 1. - 1.*nParamPlot ) );
2022 const double b_x = ( TPw - a_x ) / ( 1. * nParamPlot );
2025 X_Max[0] = X_Min[0] + a_x + b_x;
2026 for(
int i = 1; i < nParamPlot; i++)
2028 X_Min[i] = X_Max[i-1];
2029 X_Max[i] = X_Min[i]+b_x;
2032 std::vector<double> Y_Min(nParamPlot);
2033 std::vector<double> Y_Max(nParamPlot);
2036 const double TPh = 1. - TPm[1] - TPm[3];
2037 const double a_y = ( Pm[1] * TPh ) / ( 1. * nParamPlot + Pm[1] * ( 1. - 1.*nParamPlot ) );
2038 const double b_y = ( TPh - a_y ) / ( 1. * nParamPlot );
2040 Y_Min[nParamPlot-1] = TPm[1];
2041 Y_Max[nParamPlot-1] = Y_Min[nParamPlot-1] + a_y + b_y;
2042 for(
int i = nParamPlot-2; i >= 0; i--)
2044 Y_Min[i] = Y_Max[i+1];
2045 Y_Max[i] = Y_Min[i]+b_y;
2049 int counterPad = 0, counterText = 0, counterPost = 0, counter2DPost = 0;
2051 for(
int y = 0; y < nParamPlot; y++)
2054 for(
int x = 0; x <= y; x++)
2058 TrianglePad[counterPad] =
new TPad(Form(
"TPad_%i", counterPad), Form(
"TPad_%i", counterPad), X_Min[x], Y_Min[y], X_Max[x], Y_Max[y]);
2060 TrianglePad[counterPad]->SetTopMargin(0);
2061 TrianglePad[counterPad]->SetRightMargin(0);
2063 TrianglePad[counterPad]->SetGrid();
2064 TrianglePad[counterPad]->SetFrameBorderMode(0);
2065 TrianglePad[counterPad]->SetBorderMode(0);
2066 TrianglePad[counterPad]->SetBorderSize(0);
2069 TrianglePad[counterPad]->SetBottomMargin(y == (nParamPlot - 1) ? Pm[1] : 0);
2071 TrianglePad[counterPad]->SetLeftMargin(x == 0 ? Pm[0] : 0);
2073 TrianglePad[counterPad]->Draw();
2074 TrianglePad[counterPad]->cd();
2079 hpost_copy[counterPost] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i", ParamNumber[x]));
2080 hpost_cl[counterPost].resize(nCredibleIntervals);
2082 hpost_copy[counterPost]->Scale(1. / hpost_copy[counterPost]->Integral());
2083 for (
int j = 0; j < nCredibleIntervals; ++j)
2085 hpost_cl[counterPost][j] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i_CL_%f", ParamNumber[x], CredibleIntervals[j]));
2087 hpost_cl[counterPost][j]->Reset(
"");
2088 hpost_cl[counterPost][j]->Fill(0.0, 0.0);
2091 hpost_cl[counterPost][j]->Scale(1. / hpost_cl[counterPost][j]->Integral());
2092 GetCredibleIntervalSig(hpost_copy[counterPost], hpost_cl[counterPost][j], CredibleInSigmas, CredibleIntervals[j]);
2094 hpost_cl[counterPost][j]->SetFillColor(CredibleIntervalsColours[j]);
2095 hpost_cl[counterPost][j]->SetLineWidth(1);
2098 hpost_copy[counterPost]->SetMaximum(hpost_copy[counterPost]->GetMaximum()*1.2);
2099 hpost_copy[counterPost]->SetLineWidth(2);
2100 hpost_copy[counterPost]->SetLineColor(kBlack);
2103 FormatHistogram(hpost_copy[counterPost]);
2108 hpost_copy[counterPost]->GetXaxis()->SetLabelFont(133);
2109 hpost_copy[counterPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2111 hpost_copy[counterPost]->GetYaxis()->SetLabelFont(133);
2112 hpost_copy[counterPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2114 hpost_copy[counterPost]->Draw(
"HIST");
2115 for (
int j = 0; j < nCredibleIntervals; ++j){
2116 hpost_cl[counterPost][j]->Draw(
"HIST SAME");
2123 hpost_2D_copy[counter2DPost] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2124 Form(
"hpost_copy_%i_%i", ParamNumber[x], ParamNumber[y]));
2125 hpost_2D_cl[counter2DPost].resize(nCredibleRegions);
2127 for (
int k = 0; k < nCredibleRegions; ++k)
2129 hpost_2D_cl[counter2DPost][k] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2130 Form(
"hpost_copy_%i_%i_CL_%f", ParamNumber[x], ParamNumber[y], CredibleRegions[k]));
2133 hpost_2D_cl[counter2DPost][k]->SetLineColor(CredibleRegionColor[k]);
2134 hpost_2D_cl[counter2DPost][k]->SetLineWidth(2);
2135 hpost_2D_cl[counter2DPost][k]->SetLineStyle(CredibleRegionStyle[k]);
2138 FormatHistogram(hpost_2D_copy[counter2DPost]);
2143 hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelFont(133);
2144 hpost_2D_copy[counter2DPost]->GetXaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2146 hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelFont(133);
2147 hpost_2D_copy[counter2DPost]->GetYaxis()->SetLabelSize(.08*(a_y+b_y)*
Posterior->GetWh());
2149 hpost_2D_copy[counter2DPost]->Draw(
"COL");
2151 for (
int k = 0; k < nCredibleRegions; ++k){
2152 hpost_2D_cl[counter2DPost][k]->Draw(
"CONT3 SAME");
2157 if(y == (nParamPlot-1))
2160 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());
2163 TriangleText[counterText]->SetTextAlign(22);
2164 TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2165 TriangleText[counterText]->SetNDC(
true);
2166 TriangleText[counterText]->Draw();
2173 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());
2175 TriangleText[counterText]->SetTextAngle(90);
2178 TriangleText[counterText]->SetTextAlign(22);
2179 TriangleText[counterText]->SetTextSize(.08*(a_y+b_y));
2180 TriangleText[counterText]->SetNDC(
true);
2181 TriangleText[counterText]->Draw();
2190 auto legend = std::make_unique<TLegend>(0.60, 0.7, 0.9, 0.9);
2193 for (
int j = nCredibleIntervals-1; j >= 0; --j)
2195 if(CredibleInSigmas)
2196 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
2198 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f%% Credible Interval", CredibleRegions[j]*100),
"f");
2200 for (
int k = nCredibleRegions-1; k >= 0; --k)
2202 if(CredibleInSigmas)
2203 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f#sigma Credible Region", CredibleRegions[k]),
"l");
2205 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
2207 legend->Draw(
"SAME");
2220 for(
int i = 0; i < Npad; i++)
delete TrianglePad[i];
2236 Chain =
new TChain(
"posteriors",
"posteriors");
2245 TObjArray* brlis =
Chain->GetListOfBranches();
2257 Chain->SetBranchStatus(
"*",
false);
2264 TBranch* br =
static_cast<TBranch*
>(brlis->At(i));
2269 TString bname = br->GetName();
2272 bool rejected =
false;
2281 if(rejected)
continue;
2284 Chain->SetBranchStatus(bname.Data(),
true);
2286 if (bname.BeginsWith(
"ndd_"))
2292 else if (bname.BeginsWith(
"skd_joint_"))
2300 if (bname.BeginsWith(
"LogL_sample_")) {
2303 else if (bname.BeginsWith(
"LogL_systematic_")) {
2346 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);
2347 Gauss->SetLineWidth(2);
2348 Gauss->SetLineColor(kOrange-5);
2365 #pragma omp parallel for
2367 for (
int i = 0; i <
nDraw; ++i)
2378 for (
int j = 0; j <
nDraw; ++j) {
2392 for(
unsigned int j = 0; j <
ParamType.size(); j++)
2410 auto PreFitPlot = std::make_unique<TH1D>(
"Prefit",
"Prefit",
nDraw, 0,
nDraw);
2411 PreFitPlot->SetDirectory(
nullptr);
2412 for (
int i = 0; i < PreFitPlot->GetNbinsX() + 1; ++i) {
2413 PreFitPlot->SetBinContent(i+1, 0);
2414 PreFitPlot->SetBinError(i+1, 0);
2419 double CentralValueTemp, Central, Error;
2422 for (
int i = 0; i <
nDraw; ++i)
2431 if ( CentralValueTemp != 0) {
2432 Central =
ParamCentral[ParamEnum][ParamNo] / CentralValueTemp;
2433 Error =
ParamErrors[ParamEnum][ParamNo]/CentralValueTemp;
2435 Central = CentralValueTemp + 1.0;
2441 Central = CentralValueTemp;
2448 PreFitPlot->SetBinContent(i+1, Central);
2449 PreFitPlot->SetBinError(i+1, Error);
2450 PreFitPlot->GetXaxis()->SetBinLabel(i+1,
ParamNames[ParamEnum][ParamNo]);
2452 PreFitPlot->SetDirectory(
nullptr);
2454 PreFitPlot->SetFillStyle(1001);
2455 PreFitPlot->SetFillColor(kRed-3);
2456 PreFitPlot->SetMarkerStyle(21);
2457 PreFitPlot->SetMarkerSize(2.4);
2458 PreFitPlot->SetMarkerColor(kWhite);
2459 PreFitPlot->SetLineColor(PreFitPlot->GetFillColor());
2460 PreFitPlot->GetXaxis()->LabelsOption(
"v");
2490 TDirectory* CovarianceFolder = TempFile->Get<TDirectory>(
"CovarianceFolder");
2493 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2495 if (Config ==
nullptr) {
2504 bool InputNotFound =
false;
2506 CovPos[
kXSecPar] = GetFromManager<std::vector<std::string>>(Settings[
"General"][
"Systematics"][
"XsecCovFile"], {
"none"});
2510 InputNotFound =
true;
2514 if (XsecConfig ==
nullptr) {
2528 TMacro *
ReweightConfig = TempFile->Get<TMacro>(
"Reweight_Config");
2532 if (ReweightSettings[
"Weight"]) {
2535 MACH3LOG_INFO(
"Enabling reweighting with following Config");
2537 MACH3LOG_WARN(
"Found reweight config but without field ''Weight''");
2543 CovarianceFolder->Close();
2544 delete CovarianceFolder;
2556 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2558 if (Config ==
nullptr) {
2566 CovPos[
kNDPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovFile"],
"none"));
2569 MACH3LOG_WARN(
"Couldn't find NDCov (legacy) branch in output");
2572 CovNamePos[
kNDPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovName"],
"none");
2577 CovPos[
kFDDetPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovFile"],
"none"));
2580 MACH3LOG_WARN(
"Couldn't find FDCov (legacy) branch in output");
2583 CovNamePos[
kFDDetPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovName"],
"none");
2603 auto systematics = XSecFile[
"Systematics"];
2605 for (
auto it = systematics.begin(); it != systematics.end(); ++it, ++paramIndex )
2607 auto const ¶m = *it;
2609 std::string ParName = (param[
"Systematic"][
"Names"][
"FancyName"].as<std::string>());
2610 std::string Group = param[
"Systematic"][
"ParameterGroup"].as<std::string>();
2612 bool rejected =
false;
2617 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2626 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2631 if(rejected)
continue;
2634 ParamCentral[
kXSecPar].push_back(param[
"Systematic"][
"ParameterValues"][
"PreFitValue"].as<double>());
2636 ParamFlat[
kXSecPar].push_back(GetFromManager<bool>(param[
"Systematic"][
"FlatPrior"],
false));
2646 BranchNames.push_back(
"param_" + std::to_string(paramIndex));
2651 MACH3LOG_WARN(
"Couldn't find branch '{}', if you are not planning to draw posteriors this might be fine",
BranchNames.back());
2664 TMatrixDSym *NDdetMatrix = NDdetFile->Get<TMatrixDSym>(
CovNamePos[
kNDPar].c_str());
2665 TVectorD *NDdetNominal = NDdetFile->Get<TVectorD>(
"det_weights");
2666 TDirectory *BinningDirectory = NDdetFile->Get<TDirectory>(
"Binning");
2668 for (
int i = 0; i < NDdetNominal->GetNrows(); ++i)
2678 TIter next(BinningDirectory->GetListOfKeys());
2679 TKey *key =
nullptr;
2681 while ((key =
static_cast<TKey*
>(next())))
2683 std::string name = std::string(key->GetName());
2684 TH2Poly* RefPoly = BinningDirectory->Get<TH2Poly>((name).c_str());
2685 int size = RefPoly->GetNumberOfBins();
2704 for (
int i = 0; i < FDdetMatrix->GetNrows(); ++i)
2738 std::stringstream TempStream;
2739 TempStream <<
"step > " << Cuts;
2749 const unsigned int maxNsteps =
Chain->GetMaximum(
"step");
2774 for (
int i = 0; i <
nDraw; ++i)
2777 double Prior = 1.0, PriorError = 1.0;
2794 #pragma omp parallel for
2796 for (
int i = 0; i <
nDraw; ++i)
2798 for (
int j = 0; j <= i; ++j)
2802 hpost2D[i][j]->Fill(0.0, 0.0, 0.0);
2822 TDirectory *PolarDir =
OutputFile->mkdir(
"PolarDir");
2825 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2831 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Polar Plot", ParNames[k]);
2836 double Prior = 1.0, PriorError = 1.0;
2839 std::vector<double> x_val(
nBins);
2840 std::vector<double> y_val(
nBins);
2842 constexpr
double xmin = 0;
2843 constexpr
double xmax = 2*TMath::Pi();
2845 double Integral =
hpost[ParamNo]->Integral();
2846 for (Int_t ipt = 0; ipt <
nBins; ipt++)
2848 x_val[ipt] = ipt*(xmax-xmin)/
nBins+xmin;
2849 y_val[ipt] =
hpost[ParamNo]->GetBinContent(ipt+1)/Integral;
2852 auto PolarGraph = std::make_unique<TGraphPolar>(
nBins, x_val.data(), y_val.data());
2853 PolarGraph->SetLineWidth(2);
2854 PolarGraph->SetFillStyle(3001);
2855 PolarGraph->SetLineColor(kRed);
2856 PolarGraph->SetFillColor(kRed);
2857 PolarGraph->Draw(
"AFL");
2859 auto Text = std::make_unique<TText>(0.6, 0.1, Title);
2860 Text->SetTextSize(0.04);
2879 const std::vector<std::vector<double>>& Model1Bounds,
2880 const std::vector<std::vector<double>>& Model2Bounds,
2881 const std::vector<std::vector<std::string>>& ModelNames){
2886 if((ParNames.size() != Model1Bounds.size()) || (Model2Bounds.size() != Model1Bounds.size()) || (Model2Bounds.size() != ModelNames.size()))
2891 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2897 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Bayes Factor", ParNames[k]);
2901 const double M1_min = Model1Bounds[k][0];
2902 const double M2_min = Model2Bounds[k][0];
2903 const double M1_max = Model1Bounds[k][1];
2904 const double M2_max = Model2Bounds[k][1];
2906 long double IntegralMode1 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M1_min),
hpost[ParamNo]->FindFixBin(M1_max));
2907 long double IntegralMode2 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M2_min),
hpost[ParamNo]->FindFixBin(M2_max));
2909 double BayesFactor = 0.;
2910 std::string Name =
"";
2913 if(IntegralMode1 >= IntegralMode2)
2915 BayesFactor = IntegralMode1/IntegralMode2;
2916 Name =
"\\mathfrak{B}(" + ModelNames[k][0]+
"/" + ModelNames[k][1] +
") = " + std::to_string(BayesFactor);
2920 BayesFactor = IntegralMode2/IntegralMode1;
2921 Name =
"\\mathfrak{B}(" + ModelNames[k][1]+
"/" + ModelNames[k][0] +
") = " + std::to_string(BayesFactor);
2927 MACH3LOG_INFO(
"Following Jeffreys Scale = {}", JeffreysScale);
2928 MACH3LOG_INFO(
"Following Dunne-Kaboth Scale = {}", DunneKabothScale);
2936 const std::vector<double>& EvaluationPoint,
2937 const std::vector<std::vector<double>>& Bounds){
2939 if((ParNames.size() != EvaluationPoint.size()) || (Bounds.size() != EvaluationPoint.size()))
2948 TDirectory *SavageDickeyDir =
OutputFile->mkdir(
"SavageDickey");
2949 SavageDickeyDir->cd();
2951 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2957 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate SavageDickey", ParNames[k]);
2962 double Prior = 1.0, PriorError = 1.0;
2963 bool FlatPrior =
false;
2968 FlatPrior =
ParamFlat[ParType][ParamTemp];
2970 auto PosteriorHist = M3::Clone<TH1D>(
hpost[ParamNo], std::string(Title));
2973 std::unique_ptr<TH1D> PriorHist;
2977 int NBins = PosteriorHist->GetNbinsX();
2978 if(Bounds[k][0] > Bounds[k][1])
2983 PriorHist = std::make_unique<TH1D>(
"PriorHist", Title, NBins, Bounds[k][0], Bounds[k][1]);
2984 PriorHist->SetDirectory(
nullptr);
2985 double FlatProb = ( Bounds[k][1] - Bounds[k][0]) / NBins;
2986 for (
int g = 0; g < NBins + 1; ++g)
2988 PriorHist->SetBinContent(g+1, FlatProb);
2993 PriorHist = M3::Clone<TH1D>(PosteriorHist.get(),
"Prior");
2994 PriorHist->Reset(
"");
2995 PriorHist->Fill(0.0, 0.0);
2997 auto rand = std::make_unique<TRandom3>(0);
2999 for(
int g = 0; g < 1000000; ++g)
3001 PriorHist->Fill(rand->Gaus(Prior, PriorError));
3004 SavageDickeyPlot(PriorHist, PosteriorHist, std::string(Title), EvaluationPoint[k]);
3007 SavageDickeyDir->Close();
3008 delete SavageDickeyDir;
3016 std::unique_ptr<TH1D>& PosteriorHist,
3017 const std::string& Title,
3018 const double EvaluationPoint)
const {
3021 PriorHist->Scale(1./PriorHist->Integral(),
"width");
3022 PosteriorHist->Scale(1./PosteriorHist->Integral(),
"width");
3024 PriorHist->SetLineColor(kRed);
3025 PriorHist->SetMarkerColor(kRed);
3026 PriorHist->SetFillColorAlpha(kRed, 0.35);
3027 PriorHist->SetFillStyle(1001);
3028 PriorHist->GetXaxis()->SetTitle(Title.c_str());
3029 PriorHist->GetYaxis()->SetTitle(
"Posterior Probability");
3030 PriorHist->SetMaximum(PosteriorHist->GetMaximum()*1.5);
3031 PriorHist->GetYaxis()->SetLabelOffset(999);
3032 PriorHist->GetYaxis()->SetLabelSize(0);
3033 PriorHist->SetLineWidth(2);
3034 PriorHist->SetLineStyle(kSolid);
3036 PosteriorHist->SetLineColor(kBlue);
3037 PosteriorHist->SetMarkerColor(kBlue);
3038 PosteriorHist->SetFillColorAlpha(kBlue, 0.35);
3039 PosteriorHist->SetFillStyle(1001);
3041 PriorHist->Draw(
"hist");
3042 PosteriorHist->Draw(
"hist same");
3044 double ProbPrior = PriorHist->GetBinContent(PriorHist->FindBin(EvaluationPoint));
3046 if(ProbPrior < 0) ProbPrior = 0.00001;
3047 double ProbPosterior = PosteriorHist->GetBinContent(PosteriorHist->FindBin(EvaluationPoint));
3048 double SavageDickey = ProbPosterior/ProbPrior;
3052 auto PostPoint = std::make_unique<TGraph>(1);
3053 PostPoint->SetPoint(0, EvaluationPoint, ProbPosterior);
3054 PostPoint->SetMarkerStyle(20);
3055 PostPoint->SetMarkerSize(1);
3056 PostPoint->Draw(
"P same");
3058 auto PriorPoint = std::make_unique<TGraph>(1);
3059 PriorPoint->SetPoint(0, EvaluationPoint, ProbPrior);
3060 PriorPoint->SetMarkerStyle(20);
3061 PriorPoint->SetMarkerSize(1);
3062 PriorPoint->Draw(
"P same");
3064 auto legend = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
3066 legend->AddEntry(PriorHist.get(),
"Prior",
"l");
3067 legend->AddEntry(PosteriorHist.get(),
"Posterior",
"l");
3068 legend->AddEntry(PostPoint.get(), Form(
"SavageDickey = %.2f, (%s)", SavageDickey, DunneKabothScale.c_str()),
"");
3069 legend->Draw(
"same");
3078 const std::vector<double>& NewCentral,
3079 const std::vector<double>& NewError) {
3083 if( (Names.size() != NewCentral.size()) || (NewCentral.size() != NewError.size()))
3085 MACH3LOG_ERROR(
"Size of passed vectors doesn't match in {}", __func__);
3088 std::vector<int> Param;
3089 std::vector<double> OldCentral;
3090 std::vector<double> OldError;
3091 std::vector<bool> FlatPrior;
3094 for(
unsigned int k = 0; k < Names.size(); ++k)
3100 MACH3LOG_WARN(
"Couldn't find param {}. Can't reweight Prior", Names[k]);
3105 double Prior = 1.0, PriorError = 1.0;
3108 Param.push_back(ParamNo);
3109 OldCentral.push_back(Prior);
3110 OldError.push_back(PriorError);
3115 FlatPrior.push_back(
ParamFlat[ParType][ParamTemp]);
3117 std::vector<double> ParameterPos(Names.size());
3119 std::string InputFile =
MCMCFile+
".root";
3120 std::string OutputFilename =
MCMCFile +
"_reweighted.root";
3123 int ret = system((
"cp " + InputFile +
" " + OutputFilename).c_str());
3125 MACH3LOG_WARN(
"Error: system call to copy file failed with code {}", ret);
3127 TFile *OutputChain =
M3::Open(OutputFilename,
"UPDATE", __FILE__, __LINE__);
3129 TTree *post = OutputChain->Get<TTree>(
"posteriors");
3133 post->SetBranchStatus(
"*",
false);
3135 for (
unsigned int j = 0; j < Names.size(); ++j) {
3136 post->SetBranchStatus(
BranchNames[Param[j]].Data(),
true);
3137 post->SetBranchAddress(
BranchNames[Param[j]].Data(), &ParameterPos[j]);
3139 TBranch *bpt = post->Branch(
"Weight", &Weight,
"Weight/D");
3140 post->SetBranchStatus(
"Weight",
true);
3149 for (
unsigned int j = 0; j < Names.size(); ++j)
3151 double new_chi = (ParameterPos[j] - NewCentral[j])/NewError[j];
3152 double new_prior = std::exp(-0.5 * new_chi * new_chi);
3154 double old_chi = -1;
3155 double old_prior = -1;
3159 old_chi = (ParameterPos[j] - OldCentral[j])/OldError[j];
3160 old_prior = std::exp(-0.5 * old_chi * old_chi);
3162 Weight *= new_prior/old_prior;
3166 post->SetBranchStatus(
"*",
true);
3168 post->Write(
"posteriors", TObject::kOverwrite);
3171 std::ostringstream yaml_stream;
3172 yaml_stream <<
"Weight:\n";
3173 yaml_stream <<
" ReweightDim: 1\n";
3174 yaml_stream <<
" ReweightType: \"Gaussian\"\n";
3175 yaml_stream <<
" ReweightVar: [";
3176 for (
size_t k = 0; k < Names.size(); ++k) {
3177 yaml_stream <<
"\"" << Names[k] <<
"\"";
3178 if (k < Names.size() - 1) yaml_stream <<
", ";
3180 yaml_stream <<
"]\n";
3181 yaml_stream <<
" ReweightPrior: [";
3182 for (
size_t k = 0; k < Names.size(); ++k) {
3183 yaml_stream <<
"[" << NewCentral[k] <<
", " << NewError[k] <<
"]";
3184 if (k < Names.size() - 1) yaml_stream <<
", ";
3186 yaml_stream <<
"]\n";
3187 std::string yaml_string = yaml_stream.str();
3189 TMacro ConfigSave =
YAMLtoTMacro(root,
"Reweight_Config");
3192 OutputChain->Close();
3202 const std::vector<double>& Error,
3203 const bool& SaveBranch)
const {
3207 if( (Names.size() != Error.size()))
3209 MACH3LOG_ERROR(
"Size of passed vectors doesn't match in {}", __func__);
3212 std::vector<int> Param;
3215 for(
unsigned int k = 0; k < Names.size(); ++k)
3221 MACH3LOG_WARN(
"Couldn't find param {}. Can't Smear", Names[k]);
3226 double Prior = 1.0, PriorError = 1.0;
3229 Param.push_back(ParamNo);
3231 std::string InputFile =
MCMCFile+
".root";
3232 std::string OutputFilename =
MCMCFile +
"_smeared.root";
3235 int ret = system((
"cp " + InputFile +
" " + OutputFilename).c_str());
3237 MACH3LOG_WARN(
"Error: system call to copy file failed with code {}", ret);
3239 TFile *OutputChain =
M3::Open(OutputFilename,
"UPDATE", __FILE__, __LINE__);
3241 TTree *post = OutputChain->Get<TTree>(
"posteriors");
3242 TTree *treeNew = post->CloneTree(0);
3244 std::vector<double> NewParameter(Names.size());
3245 for(
size_t i = 0; i < Param.size(); i++) {
3246 post->SetBranchAddress(
BranchNames[Param[i]], &NewParameter[i]);
3249 std::vector<double> Unsmeared_Parameter;
3251 Unsmeared_Parameter.resize(Param.size());
3252 for(
size_t i = 0; i < Param.size(); i++) {
3253 treeNew->Branch((
BranchNames[Param[i]] +
"_unsmeared"), &Unsmeared_Parameter[i]);
3257 auto rand = std::make_unique<TRandom3>(0);
3258 Long64_t AllEntries = post->GetEntries();
3259 for (Long64_t i = 0; i < AllEntries; ++i) {
3264 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3265 Unsmeared_Parameter[iPar] = NewParameter[iPar];
3269 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3270 NewParameter[iPar] = NewParameter[iPar] + rand->Gaus(0, Error[iPar]);
3277 treeNew->Write(
"posteriors", TObject::kOverwrite);
3280 std::ostringstream yaml_stream;
3281 yaml_stream <<
"Smearing:\n";
3282 for (
size_t k = 0; k < Names.size(); ++k) {
3283 yaml_stream <<
" " << Names[k] <<
": [" << Error[k] <<
", " <<
"Gauss" <<
"]\n";
3285 std::string yaml_string = yaml_stream.str();
3287 TMacro ConfigSave =
YAMLtoTMacro(root,
"Smearing_Config");
3290 OutputChain->Close();
3297 const std::vector<int>& NIntervals) {
3302 for(
unsigned int k = 0; k < Names.size(); ++k)
3308 MACH3LOG_WARN(
"Couldn't find param {}. Can't reweight Prior", Names[k]);
3312 const int IntervalsSize =
nSteps/NIntervals[k];
3314 std::string filename = Names[k] +
".gif";
3315 std::ifstream f(filename);
3318 int ret = system(fmt::format(
"rm {}", filename).c_str());
3320 MACH3LOG_WARN(
"Error: system call to delete {} failed with code {}", filename, ret);
3325 for(
int i = NIntervals[k]-1; i >= 0; --i)
3330 hpost[ParamNo]->GetXaxis()->GetXmin(),
hpost[ParamNo]->GetXaxis()->GetXmax());
3331 EvePlot->SetMinimum(0);
3332 EvePlot->GetYaxis()->SetTitle(
"PDF");
3333 EvePlot->GetYaxis()->SetNoExponent(
false);
3336 std::string CutPosterior1D =
"step > " + std::to_string(i*IntervalsSize+IntervalsSize);
3345 CutPosterior1D =
"(" + CutPosterior1D +
")*(" +
ReweightName +
")";
3348 std::string TextTitle =
"Steps = 0 - "+std::to_string(Counter*IntervalsSize+IntervalsSize);
3352 EvePlot->SetLineWidth(2);
3353 EvePlot->SetLineColor(kBlue-1);
3354 EvePlot->SetTitle(Names[k].c_str());
3355 EvePlot->GetXaxis()->SetTitle(EvePlot->GetTitle());
3356 EvePlot->GetYaxis()->SetLabelOffset(1000);
3359 EvePlot->Scale(1. / EvePlot->Integral());
3360 EvePlot->Draw(
"HIST");
3362 TText text(0.3, 0.8, TextTitle.c_str());
3363 text.SetTextFont (43);
3364 text.SetTextSize (40);
3368 if(i == 0)
Posterior->Print((Names[k] +
".gif++20").c_str());
3369 else Posterior->Print((Names[k] +
".gif+20").c_str());
3414 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC");
3415 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
3420 MACH3LOG_ERROR(
"please use SetnBatches to set other value fore example 20");
3426 for (
int j = 0; j <
nDraw; ++j) {
3428 for (
int i = 0; i <
nEntries; ++i) {
3437 for (
int i = 0; i <
nEntries; ++i) {
3444 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3456 Chain->SetBranchStatus(
"*",
false);
3459 const int countwidth =
nEntries/10;
3466 for (
int i = 0; i <
nBatches; ++i) {
3469 for (
int j = 0; j <
nDraw; ++j) {
3473 std::vector<double> ParStepBranch(
nDraw);
3474 std::vector<double> SampleValuesBranch(
SampleName_v.size());
3475 std::vector<double> SystValuesBranch(
SystName_v.size());
3476 unsigned int StepNumberBranch = 0;
3477 double AccProbValuesBranch = 0;
3479 for (
int j = 0; j <
nDraw; ++j) {
3489 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3494 Chain->SetBranchStatus(
"step",
true);
3495 Chain->SetBranchAddress(
"step", &StepNumberBranch);
3497 Chain->SetBranchStatus(
"accProb",
true);
3498 Chain->SetBranchAddress(
"accProb", &AccProbValuesBranch);
3502 for (
int i = 0; i <
nEntries; ++i) {
3506 if (i % countwidth == 0)
3510 for (
int j = 0; j <
nDraw; ++j) {
3511 ParStep[j][i] = ParStepBranch[j];
3518 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3527 int BatchNumber = -1;
3529 for (
int j = 0; j <
nBatches; ++j) {
3530 if (i < (j+1)*BatchLength) {
3536 for (
int j = 0; j <
nDraw; ++j) {
3544 MACH3LOG_INFO(
"Took {:.2f}s to finish caching statistic for Diag MCMC with {} steps", clock.RealTime(),
nEntries);
3548 #pragma omp parallel for
3550 for (
int i = 0; i <
nDraw; ++i) {
3551 for (
int j = 0; j <
nBatches; ++j) {
3569 std::vector<std::unique_ptr<TH1D>> TraceParamPlots(
nDraw);
3570 std::vector<std::unique_ptr<TH1D>> TraceSamplePlots(
SampleName_v.size());
3571 std::vector<std::unique_ptr<TH1D>> TraceSystsPlots(
SystName_v.size());
3574 for (
int j = 0; j <
nDraw; ++j) {
3576 double Prior = 1.0, PriorError = 1.0;
3579 std::string HistName = Form(
"%s_%s_Trace", Title.Data(),
BranchNames[j].Data());
3580 TraceParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3581 TraceParamPlots[j]->SetDirectory(
nullptr);
3582 TraceParamPlots[j]->GetXaxis()->SetTitle(
"Step");
3583 TraceParamPlots[j]->GetYaxis()->SetTitle(
"Parameter Variation");
3588 TraceSamplePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3589 TraceSamplePlots[j]->SetDirectory(
nullptr);
3590 TraceSamplePlots[j]->GetXaxis()->SetTitle(
"Step");
3591 TraceSamplePlots[j]->GetYaxis()->SetTitle(
"Sample -logL");
3594 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3596 TraceSystsPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3597 TraceSystsPlots[j]->SetDirectory(
nullptr);
3598 TraceSystsPlots[j]->GetXaxis()->SetTitle(
"Step");
3599 TraceSystsPlots[j]->GetYaxis()->SetTitle(
"Systematic -logL");
3606 #pragma omp parallel for
3608 for (
int i = 0; i <
nEntries; ++i) {
3610 for (
int j = 0; j <
nDraw; ++j) {
3611 TraceParamPlots[j]->SetBinContent(i,
ParStep[j][i]);
3614 TraceSamplePlots[j]->SetBinContent(i,
SampleValues[i][j]);
3616 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3617 TraceSystsPlots[j]->SetBinContent(i,
SystValues[i][j]);
3622 TDirectory *TraceDir =
OutputFile->mkdir(
"Trace");
3624 for (
int j = 0; j <
nDraw; ++j) {
3626 auto Fitter = std::make_unique<TF1>(
"Fitter",
"[0]",
nEntries/2,
nEntries);
3627 Fitter->SetLineColor(kRed);
3628 TraceParamPlots[j]->Fit(
"Fitter",
"Rq");
3629 TraceParamPlots[j]->Write();
3632 TDirectory *LLDir =
OutputFile->mkdir(
"LogL");
3635 TraceSamplePlots[j]->Write();
3640 for (
size_t j = 0; j <
SystName_v.size(); ++j) {
3641 TraceSystsPlots[j]->Write();
3656 std::vector <double> ParamSums(
nDraw,0);
3659 #pragma omp parallel for
3661 for (
int j = 0; j <
nDraw; ++j) {
3662 for (
int i = 0; i <
nEntries; ++i) {
3663 ParamSums[j] +=
ParStep[j][i];
3668 #pragma omp parallel for
3670 for (
int i = 0; i <
nDraw; ++i) {
3686 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3690 TDirectory* AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3691 std::vector<std::unique_ptr<TH1D>> LagKPlots(
nDraw);
3692 std::vector<std::vector<double>> LagL(
nDraw);
3695 std::vector<double> ACFFT(
nEntries, 0.0);
3696 std::vector<double> ParVals(
nEntries, 0.0);
3697 std::vector<double> ParValsFFTR(
nEntries, 0.0);
3698 std::vector<double> ParValsFFTI(
nEntries, 0.0);
3699 std::vector<double> ParValsFFTSquare(
nEntries, 0.0);
3700 std::vector<double> ParValsComplex(
nEntries, 0.0);
3705 TVirtualFFT* fftf = TVirtualFFT::FFT(1, &
nEntries,
"C2CFORWARD");
3706 TVirtualFFT* fftb = TVirtualFFT::FFT(1, &
nEntries,
"C2CBACKWARD");
3709 for (
int j = 0; j <
nDraw; ++j) {
3711 LagL[j].resize(nLags);
3712 for (
int i = 0; i <
nEntries; ++i) {
3713 ParVals[i] =
ParStep[j][i]-ParamSums[j];
3714 ParValsComplex[i] = 0.;
3718 fftf->SetPointsComplex(ParVals.data(), ParValsComplex.data());
3720 fftf->GetPointsComplex(ParValsFFTR.data(), ParValsFFTI.data());
3723 for (
int i = 0; i <
nEntries; ++i) {
3724 ParValsFFTSquare[i] = ParValsFFTR[i]*ParValsFFTR[i] + ParValsFFTI[i]*ParValsFFTI[i];
3728 fftb->SetPointsComplex(ParValsFFTSquare.data(), ParValsComplex.data());
3730 fftb->GetPointsComplex(ACFFT.data(), ParValsComplex.data());
3733 double normAC = ACFFT[0];
3734 for (
int i = 0; i <
nEntries; ++i) {
3740 double Prior = 1.0, PriorError = 1.0;
3742 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3745 LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3746 LagKPlots[j]->SetDirectory(
nullptr);
3747 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3748 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3751 for (
int k = 0; k < nLags; ++k) {
3752 LagL[j][k] = ACFFT[k];
3753 LagKPlots[j]->SetBinContent(k, ACFFT[k]);
3758 LagKPlots[j]->Write();
3764 AutoCorrDir->Close();
3770 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3782 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3785 std::vector<std::vector<double>> DenomSum(
nDraw);
3786 std::vector<std::vector<double>> NumeratorSum(
nDraw);
3787 std::vector<std::vector<double>> LagL(
nDraw);
3789 for (
int j = 0; j <
nDraw; ++j) {
3790 DenomSum[j].resize(nLags);
3791 NumeratorSum[j].resize(nLags);
3792 LagL[j].resize(nLags);
3794 std::vector<std::unique_ptr<TH1D>> LagKPlots(
nDraw);
3796 for (
int j = 0; j <
nDraw; ++j)
3799 for (
int k = 0; k < nLags; ++k) {
3800 NumeratorSum[j][k] = 0.0;
3801 DenomSum[j][k] = 0.0;
3807 double Prior = 1.0, PriorError = 1.0;
3810 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3811 LagKPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3812 LagKPlots[j]->SetDirectory(
nullptr);
3813 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3814 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3822 #pragma omp parallel for collapse(2)
3824 for (
int j = 0; j <
nDraw; ++j) {
3825 for (
int k = 0; k < nLags; ++k) {
3827 for (
int i = 0; i <
nEntries; ++i) {
3828 const double Diff =
ParStep[j][i]-ParamSums[j];
3832 const double LagTerm =
ParStep[j][i+k]-ParamSums[j];
3833 const double Product = Diff*LagTerm;
3834 NumeratorSum[j][k] += Product;
3837 const double Denom = Diff*Diff;
3838 DenomSum[j][k] += Denom;
3845 float* ParStep_cpu =
nullptr;
3846 float* NumeratorSum_cpu =
nullptr;
3847 float* ParamSums_cpu =
nullptr;
3848 float* DenomSum_cpu =
nullptr;
3851 PrepareGPU_AutoCorr(nLags, ParamSums, ParStep_cpu, NumeratorSum_cpu, ParamSums_cpu, DenomSum_cpu);
3854 GPUProcessor->RunGPU_AutoCorr(NumeratorSum_cpu,
3858 #pragma omp parallel for collapse(2)
3861 for (
int j = 0; j <
nDraw; ++j)
3863 for (
int k = 0; k < nLags; ++k)
3865 const int temp_index = j*nLags+k;
3866 NumeratorSum[j][k] = NumeratorSum_cpu[temp_index];
3867 DenomSum[j][k] = DenomSum_cpu[temp_index];
3871 if(NumeratorSum_cpu)
delete[] NumeratorSum_cpu;
3872 if(DenomSum_cpu)
delete[] DenomSum_cpu;
3873 if(ParStep_cpu)
delete[] ParStep_cpu;
3874 if(ParamSums_cpu)
delete[] ParamSums_cpu;
3877 GPUProcessor->CleanupGPU_AutoCorr();
3883 TDirectory *AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3885 for (
int j = 0; j <
nDraw; ++j) {
3886 for (
int k = 0; k < nLags; ++k) {
3887 LagL[j][k] = NumeratorSum[j][k]/DenomSum[j][k];
3888 LagKPlots[j]->SetBinContent(k, NumeratorSum[j][k]/DenomSum[j][k]);
3891 LagKPlots[j]->Write();
3897 AutoCorrDir->Close();
3903 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3909 void MCMCProcessor::PrepareGPU_AutoCorr(
const int nLags,
const std::vector<double>& ParamSums,
float*& ParStep_cpu,
3910 float*& NumeratorSum_cpu,
float*& ParamSums_cpu,
float*& DenomSum_cpu) {
3914 NumeratorSum_cpu =
new float[
nDraw*nLags];
3915 DenomSum_cpu =
new float[
nDraw*nLags];
3916 ParamSums_cpu =
new float[
nDraw];
3920 #pragma omp parallel
3925 #pragma omp for nowait
3927 for (
int i = 0; i <
nDraw; ++i)
3930 ParamSums_cpu[i] = ParamSums[i];
3934 #pragma omp for collapse(2) nowait
3936 for (
int j = 0; j <
nDraw; ++j)
3938 for (
int k = 0; k < nLags; ++k)
3940 const int temp = j*nLags+k;
3941 NumeratorSum_cpu[temp] = 0.0;
3942 DenomSum_cpu[temp] = 0.0;
3947 #pragma omp for collapse(2)
3949 for (
int j = 0; j <
nDraw; ++j)
3954 ParStep_cpu[temp] =
ParStep[j][i];
3963 GPUProcessor->InitGPU_AutoCorr(
nEntries,
3969 GPUProcessor->CopyToGPU_AutoCorr(ParStep_cpu,
3983 if(LagL.size() == 0)
3990 TVectorD* SamplingEfficiency =
new TVectorD(
nDraw);
3991 std::vector<double> TempDenominator(
nDraw);
3993 constexpr
int Nhists = 5;
3994 constexpr
double Thresholds[Nhists + 1] = {1, 0.02, 0.005, 0.001, 0.0001, 0.0};
3995 constexpr Color_t ESSColours[Nhists] = {kGreen, kGreen + 2, kYellow, kOrange, kRed};
3998 std::vector<std::unique_ptr<TH1D>> EffectiveSampleSizeHist(Nhists);
3999 for(
int i = 0; i < Nhists; ++i)
4001 EffectiveSampleSizeHist[i] =
4002 std::make_unique<TH1D>(Form(
"EffectiveSampleSizeHist_%i", i), Form(
"EffectiveSampleSizeHist_%i", i),
nDraw, 0,
nDraw);
4003 EffectiveSampleSizeHist[i]->SetDirectory(
nullptr);
4004 EffectiveSampleSizeHist[i]->GetYaxis()->SetTitle(
"N_{eff}/N");
4005 EffectiveSampleSizeHist[i]->SetFillColor(ESSColours[i]);
4006 EffectiveSampleSizeHist[i]->SetLineColor(ESSColours[i]);
4007 EffectiveSampleSizeHist[i]->Sumw2();
4008 for (
int j = 0; j <
nDraw; ++j)
4011 double Prior = 1.0, PriorError = 1.0;
4013 EffectiveSampleSizeHist[i]->GetXaxis()->SetBinLabel(j+1, Title.Data());
4018 #pragma omp parallel for
4021 for (
int j = 0; j <
nDraw; ++j)
4025 TempDenominator[j] = 0.;
4027 for (
int k = 0; k < nLags; ++k)
4029 TempDenominator[j] += LagL[j][k];
4031 TempDenominator[j] = 1+2*TempDenominator[j];
4032 (*EffectiveSampleSize)(j) =
double(
nEntries)/TempDenominator[j];
4034 (*SamplingEfficiency)(j) = 100 * 1/TempDenominator[j];
4036 for(
int i = 0; i < Nhists; ++i)
4038 EffectiveSampleSizeHist[i]->SetBinContent(j+1, 0);
4039 EffectiveSampleSizeHist[i]->SetBinError(j+1, 0);
4042 if(Thresholds[i] >= TempEntry && TempEntry > Thresholds[i+1])
4045 EffectiveSampleSizeHist[i]->SetBinContent(j+1, TempEntry);
4054 SamplingEfficiency->Write(
"SamplingEfficiency");
4056 EffectiveSampleSizeHist[0]->SetTitle(
"Effective Sample Size");
4057 EffectiveSampleSizeHist[0]->Draw();
4058 for(
int i = 1; i < Nhists; ++i)
4060 EffectiveSampleSizeHist[i]->Draw(
"SAME");
4063 auto leg = std::make_unique<TLegend>(0.2, 0.7, 0.6, 0.95);
4065 for(
int i = 0; i < Nhists; ++i)
4067 leg->AddEntry(EffectiveSampleSizeHist[i].get(), Form(
"%.4f >= N_{eff}/N > %.4f", Thresholds[i], Thresholds[i+1]),
"f");
4068 } leg->Draw(
"SAME");
4070 Posterior->Write(
"EffectiveSampleSizeCanvas");
4074 delete SamplingEfficiency;
4084 std::vector<std::unique_ptr<TH1D>> BatchedParamPlots(
nDraw);
4085 for (
int j = 0; j <
nDraw; ++j) {
4087 double Prior = 1.0, PriorError = 1.0;
4091 std::string HistName = Form(
"%s_%s_batch", Title.Data(),
BranchNames[j].Data());
4092 BatchedParamPlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(),
nBatches, 0,
nBatches);
4093 BatchedParamPlots[j]->SetDirectory(
nullptr);
4097 #pragma omp parallel for
4099 for (
int j = 0; j <
nDraw; ++j) {
4100 for (
int i = 0; i <
nBatches; ++i) {
4104 std::stringstream ss;
4105 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4106 BatchedParamPlots[j]->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4110 TDirectory *BatchDir =
OutputFile->mkdir(
"Batched_means");
4112 for (
int j = 0; j <
nDraw; ++j) {
4113 auto Fitter = std::make_unique<TF1>(
"Fitter",
"[0]", 0,
nBatches);
4114 Fitter->SetLineColor(kRed);
4115 BatchedParamPlots[j]->Fit(
"Fitter",
"Rq");
4116 BatchedParamPlots[j]->Write();
4123 for (
int i = 0; i <
nBatches; ++i) {
4140 MACH3LOG_ERROR(
"BatchedAverages haven't been initialises or have been deleted something is wrong");
4146 TVectorD* BatchedVariance =
new TVectorD(
nDraw);
4148 TVectorD* C_Test_Statistics =
new TVectorD(
nDraw);
4150 std::vector<double> OverallBatchMean(
nDraw);
4151 std::vector<double> C_Rho_Nominator(
nDraw);
4152 std::vector<double> C_Rho_Denominator(
nDraw);
4153 std::vector<double> C_Nominator(
nDraw);
4154 std::vector<double> C_Denominator(
nDraw);
4158 #pragma omp parallel
4165 for (
int j = 0; j <
nDraw; ++j)
4167 OverallBatchMean[j] = 0.0;
4168 C_Rho_Nominator[j] = 0.0;
4169 C_Rho_Denominator[j] = 0.0;
4170 C_Nominator[j] = 0.0;
4171 C_Denominator[j] = 0.0;
4173 (*BatchedVariance)(j) = 0.0;
4174 (*C_Test_Statistics)(j) = 0.0;
4183 #pragma omp for nowait
4186 for (
int j = 0; j <
nDraw; ++j)
4192 (*BatchedVariance)(j) = (BatchLength/(
nBatches-1))* (*BatchedVariance)(j);
4197 #pragma omp for nowait
4199 for (
int j = 0; j <
nDraw; ++j)
4207 C_Denominator[j] = 2*C_Denominator[j];
4214 for (
int j = 0; j <
nDraw; ++j)
4216 for (
int i = 0; i <
nBatches-1; ++i)
4231 for (
int j = 0; j <
nDraw; ++j)
4233 (*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]);
4241 BatchedVariance->Write(
"BatchedMeansVariance");
4242 C_Test_Statistics->Write(
"C_Test_Statistics");
4245 delete BatchedVariance;
4246 delete C_Test_Statistics;
4257 const double TopMargin =
Posterior->GetTopMargin();
4258 const int OptTitle = gStyle->GetOptTitle();
4261 gStyle->SetOptTitle(1);
4266 const int N_Coeffs = std::min(10000,
nEntries);
4267 const int start = -(N_Coeffs/2-1);
4268 const int end = N_Coeffs/2-1;
4269 const int v_size = end - start;
4275 std::vector<std::vector<float>> k_j(nPrams, std::vector<float>(v_size, 0.0));
4276 std::vector<std::vector<float>> P_j(nPrams, std::vector<float>(v_size, 0.0));
4279 if (_N % 2 != 0) _N -= 1;
4282 const double two_pi_over_N = 2 * TMath::Pi() /
static_cast<double>(_N);
4286 #pragma omp parallel for collapse(2)
4289 for (
int j = 0; j < nPrams; ++j)
4291 for (
int jj = start; jj < end; ++jj)
4293 std::complex<M3::float_t> a_j = 0.0;
4294 const double two_pi_over_N_jj = two_pi_over_N * jj;
4295 for (
int n = 0; n < _N; ++n)
4298 std::complex<M3::float_t> exp_temp(0, two_pi_over_N_jj * n);
4299 a_j +=
ParStep[j][n] * std::exp(exp_temp);
4301 a_j /= std::sqrt(
float(_N));
4302 const int _c = jj - start;
4304 k_j[j][_c] = two_pi_over_N_jj;
4306 P_j[j][_c] = std::norm(a_j);
4310 TDirectory *PowerDir =
OutputFile->mkdir(
"PowerSpectrum");
4313 TVectorD* PowerSpectrumStepSize =
new TVectorD(nPrams);
4314 for (
int j = 0; j < nPrams; ++j)
4316 auto plot = std::make_unique<TGraph>(v_size, k_j[j].data(), P_j[j].data());
4319 double Prior = 1.0, PriorError = 1.0;
4322 std::string name = Form(
"Power Spectrum of %s;k;P(k)", Title.Data());
4324 plot->SetTitle(name.c_str());
4325 name = Form(
"%s_power_spectrum", Title.Data());
4326 plot->SetName(name.c_str());
4327 plot->SetMarkerStyle(7);
4330 auto func = std::make_unique<TF1>(
"power_template",
"[0]*( ([1] / x)^[2] / (([1] / x)^[2] +1) )", 0.0, 1.0);
4332 func->SetParameter(0, 10.0);
4334 func->SetParameter(1, 0.1);
4336 func->SetParameter(2, 2.0);
4339 func->SetParLimits(0, 0.0, 100.0);
4340 func->SetParLimits(1, 0.001, 1.0);
4341 func->SetParLimits(2, 0.0, 5.0);
4343 plot->Fit(
"power_template",
"Rq");
4352 (*PowerSpectrumStepSize)(j) = std::sqrt(func->GetParameter(0)/float(v_size*0.5));
4355 PowerSpectrumStepSize->Write(
"PowerSpectrumStepSize");
4356 delete PowerSpectrumStepSize;
4361 MACH3LOG_INFO(
"Making Power Spectrum took {:.2f}s", clock.RealTime());
4364 gStyle->SetOptTitle(OptTitle);
4375 std::vector<double> MeanUp(
nDraw, 0.0);
4376 std::vector<double> SpectralVarianceUp(
nDraw, 0.0);
4377 std::vector<int> DenomCounterUp(
nDraw, 0);
4378 const double Threshold = 0.5 *
nSteps;
4381 constexpr
double LowerThreshold = 0;
4382 constexpr
double UpperThreshold = 1.0;
4384 constexpr
int NChecks = 100;
4385 constexpr
double Division = (UpperThreshold - LowerThreshold)/NChecks;
4387 std::vector<std::unique_ptr<TH1D>> GewekePlots(
nDraw);
4388 for (
int j = 0; j <
nDraw; ++j)
4391 double Prior = 1.0, PriorError = 1.0;
4393 std::string HistName = Form(
"%s_%s_Geweke", Title.Data(),
BranchNames[j].Data());
4394 GewekePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), NChecks, 0.0, 100 * UpperThreshold);
4395 GewekePlots[j]->SetDirectory(
nullptr);
4396 GewekePlots[j]->GetXaxis()->SetTitle(
"Burn-In (%)");
4397 GewekePlots[j]->GetYaxis()->SetTitle(
"Geweke T score");
4402 #pragma omp parallel
4409 for (
int j = 0; j <
nDraw; ++j)
4416 DenomCounterUp[j]++;
4419 MeanUp[j] = MeanUp[j]/DenomCounterUp[j];
4424 #pragma omp for collapse(2)
4426 for (
int j = 0; j <
nDraw; ++j)
4432 SpectralVarianceUp[j] += (
ParStep[j][i] - MeanUp[j])*(
ParStep[j][i] - MeanUp[j]);
4441 for (
int k = 1; k < NChecks+1; ++k)
4444 std::vector<double> MeanDown(
nDraw, 0.0);
4445 std::vector<double> SpectralVarianceDown(
nDraw, 0.0);
4446 std::vector<int> DenomCounterDown(
nDraw, 0);
4448 const unsigned int ThresholsCheck = Division*k*
nSteps;
4450 for (
int j = 0; j <
nDraw; ++j)
4457 DenomCounterDown[j]++;
4460 MeanDown[j] = MeanDown[j]/DenomCounterDown[j];
4463 for (
int j = 0; j <
nDraw; ++j)
4469 SpectralVarianceDown[j] += (
ParStep[j][i] - MeanDown[j])*(
ParStep[j][i] - MeanDown[j]);
4474 for (
int j = 0; j <
nDraw; ++j)
4476 double T_score = std::fabs((MeanDown[j] - MeanUp[j])/std::sqrt(SpectralVarianceDown[j]/DenomCounterDown[j] + SpectralVarianceUp[j]/DenomCounterUp[j]));
4477 GewekePlots[j]->SetBinContent(k, T_score);
4486 TDirectory *GewekeDir =
OutputFile->mkdir(
"Geweke");
4487 for (
int j = 0; j <
nDraw; ++j)
4490 GewekePlots[j]->Write();
4492 for (
int i = 0; i <
nDraw; ++i) {
4511 auto AcceptanceProbPlot = std::make_unique<TH1D>(
"AcceptanceProbability",
"Acceptance Probability",
nEntries, 0,
nEntries);
4512 AcceptanceProbPlot->SetDirectory(
nullptr);
4513 AcceptanceProbPlot->GetXaxis()->SetTitle(
"Step");
4514 AcceptanceProbPlot->GetYaxis()->SetTitle(
"Acceptance Probability");
4516 auto BatchedAcceptanceProblot = std::make_unique<TH1D>(
"AcceptanceProbability_Batch",
"AcceptanceProbability_Batch",
nBatches, 0,
nBatches);
4517 BatchedAcceptanceProblot->SetDirectory(
nullptr);
4518 BatchedAcceptanceProblot->GetYaxis()->SetTitle(
"Acceptance Probability");
4520 for (
int i = 0; i <
nBatches; ++i) {
4524 std::stringstream ss;
4525 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4526 BatchedAcceptanceProblot->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4530 #pragma omp parallel for
4532 for (
int i = 0; i <
nEntries; ++i) {
4537 TDirectory *probDir =
OutputFile->mkdir(
"AccProb");
4540 AcceptanceProbPlot->Write();
4541 BatchedAcceptanceProblot->Write();
4554 if (CredibleIntervals.size() != CredibleIntervalsColours.size()) {
4555 MACH3LOG_ERROR(
"size of CredibleIntervals is not equal to size of CredibleIntervalsColours");
4558 if (CredibleIntervals.size() > 1) {
4559 for (
unsigned int i = 1; i < CredibleIntervals.size(); i++) {
4560 if (CredibleIntervals[i] > CredibleIntervals[i - 1]) {
4562 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleIntervals[i], CredibleIntervals[i - 1]);
4572 const std::vector<Style_t>& CredibleRegionStyle,
4573 const std::vector<Color_t>& CredibleRegionColor) {
4575 if ((CredibleRegions.size() != CredibleRegionStyle.size()) || (CredibleRegionStyle.size() != CredibleRegionColor.size())) {
4576 MACH3LOG_ERROR(
"size of CredibleRegions is not equal to size of CredibleRegionStyle or CredibleRegionColor");
4579 for (
unsigned int i = 1; i < CredibleRegions.size(); i++) {
4580 if (CredibleRegions[i] > CredibleRegions[i - 1]) {
4582 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleRegions[i], CredibleRegions[i - 1]);
4593 auto caseInsensitiveCompare = [](
const std::string& a,
const std::string& b) {
4594 return std::equal(a.begin(), a.end(), b.begin(), b.end(),
4595 [](
char c1,
char c2) { return std::tolower(c1) == std::tolower(c2); });
4599 if (caseInsensitiveCompare(groupName, name)) {
4610 std::unordered_map<std::string, int> paramCounts;
4611 std::vector<std::string> orderedKeys;
4614 if (paramCounts[param] == 0) {
4615 orderedKeys.push_back(param);
4617 paramCounts[param]++;
4620 MACH3LOG_INFO(
"************************************************");
4625 for (
const std::string& key : orderedKeys) {
4630 MACH3LOG_INFO(
"************************************************");
4636 return std::vector<double>{Canv->GetTopMargin(), Canv->GetBottomMargin(),
4637 Canv->GetLeftMargin(), Canv->GetRightMargin()};
4647 if (margins.size() != 4) {
4651 Canv->SetTopMargin(margins[0]);
4652 Canv->SetBottomMargin(margins[1]);
4653 Canv->SetLeftMargin(margins[2]);
4654 Canv->SetRightMargin(margins[3]);
4660 Line->SetLineColor(Colour);
4661 Line->SetLineWidth(Width);
4662 Line->SetLineStyle(
Style);
4668 Legend->SetTextSize(size);
4669 Legend->SetLineColor(0);
4670 Legend->SetLineStyle(0);
4671 Legend->SetFillColor(0);
4672 Legend->SetFillStyle(0);
4673 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.
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
constexpr ELineStyle Style[NVars]
double * EffectiveSampleSize
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,...
std::string GetJeffreysScale(const double BayesFactor)
KS: Following H. Jeffreys .
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...
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 STRINGtoYAML(const std::string &yaml_string)
Function to convert a YAML string to a YAML node.
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.
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 systematic.
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,.
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.
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 sample PDF object.
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 ReweightPrior(const std::vector< std::string > &Names, const std::vector< double > &NewCentral, const std::vector< double > &NewError)
Reweight Prior by giving new central value and new error.
std::string ReweightName
Name of branch used for chain reweighting.
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::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.
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.