14 #pragma GCC diagnostic ignored "-Wfloat-conversion"
18 Chain(nullptr), StepCut(
""), MadePostfit(false) {
95 ParStep_cpu =
nullptr;
96 NumeratorSum_cpu =
nullptr;
97 ParamSums_cpu =
nullptr;
98 DenomSum_cpu =
nullptr;
100 ParStep_gpu =
nullptr;
101 NumeratorSum_gpu =
nullptr;
102 ParamSums_gpu =
nullptr;
103 DenomSum_gpu =
nullptr;
129 for (
int i = 0; i <
nDraw; ++i)
135 for (
int i = 0; i <
nDraw; ++i)
137 for (
int j = 0; j <
nDraw; ++j)
163 void MCMCProcessor::GetPostfit(TVectorD *&Central_PDF, TVectorD *&Errors_PDF, TVectorD *&Central_G, TVectorD *&Errors_G, TVectorD *&Peak_Values) {
184 const int ParamTypeSize = int(
ParamType.size());
186 for (
int i = 0; i < ParamTypeSize; ++i) {
188 (*PDF_Central)(ParamNumber) = (*
Means)(i);
189 (*PDF_Errors)(ParamNumber) = (*
Errors)(i);
190 (*Peak_Values)(ParamNumber) = (*
Means_HPD)(i);
200 Cov =
static_cast<TMatrixDSym*
>(
Covariance->Clone());
201 Corr =
static_cast<TMatrixDSym*
>(
Correlation->Clone());
208 auto rand = std::make_unique<TRandom3>(0);
209 const int uniform = int(rand->Uniform(0, 10000));
211 Posterior = std::make_unique<TCanvas>((
"Posterior" + std::to_string(uniform)).c_str(), (
"Posterior" + std::to_string(uniform)).c_str(), 0, 0, 1024, 1024);
213 TCandle::SetScaledViolin(
false);
216 gStyle->SetOptStat(0);
217 gStyle->SetOptTitle(0);
227 gErrorIgnoreLevel = kWarning;
250 int originalErrorLevel = gErrorIgnoreLevel;
251 gErrorIgnoreLevel = kFatal;
254 TDirectory *PostDir =
OutputFile->mkdir(
"Post");
255 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_1d_hists");
258 std::string CutPosterior1D =
"";
261 }
else CutPosterior1D =
StepCut;
265 CutPosterior1D =
"(" + CutPosterior1D +
")*(" +
ReweightName +
")";
270 for (
int i = 0; i <
nDraw; ++i)
272 if (i % (
nDraw/5) == 0) {
277 double Prior = 1.0, PriorError = 1.0;
281 if (Edges.find(Title.Data()) != Edges.end()) {
282 mini = Edges.at(Title.Data()).first;
283 maxi = Edges.at(Title.Data()).second;
288 MACH3LOG_DEBUG(
"Initialising histogram for {} with binning {:.4f}, {:.4f}", Title, mini, maxi);
291 hpost[i]->SetMinimum(0);
292 hpost[i]->GetYaxis()->SetTitle(
"Steps");
293 hpost[i]->GetYaxis()->SetNoExponent(
false);
301 (*Central_Value)(i) = Prior;
303 double Mean, Err, Err_p, Err_m;
309 (*Means_Gauss)(i) =
Mean;
310 (*Errors_Gauss)(i) = Err;
313 (*Means_HPD)(i) =
Mean;
314 (*Errors_HPD)(i) = Err;
315 (*Errors_HPD_Positive)(i) = Err_p;
316 (*Errors_HPD_Negative)(i) = Err_m;
320 (*Correlation)(i,i) = 1.0;
326 hpost[i]->SetLineWidth(2);
327 hpost[i]->SetLineColor(kBlue-1);
329 hpost[i]->SetTitle(Title);
330 hpost[i]->GetXaxis()->SetTitle(
hpost[i]->GetTitle());
333 auto Asimov = std::make_unique<TLine>(Prior,
hpost[i]->GetMinimum(), Prior,
hpost[i]->GetMaximum());
336 auto leg = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
338 leg->AddEntry(
hpost[i], Form(
"#splitline{PDF}{#mu = %.2f, #sigma = %.2f}",
hpost[i]->GetMean(),
hpost[i]->GetRMS()),
"l");
339 leg->AddEntry(
Gauss.get(), Form(
"#splitline{Gauss}{#mu = %.2f, #sigma = %.2f}",
Gauss->GetParameter(1),
Gauss->GetParameter(2)),
"l");
341 leg->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
350 MACH3LOG_WARN(
"Found fixed parameter: {} ({}), moving on", Title, i);
353 (*Means_HPD)(i) = Prior;
354 (*Errors_HPD)(i) = PriorError;
355 (*Errors_HPD_Positive)(i) = PriorError;
356 (*Errors_HPD_Negative)(i) = PriorError;
358 (*Means_Gauss)(i) = Prior;
359 (*Errors_Gauss)(i) = PriorError;
362 (*Errors)(i) = PriorError;
372 Asimov->Draw(
"same");
381 hpost[i]->SetName(Title);
382 hpost[i]->SetTitle(Title);
388 TTree *SettingsBranch =
new TTree(
"Settings",
"Settings");
402 SettingsBranch->Fill();
403 SettingsBranch->Write();
404 delete SettingsBranch;
406 TDirectory *Names =
OutputFile->mkdir(
"Names");
409 TObjString((*it)).Write();
416 Means->Write(
"PDF_Means");
417 Errors->Write(
"PDF_Error");
427 PostHistDir->Close();
431 gErrorIgnoreLevel = originalErrorLevel;
443 prefit->GetXaxis()->SetTitle(
"");
447 std::string CutPosterior1D =
"";
455 TH1D *paramPlot =
new TH1D(
"paramPlot",
"paramPlot",
nDraw, 0,
nDraw);
456 paramPlot->SetName(
"mach3params");
457 paramPlot->SetTitle(CutPosterior1D.c_str());
458 paramPlot->SetFillStyle(3001);
459 paramPlot->SetFillColor(kBlue-1);
460 paramPlot->SetMarkerColor(paramPlot->GetFillColor());
461 paramPlot->SetMarkerStyle(20);
462 paramPlot->SetLineColor(paramPlot->GetFillColor());
463 paramPlot->SetMarkerSize(prefit->GetMarkerSize());
464 paramPlot->GetXaxis()->SetTitle(
"");
467 TH1D *paramPlot_Gauss =
static_cast<TH1D*
>(paramPlot->Clone());
468 paramPlot_Gauss->SetMarkerColor(kOrange-5);
469 paramPlot_Gauss->SetMarkerStyle(23);
470 paramPlot_Gauss->SetLineWidth(2);
471 paramPlot_Gauss->SetMarkerSize((prefit->GetMarkerSize())*0.75);
472 paramPlot_Gauss->SetFillColor(paramPlot_Gauss->GetMarkerColor());
473 paramPlot_Gauss->SetFillStyle(3244);
474 paramPlot_Gauss->SetLineColor(paramPlot_Gauss->GetMarkerColor());
475 paramPlot_Gauss->GetXaxis()->SetTitle(
"");
478 TH1D *paramPlot_HPD =
static_cast<TH1D*
>(paramPlot->Clone());
479 paramPlot_HPD->SetMarkerColor(kBlack);
480 paramPlot_HPD->SetMarkerStyle(25);
481 paramPlot_HPD->SetLineWidth(2);
482 paramPlot_HPD->SetMarkerSize((prefit->GetMarkerSize())*0.5);
483 paramPlot_HPD->SetFillColor(0);
484 paramPlot_HPD->SetFillStyle(0);
485 paramPlot_HPD->SetLineColor(paramPlot_HPD->GetMarkerColor());
486 paramPlot_HPD->GetXaxis()->SetTitle(
"");
489 for (
int i = 0; i <
nDraw; ++i)
497 double CentralValueTemp = 0;
498 double Central, Central_gauss, Central_HPD;
499 double Err, Err_Gauss, Err_HPD;
505 if ( CentralValueTemp != 0)
507 Central = (*Means)(i) / CentralValueTemp;
508 Err = (*Errors)(i) / CentralValueTemp;
510 Central_gauss = (*Means_Gauss)(i) / CentralValueTemp;
511 Err_Gauss = (*Errors_Gauss)(i) / CentralValueTemp;
513 Central_HPD = (*Means_HPD)(i) / CentralValueTemp;
514 Err_HPD = (*Errors_HPD)(i) / CentralValueTemp;
517 Central = 1+(*Means)(i);
520 Central_gauss = 1+(*Means_Gauss)(i);
521 Err_Gauss = (*Errors_Gauss)(i);
523 Central_HPD = 1+(*Means_HPD)(i) ;
524 Err_HPD = (*Errors_HPD)(i);
530 Central = (*Means)(i);
533 Central_gauss = (*Means_Gauss)(i);
534 Err_Gauss = (*Errors_Gauss)(i);
536 Central_HPD = (*Means_HPD)(i) ;
537 Err_HPD = (*Errors_HPD)(i);
540 paramPlot->SetBinContent(i+1, Central);
541 paramPlot->SetBinError(i+1, Err);
543 paramPlot_Gauss->SetBinContent(i+1, Central_gauss);
544 paramPlot_Gauss->SetBinError(i+1, Err_Gauss);
546 paramPlot_HPD->SetBinContent(i+1, Central_HPD);
547 paramPlot_HPD->SetBinError(i+1, Err_HPD);
549 paramPlot->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
550 paramPlot_Gauss->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
551 paramPlot_HPD->GetXaxis()->SetBinLabel(i+1, prefit->GetXaxis()->GetBinLabel(i+1));
553 prefit->GetXaxis()->LabelsOption(
"v");
554 paramPlot->GetXaxis()->LabelsOption(
"v");\
555 paramPlot_Gauss->GetXaxis()->LabelsOption(
"v");
556 paramPlot_HPD->GetXaxis()->LabelsOption(
"v");
559 auto CompLeg = std::make_unique<TLegend>(0.33, 0.73, 0.76, 0.95);
560 CompLeg->AddEntry(prefit.get(),
"Prefit",
"fp");
561 CompLeg->AddEntry(paramPlot,
"Postfit PDF",
"fp");
562 CompLeg->AddEntry(paramPlot_Gauss,
"Postfit Gauss",
"fp");
563 CompLeg->AddEntry(paramPlot_HPD,
"Postfit HPD",
"lfep");
564 CompLeg->SetFillColor(0);
565 CompLeg->SetFillStyle(0);
566 CompLeg->SetLineWidth(0);
567 CompLeg->SetLineStyle(0);
568 CompLeg->SetBorderSize(0);
576 prefit->Write(
"param_xsec_prefit");
577 paramPlot->Write(
"param_xsec");
578 paramPlot_Gauss->Write(
"param_xsec_gaus");
579 paramPlot_HPD->Write(
"param_xsec_HPD");
584 else prefit->GetYaxis()->SetTitle(
"Parameter Value");
585 prefit->GetYaxis()->SetRangeUser(-2.5, 2.5);
589 paramPlot->Draw(
"e2, same");
590 paramPlot_Gauss->Draw(
"e2, same");
591 paramPlot_HPD->Draw(
"e1, same");
592 CompLeg->Draw(
"same");
596 constexpr
int IntervalsSize = 20;
597 const int NIntervals =
nDraw/IntervalsSize;
599 for (
int i = 0; i < NIntervals+1; ++i)
601 int RangeMin = i*IntervalsSize;
602 int RangeMax =RangeMin + IntervalsSize;
603 if(i == NIntervals+1) {
604 RangeMin = i*IntervalsSize;
607 if(RangeMin >=
nDraw)
break;
609 double ymin = std::numeric_limits<double>::max();
610 double ymax = -std::numeric_limits<double>::max();
611 for (
int b = RangeMin; b <= RangeMax; ++b) {
614 double val = prefit->GetBinContent(b);
615 double err = prefit->GetBinError(b);
616 ymin = std::min(ymin, val - err);
617 ymax = std::max(ymax, val + err);
621 double val = paramPlot_HPD->GetBinContent(b);
622 double err = paramPlot_HPD->GetBinError(b);
623 ymin = std::min(ymin, val - err);
624 ymax = std::max(ymax, val + err);
628 double margin = 0.1 * (ymax - ymin);
629 prefit->GetYaxis()->SetRangeUser(ymin - margin, ymax + margin);
631 prefit->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
632 paramPlot->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
633 paramPlot_Gauss->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
634 paramPlot_HPD->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
638 paramPlot->Draw(
"e2, same");
639 paramPlot_Gauss->Draw(
"e2, same");
640 paramPlot_HPD->Draw(
"e1, same");
641 CompLeg->Draw(
"same");
649 int NDbinCounter = Start;
656 prefit->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
657 prefit->GetYaxis()->SetRangeUser(0.6, 1.4);
658 prefit->GetXaxis()->SetRangeUser(Start, NDbinCounter);
660 paramPlot->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
661 paramPlot->GetYaxis()->SetRangeUser(0.6, 1.4);
662 paramPlot->GetXaxis()->SetRangeUser(Start, NDbinCounter);
663 paramPlot->SetTitle(CutPosterior1D.c_str());
665 paramPlot_Gauss->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
666 paramPlot_Gauss->GetYaxis()->SetRangeUser(0.6, 1.4);
667 paramPlot_Gauss->GetXaxis()->SetRangeUser(Start, NDbinCounter);
668 paramPlot_Gauss->SetTitle(CutPosterior1D.c_str());
670 paramPlot_HPD->GetYaxis()->SetTitle((
"Variation for "+NDname).c_str());
671 paramPlot_HPD->GetYaxis()->SetRangeUser(0.6, 1.4);
672 paramPlot_HPD->GetXaxis()->SetRangeUser(Start, NDbinCounter);
673 paramPlot_HPD->SetTitle(CutPosterior1D.c_str());
675 prefit->Write((
"param_"+NDname+
"_prefit").c_str());
676 paramPlot->Write((
"param_"+NDname).c_str());
677 paramPlot_Gauss->Write((
"param_"+NDname+
"_gaus").c_str());
678 paramPlot_HPD->Write((
"param_"+NDname+
"_HPD").c_str());
681 paramPlot->Draw(
"e2, same");
682 paramPlot_Gauss->Draw(
"e1, same");
683 paramPlot_HPD->Draw(
"e1, same");
684 CompLeg->Draw(
"same");
685 Posterior->Write((
"param_"+NDname+
"_canv").c_str());
692 delete paramPlot_Gauss;
693 delete paramPlot_HPD;
702 const std::vector<Color_t>& CredibleIntervalsColours,
703 const bool CredibleInSigmas) {
708 const double LeftMargin =
Posterior->GetLeftMargin();
713 const int nCredible = int(CredibleIntervals.size());
714 std::vector<std::unique_ptr<TH1D>> hpost_copy(
nDraw);
715 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(
nDraw);
718 for (
int i = 0; i <
nDraw; ++i)
720 hpost_copy[i] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i", i));
721 hpost_cl[i].resize(nCredible);
722 for (
int j = 0; j < nCredible; ++j)
724 hpost_cl[i][j] = M3::Clone<TH1D>(
hpost[i], Form(
"hpost_copy_%i_CL_%f", i, CredibleIntervals[j]));
727 hpost_cl[i][j]->Reset(
"");
728 hpost_cl[i][j]->Fill(0.0, 0.0);
733 #pragma omp parallel for
735 for (
int i = 0; i <
nDraw; ++i)
738 hpost_copy[i]->Scale(1. / hpost_copy[i]->Integral());
739 for (
int j = 0; j < nCredible; ++j)
742 hpost_cl[i][j]->Scale(1. / hpost_cl[i][j]->Integral());
745 hpost_cl[i][j]->SetFillColor(CredibleIntervalsColours[j]);
746 hpost_cl[i][j]->SetLineWidth(1);
748 hpost_copy[i]->GetYaxis()->SetTitleOffset(1.8);
749 hpost_copy[i]->SetLineWidth(1);
750 hpost_copy[i]->SetMaximum(hpost_copy[i]->GetMaximum()*1.2);
751 hpost_copy[i]->SetLineWidth(2);
752 hpost_copy[i]->SetLineColor(kBlack);
753 hpost_copy[i]->GetYaxis()->SetTitle(
"Posterior Probability");
757 TDirectory *CredibleDir =
OutputFile->mkdir(
"Credible");
759 for (
int i = 0; i <
nDraw; ++i)
765 double Prior = 1.0, PriorError = 1.0;
768 auto Asimov = std::make_unique<TLine>(Prior, hpost_copy[i]->GetMinimum(), Prior, hpost_copy[i]->GetMaximum());
771 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
773 hpost_copy[i]->Draw(
"HIST");
775 for (
int j = 0; j < nCredible; ++j)
776 hpost_cl[i][j]->Draw(
"HIST SAME");
777 for (
int j = nCredible-1; j >= 0; --j)
780 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
782 legend->AddEntry(hpost_cl[i][j].get(), Form(
"%.0f%% Credible Interval", CredibleIntervals[j]*100),
"f");
784 legend->AddEntry(Asimov.get(), Form(
"#splitline{Prior}{x = %.2f , #sigma = %.2f}", Prior, PriorError),
"l");
785 legend->Draw(
"SAME");
786 Asimov->Draw(
"SAME");
797 CredibleDir->Close();
816 double tempVal = 0.0;
818 double maxi_y = -9999;
819 double mini_y = +9999;
820 for (
int i = 0; i <
nDraw; ++i)
826 maxi_y = std::max(maxi_y, max_val);
827 mini_y = std::min(mini_y, min_val);
830 const int vBins = (maxi_y-mini_y)*25;
831 hviolin = std::make_unique<TH2D>(
"hviolin",
"hviolin",
nDraw, 0,
nDraw, vBins, mini_y, maxi_y);
832 hviolin->SetDirectory(
nullptr);
834 constexpr
int PriorFactor = 4;
835 hviolin_prior = std::make_unique<TH2D>(
"hviolin_prior",
"hviolin_prior",
nDraw, 0,
nDraw, PriorFactor*vBins, PriorFactor*mini_y, PriorFactor*maxi_y);
838 auto rand = std::make_unique<TRandom3>(0);
839 std::vector<double> PriorVec(
nDraw);
840 std::vector<double> PriorErrorVec(
nDraw);
841 std::vector<bool> PriorFlatVec(
nDraw);
843 for (
int x = 0; x <
nDraw; ++x)
846 double Prior, PriorError;
850 hviolin->GetXaxis()->SetBinLabel(x+1, Title);
853 PriorErrorVec[x] = PriorError;
857 PriorFlatVec[x] =
ParamFlat[ParType][ParamTemp];
865 #pragma omp parallel for
867 for (
int x = 0; x <
nDraw; ++x)
889 const double Entry = rand->Gaus(PriorVec[x], PriorErrorVec[x]);
899 constexpr
int IntervalsSize = 10;
900 const int NIntervals =
nDraw/IntervalsSize;
902 hviolin->GetYaxis()->SetTitle(
"Parameter Value");
903 hviolin->GetXaxis()->SetTitle();
904 hviolin->GetXaxis()->LabelsOption(
"v");
921 hviolin->SetMarkerColor(kBlue);
922 hviolin->SetFillColorAlpha(kBlue, 0.35);
926 const double BottomMargin =
Posterior->GetBottomMargin();
930 hviolin->Write(
"param_violin");
933 hviolin->GetYaxis()->SetRangeUser(-1, +2);
935 for (
int i = 0; i < NIntervals+1; ++i)
937 int RangeMin = i*IntervalsSize;
938 int RangeMax =RangeMin + IntervalsSize;
939 if(i == NIntervals+1) {
940 RangeMin = i*IntervalsSize;
943 if(RangeMin >=
nDraw)
break;
945 hviolin->GetXaxis()->SetRangeUser(RangeMin, RangeMax);
950 hviolin->Draw(
"violinX(03100300) SAME");
954 Posterior->SetBottomMargin(BottomMargin);
963 bool HaveMadeDiagonal =
false;
967 for (
int i = 0; i <
nDraw; ++i) {
969 HaveMadeDiagonal =
false;
970 MACH3LOG_INFO(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
973 HaveMadeDiagonal =
true;
977 if (HaveMadeDiagonal ==
false) {
981 TDirectory *PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
983 gStyle->SetPalette(55);
985 for (
int i = 0; i <
nDraw; ++i)
987 if (i % (
nDraw/5) == 0)
990 TString Title_i =
"";
991 double Prior_i, PriorError;
996 for (
int j = 0; j <= i; ++j) {
998 if (j == i)
continue;
1002 (*Covariance)(i,j) = 0.0;
1004 (*Correlation)(i,j) = 0.0;
1009 TString Title_j =
"";
1010 double Prior_j, PriorError_j;
1019 auto hpost_2D = std::make_unique<TH2D>(DrawMe, DrawMe,
1020 nBins,
hpost[i]->GetXaxis()->GetXmin(),
hpost[i]->GetXaxis()->GetXmax(),
1021 nBins,
hpost[j]->GetXaxis()->GetXmin(),
hpost[j]->GetXaxis()->GetXmax());
1022 hpost_2D->SetMinimum(0);
1023 hpost_2D->GetXaxis()->SetTitle(Title_i);
1024 hpost_2D->GetYaxis()->SetTitle(Title_j);
1025 hpost_2D->GetZaxis()->SetTitle(
"Steps");
1027 std::string SelectionStr =
StepCut;
1032 Chain->Project(DrawMe, DrawMe, SelectionStr.c_str());
1036 (*Covariance)(i,j) = hpost_2D->GetCovariance();
1039 (*Correlation)(i,j) = hpost_2D->GetCorrelationFactor();
1050 hpost_2D->Draw(
"colz");
1051 Posterior->SetName(hpost_2D->GetName());
1052 Posterior->SetTitle(hpost_2D->GetTitle());
1063 PostHistDir->Close();
1081 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC ");
1082 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
1095 for (
int i = 0; i <
nDraw; ++i)
1108 Chain->SetBranchStatus(
"*",
false);
1109 unsigned int stepBranch = 0;
1110 double* ParValBranch =
new double[
nDraw]();
1112 for (
int i = 0; i <
nDraw; ++i)
1117 Chain->SetBranchStatus(
"step",
true);
1118 Chain->SetBranchAddress(
"step", &stepBranch);
1120 double ReweightWeight = 1.;
1128 const Long64_t countwidth =
nEntries/10;
1132 for (Long64_t j = 0; j <
nEntries; ++j)
1134 if (j % countwidth == 0) {
1142 for (
int i = 0; i <
nDraw; ++i) {
1143 ParStep[i][j] = ParValBranch[i];
1150 delete[] ParValBranch;
1153 Chain->SetBranchStatus(
"*",
true);
1156 double tempVal = 0.0;
1157 std::vector<double> Min_Chain(
nDraw);
1158 std::vector<double> Max_Chain(
nDraw);
1159 for (
int i = 0; i <
nDraw; ++i)
1167 size_t nHistograms =
nDraw * (
nDraw + 1) / 2;
1169 MACH3LOG_INFO(
"Allocating {:.2f} MB for {} 2D Posteriors (each {}x{} bins)",
1172 for (
int i = 0; i <
nDraw; ++i)
1174 TString Title_i =
"";
1175 double Prior_i, PriorError_i;
1178 for (
int j = 0; j <= i; ++j)
1180 TString Title_j =
"";
1181 double Prior_j, PriorError_j;
1185 hpost2D[i][j] =
new TH2D((Title_i +
"_" + Title_j).Data(), (Title_i +
"_" + Title_j).Data(),
1186 nBins,
hpost[i]->GetXaxis()->GetXmin(),
hpost[i]->GetXaxis()->GetXmax(),
1187 nBins,
hpost[j]->GetXaxis()->GetXmin(),
hpost[j]->GetXaxis()->GetXmax());
1189 hpost2D[i][j]->GetXaxis()->SetTitle(Title_i);
1190 hpost2D[i][j]->GetYaxis()->SetTitle(Title_j);
1191 hpost2D[i][j]->GetZaxis()->SetTitle(
"Steps");
1206 bool HaveMadeDiagonal =
false;
1209 for (
int i = 0; i <
nDraw; ++i) {
1211 HaveMadeDiagonal =
false;
1212 MACH3LOG_WARN(
"Have not run diagonal elements in covariance, will do so now by calling MakePostfit()");
1215 HaveMadeDiagonal =
true;
1221 TDirectory *PostHistDir =
nullptr;
1226 PostHistDir =
OutputFile->mkdir(
"Post_2d_hists");
1232 gStyle->SetPalette(55);
1235 #pragma omp parallel for
1237 for (
int i = 0; i <
nDraw; ++i)
1239 for (
int j = 0; j <= i; ++j)
1242 if (j == i)
continue;
1246 (*Covariance)(i,j) = 0.0;
1248 (*Correlation)(i,j) = 0.0;
1271 (*Correlation)(i,j) =
hpost2D[i][j]->GetCorrelationFactor();
1282 for (
int i = 0; i <
nDraw; ++i)
1284 for (
int j = 0; j <= i; ++j)
1287 if (j == i)
continue;
1305 PostHistDir->Close();
1319 const int DefaultUpperCut =
UpperCut;
1329 const int IntervalsSize =
nSteps/NIntervals;
1335 std::unique_ptr<TH1D> SubOptimality = std::make_unique<TH1D>(
"Suboptimality",
"Suboptimality", NIntervals, MinStep, MaxStep);
1336 SubOptimality->GetXaxis()->SetTitle(
"Step");
1337 SubOptimality->GetYaxis()->SetTitle(
"Suboptimality");
1338 SubOptimality->SetLineWidth(2);
1339 SubOptimality->SetLineColor(kBlue);
1341 for(
int i = 0; i < NIntervals; ++i)
1353 TVectorD eigen_values;
1354 eigen_values.ResizeTo(eigen.GetEigenValues());
1355 eigen_values = eigen.GetEigenValues();
1358 std::vector<double> EigenValues(eigen_values.GetNrows());
1359 for(
unsigned int j = 0; j < EigenValues.size(); j++)
1361 EigenValues[j] = eigen_values(j);
1364 SubOptimality->SetBinContent(i+1, SubOptimalityValue);
1367 MACH3LOG_INFO(
"Making Suboptimality took {:.2f}s to finish for {} steps", clock.RealTime(),
nEntries);
1373 SubOptimality->Draw(
"l");
1374 Posterior->SetName(SubOptimality->GetName());
1375 Posterior->SetTitle(SubOptimality->GetTitle());
1387 const double RightMargin =
Posterior->GetRightMargin();
1392 hCov->GetZaxis()->SetTitle(
"Covariance");
1395 hCovSq->GetZaxis()->SetTitle(
"Covariance");
1398 hCorr->GetZaxis()->SetTitle(
"Correlation");
1399 hCorr->SetMinimum(-1);
1400 hCorr->SetMaximum(1);
1401 hCov->GetXaxis()->SetLabelSize(0.015);
1402 hCov->GetYaxis()->SetLabelSize(0.015);
1403 hCovSq->GetXaxis()->SetLabelSize(0.015);
1404 hCovSq->GetYaxis()->SetLabelSize(0.015);
1405 hCorr->GetXaxis()->SetLabelSize(0.015);
1406 hCorr->GetYaxis()->SetLabelSize(0.015);
1409 for (
int i = 0; i <
nDraw; ++i)
1411 TString titlex =
"";
1415 hCov->GetXaxis()->SetBinLabel(i+1, titlex);
1416 hCovSq->GetXaxis()->SetBinLabel(i+1, titlex);
1417 hCorr->GetXaxis()->SetBinLabel(i+1, titlex);
1419 for (
int j = 0; j <
nDraw; ++j)
1422 const double cov = (*Covariance)(i,j);
1423 const double corr = (*Correlation)(i,j);
1425 hCov->SetBinContent(i+1, j+1, cov);
1426 hCovSq->SetBinContent(i+1, j+1, ((cov > 0) - (cov < 0))*std::sqrt(std::fabs(cov)));
1427 hCorr->SetBinContent(i+1, j+1, corr);
1429 TString titley =
"";
1430 double nom_j, err_j;
1433 hCov->GetYaxis()->SetBinLabel(j+1, titley);
1434 hCovSq->GetYaxis()->SetBinLabel(j+1, titley);
1435 hCorr->GetYaxis()->SetBinLabel(j+1, titley);
1440 gStyle->SetOptStat(0);
1443 constexpr
int NRGBs = 5;
1444 TColor::InitializeColors();
1445 Double_t stops[NRGBs] = { 0.00, 0.25, 0.50, 0.75, 1.00 };
1446 Double_t red[NRGBs] = { 0.00, 0.25, 1.00, 1.00, 0.50 };
1447 Double_t green[NRGBs] = { 0.00, 0.25, 1.00, 0.25, 0.00 };
1448 Double_t blue[NRGBs] = { 0.50, 1.00, 1.00, 0.25, 0.00 };
1449 TColor::CreateGradientColorTable(5, stops, red, green, blue, 255);
1450 gStyle->SetNumberContours(255);
1458 else hCov->Draw(
"colz");
1464 else hCorr->Draw(
"colz");
1467 hCov->Write(
"Covariance_plot");
1468 hCovSq->Write(
"Covariance_sq_plot");
1469 hCorr->Write(
"Correlation_plot");
1483 MACH3LOG_ERROR(
"Using Legacy Parameters i.e. not one from Parameter Handler Generic, this will not work");
1486 std::vector<double> MeanArray(
nDraw);
1487 std::vector<double> ErrorArray(
nDraw);
1488 std::vector<std::vector<double>> CorrelationMatrix(
nDraw, std::vector<double>(
nDraw, 0.0));
1490 TVectorD* means_vec;
1491 TVectorD* errors_vec;
1493 if (MeansMethod ==
"Arithmetic") {
1496 }
else if (MeansMethod ==
"Gaussian") {
1499 }
else if (MeansMethod ==
"HPD") {
1503 MACH3LOG_ERROR(
"Unknown means method: {}, should be either 'Arithmetic', 'Gaussian', or 'HPD'.", MeansMethod);
1508 for (
int i = 0; i <
nDraw; i++)
1510 MeanArray[i] = (*means_vec)(i);
1511 ErrorArray[i] = (*errors_vec)(i);
1512 for (
int j = 0; j <= i; j++)
1514 CorrelationMatrix[i][j] = (*Correlation)(i,j);
1515 if(i != j) CorrelationMatrix[j][i] = (*Correlation)(i,j);
1534 const double RightMargin =
Posterior->GetRightMargin();
1536 auto MatrixCopy =
M3::Clone(CorrMatrix.get());
1538 std::vector<std::string> GroupName;
1539 std::vector<int> GroupStart;
1540 std::vector<int> GroupEnd;
1543 for (
int iPar = 0; iPar <
nDraw; ++iPar)
1545 std::string GroupNameCurr;
1550 GroupNameCurr =
"Other";
1554 GroupName.push_back(GroupNameCurr);
1555 GroupStart.push_back(0);
1556 }
else if(GroupName.back() != GroupNameCurr ){
1557 GroupName.push_back(GroupNameCurr);
1558 GroupEnd.push_back(iPar);
1559 GroupStart.push_back(iPar);
1562 MatrixCopy->GetXaxis()->SetBinLabel(iPar+1,
"");
1563 MatrixCopy->GetYaxis()->SetBinLabel(iPar+1,
"");
1565 GroupEnd.push_back(
nDraw);
1567 for(
size_t iPar = 0; iPar < GroupName.size(); iPar++) {
1568 MACH3LOG_INFO(
"Group name {} from {} to {}", GroupName[iPar], GroupStart[iPar], GroupEnd[iPar]);
1572 MatrixCopy->Draw(
"colz");
1574 std::vector<std::unique_ptr<TLine>> groupLines;
1576 int nBinsX = MatrixCopy->GetNbinsX();
1577 int nBinsY = MatrixCopy->GetNbinsY();
1580 double xMin = MatrixCopy->GetXaxis()->GetBinLowEdge(1);
1581 double xMax = MatrixCopy->GetXaxis()->GetBinUpEdge(nBinsX);
1582 double yMin = MatrixCopy->GetYaxis()->GetBinLowEdge(1);
1583 double yMax = MatrixCopy->GetYaxis()->GetBinUpEdge(nBinsY);
1585 for (
size_t g = 1; g < GroupStart.size(); ++g) {
1586 double posX = MatrixCopy->GetXaxis()->GetBinLowEdge(GroupStart[g] + 1);
1587 double posY = MatrixCopy->GetYaxis()->GetBinLowEdge(GroupStart[g] + 1);
1590 auto vLine = std::make_unique<TLine>(posX, yMin, posX, yMax);
1591 vLine->SetLineColor(kBlack);
1592 vLine->SetLineWidth(2);
1594 groupLines.push_back(std::move(vLine));
1597 auto hLine = std::make_unique<TLine>(xMin, posY, xMax, posY);
1598 hLine->SetLineColor(kBlack);
1599 hLine->SetLineWidth(2);
1601 groupLines.push_back(std::move(hLine));
1604 std::vector<std::unique_ptr<TText>> groupLabels(GroupName.size() * 2);
1605 double yOffsetBelow = 0.05 * (yMax - yMin);
1606 double xOffsetRight = 0.02 * (xMax - xMin);
1608 for (
size_t g = 0; g < GroupName.size(); ++g) {
1609 int startBin = GroupStart[g] + 1;
1610 int endBin = GroupEnd[g];
1612 double xStart = MatrixCopy->GetXaxis()->GetBinLowEdge(startBin);
1613 double xEnd = MatrixCopy->GetXaxis()->GetBinUpEdge(endBin);
1614 double xMid = 0.5 * (xStart + xEnd);
1616 double yStart = MatrixCopy->GetYaxis()->GetBinLowEdge(startBin);
1617 double yEnd = MatrixCopy->GetYaxis()->GetBinUpEdge(endBin);
1618 double yMid = 0.5 * (yStart + yEnd);
1621 auto labelX = std::make_unique<TText>(xMid, yMin - yOffsetBelow, GroupName[g].c_str());
1622 labelX->SetTextAlign(23);
1623 labelX->SetTextSize(0.025);
1625 groupLabels.push_back(std::move(labelX));
1628 auto labelY = std::make_unique<TText>(xMin - xOffsetRight, yMid, GroupName[g].c_str());
1629 labelY->SetTextAlign(32);
1630 labelY->SetTextSize(0.025);
1632 groupLabels.push_back(std::move(labelY));
1645 const int OptTitle = gStyle->GetOptTitle();
1649 gStyle->SetOptTitle(1);
1651 constexpr
int Nhists = 3;
1653 constexpr
double Thresholds[Nhists+1] = {0, 0.25, 0.5, 1.0001};
1654 constexpr Color_t CorrColours[Nhists] = {kRed-10, kRed-6, kRed};
1657 std::vector<std::vector<double>> CorrOfInterest;
1658 CorrOfInterest.resize(
nDraw);
1659 std::vector<std::vector<std::string>> NameCorrOfInterest;
1660 NameCorrOfInterest.resize(
nDraw);
1662 std::vector<std::vector<std::unique_ptr<TH1D>>> Corr1DHist(
nDraw);
1664 for(
int i = 0; i <
nDraw; ++i)
1667 double Prior = 1.0, PriorError = 1.0;
1670 Corr1DHist[i].resize(Nhists);
1671 for(
int j = 0; j < Nhists; ++j)
1673 Corr1DHist[i][j] = std::make_unique<TH1D>(Form(
"Corr1DHist_%i_%i", i, j), Form(
"Corr1DHist_%i_%i", i, j),
nDraw, 0,
nDraw);
1674 Corr1DHist[i][j]->SetTitle(Form(
"%s",Title.Data()));
1675 Corr1DHist[i][j]->GetYaxis()->SetTitle(
"Correlation");
1676 Corr1DHist[i][j]->SetFillColor(CorrColours[j]);
1677 Corr1DHist[i][j]->SetLineColor(kBlack);
1679 for (
int k = 0; k <
nDraw; ++k)
1681 TString Title_y =
"";
1682 double Prior_y = 1.0;
1683 double PriorError_y = 1.0;
1685 Corr1DHist[i][j]->GetXaxis()->SetBinLabel(k+1, Title_y.Data());
1691 #pragma omp parallel for collapse(2)
1693 for(
int i = 0; i <
nDraw; ++i)
1695 for(
int j = 0; j <
nDraw; ++j)
1697 for(
int k = 0; k < Nhists; ++k)
1699 const double TempEntry = std::fabs((*
Correlation)(i,j));
1700 if(Thresholds[k+1] > TempEntry && TempEntry >= Thresholds[k])
1702 Corr1DHist[i][k]->SetBinContent(j+1, (*
Correlation)(i,j));
1708 NameCorrOfInterest[i].push_back(Corr1DHist[i][0]->GetXaxis()->GetBinLabel(j+1));
1713 TDirectory *CorrDir =
OutputFile->mkdir(
"Corr1D");
1716 for(
int i = 0; i <
nDraw; i++)
1720 Corr1DHist[i][0]->GetXaxis()->LabelsOption(
"v");
1721 Corr1DHist[i][0]->SetMaximum(+1.);
1722 Corr1DHist[i][0]->SetMinimum(-1.);
1723 Corr1DHist[i][0]->Draw();
1724 for(
int k = 1; k < Nhists; k++) {
1725 Corr1DHist[i][k]->Draw(
"SAME");
1728 auto leg = std::make_unique<TLegend>(0.3, 0.75, 0.6, 0.90);
1730 for(
int k = 0; k < Nhists; k++) {
1731 leg->AddEntry(Corr1DHist[i][k].get(), Form(
"%.2f > |Corr| >= %.2f", Thresholds[k+1], Thresholds[k]),
"f");
1735 Posterior->Write(Corr1DHist[i][0]->GetTitle());
1740 for(
int i = 0; i <
nDraw; i++)
1742 const int size = int(CorrOfInterest[i].
size());
1744 if(
size == 0)
continue;
1745 auto Corr1DHist_Reduced = std::make_unique<TH1D>(
"Corr1DHist_Reduced",
"Corr1DHist_Reduced",
size, 0,
size);
1746 Corr1DHist_Reduced->SetTitle(Corr1DHist[i][0]->GetTitle());
1747 Corr1DHist_Reduced->GetYaxis()->SetTitle(
"Correlation");
1748 Corr1DHist_Reduced->SetFillColor(kBlue);
1749 Corr1DHist_Reduced->SetLineColor(kBlue);
1751 for (
int j = 0; j <
size; ++j)
1753 Corr1DHist_Reduced->GetXaxis()->SetBinLabel(j+1, NameCorrOfInterest[i][j].c_str());
1754 Corr1DHist_Reduced->SetBinContent(j+1, CorrOfInterest[i][j]);
1756 Corr1DHist_Reduced->GetXaxis()->LabelsOption(
"v");
1758 Corr1DHist_Reduced->SetMaximum(+1.);
1759 Corr1DHist_Reduced->SetMinimum(-1.);
1760 Corr1DHist_Reduced->Draw();
1762 Posterior->Write(Form(
"%s_Red", Corr1DHist_Reduced->GetTitle()));
1771 gStyle->SetOptTitle(OptTitle);
1777 const std::vector<Style_t>& CredibleRegionStyle,
1778 const std::vector<Color_t>& CredibleRegionColor,
1779 const bool CredibleInSigmas,
1780 const bool Draw2DPosterior,
1781 const bool DrawBestFit) {
1787 const int nCredible = int(CredibleRegions.size());
1789 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_copy(
nDraw);
1790 std::vector<std::vector<std::vector<std::unique_ptr<TH2D>>>> hpost_2D_cl(
nDraw);
1792 for (
int i = 0; i <
nDraw; ++i)
1794 hpost_2D_copy[i].resize(
nDraw);
1795 hpost_2D_cl[i].resize(
nDraw);
1796 for (
int j = 0; j <= i; ++j)
1798 hpost_2D_copy[i][j] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i", i, j));
1799 hpost_2D_cl[i][j].resize(nCredible);
1800 for (
int k = 0; k < nCredible; ++k)
1802 hpost_2D_cl[i][j][k] = M3::Clone<TH2D>(
hpost2D[i][j], Form(
"hpost_copy_%i_%i_CL_%f", i, j, CredibleRegions[k]));
1808 #pragma omp parallel for
1811 for (
int i = 0; i <
nDraw; ++i)
1813 for (
int j = 0; j <= i; ++j)
1815 for (
int k = 0; k < nCredible; ++k)
1818 hpost_2D_cl[i][j][k]->SetLineColor(CredibleRegionColor[k]);
1819 hpost_2D_cl[i][j][k]->SetLineWidth(2);
1820 hpost_2D_cl[i][j][k]->SetLineStyle(CredibleRegionStyle[k]);
1825 gStyle->SetPalette(51);
1826 for (
int i = 0; i <
nDraw; ++i)
1828 for (
int j = 0; j <= i; ++j)
1831 if (j == i)
continue;
1834 auto legend = std::make_unique<TLegend>(0.20, 0.7, 0.4, 0.92);
1835 legend->SetTextColor(kRed);
1839 auto bestfitM = std::make_unique<TGraph>(1);
1840 const int MaxBin = hpost_2D_copy[i][j]->GetMaximumBin();
1842 hpost_2D_copy[i][j]->GetBinXYZ(MaxBin, Mbx, Mby, Mbz);
1843 const double Mx = hpost_2D_copy[i][j]->GetXaxis()->GetBinCenter(Mbx);
1844 const double My = hpost_2D_copy[i][j]->GetYaxis()->GetBinCenter(Mby);
1846 bestfitM->SetPoint(0, Mx, My);
1847 bestfitM->SetMarkerStyle(22);
1848 bestfitM->SetMarkerSize(1);
1849 bestfitM->SetMarkerColor(kMagenta);
1853 if(Draw2DPosterior){
1854 hpost_2D_copy[i][j]->Draw(
"COLZ");
1856 hpost_2D_copy[i][j]->Draw(
"AXIS");
1860 for (
int k = 0; k < nCredible; ++k)
1861 hpost_2D_cl[i][j][k]->Draw(
"CONT3 SAME");
1862 for (
int k = nCredible-1; k >= 0; --k)
1864 if(CredibleInSigmas)
1865 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f#sigma Credible Interval", CredibleRegions[k]),
"l");
1867 legend->AddEntry(hpost_2D_cl[i][j][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
1869 legend->Draw(
"SAME");
1872 legend->AddEntry(bestfitM.get(),
"Best Fit",
"p");
1873 bestfitM->Draw(
"SAME.P");
1895 const std::vector<double>& CredibleIntervals,
1896 const std::vector<Color_t>& CredibleIntervalsColours,
1898 const std::vector<double>& CredibleRegions,
1899 const std::vector<Style_t>& CredibleRegionStyle,
1900 const std::vector<Color_t>& CredibleRegionColor,
1902 const bool CredibleInSigmas) {
1907 const int nParamPlot = int(ParNames.size());
1908 std::vector<int> ParamNumber;
1909 for(
int j = 0; j < nParamPlot; ++j)
1914 MACH3LOG_WARN(
"Couldn't find param {}. Will not plot Triangle plot", ParNames[j]);
1917 ParamNumber.push_back(ParamNo);
1928 auto FormatHistogram = [](
auto& hist) {
1929 hist->GetXaxis()->SetTitle(
"");
1930 hist->GetYaxis()->SetTitle(
"");
1933 hist->GetXaxis()->SetLabelSize(0.1);
1934 hist->GetYaxis()->SetLabelSize(0.1);
1936 hist->GetXaxis()->SetNdivisions(4);
1937 hist->GetYaxis()->SetNdivisions(4);
1945 std::sort(ParamNumber.begin(), ParamNumber.end(), std::greater<int>());
1949 for(
int j = 1; j < nParamPlot+1; j++) Npad += j;
1955 const int nCredibleIntervals = int(CredibleIntervals.size());
1956 const int nCredibleRegions = int(CredibleRegions.size());
1959 std::vector<TPad*> TrianglePad(Npad);
1961 std::vector<std::unique_ptr<TH1D>> hpost_copy(nParamPlot);
1962 std::vector<std::vector<std::unique_ptr<TH1D>>> hpost_cl(nParamPlot);
1963 std::vector<std::unique_ptr<TText>> TriangleText(nParamPlot * 2);
1964 std::vector<std::unique_ptr<TH2D>> hpost_2D_copy(Npad-nParamPlot);
1965 std::vector<std::vector<std::unique_ptr<TH2D>>> hpost_2D_cl(Npad-nParamPlot);
1966 gStyle->SetPalette(51);
1969 std::vector<double> X_Min(nParamPlot);
1970 std::vector<double> X_Max(nParamPlot);
1972 double xScale = (0.95 - (X_Min[0]+0.05))/nParamPlot;
1974 X_Max[0] = X_Min[0]+xScale+0.05;
1975 for(
int i = 1; i < nParamPlot; i++)
1977 X_Min[i] = X_Max[i-1];
1978 X_Max[i] = X_Min[i]+xScale;
1980 std::vector<double> Y_Min(nParamPlot);
1981 std::vector<double> Y_Max(nParamPlot);
1984 double yScale = std::fabs(0.10 - (Y_Max[0]))/nParamPlot;
1985 Y_Min[0] = Y_Max[0]-yScale;
1986 for(
int i = 1; i < nParamPlot; i++)
1988 Y_Max[i] = Y_Min[i-1];
1989 Y_Min[i] = Y_Max[i]-yScale;
1993 int counterPad = 0, counterText = 0, counterPost = 0, counter2DPost = 0;
1995 for(
int y = 0; y < nParamPlot; y++)
1998 for(
int x = 0; x <= y; x++)
2002 TrianglePad[counterPad] =
new TPad(Form(
"TPad_%i", counterPad), Form(
"TPad_%i", counterPad),
2003 X_Min[x], Y_Min[y], X_Max[x], Y_Max[y]);
2005 TrianglePad[counterPad]->SetTopMargin(0);
2006 TrianglePad[counterPad]->SetRightMargin(0);
2008 TrianglePad[counterPad]->SetGrid();
2009 TrianglePad[counterPad]->SetFrameBorderMode(0);
2010 TrianglePad[counterPad]->SetBorderMode(0);
2011 TrianglePad[counterPad]->SetBorderSize(0);
2014 TrianglePad[counterPad]->SetBottomMargin(y == (nParamPlot - 1) ? 0.1 : 0);
2016 TrianglePad[counterPad]->SetLeftMargin(x == 0 ? 0.15 : 0);
2018 TrianglePad[counterPad]->Draw();
2019 TrianglePad[counterPad]->cd();
2024 hpost_copy[counterPost] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i", ParamNumber[x]));
2025 hpost_cl[counterPost].resize(nCredibleIntervals);
2027 hpost_copy[counterPost]->Scale(1. / hpost_copy[counterPost]->Integral());
2028 for (
int j = 0; j < nCredibleIntervals; ++j)
2030 hpost_cl[counterPost][j] = M3::Clone<TH1D>(
hpost[ParamNumber[x]], Form(
"hpost_copy_%i_CL_%f", ParamNumber[x], CredibleIntervals[j]));
2032 hpost_cl[counterPost][j]->Reset(
"");
2033 hpost_cl[counterPost][j]->Fill(0.0, 0.0);
2036 hpost_cl[counterPost][j]->Scale(1. / hpost_cl[counterPost][j]->Integral());
2037 GetCredibleIntervalSig(hpost_copy[counterPost], hpost_cl[counterPost][j], CredibleInSigmas, CredibleIntervals[j]);
2039 hpost_cl[counterPost][j]->SetFillColor(CredibleIntervalsColours[j]);
2040 hpost_cl[counterPost][j]->SetLineWidth(1);
2043 hpost_copy[counterPost]->SetMaximum(hpost_copy[counterPost]->GetMaximum()*1.2);
2044 hpost_copy[counterPost]->SetLineWidth(2);
2045 hpost_copy[counterPost]->SetLineColor(kBlack);
2048 FormatHistogram(hpost_copy[counterPost]);
2050 hpost_copy[counterPost]->Draw(
"HIST");
2051 for (
int j = 0; j < nCredibleIntervals; ++j){
2052 hpost_cl[counterPost][j]->Draw(
"HIST SAME");
2059 hpost_2D_copy[counter2DPost] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2060 Form(
"hpost_copy_%i_%i", ParamNumber[x], ParamNumber[y]));
2061 hpost_2D_cl[counter2DPost].resize(nCredibleRegions);
2063 for (
int k = 0; k < nCredibleRegions; ++k)
2065 hpost_2D_cl[counter2DPost][k] = M3::Clone<TH2D>(
hpost2D[ParamNumber[x]][ParamNumber[y]],
2066 Form(
"hpost_copy_%i_%i_CL_%f", ParamNumber[x], ParamNumber[y], CredibleRegions[k]));
2069 hpost_2D_cl[counter2DPost][k]->SetLineColor(CredibleRegionColor[k]);
2070 hpost_2D_cl[counter2DPost][k]->SetLineWidth(2);
2071 hpost_2D_cl[counter2DPost][k]->SetLineStyle(CredibleRegionStyle[k]);
2074 FormatHistogram(hpost_2D_copy[counter2DPost]);
2076 hpost_2D_copy[counter2DPost]->Draw(
"COL");
2078 for (
int k = 0; k < nCredibleRegions; ++k){
2079 hpost_2D_cl[counter2DPost][k]->Draw(
"CONT3 SAME");
2084 if(y == (nParamPlot-1))
2087 TriangleText[counterText] = std::make_unique<TText>(X_Min[x]+ (X_Max[x]-X_Min[x])/4, 0.04,
hpost[ParamNumber[x]]->GetTitle());
2089 TriangleText[counterText]->SetTextSize(0.015);
2090 TriangleText[counterText]->SetNDC(
true);
2091 TriangleText[counterText]->Draw();
2098 TriangleText[counterText] = std::make_unique<TText>(0.04, Y_Min[y] + (Y_Max[y]-Y_Min[y])/4,
hpost[ParamNumber[y]]->GetTitle());
2100 TriangleText[counterText]->SetTextAngle(90);
2102 TriangleText[counterText]->SetTextSize(0.015);
2103 TriangleText[counterText]->SetNDC(
true);
2104 TriangleText[counterText]->Draw();
2113 auto legend = std::make_unique<TLegend>(0.60, 0.7, 0.9, 0.9);
2116 for (
int j = nCredibleIntervals-1; j >= 0; --j)
2118 if(CredibleInSigmas)
2119 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f#sigma Credible Interval", CredibleIntervals[j]),
"f");
2121 legend->AddEntry(hpost_cl[0][j].get(), Form(
"%.0f%% Credible Interval", CredibleRegions[j]*100),
"f");
2123 for (
int k = nCredibleRegions-1; k >= 0; --k)
2125 if(CredibleInSigmas)
2126 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f#sigma Credible Region", CredibleRegions[k]),
"l");
2128 legend->AddEntry(hpost_2D_cl[0][k].get(), Form(
"%.0f%% Credible Region", CredibleRegions[k]*100),
"l");
2130 legend->Draw(
"SAME");
2143 for(
int i = 0; i < Npad; i++)
delete TrianglePad[i];
2159 Chain =
new TChain(
"posteriors",
"posteriors");
2168 TObjArray* brlis =
Chain->GetListOfBranches();
2180 Chain->SetBranchStatus(
"*",
false);
2187 TBranch* br =
static_cast<TBranch*
>(brlis->At(i));
2192 TString bname = br->GetName();
2195 bool rejected =
false;
2204 if(rejected)
continue;
2207 Chain->SetBranchStatus(bname.Data(),
true);
2209 if (bname.BeginsWith(
"ndd_"))
2215 else if (bname.BeginsWith(
"skd_joint_"))
2223 if (bname.BeginsWith(
"LogL_sample_")) {
2227 else if (bname.BeginsWith(
"LogL_systematic_")) {
2271 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);
2272 Gauss->SetLineWidth(2);
2273 Gauss->SetLineColor(kOrange-5);
2290 #pragma omp parallel for
2292 for (
int i = 0; i <
nDraw; ++i)
2303 for (
int j = 0; j <
nDraw; ++j) {
2317 for(
unsigned int j = 0; j <
ParamType.size(); j++)
2335 auto PreFitPlot = std::make_unique<TH1D>(
"Prefit",
"Prefit",
nDraw, 0,
nDraw);
2336 PreFitPlot->SetDirectory(
nullptr);
2337 for (
int i = 0; i < PreFitPlot->GetNbinsX() + 1; ++i) {
2338 PreFitPlot->SetBinContent(i+1, 0);
2339 PreFitPlot->SetBinError(i+1, 0);
2344 double CentralValueTemp, Central, Error;
2347 for (
int i = 0; i <
nDraw; ++i)
2356 if ( CentralValueTemp != 0) {
2357 Central =
ParamCentral[ParamEnum][ParamNo] / CentralValueTemp;
2358 Error =
ParamErrors[ParamEnum][ParamNo]/CentralValueTemp;
2360 Central = CentralValueTemp + 1.0;
2366 Central = CentralValueTemp;
2373 PreFitPlot->SetBinContent(i+1, Central);
2374 PreFitPlot->SetBinError(i+1, Error);
2375 PreFitPlot->GetXaxis()->SetBinLabel(i+1,
ParamNames[ParamEnum][ParamNo]);
2377 PreFitPlot->SetDirectory(
nullptr);
2379 PreFitPlot->SetFillStyle(1001);
2380 PreFitPlot->SetFillColor(kRed-3);
2381 PreFitPlot->SetMarkerStyle(21);
2382 PreFitPlot->SetMarkerSize(2.4);
2383 PreFitPlot->SetMarkerColor(kWhite);
2384 PreFitPlot->SetLineColor(PreFitPlot->GetFillColor());
2385 PreFitPlot->GetXaxis()->LabelsOption(
"v");
2414 TFile *TempFile =
new TFile(
MCMCFile.c_str(),
"open");
2415 TDirectory* CovarianceFolder = TempFile->Get<TDirectory>(
"CovarianceFolder");
2418 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2420 if (Config ==
nullptr) {
2429 bool InputNotFound =
false;
2431 CovPos[
kXSecPar] = GetFromManager<std::vector<std::string>>(Settings[
"General"][
"Systematics"][
"XsecCovFile"], {
"none"});
2435 InputNotFound =
true;
2439 if (XsecConfig ==
nullptr) {
2453 TMacro *ReweightConfig = TempFile->Get<TMacro>(
"Reweight_Config");
2454 if (ReweightConfig !=
nullptr) {
2455 YAML::Node ReweightSettings =
TMacroToYAML(*ReweightConfig);
2457 if (ReweightSettings[
"Weight"]) {
2460 MACH3LOG_INFO(
"Enabling reweighting with following Config");
2462 MACH3LOG_WARN(
"Found reweight config but without field ''Weight''");
2468 CovarianceFolder->Close();
2469 delete CovarianceFolder;
2479 TFile *TempFile =
new TFile(
MCMCFile.c_str(),
"open");
2482 TMacro *Config = TempFile->Get<TMacro>(
"MaCh3_Config");
2484 if (Config ==
nullptr) {
2492 CovPos[
kNDPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovFile"],
"none"));
2495 MACH3LOG_WARN(
"Couldn't find NDCov (legacy) branch in output");
2498 CovNamePos[
kNDPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"NDCovName"],
"none");
2503 CovPos[
kFDDetPar].push_back(GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovFile"],
"none"));
2506 MACH3LOG_WARN(
"Couldn't find FDCov (legacy) branch in output");
2509 CovNamePos[
kFDDetPar] = GetFromManager<std::string>(Settings[
"General"][
"Systematics"][
"FDCovName"],
"none");
2529 auto systematics = XSecFile[
"Systematics"];
2531 for (
auto it = systematics.begin(); it != systematics.end(); ++it, ++paramIndex )
2533 auto const ¶m = *it;
2535 std::string ParName = (param[
"Systematic"][
"Names"][
"FancyName"].as<std::string>());
2536 std::string Group = param[
"Systematic"][
"ParameterGroup"].as<std::string>();
2538 bool rejected =
false;
2543 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2552 MACH3LOG_DEBUG(
"Excluding param {}, from group {}", ParName, Group);
2557 if(rejected)
continue;
2560 ParamCentral[
kXSecPar].push_back(param[
"Systematic"][
"ParameterValues"][
"PreFitValue"].as<double>());
2561 ParamNom[
kXSecPar].push_back(param[
"Systematic"][
"ParameterValues"][
"Generated"].as<double>());
2563 ParamFlat[
kXSecPar].push_back(GetFromManager<bool>(param[
"Systematic"][
"FlatPrior"],
false));
2573 BranchNames.push_back(
"xsec_" + std::to_string(paramIndex));
2589 TFile *NDdetFile =
new TFile(
CovPos[
kNDPar].back().c_str(),
"open");
2590 if (NDdetFile->IsZombie()) {
2596 TMatrixDSym *NDdetMatrix = NDdetFile->Get<TMatrixDSym>(
CovNamePos[
kNDPar].c_str());
2597 TVectorD *NDdetNominal = NDdetFile->Get<TVectorD>(
"det_weights");
2598 TDirectory *BinningDirectory = NDdetFile->Get<TDirectory>(
"Binning");
2600 for (
int i = 0; i < NDdetNominal->GetNrows(); ++i)
2611 TIter next(BinningDirectory->GetListOfKeys());
2612 TKey *key =
nullptr;
2614 while ((key =
static_cast<TKey*
>(next())))
2616 std::string name = std::string(key->GetName());
2617 TH2Poly* RefPoly = BinningDirectory->Get<TH2Poly>((name).c_str());
2618 int size = RefPoly->GetNumberOfBins();
2632 TFile *FDdetFile =
new TFile(
CovPos[
kFDDetPar].back().c_str(),
"open");
2633 if (FDdetFile->IsZombie()) {
2641 for (
int i = 0; i < FDdetMatrix->GetNrows(); ++i)
2676 std::stringstream TempStream;
2677 TempStream <<
"step > " << Cuts;
2687 const unsigned int maxNsteps =
Chain->GetMaximum(
"step");
2712 for (
int i = 0; i <
nDraw; ++i)
2715 double Prior = 1.0, PriorError = 1.0;
2732 #pragma omp parallel for
2734 for (
int i = 0; i <
nDraw; ++i)
2736 for (
int j = 0; j <= i; ++j)
2740 hpost2D[i][j]->Fill(0.0, 0.0, 0.0);
2760 TDirectory *PolarDir =
OutputFile->mkdir(
"PolarDir");
2763 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2769 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Polar Plot", ParNames[k]);
2774 double Prior = 1.0, PriorError = 1.0;
2777 std::vector<double> x_val(
nBins);
2778 std::vector<double> y_val(
nBins);
2780 constexpr
double xmin = 0;
2781 constexpr
double xmax = 2*TMath::Pi();
2783 double Integral =
hpost[ParamNo]->Integral();
2784 for (Int_t ipt = 0; ipt <
nBins; ipt++)
2786 x_val[ipt] = ipt*(xmax-xmin)/
nBins+xmin;
2787 y_val[ipt] =
hpost[ParamNo]->GetBinContent(ipt+1)/Integral;
2790 auto PolarGraph = std::make_unique<TGraphPolar>(
nBins, x_val.data(), y_val.data());
2791 PolarGraph->SetLineWidth(2);
2792 PolarGraph->SetFillStyle(3001);
2793 PolarGraph->SetLineColor(kRed);
2794 PolarGraph->SetFillColor(kRed);
2795 PolarGraph->Draw(
"AFL");
2797 auto Text = std::make_unique<TText>(0.6, 0.1, Title);
2798 Text->SetTextSize(0.04);
2817 const std::vector<std::vector<double>>& Model1Bounds,
2818 const std::vector<std::vector<double>>& Model2Bounds,
2819 const std::vector<std::vector<std::string>>& ModelNames){
2824 if((ParNames.size() != Model1Bounds.size()) || (Model2Bounds.size() != Model1Bounds.size()) || (Model2Bounds.size() != ModelNames.size()))
2829 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2835 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate Bayes Factor", ParNames[k]);
2839 const double M1_min = Model1Bounds[k][0];
2840 const double M2_min = Model2Bounds[k][0];
2841 const double M1_max = Model1Bounds[k][1];
2842 const double M2_max = Model2Bounds[k][1];
2844 long double IntegralMode1 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M1_min),
hpost[ParamNo]->FindFixBin(M1_max));
2845 long double IntegralMode2 =
hpost[ParamNo]->Integral(
hpost[ParamNo]->FindFixBin(M2_min),
hpost[ParamNo]->FindFixBin(M2_max));
2847 double BayesFactor = 0.;
2848 std::string Name =
"";
2851 if(IntegralMode1 >= IntegralMode2)
2853 BayesFactor = IntegralMode1/IntegralMode2;
2854 Name =
"\\mathfrak{B}(" + ModelNames[k][0]+
"/" + ModelNames[k][1] +
") = " + std::to_string(BayesFactor);
2858 BayesFactor = IntegralMode2/IntegralMode1;
2859 Name =
"\\mathfrak{B}(" + ModelNames[k][1]+
"/" + ModelNames[k][0] +
") = " + std::to_string(BayesFactor);
2865 MACH3LOG_INFO(
"Following Jeffreys Scale = {}", JeffreysScale);
2866 MACH3LOG_INFO(
"Following Dunne-Kaboth Scale = {}", DunneKabothScale);
2874 const std::vector<double>& EvaluationPoint,
2875 const std::vector<std::vector<double>>& Bounds){
2877 if((ParNames.size() != EvaluationPoint.size()) || (Bounds.size() != EvaluationPoint.size()))
2886 TDirectory *SavageDickeyDir =
OutputFile->mkdir(
"SavageDickey");
2887 SavageDickeyDir->cd();
2889 for(
unsigned int k = 0; k < ParNames.size(); ++k)
2895 MACH3LOG_WARN(
"Couldn't find param {}. Will not calculate SavageDickey", ParNames[k]);
2900 double Prior = 1.0, PriorError = 1.0;
2901 bool FlatPrior =
false;
2906 FlatPrior =
ParamFlat[ParType][ParamTemp];
2908 auto PosteriorHist = M3::Clone<TH1D>(
hpost[ParamNo], std::string(Title));
2911 std::unique_ptr<TH1D> PriorHist;
2915 int NBins = PosteriorHist->GetNbinsX();
2916 if(Bounds[k][0] > Bounds[k][1])
2921 PriorHist = std::make_unique<TH1D>(
"PriorHist", Title, NBins, Bounds[k][0], Bounds[k][1]);
2923 double FlatProb = ( Bounds[k][1] - Bounds[k][0]) / NBins;
2924 for (
int g = 0; g < NBins + 1; ++g)
2926 PriorHist->SetBinContent(g+1, FlatProb);
2931 PriorHist = M3::Clone<TH1D>(PosteriorHist.get(),
"Prior");
2932 PriorHist->Reset(
"");
2933 PriorHist->Fill(0.0, 0.0);
2935 auto rand = std::make_unique<TRandom3>(0);
2937 for(
int g = 0; g < 1000000; ++g)
2939 PriorHist->Fill(rand->Gaus(Prior, PriorError));
2942 SavageDickeyPlot(PriorHist, PosteriorHist, std::string(Title), EvaluationPoint[k]);
2945 SavageDickeyDir->Close();
2946 delete SavageDickeyDir;
2954 std::unique_ptr<TH1D>& PosteriorHist,
2955 const std::string& Title,
2956 const double EvaluationPoint)
const {
2959 PriorHist->Scale(1./PriorHist->Integral(),
"width");
2960 PosteriorHist->Scale(1./PosteriorHist->Integral(),
"width");
2962 PriorHist->SetLineColor(kRed);
2963 PriorHist->SetMarkerColor(kRed);
2964 PriorHist->SetFillColorAlpha(kRed, 0.35);
2965 PriorHist->SetFillStyle(1001);
2966 PriorHist->GetXaxis()->SetTitle(Title.c_str());
2967 PriorHist->GetYaxis()->SetTitle(
"Posterior Probability");
2968 PriorHist->SetMaximum(PosteriorHist->GetMaximum()*1.5);
2969 PriorHist->GetYaxis()->SetLabelOffset(999);
2970 PriorHist->GetYaxis()->SetLabelSize(0);
2971 PriorHist->SetLineWidth(2);
2972 PriorHist->SetLineStyle(kSolid);
2974 PosteriorHist->SetLineColor(kBlue);
2975 PosteriorHist->SetMarkerColor(kBlue);
2976 PosteriorHist->SetFillColorAlpha(kBlue, 0.35);
2977 PosteriorHist->SetFillStyle(1001);
2979 PriorHist->Draw(
"hist");
2980 PosteriorHist->Draw(
"hist same");
2982 double ProbPrior = PriorHist->GetBinContent(PriorHist->FindBin(EvaluationPoint));
2984 if(ProbPrior < 0) ProbPrior = 0.00001;
2985 double ProbPosterior = PosteriorHist->GetBinContent(PosteriorHist->FindBin(EvaluationPoint));
2986 double SavageDickey = ProbPosterior/ProbPrior;
2990 auto PostPoint = std::make_unique<TGraph>(1);
2991 PostPoint->SetPoint(0, EvaluationPoint, ProbPosterior);
2992 PostPoint->SetMarkerStyle(20);
2993 PostPoint->SetMarkerSize(1);
2994 PostPoint->Draw(
"P same");
2996 auto PriorPoint = std::make_unique<TGraph>(1);
2997 PriorPoint->SetPoint(0, EvaluationPoint, ProbPrior);
2998 PriorPoint->SetMarkerStyle(20);
2999 PriorPoint->SetMarkerSize(1);
3000 PriorPoint->Draw(
"P same");
3002 auto legend = std::make_unique<TLegend>(0.12, 0.6, 0.6, 0.97);
3004 legend->AddEntry(PriorHist.get(),
"Prior",
"l");
3005 legend->AddEntry(PosteriorHist.get(),
"Posterior",
"l");
3006 legend->AddEntry(PostPoint.get(), Form(
"SavageDickey = %.2f, (%s)", SavageDickey, DunneKabothScale.c_str()),
"");
3007 legend->Draw(
"same");
3016 const std::vector<double>& NewCentral,
3017 const std::vector<double>& NewError) {
3021 if( (Names.size() != NewCentral.size()) || (NewCentral.size() != NewError.size()))
3023 MACH3LOG_ERROR(
"Size of passed vectors doesn't match in {}", __func__);
3026 std::vector<int> Param;
3027 std::vector<double> OldCentral;
3028 std::vector<double> OldError;
3029 std::vector<bool> FlatPrior;
3032 for(
unsigned int k = 0; k < Names.size(); ++k)
3038 MACH3LOG_WARN(
"Couldn't find param {}. Can't reweight Prior", Names[k]);
3043 double Prior = 1.0, PriorError = 1.0;
3046 Param.push_back(ParamNo);
3047 OldCentral.push_back(Prior);
3048 OldError.push_back(PriorError);
3053 FlatPrior.push_back(
ParamFlat[ParType][ParamTemp]);
3055 std::vector<double> ParameterPos(Names.size());
3057 std::string InputFile =
MCMCFile+
".root";
3058 std::string OutputFilename =
MCMCFile +
"_reweighted.root";
3061 int ret = system((
"cp " + InputFile +
" " + OutputFilename).c_str());
3063 MACH3LOG_WARN(
"Error: system call to copy file failed with code {}", ret);
3065 TFile *OutputChain =
new TFile(OutputFilename.c_str(),
"UPDATE");
3067 TTree *post = OutputChain->Get<TTree>(
"posteriors");
3071 post->SetBranchStatus(
"*",
false);
3073 for (
unsigned int j = 0; j < Names.size(); ++j) {
3074 post->SetBranchStatus(
BranchNames[Param[j]].Data(),
true);
3075 post->SetBranchAddress(
BranchNames[Param[j]].Data(), &ParameterPos[j]);
3077 TBranch *bpt = post->Branch(
"Weight", &Weight,
"Weight/D");
3078 post->SetBranchStatus(
"Weight",
true);
3086 for (
unsigned int j = 0; j < Names.size(); ++j)
3088 double new_chi = (ParameterPos[j] - NewCentral[j])/NewError[j];
3089 double new_prior = std::exp(-0.5 * new_chi * new_chi);
3091 double old_chi = -1;
3092 double old_prior = -1;
3096 old_chi = (ParameterPos[j] - OldCentral[j])/OldError[j];
3097 old_prior = std::exp(-0.5 * old_chi * old_chi);
3099 Weight *= new_prior/old_prior;
3103 post->SetBranchStatus(
"*",
true);
3105 post->Write(
"posteriors", TObject::kOverwrite);
3108 std::ostringstream yaml_stream;
3109 yaml_stream <<
"Weight:\n";
3110 for (
size_t k = 0; k < Names.size(); ++k) {
3111 yaml_stream <<
" " << Names[k] <<
": [" << NewCentral[k] <<
", " << NewError[k] <<
"]\n";
3113 std::string yaml_string = yaml_stream.str();
3115 TMacro ConfigSave =
YAMLtoTMacro(root,
"Reweight_Config");
3118 OutputChain->Close();
3128 const std::vector<double>& Error,
3129 const bool& SaveBranch) {
3133 if( (Names.size() != Error.size()))
3135 MACH3LOG_ERROR(
"Size of passed vectors doesn't match in {}", __func__);
3138 std::vector<int> Param;
3141 for(
unsigned int k = 0; k < Names.size(); ++k)
3147 MACH3LOG_WARN(
"Couldn't find param {}. Can't Smear", Names[k]);
3152 double Prior = 1.0, PriorError = 1.0;
3155 Param.push_back(ParamNo);
3157 std::string InputFile =
MCMCFile+
".root";
3158 std::string OutputFilename =
MCMCFile +
"_smeared.root";
3161 int ret = system((
"cp " + InputFile +
" " + OutputFilename).c_str());
3163 MACH3LOG_WARN(
"Error: system call to copy file failed with code {}", ret);
3165 TFile *OutputChain =
new TFile(OutputFilename.c_str(),
"UPDATE");
3167 TTree *post = OutputChain->Get<TTree>(
"posteriors");
3168 TTree *treeNew = post->CloneTree(0);
3170 std::vector<double> NewParameter(Names.size());
3171 for(
size_t i = 0; i < Param.size(); i++) {
3172 post->SetBranchAddress(
BranchNames[Param[i]], &NewParameter[i]);
3175 std::vector<double> Unsmeared_Parameter;
3177 Unsmeared_Parameter.resize(Param.size());
3178 for(
size_t i = 0; i < Param.size(); i++) {
3179 treeNew->Branch((
BranchNames[Param[i]] +
"_unsmeared"), &Unsmeared_Parameter[i]);
3183 auto rand = std::make_unique<TRandom3>(0);
3184 Long64_t AllEntries = post->GetEntries();
3185 for (Long64_t i = 0; i < AllEntries; ++i) {
3190 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3191 Unsmeared_Parameter[iPar] = NewParameter[iPar];
3195 for(
size_t iPar = 0; iPar < Param.size(); iPar++) {
3196 NewParameter[iPar] = NewParameter[iPar] + rand->Gaus(0, Error[iPar]);
3203 treeNew->Write(
"posteriors", TObject::kOverwrite);
3206 std::ostringstream yaml_stream;
3207 yaml_stream <<
"Smearing:\n";
3208 for (
size_t k = 0; k < Names.size(); ++k) {
3209 yaml_stream <<
" " << Names[k] <<
": [" << Error[k] <<
", " <<
"Gauss" <<
"]\n";
3211 std::string yaml_string = yaml_stream.str();
3213 TMacro ConfigSave =
YAMLtoTMacro(root,
"Smearing_Config");
3216 OutputChain->Close();
3223 const std::vector<int>& NIntervals) {
3228 for(
unsigned int k = 0; k < Names.size(); ++k)
3234 MACH3LOG_WARN(
"Couldn't find param {}. Can't reweight Prior", Names[k]);
3238 const int IntervalsSize =
nSteps/NIntervals[k];
3240 std::string filename = Names[k] +
".gif";
3241 std::ifstream f(filename);
3244 int ret = system(fmt::format(
"rm {}", filename).c_str());
3246 MACH3LOG_WARN(
"Error: system call to delete {} failed with code {}", filename, ret);
3251 for(
int i = NIntervals[k]-1; i >= 0; --i)
3256 hpost[ParamNo]->GetXaxis()->GetXmin(),
hpost[ParamNo]->GetXaxis()->GetXmax());
3257 EvePlot->SetMinimum(0);
3258 EvePlot->GetYaxis()->SetTitle(
"PDF");
3259 EvePlot->GetYaxis()->SetNoExponent(
false);
3262 std::string CutPosterior1D =
"step > " + std::to_string(i*IntervalsSize+IntervalsSize);
3271 CutPosterior1D =
"(" + CutPosterior1D +
")*(" +
ReweightName +
")";
3274 std::string TextTitle =
"Steps = 0 - "+std::to_string(Counter*IntervalsSize+IntervalsSize);
3278 EvePlot->SetLineWidth(2);
3279 EvePlot->SetLineColor(kBlue-1);
3280 EvePlot->SetTitle(Names[k].c_str());
3281 EvePlot->GetXaxis()->SetTitle(EvePlot->GetTitle());
3282 EvePlot->GetYaxis()->SetLabelOffset(1000);
3285 EvePlot->Scale(1. / EvePlot->Integral());
3286 EvePlot->Draw(
"HIST");
3288 TText text(0.3, 0.8, TextTitle.c_str());
3289 text.SetTextFont (43);
3290 text.SetTextSize (40);
3294 if(i == 0)
Posterior->Print((Names[k] +
".gif++20").c_str());
3295 else Posterior->Print((Names[k] +
".gif+20").c_str());
3340 MACH3LOG_ERROR(
"Even though it is used for MakeCovariance_MP and for DiagMCMC");
3341 MACH3LOG_ERROR(
"it has different structure in both for cache hits, sorry ");
3346 MACH3LOG_ERROR(
"please use SetnBatches to set other value fore example 20");
3352 for (
int j = 0; j <
nDraw; ++j) {
3354 for (
int i = 0; i <
nEntries; ++i) {
3363 for (
int i = 0; i <
nEntries; ++i) {
3367 for (
int j = 0; j <
nSamples; ++j) {
3370 for (
int j = 0; j <
nSysts; ++j) {
3379 for (
int i = 0; i <
nDraw; ++i) {
3387 Chain->SetBranchStatus(
"*",
false);
3390 const int countwidth =
nEntries/10;
3397 for (
int i = 0; i <
nBatches; ++i) {
3400 for (
int j = 0; j <
nDraw; ++j) {
3404 std::vector<double> ParStepBranch(
nDraw);
3405 std::vector<double> SampleValuesBranch(
nSamples);
3406 std::vector<double> SystValuesBranch(
nSysts);
3407 int StepNumberBranch = 0;
3408 double AccProbValuesBranch = 0;
3410 for (
int j = 0; j <
nDraw; ++j) {
3415 for (
int j = 0; j <
nSamples; ++j) {
3420 for (
int j = 0; j <
nSysts; ++j) {
3425 Chain->SetBranchStatus(
"step",
true);
3426 Chain->SetBranchAddress(
"step", &StepNumberBranch);
3428 Chain->SetBranchStatus(
"accProb",
true);
3429 Chain->SetBranchAddress(
"accProb", &AccProbValuesBranch);
3433 for (
int i = 0; i <
nEntries; ++i) {
3437 if (i % countwidth == 0)
3441 for (
int j = 0; j <
nDraw; ++j) {
3442 ParStep[j][i] = ParStepBranch[j];
3445 for (
int j = 0; j <
nSamples; ++j) {
3449 for (
int j = 0; j <
nSysts; ++j) {
3458 int BatchNumber = -1;
3460 for (
int j = 0; j <
nBatches; ++j) {
3461 if (i < (j+1)*BatchLength) {
3467 for (
int j = 0; j <
nDraw; ++j) {
3476 MACH3LOG_INFO(
"Took {:.2f}s to finish caching statistic for Diag MCMC with {} steps", clock.RealTime(),
nEntries);
3480 #pragma omp parallel for
3482 for (
int i = 0; i <
nDraw; ++i) {
3484 for (
int j = 0; j <
nBatches; ++j) {
3502 std::vector<TH1D*> TraceParamPlots(
nDraw);
3503 std::vector<TH1D*> TraceSamplePlots(
nSamples);
3504 std::vector<TH1D*> TraceSystsPlots(
nSysts);
3507 for (
int j = 0; j <
nDraw; ++j) {
3509 double Prior = 1.0, PriorError = 1.0;
3512 std::string HistName = Form(
"%s_%s_Trace", Title.Data(),
BranchNames[j].Data());
3513 TraceParamPlots[j] =
new TH1D(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3514 TraceParamPlots[j]->GetXaxis()->SetTitle(
"Step");
3515 TraceParamPlots[j]->GetYaxis()->SetTitle(
"Parameter Variation");
3518 for (
int j = 0; j <
nSamples; ++j) {
3520 TraceSamplePlots[j] =
new TH1D(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3521 TraceSamplePlots[j]->GetXaxis()->SetTitle(
"Step");
3522 TraceSamplePlots[j]->GetYaxis()->SetTitle(
"Sample -logL");
3525 for (
int j = 0; j <
nSysts; ++j) {
3527 TraceSystsPlots[j] =
new TH1D(HistName.c_str(), HistName.c_str(),
nEntries, 0,
nEntries);
3528 TraceSystsPlots[j]->GetXaxis()->SetTitle(
"Step");
3529 TraceSystsPlots[j]->GetYaxis()->SetTitle(
"Systematic -logL");
3537 #pragma omp parallel for
3539 for (
int i = 0; i <
nEntries; ++i) {
3541 for (
int j = 0; j <
nDraw; ++j) {
3542 TraceParamPlots[j]->SetBinContent(i,
ParStep[j][i]);
3544 for (
int j = 0; j <
nSamples; ++j) {
3545 TraceSamplePlots[j]->SetBinContent(i,
SampleValues[i][j]);
3547 for (
int j = 0; j <
nSysts; ++j) {
3548 TraceSystsPlots[j]->SetBinContent(i,
SystValues[i][j]);
3553 TDirectory *TraceDir =
OutputFile->mkdir(
"Trace");
3555 for (
int j = 0; j <
nDraw; ++j) {
3558 Fitter->SetLineColor(kRed);
3559 TraceParamPlots[j]->Fit(
"Fitter",
"Rq");
3560 TraceParamPlots[j]->Write();
3562 delete TraceParamPlots[j];
3565 TDirectory *LLDir =
OutputFile->mkdir(
"LogL");
3567 for (
int j = 0; j <
nSamples; ++j) {
3568 TraceSamplePlots[j]->Write();
3569 delete TraceSamplePlots[j];
3574 for (
int j = 0; j <
nSysts; ++j) {
3575 TraceSystsPlots[j]->Write();
3576 delete TraceSystsPlots[j];
3597 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3601 TDirectory* AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3602 std::vector<TH1D*> LagKPlots(
nDraw);
3603 std::vector<std::vector<double>> LagL(
nDraw);
3606 std::vector<double> ACFFT(
nEntries, 0.0);
3607 std::vector<double> ParVals(
nEntries, 0.0);
3608 std::vector<double> ParValsFFTR(
nEntries, 0.0);
3609 std::vector<double> ParValsFFTI(
nEntries, 0.0);
3610 std::vector<double> ParValsFFTSquare(
nEntries, 0.0);
3611 std::vector<double> ParValsComplex(
nEntries, 0.0);
3615 TVirtualFFT* fftf = TVirtualFFT::FFT(1, &
nEntries,
"C2CFORWARD");
3616 TVirtualFFT* fftb = TVirtualFFT::FFT(1, &
nEntries,
"C2CBACKWARD");
3619 for (
int j = 0; j <
nDraw; ++j) {
3621 LagL[j].resize(nLags);
3622 for (
int i = 0; i <
nEntries; ++i) {
3624 ParValsComplex[i] = 0.;
3628 fftf->SetPointsComplex(ParVals.data(), ParValsComplex.data());
3630 fftf->GetPointsComplex(ParValsFFTR.data(), ParValsFFTI.data());
3633 for (
int i = 0; i <
nEntries; ++i) {
3634 ParValsFFTSquare[i] = ParValsFFTR[i]*ParValsFFTR[i] + ParValsFFTI[i]*ParValsFFTI[i];
3638 fftb->SetPointsComplex(ParValsFFTSquare.data(), ParValsComplex.data());
3640 fftb->GetPointsComplex(ACFFT.data(), ParValsComplex.data());
3643 double normAC = ACFFT[0];
3644 for (
int i = 0; i <
nEntries; ++i) {
3650 double Prior = 1.0, PriorError = 1.0;
3652 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3655 LagKPlots[j] =
new TH1D(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3656 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3657 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3660 for (
int k = 0; k < nLags; ++k) {
3661 LagL[j][k] = ACFFT[k];
3662 LagKPlots[j]->SetBinContent(k, ACFFT[k]);
3667 LagKPlots[j]->Write();
3668 delete LagKPlots[j];
3674 AutoCorrDir->Close();
3680 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3692 MACH3LOG_INFO(
"Making auto-correlations for nLags = {}", nLags);
3695 std::vector<std::vector<double>> DenomSum(
nDraw);
3696 std::vector<std::vector<double>> NumeratorSum(
nDraw);
3697 std::vector<std::vector<double>> LagL(
nDraw);
3698 for (
int j = 0; j <
nDraw; ++j) {
3699 DenomSum[j].resize(nLags);
3700 NumeratorSum[j].resize(nLags);
3701 LagL[j].resize(nLags);
3703 std::vector<TH1D*> LagKPlots(
nDraw);
3705 for (
int j = 0; j <
nDraw; ++j)
3708 for (
int k = 0; k < nLags; ++k) {
3709 NumeratorSum[j][k] = 0.0;
3710 DenomSum[j][k] = 0.0;
3716 double Prior = 1.0, PriorError = 1.0;
3719 std::string HistName = Form(
"%s_%s_Lag", Title.Data(),
BranchNames[j].Data());
3720 LagKPlots[j] =
new TH1D(HistName.c_str(), HistName.c_str(), nLags, 0.0, nLags);
3721 LagKPlots[j]->GetXaxis()->SetTitle(
"Lag");
3722 LagKPlots[j]->GetYaxis()->SetTitle(
"Auto-correlation function");
3730 #pragma omp parallel for collapse(2)
3732 for (
int j = 0; j <
nDraw; ++j) {
3733 for (
int k = 0; k < nLags; ++k) {
3735 for (
int i = 0; i <
nEntries; ++i) {
3741 const double Product = Diff*LagTerm;
3742 NumeratorSum[j][k] += Product;
3745 const double Denom = Diff*Diff;
3746 DenomSum[j][k] += Denom;
3753 PrepareGPU_AutoCorr(nLags);
3765 #pragma omp parallel for collapse(2)
3768 for (
int j = 0; j <
nDraw; ++j)
3770 for (
int k = 0; k < nLags; ++k)
3772 const int temp_index = j*nLags+k;
3773 NumeratorSum[j][k] = NumeratorSum_cpu[temp_index];
3774 DenomSum[j][k] = DenomSum_cpu[temp_index];
3778 delete[] NumeratorSum_cpu;
3779 delete[] DenomSum_cpu;
3780 delete[] ParStep_cpu;
3781 delete[] ParamSums_cpu;
3794 TDirectory *AutoCorrDir =
OutputFile->mkdir(
"Auto_corr");
3796 for (
int j = 0; j <
nDraw; ++j) {
3797 for (
int k = 0; k < nLags; ++k) {
3798 LagL[j][k] = NumeratorSum[j][k]/DenomSum[j][k];
3799 LagKPlots[j]->SetBinContent(k, NumeratorSum[j][k]/DenomSum[j][k]);
3802 LagKPlots[j]->Write();
3803 delete LagKPlots[j];
3811 AutoCorrDir->Close();
3817 MACH3LOG_INFO(
"Making auto-correlations took {:.2f}s", clock.RealTime());
3823 void MCMCProcessor::PrepareGPU_AutoCorr(
const int nLags) {
3827 NumeratorSum_cpu =
new float[
nDraw*nLags];
3828 DenomSum_cpu =
new float[
nDraw*nLags];
3829 ParamSums_cpu =
new float[
nDraw];
3833 #pragma omp parallel
3838 #pragma omp for nowait
3840 for (
int i = 0; i <
nDraw; ++i)
3847 #pragma omp for collapse(2) nowait
3849 for (
int j = 0; j <
nDraw; ++j)
3851 for (
int k = 0; k < nLags; ++k)
3853 const int temp = j*nLags+k;
3854 NumeratorSum_cpu[temp] = 0.0;
3855 DenomSum_cpu[temp] = 0.0;
3860 #pragma omp for collapse(2)
3862 for (
int j = 0; j <
nDraw; ++j)
3867 ParStep_cpu[temp] =
ParStep[j][i];
3906 if(LagL.size() == 0)
3913 TVectorD* SamplingEfficiency =
new TVectorD(
nDraw);
3914 std::vector<double> TempDenominator(
nDraw);
3916 constexpr
int Nhists = 5;
3917 constexpr
double Thresholds[Nhists + 1] = {1, 0.02, 0.005, 0.001, 0.0001, 0.0};
3918 constexpr Color_t ESSColours[Nhists] = {kGreen, kGreen + 2, kYellow, kOrange, kRed};
3921 std::vector<std::unique_ptr<TH1D>> EffectiveSampleSizeHist(Nhists);
3922 for(
int i = 0; i < Nhists; ++i)
3924 EffectiveSampleSizeHist[i] =
3925 std::make_unique<TH1D>(Form(
"EffectiveSampleSizeHist_%i", i), Form(
"EffectiveSampleSizeHist_%i", i),
nDraw, 0,
nDraw);
3926 EffectiveSampleSizeHist[i]->GetYaxis()->SetTitle(
"N_{eff}/N");
3927 EffectiveSampleSizeHist[i]->SetFillColor(ESSColours[i]);
3928 EffectiveSampleSizeHist[i]->SetLineColor(ESSColours[i]);
3929 EffectiveSampleSizeHist[i]->Sumw2();
3930 for (
int j = 0; j <
nDraw; ++j)
3933 double Prior = 1.0, PriorError = 1.0;
3935 EffectiveSampleSizeHist[i]->GetXaxis()->SetBinLabel(j+1, Title.Data());
3940 #pragma omp parallel for
3943 for (
int j = 0; j <
nDraw; ++j)
3947 TempDenominator[j] = 0.;
3949 for (
int k = 0; k < nLags; ++k)
3951 TempDenominator[j] += LagL[j][k];
3953 TempDenominator[j] = 1+2*TempDenominator[j];
3954 (*EffectiveSampleSize)(j) =
double(
nEntries)/TempDenominator[j];
3956 (*SamplingEfficiency)(j) = 100 * 1/TempDenominator[j];
3958 for(
int i = 0; i < Nhists; ++i)
3960 EffectiveSampleSizeHist[i]->SetBinContent(j+1, 0);
3961 EffectiveSampleSizeHist[i]->SetBinError(j+1, 0);
3964 if(Thresholds[i] >= TempEntry && TempEntry > Thresholds[i+1])
3967 EffectiveSampleSizeHist[i]->SetBinContent(j+1, TempEntry);
3976 SamplingEfficiency->Write(
"SamplingEfficiency");
3978 EffectiveSampleSizeHist[0]->SetTitle(
"Effective Sample Size");
3979 EffectiveSampleSizeHist[0]->Draw();
3980 for(
int i = 1; i < Nhists; ++i)
3982 EffectiveSampleSizeHist[i]->Draw(
"SAME");
3985 auto leg = std::make_unique<TLegend>(0.2, 0.7, 0.6, 0.95);
3987 for(
int i = 0; i < Nhists; ++i)
3989 leg->AddEntry(EffectiveSampleSizeHist[i].get(), Form(
"%.4f >= N_{eff}/N > %.4f", Thresholds[i], Thresholds[i+1]),
"f");
3990 } leg->Draw(
"SAME");
3992 Posterior->Write(
"EffectiveSampleSizeCanvas");
3996 delete SamplingEfficiency;
4006 std::vector<TH1D*> BatchedParamPlots(
nDraw);
4007 for (
int j = 0; j <
nDraw; ++j) {
4009 double Prior = 1.0, PriorError = 1.0;
4013 std::string HistName = Form(
"%s_%s_batch", Title.Data(),
BranchNames[j].Data());
4014 BatchedParamPlots[j] =
new TH1D(HistName.c_str(), HistName.c_str(),
nBatches, 0,
nBatches);
4018 #pragma omp parallel for
4020 for (
int j = 0; j <
nDraw; ++j) {
4021 for (
int i = 0; i <
nBatches; ++i) {
4025 std::stringstream ss;
4026 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4027 BatchedParamPlots[j]->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4031 TDirectory *BatchDir =
OutputFile->mkdir(
"Batched_means");
4033 for (
int j = 0; j <
nDraw; ++j) {
4034 TF1 *Fitter =
new TF1(
"Fitter",
"[0]", 0,
nBatches);
4035 Fitter->SetLineColor(kRed);
4036 BatchedParamPlots[j]->Fit(
"Fitter",
"Rq");
4037 BatchedParamPlots[j]->Write();
4039 delete BatchedParamPlots[j];
4046 for (
int i = 0; i <
nBatches; ++i) {
4063 MACH3LOG_ERROR(
"BatchedAverages haven't been initialises or have been deleted something is wrong");
4069 TVectorD* BatchedVariance =
new TVectorD(
nDraw);
4071 TVectorD* C_Test_Statistics =
new TVectorD(
nDraw);
4073 std::vector<double> OverallBatchMean(
nDraw);
4074 std::vector<double> C_Rho_Nominator(
nDraw);
4075 std::vector<double> C_Rho_Denominator(
nDraw);
4076 std::vector<double> C_Nominator(
nDraw);
4077 std::vector<double> C_Denominator(
nDraw);
4081 #pragma omp parallel
4088 for (
int j = 0; j <
nDraw; ++j)
4090 OverallBatchMean[j] = 0.0;
4091 C_Rho_Nominator[j] = 0.0;
4092 C_Rho_Denominator[j] = 0.0;
4093 C_Nominator[j] = 0.0;
4094 C_Denominator[j] = 0.0;
4096 (*BatchedVariance)(j) = 0.0;
4097 (*C_Test_Statistics)(j) = 0.0;
4106 #pragma omp for nowait
4109 for (
int j = 0; j <
nDraw; ++j)
4115 (*BatchedVariance)(j) = (BatchLength/(
nBatches-1))* (*BatchedVariance)(j);
4120 #pragma omp for nowait
4122 for (
int j = 0; j <
nDraw; ++j)
4130 C_Denominator[j] = 2*C_Denominator[j];
4137 for (
int j = 0; j <
nDraw; ++j)
4139 for (
int i = 0; i <
nBatches-1; ++i)
4154 for (
int j = 0; j <
nDraw; ++j)
4156 (*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]);
4164 BatchedVariance->Write(
"BatchedMeansVariance");
4165 C_Test_Statistics->Write(
"C_Test_Statistics");
4168 delete BatchedVariance;
4169 delete C_Test_Statistics;
4180 const double TopMargin =
Posterior->GetTopMargin();
4181 const int OptTitle = gStyle->GetOptTitle();
4184 gStyle->SetOptTitle(1);
4189 const int N_Coeffs = std::min(10000,
nEntries);
4190 const int start = -(N_Coeffs/2-1);
4191 const int end = N_Coeffs/2-1;
4192 const int v_size = end - start;
4198 std::vector<std::vector<float>> k_j(nPrams, std::vector<float>(v_size, 0.0));
4199 std::vector<std::vector<float>> P_j(nPrams, std::vector<float>(v_size, 0.0));
4202 if (_N % 2 != 0) _N -= 1;
4205 const double two_pi_over_N = 2 * TMath::Pi() /
static_cast<double>(_N);
4209 #pragma omp parallel for collapse(2)
4212 for (
int j = 0; j < nPrams; ++j)
4214 for (
int jj = start; jj < end; ++jj)
4216 std::complex<double> a_j = 0.0;
4217 for (
int n = 0; n < _N; ++n)
4220 std::complex<double> exp_temp(0, two_pi_over_N * jj * n);
4221 a_j +=
ParStep[j][n] * std::exp(exp_temp);
4223 a_j /= std::sqrt(
float(_N));
4224 const int _c = jj - start;
4226 k_j[j][_c] = two_pi_over_N * jj;
4228 P_j[j][_c] = std::norm(a_j);
4232 TDirectory *PowerDir =
OutputFile->mkdir(
"PowerSpectrum");
4235 TVectorD* PowerSpectrumStepSize =
new TVectorD(nPrams);
4236 for (
int j = 0; j < nPrams; ++j)
4238 auto plot = std::make_unique<TGraph>(v_size, k_j[j].data(), P_j[j].data());
4241 double Prior = 1.0, PriorError = 1.0;
4244 std::string name = Form(
"Power Spectrum of %s;k;P(k)", Title.Data());
4246 plot->SetTitle(name.c_str());
4247 name = Form(
"%s_power_spectrum", Title.Data());
4248 plot->SetName(name.c_str());
4249 plot->SetMarkerStyle(7);
4252 TF1 *func =
new TF1(
"power_template",
"[0]*( ([1] / x)^[2] / (([1] / x)^[2] +1) )", 0.0, 1.0);
4254 func->SetParameter(0, 10.0);
4256 func->SetParameter(1, 0.1);
4258 func->SetParameter(2, 2.0);
4261 func->SetParLimits(0, 0.0, 100.0);
4262 func->SetParLimits(1, 0.001, 1.0);
4263 func->SetParLimits(2, 0.0, 5.0);
4265 plot->Fit(
"power_template",
"Rq");
4270 plot->Write(plot->GetName());
4276 (*PowerSpectrumStepSize)(j) = std::sqrt(func->GetParameter(0)/float(v_size*0.5));
4280 PowerSpectrumStepSize->Write(
"PowerSpectrumStepSize");
4281 delete PowerSpectrumStepSize;
4286 MACH3LOG_INFO(
"Making Power Spectrum took {:.2f}s", clock.RealTime());
4289 gStyle->SetOptTitle(OptTitle);
4300 std::vector<double> MeanUp(
nDraw, 0.0);
4301 std::vector<double> SpectralVarianceUp(
nDraw, 0.0);
4302 std::vector<int> DenomCounterUp(
nDraw, 0);
4303 const double Threshold = 0.5 *
nSteps;
4306 constexpr
double LowerThreshold = 0;
4307 constexpr
double UpperThreshold = 1.0;
4309 constexpr
int NChecks = 100;
4310 constexpr
double Division = (UpperThreshold - LowerThreshold)/NChecks;
4312 std::vector<std::unique_ptr<TH1D>> GewekePlots(
nDraw);
4313 for (
int j = 0; j <
nDraw; ++j)
4316 double Prior = 1.0, PriorError = 1.0;
4318 std::string HistName = Form(
"%s_%s_Geweke", Title.Data(),
BranchNames[j].Data());
4319 GewekePlots[j] = std::make_unique<TH1D>(HistName.c_str(), HistName.c_str(), NChecks, 0.0, 100 * UpperThreshold);
4320 GewekePlots[j]->GetXaxis()->SetTitle(
"Burn-In (%)");
4321 GewekePlots[j]->GetYaxis()->SetTitle(
"Geweke T score");
4326 #pragma omp parallel
4333 for (
int j = 0; j <
nDraw; ++j)
4340 DenomCounterUp[j]++;
4343 MeanUp[j] = MeanUp[j]/DenomCounterUp[j];
4348 #pragma omp for collapse(2)
4350 for (
int j = 0; j <
nDraw; ++j)
4356 SpectralVarianceUp[j] += (
ParStep[j][i] - MeanUp[j])*(
ParStep[j][i] - MeanUp[j]);
4365 for (
int k = 1; k < NChecks+1; ++k)
4368 std::vector<double> MeanDown(
nDraw, 0.0);
4369 std::vector<double> SpectralVarianceDown(
nDraw, 0.0);
4370 std::vector<int> DenomCounterDown(
nDraw, 0);
4372 const unsigned int ThresholsCheck = Division*k*
nSteps;
4374 for (
int j = 0; j <
nDraw; ++j)
4381 DenomCounterDown[j]++;
4384 MeanDown[j] = MeanDown[j]/DenomCounterDown[j];
4387 for (
int j = 0; j <
nDraw; ++j)
4393 SpectralVarianceDown[j] += (
ParStep[j][i] - MeanDown[j])*(
ParStep[j][i] - MeanDown[j]);
4398 for (
int j = 0; j <
nDraw; ++j)
4400 double T_score = std::fabs((MeanDown[j] - MeanUp[j])/std::sqrt(SpectralVarianceDown[j]/DenomCounterDown[j] + SpectralVarianceUp[j]/DenomCounterUp[j]));
4401 GewekePlots[j]->SetBinContent(k, T_score);
4410 TDirectory *GewekeDir =
OutputFile->mkdir(
"Geweke");
4411 for (
int j = 0; j <
nDraw; ++j)
4414 GewekePlots[j]->Write();
4416 for (
int i = 0; i <
nDraw; ++i) {
4435 auto AcceptanceProbPlot = std::make_unique<TH1D>(
"AcceptanceProbability",
"Acceptance Probability",
nEntries, 0,
nEntries);
4436 AcceptanceProbPlot->GetXaxis()->SetTitle(
"Step");
4437 AcceptanceProbPlot->GetYaxis()->SetTitle(
"Acceptance Probability");
4439 auto BatchedAcceptanceProblot = std::make_unique<TH1D>(
"AcceptanceProbability_Batch",
"AcceptanceProbability_Batch",
nBatches, 0,
nBatches);
4440 BatchedAcceptanceProblot->GetYaxis()->SetTitle(
"Acceptance Probability");
4442 for (
int i = 0; i <
nBatches; ++i) {
4446 std::stringstream ss;
4447 ss << BatchRangeLow <<
" - " << BatchRangeHigh;
4448 BatchedAcceptanceProblot->GetXaxis()->SetBinLabel(i+1, ss.str().c_str());
4452 #pragma omp parallel for
4454 for (
int i = 0; i <
nEntries; ++i) {
4459 TDirectory *probDir =
OutputFile->mkdir(
"AccProb");
4462 AcceptanceProbPlot->Write();
4463 BatchedAcceptanceProblot->Write();
4476 if (CredibleIntervals.size() != CredibleIntervalsColours.size()) {
4477 MACH3LOG_ERROR(
"size of CredibleIntervals is not equal to size of CredibleIntervalsColours");
4480 if (CredibleIntervals.size() > 1) {
4481 for (
unsigned int i = 1; i < CredibleIntervals.size(); i++) {
4482 if (CredibleIntervals[i] > CredibleIntervals[i - 1]) {
4484 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleIntervals[i], CredibleIntervals[i - 1]);
4494 const std::vector<Style_t>& CredibleRegionStyle,
4495 const std::vector<Color_t>& CredibleRegionColor) {
4497 if ((CredibleRegions.size() != CredibleRegionStyle.size()) || (CredibleRegionStyle.size() != CredibleRegionColor.size())) {
4498 MACH3LOG_ERROR(
"size of CredibleRegions is not equal to size of CredibleRegionStyle or CredibleRegionColor");
4501 for (
unsigned int i = 1; i < CredibleRegions.size(); i++) {
4502 if (CredibleRegions[i] > CredibleRegions[i - 1]) {
4504 MACH3LOG_ERROR(
"{:.2f} {:.2f}", CredibleRegions[i], CredibleRegions[i - 1]);
4515 auto caseInsensitiveCompare = [](
const std::string& a,
const std::string& b) {
4516 return std::equal(a.begin(), a.end(), b.begin(), b.end(),
4517 [](
char c1,
char c2) { return std::tolower(c1) == std::tolower(c2); });
4521 if (caseInsensitiveCompare(groupName, name)) {
4532 std::unordered_map<std::string, int> paramCounts;
4533 std::vector<std::string> orderedKeys;
4536 if (paramCounts[param] == 0) {
4537 orderedKeys.push_back(param);
4539 paramCounts[param]++;
4542 MACH3LOG_INFO(
"************************************************");
4547 for (
const std::string& key : orderedKeys) {
4552 MACH3LOG_INFO(
"************************************************");
4558 return std::vector<double>{Canv->GetTopMargin(), Canv->GetBottomMargin(),
4559 Canv->GetLeftMargin(), Canv->GetRightMargin()};
4569 if (margins.size() != 4) {
4573 Canv->SetTopMargin(margins[0]);
4574 Canv->SetBottomMargin(margins[1]);
4575 Canv->SetLeftMargin(margins[2]);
4576 Canv->SetRightMargin(margins[3]);
4582 Line->SetLineColor(Colour);
4583 Line->SetLineWidth(Width);
4584 Line->SetLineStyle(
Style);
4590 Legend->SetTextSize(
size);
4591 Legend->SetLineColor(0);
4592 Legend->SetLineStyle(0);
4593 Legend->SetFillColor(0);
4594 Legend->SetFillStyle(0);
4595 Legend->SetBorderSize(0);
#define _MaCh3_Safe_Include_Start_
KS: Avoiding warning checking for headers.
#define _MaCh3_Safe_Include_End_
KS: Restore warning checking after including external headers.
int FDParametersStartingPos
int NDParametersStartingPos
void RemoveFitter(TH1D *hist, const std::string &name)
KS: Remove fitted TF1 from hist to make comparison easier.
ParameterEnum
KS: Enum for different covariance classes.
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
constexpr ELineStyle Style[NVars]
double * EffectiveSampleSize
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)
KS: Based on Table 1 in https://www.t2k.org/docs/technotes/435.
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.
double ** ParStep
Array holding values for all parameters.
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.
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.
void ResetHistograms()
Reset 2D posteriors, in case we would like to calculate in again with different BurnInCut.
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,.
int nSamples
Number of sample PDF objects.
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.
std::vector< std::vector< double > > ParamNom
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)?
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.
int GetParamIndexFromName(const std::string &Name)
Get parameter number based on name.
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.
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...
double * ParamSums
Total parameter sum for each param.
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()
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::vector< bool > IamVaried
Is the ith parameter varied.
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
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 SmearChain(const std::vector< std::string > &Names, const std::vector< double > &NewCentral, const bool &SaveBranch)
Smear chain contours.
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.
int nSysts
Number of covariance objects.
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 ReadInputCov()
CW: Read the input Covariance matrix entries. Get stuff like parameter input errors,...
Custom exception class for MaCh3 errors.
__host__ void InitGPU_AutoCorr(float **ParStep_gpu, float **NumeratorSum_gpu, float **ParamSums_gpu, float **DenomSum_gpu, int n_Entries, int n_Pars, const int n_Lags)
KS: Initialiser, here we allocate memory for variables and copy constants.
__host__ void CopyToGPU_AutoCorr(float *ParStep_cpu, float *NumeratorSum_cpu, float *ParamSums_cpu, float *DenomSum_cpu, float *ParStep_gpu, float *NumeratorSum_gpu, float *ParamSums_gpu, float *DenomSum_gpu)
KS: Copy necessary variables from CPU to GPU.
__host__ void RunGPU_AutoCorr(float *ParStep_gpu, float *ParamSums_gpu, float *NumeratorSum_gpu, float *DenomSum_gpu, float *NumeratorSum_cpu, float *DenomSum_cpu)
KS: This call the main kernel responsible for calculating LagL and later copy results back to CPU.
__host__ void CleanupGPU_AutoCorr(float *ParStep_gpu, float *NumeratorSum_gpu, float *ParamSums_gpu, float *DenomSum_gpu)
KS: free memory on gpu.
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.
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,...
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
void PrintConfig(const YAML::Node &node)
KS: Print Yaml config using logger.
void MaCh3Welcome()
KS: Prints welcome message with MaCh3 logo.
void EstimateDataTransferRate(TChain *chain, const Long64_t entry)
KS: Check what CPU you are using.