MaCh3  2.8.0
Reference Guide
Public Member Functions | Private Member Functions | Private Attributes | List of all members
PredictiveThrower Class Reference

Implementation of Prior/Posterior Predictive and Bayesian p-Value calculations following the approach described in [13] , [14], [16]. More...

#include <Fitters/Algorithms/PredictiveThrower.h>

Inheritance diagram for PredictiveThrower:
[legend]
Collaboration diagram for PredictiveThrower:
[legend]

Public Member Functions

 PredictiveThrower (Manager *const fitMan)
 Constructor. More...
 
virtual ~PredictiveThrower ()
 Destructor. More...
 
void ProduceToys ()
 Produce toys by throwing from MCMC. More...
 
void RunPredictiveAnalysis ()
 Main routine responsible for producing posterior predictive distributions and $p$-value. More...
 
void RunMCMC () override
 This is not used in this class. More...
 
- Public Member Functions inherited from FitterBase
 FitterBase (Manager *const fitMan)
 Constructor. More...
 
virtual ~FitterBase ()
 Destructor for the FitterBase class. More...
 
void AddSampleHandler (SampleHandlerInterface *sample)
 This function adds a sample PDF object to the analysis framework. The sample PDF object will be utilized in fitting procedures or likelihood scans. More...
 
void AddSystObj (ParameterHandlerBase *cov)
 This function adds a Covariance object to the analysis framework. The Covariance object will be utilized in fitting procedures or likelihood scans. More...
 
void DragRace (const int NLaps=100)
 Calculates the required time for each sample or covariance object in a drag race simulation. Inspired by Dan's feature. More...
 
void RunLLHScan ()
 Perform a 1D likelihood scan. More...
 
void RunLLHMap ()
 Perform a general multi-dimensional likelihood scan. More...
 
void GetStepScaleBasedOnLLHScan (const std::string &filename="")
 LLH scan is good first estimate of step scale. More...
 
void Run2DLLHScan ()
 Perform a 2D likelihood scan. More...
 
void RunSigmaVar ()
 Perform a 1D/2D sigma var for all samples. More...
 
virtual void StartFromPreviousFit (const std::string &FitName)
 Allow to start from previous fit/chain. More...
 
std::string GetName () const
 Get name of class. More...
 
virtual std::string GetFancyName () const
 This name is to get include some special algorithm extensions. More...
 

Private Member Functions

void SetParamters (std::vector< std::string > &ParameterGroupsNotVaried, std::unordered_set< int > &ParameterOnlyToVary)
 This set some params to prior value this way you can evaluate errors from subset of errors. More...
 
void SetupToyGeneration (std::vector< std::string > &ParameterGroupsNotVaried, std::unordered_set< int > &ParameterOnlyToVary, std::vector< const M3::float_t * > &BoundValuePointer, std::vector< std::pair< double, double >> &ParamBounds)
 Setup useful variables etc before stating toy generation. More...
 
bool LoadToys ()
 Load existing toys. More...
 
void WriteToy (TDirectory *ToyDirectory, TDirectory *Toy_1DDirectory, TDirectory *Toy_2DDirectory, const int iToy)
 Save histograms for a single MCMC Throw/Toy. More...
 
void WriteByModeToys (TDirectory *ByModeDirectory, const int iToy)
 Save mode histograms for a single MCMC Throw/Toy. More...
 
void SetupSampleInformation ()
 Setup sample information. More...
 
std::vector< std::string > GetStoredFancyName (ParameterHandlerBase *Systematics) const
 Get Fancy parameters stored in mcmc chains for passed ParameterHandler. More...
 
std::vector< std::unique_ptr< TH1 > > MakePredictive (const std::vector< std::vector< std::unique_ptr< TH1 >>> &Toys, const std::vector< TDirectory * > &Director, const std::string &suffix, const bool DebugHistograms, const bool WriteHist)
 Produce posterior predictive distribution. More...
 
void Study1DProjections (const std::vector< TDirectory * > &SampleDirectories) const
 Load 1D projections and later produce violin plots for each. More...
 
void StudyByMode1DProjections (const std::vector< TDirectory * > &SampleDirectories) const
 Load 1D projections by mode and produce post pred for each. More...
 
void ProduceSpectra (const std::vector< std::vector< std::vector< std::unique_ptr< TH1D >>>> &Toys, const std::vector< TDirectory * > &Director, const std::string suffix, const bool DoSummary=true) const
 Produce Violin style spectra. More...
 
void MakeFluctuatedHistogram (TH1 *FluctHist, TH1 *Hist)
 Make Poisson fluctuation of TH1D hist. More...
 
void PredictiveLLH (const std::vector< std::unique_ptr< TH1 >> &Data_histogram, const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w, const std::vector< TDirectory * > &SampleDir)
 Calculate Posterior Predictive LLH. More...
 
void PosteriorPredictivepValue (const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< TDirectory * > &SampleDir)
 Calculate Posterior Predictive $p$-value Compares observed data to toy datasets generated from: More...
 
void ExtractLLH (TH1 *DatHist, TH1 *MCHist, TH1 *W2Hist, const SampleHandlerInterface *SampleHandler) const
 Calculate the LLH for TH1, set the LLH to title of MCHist. More...
 
double CalcLLH (const double data, const double mc, const double w2, const SampleHandlerInterface *SampleHandler) const
 Calculates the -2LLH (likelihood) for a single sample. More...
 
double CalcLLH (const TH1 *DatHist, const TH1 *MCHist, const TH1 *W2Hist, const SampleHandlerInterface *SampleHandler) const
 Calculates the likelihood (-2LLH) for a single sample; dynamically casts to call the correct GetLLH overload. More...
 
double GetLLH (const TH1D *DatHist, const TH1D *MCHist, const TH1D *W2Hist, const SampleHandlerInterface *SampleHandler) const
 Helper functions to calculate likelihoods using TH1D. More...
 
double GetLLH (const TH2D *DatHist, const TH2D *MCHist, const TH2D *W2Hist, const SampleHandlerInterface *SampleHandler) const
 Helper functions to calculate likelihoods using TH2D. More...
 
double GetLLH (const TH2Poly *DatHist, const TH2Poly *MCHist, const TH2Poly *W2Hist, const SampleHandlerInterface *SampleHandler) const
 Helper functions to calculate likelihoods using TH2Poly. More...
 
void MakeChi2Plots (const std::vector< std::vector< double >> &Chi2_x, const std::string &Chi2_x_title, const std::vector< std::vector< double >> &Chi2_y, const std::string &Chi2_y_title, const std::vector< TDirectory * > &SampleDir, const std::string Title)
 Produce Chi2 plot for a single sample based on which $p$-value is calculated. More...
 
void StudyCorrelations (TDirectory *PredictiveDir, const std::vector< std::vector< std::unique_ptr< TH1 >>> &Toys, const bool DebugHistograms) const
 Study Prior/Posterior correlations between samples etc. More...
 
void StudyInformationCriterion (M3::kInfCrit Criterion, const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w)
 Information Criterion. More...
 
void StudyBIC (const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w)
 Study Bayesian Information Criterion (BIC) The BIC is defined as: More...
 
void StudyDIC (const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w)
 KS: Get the Deviance Information Criterion (DIC) The deviance is defined as: More...
 
void StudyWAIC ()
 KS: Get the Watanabe-Akaike information criterion (WAIC) More...
 
std::string GetBinName (TH1 *hist, const bool uniform, const int Dim, const std::vector< int > &bins) const
 Construct a human-readable label describing a specific analysis bin. More...
 
std::vector< std::unique_ptr< TH1D > > PerBinHistogram (TH1 *hist, const int SampleId, const int Dim, const std::string &suffix) const
 Create per-bin posterior histograms for a given sample. More...
 
void StudyBetaParameters (TDirectory *PredictiveDir)
 Evaluate prior/post predictive distribution for beta parameters (used for evaluating impact MC statistical uncertainty) More...
 
void MakeCutEventRate (TH1D *Histogram, const double DataRate) const
 Make the 1D Event Rate Hist. More...
 
void RateAnalysis (const std::vector< std::vector< std::unique_ptr< TH1 >>> &Toys, const std::vector< TDirectory * > &SampleDirectories) const
 Produce distribution of number of events for each sample. More...
 

Private Attributes

bool FullLLH
 KS: Use Full LLH or only sample contribution based on discussion with Asher we almost always only want the sample likelihood. More...
 
int NModelParams
 KS: Count total number of model parameters which can be used for stuff like BIC. More...
 
bool Is_PriorPredictive
 Whether it is Prior or Posterior predictive. More...
 
int TotalNumberOfSamples
 Number of toys we are generating analysing. More...
 
std::vector< PredictiveSample > SampleInfo
 Handy struct for all sample info. More...
 
int Ntoys
 Number of toys we are generating analysing. More...
 
ParameterHandlerGeneric * ModelSystematic
 Pointer to El Generico. More...
 
std::vector< std::unique_ptr< TH1 > > Data_Hist
 Vector of Data histograms. More...
 
std::vector< std::unique_ptr< TH1 > > MC_Nom_Hist
 Vector of MC histograms. More...
 
std::vector< std::unique_ptr< TH1 > > W2_Nom_Hist
 Vector of W2 histograms. More...
 
std::vector< std::vector< std::unique_ptr< TH1 > > > MC_Hist_Toy
 
std::vector< std::vector< std::unique_ptr< TH1 > > > W2_Hist_Toy
 
std::vector< double > ReweightWeight
 Reweighting factors applied for each toy, by default 1. More...
 
std::vector< double > PenaltyTerm
 Penalty term values for each toy by default 0. More...
 
bool StandardFluctuation
 KS: We have two methods for Poissonian fluctuation. More...
 

Additional Inherited Members

- Protected Member Functions inherited from FitterBase
void ProcessMCMC ()
 Process MCMC output. More...
 
void PrepareOutput ()
 Prepare the output file. More...
 
void SaveOutput ()
 Save output and close files. More...
 
void SanitiseInputs ()
 Remove obsolete memory and make other checks before fit starts. More...
 
void SaveSettings ()
 Save the settings that the MCMC was run with. More...
 
bool GetScanRange (std::map< std::string, std::vector< double >> &scanRanges) const
 YSP: Set up a mapping to store parameters with user-specified ranges, suggested by D. Barrow. More...
 
void GetParameterScanRange (const ParameterHandlerBase *cov, const int i, double &CentralValue, double &lower, double &upper, const int n_points, const std::string &suffix="") const
 Helper function to get parameter scan range, central value. More...
 
bool CheckSkipParameter (const std::vector< std::string > &SkipVector, const std::string &ParamName) const
 KS: Check whether we want to skip parameter using skip vector. More...
 
void CustomRange (const std::string &ParName, const double sigma, double &ParamShiftValue) const
 For comparison with other fitting frameworks (like P-Theta) we usually have to apply different parameter values then usual 1, 3 sigma. More...
 
std::vector< double > CalculateBinEdges (double lowerlimit, double upperlimit, int n_points) const
 
- Protected Attributes inherited from FitterBase
Manager * fitMan
 The manager for configuration handling. More...
 
unsigned int step
 current state More...
 
double logLCurr
 current likelihood More...
 
double logLProp
 proposed likelihood More...
 
double accProb
 current acceptance prob More...
 
int accCount
 counts accepted steps More...
 
unsigned int stepStart
 step start, by default 0 if we start from previous chain then it will be different More...
 
std::vector< double > sample_llh
 store the llh breakdowns More...
 
std::vector< double > syst_llh
 systematic llh breakdowns More...
 
std::vector< SampleHandlerInterface * > samples
 Sample holder. More...
 
unsigned int TotalNSamples
 Total number of samples used, single SampleHandler can store more than one analysis sample! More...
 
std::vector< ParameterHandlerBase * > systematics
 Systematic holder. More...
 
std::unique_ptr< TStopwatch > clock
 tells global time how long fit took More...
 
std::unique_ptr< TStopwatch > stepClock
 tells how long single step/fit iteration took More...
 
double stepTime
 Time of single step. More...
 
TFile * outputFile
 Output. More...
 
TDirectory * CovFolder
 Output cov folder. More...
 
TDirectory * SampleFolder
 Output sample folder. More...
 
TTree * outTree
 Output tree with posteriors. More...
 
int auto_save
 auto save every N steps More...
 
bool fTestLikelihood
 Necessary for some fitting algorithms like PSO. More...
 
bool FileSaved
 Checks if file saved not repeat some operations. More...
 
bool SettingsSaved
 Checks if setting saved not repeat some operations. More...
 
bool OutputPrepared
 Checks if output prepared not repeat some operations. More...
 
std::string AlgorithmName
 Name of fitting algorithm that is being used. More...
 

Detailed Description

Implementation of Prior/Posterior Predictive and Bayesian p-Value calculations following the approach described in [13] , [14], [16].

For more information, visit the Posterior Predictive page.

Author
Asher Kaboth
Dan Barrow
Ed Atkin
Yashwanth S Prabhu
Kamil Skwarczynski
Patrick Dunne
Clarence Wret

Definition at line 32 of file PredictiveThrower.h.

Constructor & Destructor Documentation

◆ PredictiveThrower()

_MaCh3_Safe_Include_Start_ _MaCh3_Safe_Include_End_ PredictiveThrower::PredictiveThrower ( Manager *const  fitMan)

Constructor.

Parameters
fitManA pointer to a manager object, which will handle all settings.

Definition at line 12 of file PredictiveThrower.cpp.

12  : FitterBase(man) {
13 // *************************
14  AlgorithmName = "PredictiveThrower";
15  if(!CheckNodeExists(fitMan->raw(), "Predictive")) {
16  MACH3LOG_ERROR("Predictive is missing in your main yaml config");
17  throw MaCh3Exception(__FILE__ , __LINE__ );
18  }
19 
20  StandardFluctuation = GetFromManager<bool>(fitMan->raw()["Predictive"]["StandardFluctuation"], true, __FILE__, __LINE__ );
21 
22  if(StandardFluctuation) MACH3LOG_INFO("Using standard method of statistical fluctuation");
23  else MACH3LOG_INFO("Using alternative method of statistical fluctuation, which is much slower");
24 
25  ModelSystematic = nullptr;
26  // Use the full likelihood for the Prior/Posterior predictive pvalue
27  FullLLH = GetFromManager<bool>(fitMan->raw()["Predictive"]["FullLLH"], false, __FILE__, __LINE__ );
28  NModelParams = 0;
29 
30  Is_PriorPredictive = Get<bool>(fitMan->raw()["Predictive"]["PriorPredictive"], __FILE__, __LINE__);
31  Ntoys = Get<int>(fitMan->raw()["Predictive"]["Ntoy"], __FILE__, __LINE__);
32 
33  if(!Is_PriorPredictive) {
34  auto PosteriorFileName = Get<std::string>(fitMan->raw()["Predictive"]["PosteriorFile"], __FILE__, __LINE__);
35  auto outfile = Get<std::string>(fitMan->raw()["General"]["OutputFile"], __FILE__ , __LINE__);
36  if(PosteriorFileName == outfile){
37  MACH3LOG_ERROR("Output file ({}) and posterior files ({}) have same name", outfile, PosteriorFileName);
38  throw MaCh3Exception(__FILE__ , __LINE__ );
39  }
40  }
41 
42  ReweightWeight.resize(Ntoys);
43  PenaltyTerm.resize(Ntoys);
44 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
bool CheckNodeExists(const YAML::Node &node, Args... args)
KS: Wrapper function to call the recursive helper.
Definition: YamlHelper.h:59
FitterBase(Manager *const fitMan)
Constructor.
Definition: FitterBase.cpp:17
std::string AlgorithmName
Name of fitting algorithm that is being used.
Definition: FitterBase.h:177
Manager * fitMan
The manager for configuration handling.
Definition: FitterBase.h:120
Custom exception class used throughout MaCh3.
YAML::Node const & raw() const
Return config.
Definition: Manager.h:48
std::vector< double > PenaltyTerm
Penalty term values for each toy by default 0.
bool FullLLH
KS: Use Full LLH or only sample contribution based on discussion with Asher we almost always only wan...
bool Is_PriorPredictive
Whether it is Prior or Posterior predictive.
int NModelParams
KS: Count total number of model parameters which can be used for stuff like BIC.
int Ntoys
Number of toys we are generating analysing.
bool StandardFluctuation
KS: We have two methods for Poissonian fluctuation.
ParameterHandlerGeneric * ModelSystematic
Pointer to El Generico.
std::vector< double > ReweightWeight
Reweighting factors applied for each toy, by default 1.

◆ ~PredictiveThrower()

PredictiveThrower::~PredictiveThrower ( )
virtual

Destructor.

Definition at line 48 of file PredictiveThrower.cpp.

48  {
49 // *************************
50 }

Member Function Documentation

◆ CalcLLH() [1/2]

double PredictiveThrower::CalcLLH ( const double  data,
const double  mc,
const double  w2,
const SampleHandlerInterface *  SampleHandler 
) const
private

Calculates the -2LLH (likelihood) for a single sample.

Parameters
dataData value for the sample.
mcMC (Monte Carlo) value for the sample.
w2W2 value for the sample.
SampleHandlerPointer to SampleHandlerInterface providing the LLH test statistic.

Definition at line 1225 of file PredictiveThrower.cpp.

1228  {
1229 // *************************
1230  double llh = SampleHandler->GetTestStatLLH(data, mc, w2);
1231  //KS: do times 2 because banff reports chi2
1232  return 2*llh;
1233 }
double GetTestStatLLH(const double data, const double mc, const double w2) const
Calculate test statistic for a single bin. Calculation depends on setting of fTestStatistic....

◆ CalcLLH() [2/2]

double PredictiveThrower::CalcLLH ( const TH1 *  DatHist,
const TH1 *  MCHist,
const TH1 *  W2Hist,
const SampleHandlerInterface *  SampleHandler 
) const
private

Calculates the likelihood (-2LLH) for a single sample; dynamically casts to call the correct GetLLH overload.

Parameters
DatHistData histogram with data distribution for a single sample
MCHistMC histogram with MC distribution for a single sample
W2HistW2 histogram with W2 distribution for a single sample
SampleHandlerPointer to SampleHandlerInterface providing LLH test statistic

Definition at line 1236 of file PredictiveThrower.cpp.

1239  {
1240 // *************************
1241  // 1D case
1242  if (auto h1 = dynamic_cast<const TH1D*>(DatHist)) {
1243  return GetLLH(h1,
1244  static_cast<const TH1D*>(MCHist),
1245  static_cast<const TH1D*>(W2Hist),
1246  SampleHandler);
1247  }
1248 
1249  // 2D case
1250  if (auto h2 = dynamic_cast<const TH2D*>(DatHist)) {
1251  return GetLLH(h2,
1252  static_cast<const TH2D*>(MCHist),
1253  static_cast<const TH2D*>(W2Hist),
1254  SampleHandler);
1255  }
1256 
1257  // 2D poly case
1258  if (auto h2p = dynamic_cast<const TH2Poly*>(DatHist)) {
1259  return GetLLH(h2p,
1260  static_cast<const TH2Poly*>(MCHist),
1261  static_cast<const TH2Poly*>(W2Hist),
1262  SampleHandler);
1263  }
1264 
1265  MACH3LOG_ERROR("Unsupported histogram type in {}", __func__);
1266  throw MaCh3Exception(__FILE__ , __LINE__ );
1267 }
double GetLLH(const TH1D *DatHist, const TH1D *MCHist, const TH1D *W2Hist, const SampleHandlerInterface *SampleHandler) const
Helper functions to calculate likelihoods using TH1D.

◆ ExtractLLH()

void PredictiveThrower::ExtractLLH ( TH1 *  DatHist,
TH1 *  MCHist,
TH1 *  W2Hist,
const SampleHandlerInterface *  SampleHandler 
) const
private

Calculate the LLH for TH1, set the LLH to title of MCHist.

Parameters
DatHistData histogram with data distribution for a single sample
MCHistMC histogram with MC distribution for a single sample
W2HistW2 histogram with W2 distribution for a single sample
SampleHandlerPointer to SampleHandlerInterface providing LLH test statistic

Definition at line 1688 of file PredictiveThrower.cpp.

1688  {
1689 // ****************
1690  const double llh = CalcLLH(DatHist, MCHist, W2Hist, SampleHandler);
1691  std::stringstream ss;
1692  ss << "_2LLH=" << llh;
1693  MCHist->SetTitle((std::string(MCHist->GetTitle())+ss.str()).c_str());
1694  MACH3LOG_INFO("{:<55} {:<10.2f} {:<10.2f} {:<10.2f}", MCHist->GetName(), DatHist->Integral(), MCHist->Integral(), llh);
1695 }
double CalcLLH(const double data, const double mc, const double w2, const SampleHandlerInterface *SampleHandler) const
Calculates the -2LLH (likelihood) for a single sample.

◆ GetBinName()

std::string PredictiveThrower::GetBinName ( TH1 *  hist,
const bool  uniform,
const int  Dim,
const std::vector< int > &  bins 
) const
private

Construct a human-readable label describing a specific analysis bin.

Parameters
histHistogram providing the binning definition.
uniformFlag indicating whether the histogram uses regular axis binning (TH1/TH2) or irregular polygonal binning (e.g. TH2Poly).
DimDimensionality of the original distribution.
binsVector of per-dimension bin indices in analysis coordinates.

Definition at line 971 of file PredictiveThrower.cpp.

974  {
975 // *************************
976  std::string BinName = "";
977  if(Dim == 1) { // True 1D distribution using TH1D
978  const int b = bins[0];
979  const TAxis* ax = hist->GetXaxis();
980  const double low = ax->GetBinLowEdge(b);
981  const double up = ax->GetBinUpEdge(b);
982 
983  BinName = fmt::format("Dim0 ({:g}, {:g})", low, up);
984  } else if (Dim == 2) { // True 2D distributions
985  if(uniform == true) { //using TH2D
986  const int bx = bins[0];
987  const int by = bins[1];
988  const TAxis* ax = hist->GetXaxis();
989  const TAxis* ay = hist->GetYaxis();
990  BinName = fmt::format("Dim0 ({:g}, {:g}), ", ax->GetBinLowEdge(bx), ax->GetBinUpEdge(bx));
991  BinName += fmt::format("Dim1 ({:g}, {:g})", ay->GetBinLowEdge(by), ay->GetBinUpEdge(by));
992  } else { // using TH2Poly
993  TH2PolyBin* bin = static_cast<TH2PolyBin*>(static_cast<TH2Poly*>(hist)->GetBins()->At(bins[0]-1));
994  // Just make a little fancy name
995  BinName += fmt::format("Dim{} ({:g}, {:g})", 0, bin->GetXMin(), bin->GetXMax());
996  BinName += fmt::format("Dim{} ({:g}, {:g})", 1, bin->GetYMin(), bin->GetYMax());
997  }
998  } else { // N-dimensional distribution using flatten TH1D
999  BinName = hist->GetXaxis()->GetBinLabel(bins[0]);
1000  }
1001  return BinName;
1002 }

◆ GetLLH() [1/3]

double PredictiveThrower::GetLLH ( const TH1D *  DatHist,
const TH1D *  MCHist,
const TH1D *  W2Hist,
const SampleHandlerInterface *  SampleHandler 
) const
private

Helper functions to calculate likelihoods using TH1D.

Parameters
DatHistData histogram with data distribution for a single sample
MCHistMC histogram with MC distribution for a single sample
W2HistW2 histogram with W2 distribution for a single sample
SampleHandlerPointer to SampleHandlerInterface providing LLH test statistic

Definition at line 1270 of file PredictiveThrower.cpp.

1273  {
1274 // *************************
1275  double llh = 0.0;
1276  for (int i = 1; i <= DatHist->GetXaxis()->GetNbins(); ++i)
1277  {
1278  const double data = DatHist->GetBinContent(i);
1279  const double mc = MCHist->GetBinContent(i);
1280  const double w2 = W2Hist->GetBinContent(i);
1281  llh += SampleHandler->GetTestStatLLH(data, mc, w2);
1282  }
1283  //KS: do times 2 because banff reports chi2
1284  return 2*llh;
1285 }

◆ GetLLH() [2/3]

double PredictiveThrower::GetLLH ( const TH2D *  DatHist,
const TH2D *  MCHist,
const TH2D *  W2Hist,
const SampleHandlerInterface *  SampleHandler 
) const
private

Helper functions to calculate likelihoods using TH2D.

Parameters
DatHistData 2D histogram with data distribution for a single sample
MCHistMC 2D histogram with MC distribution for a single sample
W2HistW2 2D histogram with W2 distribution for a single sample
SampleHandlerPointer to SampleHandlerInterface providing LLH test statistic

Definition at line 1306 of file PredictiveThrower.cpp.

1309  {
1310 // *************************
1311  double llh = 0.0;
1312 
1313  const int nBinsX = DatHist->GetXaxis()->GetNbins();
1314  const int nBinsY = DatHist->GetYaxis()->GetNbins();
1315 
1316  for (int i = 1; i <= nBinsX; ++i)
1317  {
1318  for (int j = 1; j <= nBinsY; ++j)
1319  {
1320  const double data = DatHist->GetBinContent(i, j);
1321  const double mc = MCHist->GetBinContent(i, j);
1322  const double w2 = W2Hist->GetBinContent(i, j);
1323 
1324  llh += SampleHandler->GetTestStatLLH(data, mc, w2);
1325  }
1326  }
1327 
1328  // KS: do times 2 because banff reports chi2
1329  return 2 * llh;
1330 }

◆ GetLLH() [3/3]

double PredictiveThrower::GetLLH ( const TH2Poly *  DatHist,
const TH2Poly *  MCHist,
const TH2Poly *  W2Hist,
const SampleHandlerInterface *  SampleHandler 
) const
private

Helper functions to calculate likelihoods using TH2Poly.

Parameters
DatHistData 2D poly histogram with data distribution for a single sample
MCHistMC 2D poly histogram with MC distribution for a single sample
W2HistW2 2D poly histogram with W2 distribution for a single sample
SampleHandlerPointer to SampleHandlerInterface providing LLH test statistic

Definition at line 1288 of file PredictiveThrower.cpp.

1291  {
1292 // *************************
1293  double llh = 0.0;
1294  for (int i = 1; i <= DatHist->GetNumberOfBins(); ++i)
1295  {
1296  const double data = DatHist->GetBinContent(i);
1297  const double mc = MCHist->GetBinContent(i);
1298  const double w2 = W2Hist->GetBinContent(i);
1299  llh += SampleHandler->GetTestStatLLH(data, mc, w2);
1300  }
1301  //KS: do times 2 because banff reports chi2
1302  return 2*llh;
1303 }

◆ GetStoredFancyName()

std::vector< std::string > PredictiveThrower::GetStoredFancyName ( ParameterHandlerBase *  Systematics) const
private

Get Fancy parameters stored in mcmc chains for passed ParameterHandler.

Definition at line 338 of file PredictiveThrower.cpp.

338  {
339 // *************************
340  TDirectory * ogdir = gDirectory;
341 
342  std::vector<std::string> FancyNames;
343  std::string Name = std::string("Config_") + Systematics->GetName();
344  auto PosteriorFileName = Get<std::string>(fitMan->raw()["Predictive"]["PosteriorFile"], __FILE__, __LINE__);
345 
346  TFile* file = TFile::Open(PosteriorFileName.c_str(), "READ");
347  TDirectory* CovarianceFolder = file->GetDirectory("CovarianceFolder");
348 
349  TMacro* FoundMacro = static_cast<TMacro*>(CovarianceFolder->Get(Name.c_str()));
350  if(FoundMacro == nullptr) {
351  file->Close();
352  delete file;
353  if(ogdir){ ogdir->cd(); }
354 
355  return FancyNames;
356  }
357  MACH3LOG_DEBUG("Found config for {}", Name);
358  YAML::Node Settings = TMacroToYAML(*FoundMacro);
359 
360  int params = int(Settings["Systematics"].size());
361  FancyNames.resize(params);
362  int iPar = 0;
363  for (auto const &param : Settings["Systematics"]) {
364  FancyNames[iPar] = Get<std::string>(param["Systematic"]["Names"]["FancyName"], __FILE__ , __LINE__);
365  iPar++;
366  }
367  file->Close();
368  delete file;
369  if(ogdir){ ogdir->cd(); }
370  return FancyNames;
371 }
#define MACH3LOG_DEBUG
Definition: MaCh3Logger.h:34
YAML::Node TMacroToYAML(const TMacro &macro)
KS: Convert a ROOT TMacro object to a YAML node.
Definition: YamlHelper.h:151
std::string GetName() const
Get name of covariance.

◆ LoadToys()

bool PredictiveThrower::LoadToys ( )
private

Load existing toys.

Definition at line 245 of file PredictiveThrower.cpp.

245  {
246 // *************************
247  auto ToyFileName = Get<std::string>(fitMan->raw()["Predictive"]["ToyFile"], __FILE__ , __LINE__);
248  // Open the ROOT file
249  int originalErrorWarning = gErrorIgnoreLevel;
250  gErrorIgnoreLevel = kFatal;
251  TFile* file = TFile::Open(ToyFileName.c_str(), "READ");
252 
253  gErrorIgnoreLevel = originalErrorWarning;
254  TDirectory* ToyDir = nullptr;
255  if (!file || file->IsZombie()) {
256  return false;
257  } else {
258  // Check for the "toys" directory
259  if ((ToyDir = file->GetDirectory("Toys"))) {
260  MACH3LOG_INFO("Found toys in Posterior file will attempt toy reading");
261  } else {
262  file->Close();
263  delete file;
264  return false;
265  }
266  }
267 
268  // Finally get the TTree branch with the penalty vectors for each of the toy throws
269  TTree* PenaltyTree = static_cast<TTree*>(file->Get("ToySummary"));
270  if (!PenaltyTree) {
271  MACH3LOG_WARN("ToySummary TTree not found in file.");
272  file->Close();
273  delete file;
274  return false;
275  }
276 
277  Ntoys = static_cast<int>(PenaltyTree->GetEntries());
278  int ConfigNtoys = Get<int>(fitMan->raw()["Predictive"]["Ntoy"], __FILE__, __LINE__);;
279  if (Ntoys != ConfigNtoys) {
280  MACH3LOG_WARN("Found different number of toys in saved file than asked to run!");
281  MACH3LOG_INFO("Will read _ALL_ toys in the file");
282  MACH3LOG_INFO("Ntoys in file: {}", Ntoys);
283  MACH3LOG_INFO("Ntoys specified: {}", ConfigNtoys);
284  }
285 
286  PenaltyTerm.resize(Ntoys);
287  ReweightWeight.resize(Ntoys);
288 
289  double Penalty = 0, Weight = 1;
290  PenaltyTree->SetBranchAddress("Penalty", &Penalty);
291  PenaltyTree->SetBranchAddress("Weight", &Weight);
292  PenaltyTree->SetBranchAddress("NModelParams", &NModelParams);
293 
294  for (int i = 0; i < Ntoys; ++i) {
295  PenaltyTree->GetEntry(i);
296  if (FullLLH) {
297  PenaltyTerm[i] = Penalty;
298  } else {
299  PenaltyTerm[i] = 0.0;
300  }
301 
302  ReweightWeight[i] = Weight;
303  }
304  // Resize all vectors and get sample names
306 
307  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
308  TH1* DataHist1D = static_cast<TH1*>(ToyDir->Get((SampleInfo[sample].Name + "_data").c_str()));
309  Data_Hist[sample] = M3::Clone(DataHist1D);
310 
311  TH1* MCHist1D = static_cast<TH1*>(ToyDir->Get((SampleInfo[sample].Name + "_mc").c_str()));
312  MC_Nom_Hist[sample] = M3::Clone(MCHist1D);
313 
314  TH1* W2Hist1D = static_cast<TH1*>(ToyDir->Get((SampleInfo[sample].Name + "_w2").c_str()));
315  W2_Nom_Hist[sample] = M3::Clone(W2Hist1D);
316  }
317 
318 
319  for (int iToy = 0; iToy < Ntoys; ++iToy)
320  {
321  if (iToy % 100 == 0) MACH3LOG_INFO(" Loaded toy {}", iToy);
322 
323  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
324  TH1* MCHist1D = static_cast<TH1*>(ToyDir->Get((SampleInfo[sample].Name + "_mc_" + std::to_string(iToy)).c_str()));
325  TH1* W2Hist1D = static_cast<TH1*>(ToyDir->Get((SampleInfo[sample].Name + "_w2_" + std::to_string(iToy)).c_str()));
326 
327  MC_Hist_Toy[sample][iToy] = M3::Clone(MCHist1D);
328  W2_Hist_Toy[sample][iToy] = M3::Clone(W2Hist1D);
329  }
330  }
331 
332  file->Close();
333  delete file;
334  return true;
335 }
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
std::vector< std::unique_ptr< TH1 > > W2_Nom_Hist
Vector of W2 histograms.
std::vector< std::vector< std::unique_ptr< TH1 > > > W2_Hist_Toy
void SetupSampleInformation()
Setup sample information.
std::vector< std::unique_ptr< TH1 > > MC_Nom_Hist
Vector of MC histograms.
int TotalNumberOfSamples
Number of toys we are generating analysing.
std::vector< std::unique_ptr< TH1 > > Data_Hist
Vector of Data histograms.
std::vector< std::vector< std::unique_ptr< TH1 > > > MC_Hist_Toy
KS: Store info about MC sample.
Definition: SampleInfo.h:40

◆ MakeChi2Plots()

void PredictiveThrower::MakeChi2Plots ( const std::vector< std::vector< double >> &  Chi2_x,
const std::string &  Chi2_x_title,
const std::vector< std::vector< double >> &  Chi2_y,
const std::string &  Chi2_y_title,
const std::vector< TDirectory * > &  SampleDir,
const std::string  Title 
)
private

Produce Chi2 plot for a single sample based on which $p$-value is calculated.

Definition at line 1449 of file PredictiveThrower.cpp.

1454  {
1455 // *************************
1456  for (int iSample = 0; iSample < TotalNumberOfSamples+1; ++iSample) {
1457  SampleDir[iSample]->cd();
1458 
1459  // Transpose to extract chi2 values for a given sample across all toys
1460  std::vector<double> chi2_y_sample(Ntoys);
1461  std::vector<double> chi2_x_per_sample(Ntoys);
1462 
1463  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1464  chi2_y_sample[iToy] = Chi2_y[iSample][iToy];
1465  chi2_x_per_sample[iToy] = Chi2_x[iSample][iToy];
1466  }
1467 
1468  const double min_val = std::min(*std::min_element(chi2_y_sample.begin(), chi2_y_sample.end()),
1469  *std::min_element(chi2_x_per_sample.begin(), chi2_x_per_sample.end()));
1470  const double max_val = std::max(*std::max_element(chi2_y_sample.begin(), chi2_y_sample.end()),
1471  *std::max_element(chi2_x_per_sample.begin(), chi2_x_per_sample.end()));
1472 
1473  auto chi2_hist = std::make_unique<TH2D>((SampleInfo[iSample].Name+ Title).c_str(),
1474  (SampleInfo[iSample].Name+ Title).c_str(),
1475  50, min_val, max_val, 50, min_val, max_val);
1476  chi2_hist->SetDirectory(nullptr);
1477  chi2_hist->GetXaxis()->SetTitle(Chi2_x_title.c_str());
1478  chi2_hist->GetYaxis()->SetTitle(Chi2_y_title.c_str());
1479 
1480  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1481  chi2_hist->Fill(chi2_x_per_sample[iToy], chi2_y_sample[iToy]);
1482  }
1483 
1484  Get2DBayesianpValue(chi2_hist.get());
1485  chi2_hist->Write();
1486  }
1487 }
void Get2DBayesianpValue(TH2D *Histogram)
Calculates the 2D Bayesian p-value and generates a visualization.

◆ MakeCutEventRate()

void PredictiveThrower::MakeCutEventRate ( TH1D *  Histogram,
const double  DataRate 
) const
private

Make the 1D Event Rate Hist.

Definition at line 1699 of file PredictiveThrower.cpp.

1699  {
1700 // ****************
1701  // Open the ROOT file
1702  int originalErrorWarning = gErrorIgnoreLevel;
1703  gErrorIgnoreLevel = kFatal;
1704 
1705  // For the event rate histogram add a TLine to the data rate
1706  auto TempLine = std::make_unique<TLine>(DataRate, Histogram->GetMinimum(), DataRate, Histogram->GetMaximum());
1707  TempLine->SetLineColor(kRed);
1708  TempLine->SetLineWidth(2);
1709  // Also fit a Gaussian because why not?
1710  auto Fitter = std::make_unique<TF1>("Fit", "gaus", Histogram->GetBinLowEdge(1), Histogram->GetBinLowEdge(Histogram->GetNbinsX()+1));
1711  Histogram->Fit(Fitter.get(), "RQ");
1712  Fitter->SetLineColor(kRed-5);
1713  // Calculate a p-value
1714  double Above = 0.0;
1715  for (int z = 0; z < Histogram->GetNbinsX(); ++z) {
1716  const double xvalue = Histogram->GetBinCenter(z+1);
1717  if (xvalue >= DataRate) {
1718  Above += Histogram->GetBinContent(z+1);
1719  }
1720  }
1721  const double pvalue = Above/Histogram->Integral();
1722  TLegend Legend(0.4, 0.75, 0.98, 0.90);
1723  Legend.SetFillColor(0);
1724  Legend.SetFillStyle(0);
1725  Legend.SetLineWidth(0);
1726  Legend.SetLineColor(0);
1727  Legend.AddEntry(TempLine.get(), Form("Data, %.0f, p-value=%.2f", DataRate, pvalue), "l");
1728  Legend.AddEntry(Histogram, Form("MC, #mu=%.1f#pm%.1f", Histogram->GetMean(), Histogram->GetRMS()), "l");
1729  Legend.AddEntry(Fitter.get(), Form("Gauss, #mu=%.1f#pm%.1f", Fitter->GetParameter(1), Fitter->GetParameter(2)), "l");
1730  std::string TempTitle = std::string(Histogram->GetName());
1731  TempTitle += "_canv";
1732  TCanvas TempCanvas(TempTitle.c_str(), TempTitle.c_str(), 1024, 1024);
1733  TempCanvas.SetGridx();
1734  TempCanvas.SetGridy();
1735  TempCanvas.SetRightMargin(0.03);
1736  TempCanvas.SetBottomMargin(0.08);
1737  TempCanvas.SetLeftMargin(0.10);
1738  TempCanvas.SetTopMargin(0.06);
1739  TempCanvas.cd();
1740  Histogram->Draw();
1741  TempLine->Draw("same");
1742  Fitter->Draw("same");
1743  Legend.Draw("same");
1744  TempCanvas.Write();
1745  Histogram->Write();
1746  gErrorIgnoreLevel = originalErrorWarning;
1747 }

◆ MakeFluctuatedHistogram()

void PredictiveThrower::MakeFluctuatedHistogram ( TH1 *  FluctHist,
TH1 *  Hist 
)
private

Make Poisson fluctuation of TH1D hist.

Parameters
FluctHistHistogram to store fluctuated values (must match Hist type)
HistOriginal histogram to fluctuate

Definition at line 1334 of file PredictiveThrower.cpp.

1334  {
1335 // ****************
1336  // Determine which fluctuation function to call
1337  auto applyFluctuation = [&](auto* f, auto* h) {
1338  if (StandardFluctuation) {
1339  MakeFluctuatedHistogramStandard(f, h);
1340  } else {
1341  MakeFluctuatedHistogramAlternative(f, h);
1342  }
1343  };
1344 
1345  if (Hist->InheritsFrom(TH2Poly::Class())) {
1346  applyFluctuation(static_cast<TH2Poly*>(FluctHist), static_cast<TH2Poly*>(Hist));
1347  }
1348  else if (Hist->InheritsFrom(TH2D::Class())) {
1349  applyFluctuation(static_cast<TH2D*>(FluctHist), static_cast<TH2D*>(Hist));
1350  }
1351  else if (Hist->InheritsFrom(TH1D::Class())) {
1352  applyFluctuation(static_cast<TH1D*>(FluctHist), static_cast<TH1D*>(Hist));
1353  }
1354  else {
1355  MACH3LOG_ERROR("Unsupported histogram type");
1356  throw MaCh3Exception(__FILE__ , __LINE__ );
1357  }
1358 }

◆ MakePredictive()

std::vector< std::unique_ptr< TH1 > > PredictiveThrower::MakePredictive ( const std::vector< std::vector< std::unique_ptr< TH1 >>> &  Toys,
const std::vector< TDirectory * > &  Director,
const std::string &  suffix,
const bool  DebugHistograms,
const bool  WriteHist 
)
private

Produce posterior predictive distribution.

  1. Fill histograms, thread safe as all histograms are allocated before and we loop over samples

Definition at line 1062 of file PredictiveThrower.cpp.

1066  {
1067 // *************************
1068  std::vector<std::unique_ptr<TH1>> PostPred(TotalNumberOfSamples);
1069  std::vector<std::vector<std::unique_ptr<TH1D>>> Posterior_hist(TotalNumberOfSamples);
1070  // 1.initialisation
1071  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
1072  const int nDims = SampleInfo[sample].Dimenstion;
1073  const std::string Sample_Name = SampleInfo[sample].Name;
1074  Posterior_hist[sample] = PerBinHistogram(Toys[sample][0].get(), sample, nDims, suffix);
1075  auto PredictiveHist = M3::Clone(Toys[sample][0].get());
1076  // Clear the bin contents
1077  PredictiveHist->Reset();
1078  PredictiveHist->SetName((Sample_Name + "_" + suffix + "_PostPred").c_str());
1079  PredictiveHist->SetTitle((Sample_Name + "_" + suffix + "_PostPred").c_str());
1080  PredictiveHist->SetDirectory(nullptr);
1081  PostPred[sample] = std::move(PredictiveHist);
1082  }
1083 
1085  #ifdef MULTITHREAD
1086  #pragma omp parallel for
1087  #endif
1088  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
1089  const int nDims = SampleInfo[sample].Dimenstion;
1090  auto& hist = Toys[sample][0];
1091  for (size_t iToy = 0; iToy < Toys[sample].size(); ++iToy) {
1092  if(nDims == 2) {
1093  if(std::string(hist->ClassName()) == "TH2Poly") {
1094  for (int i = 1; i <= static_cast<TH2Poly*>(hist.get())->GetNumberOfBins(); ++i) {
1095  double content = Toys[sample][iToy]->GetBinContent(i);
1096  Posterior_hist[sample][i-1]->Fill(content, ReweightWeight[iToy]);
1097  }
1098  } else {
1099  int nbinsx = hist->GetNbinsX();
1100  int nbinsy = hist->GetNbinsY();
1101  for (int iy = 1; iy <= nbinsy; ++iy) {
1102  for (int ix = 1; ix <= nbinsx; ++ix) {
1103  int Bin = (iy-1) * nbinsx + (ix-1);
1104  double content = Toys[sample][iToy]->GetBinContent(ix, iy);
1105  Posterior_hist[sample][Bin]->Fill(content, ReweightWeight[iToy]);
1106  } // end loop over X bins
1107  } // end loop over Y bins
1108  }
1109  } else {
1110  int nbinsx = hist->GetNbinsX();
1111  for (int i = 1; i <= nbinsx; ++i) {
1112  double content = Toys[sample][iToy]->GetBinContent(i);
1113  Posterior_hist[sample][i-1]->Fill(content, ReweightWeight[iToy]);
1114  } // end loop over bins
1115  } // end if over dimensions
1116  } // end loop over toys
1117  } // end loop over samples
1118 
1119  // 3.save
1120  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
1121  const int nDims = SampleInfo[sample].Dimenstion;
1122  auto& hist = Toys[sample][0];
1123  Directory[sample]->cd();
1124  if(nDims == 2) {
1125  if(std::string(hist->ClassName()) == "TH2Poly") {
1126  for (int i = 1; i <= static_cast<TH2Poly*>(hist.get())->GetNumberOfBins(); ++i) {
1127  PostPred[sample]->SetBinContent(i, Posterior_hist[sample][i-1]->GetMean());
1128  // KS: If ROOT below 6.18 one need -1 only for error due to stupid bug...
1129  PostPred[sample]->SetBinError(i, Posterior_hist[sample][i-1]->GetRMS());
1130  if (DebugHistograms) Posterior_hist[sample][i-1]->Write();
1131  } // end loop over poly bins
1132  } else {
1133  int nbinsx = hist->GetNbinsX();
1134  int nbinsy = hist->GetNbinsY();
1135  for (int iy = 1; iy <= nbinsy; ++iy) {
1136  for (int ix = 1; ix <= nbinsx; ++ix) {
1137  int Bin = (iy-1) * nbinsx + (ix-1);
1138  if (DebugHistograms) Posterior_hist[sample][Bin]->Write();
1139  PostPred[sample]->SetBinContent(ix, iy, Posterior_hist[sample][Bin]->GetMean());
1140  PostPred[sample]->SetBinError(ix, iy, Posterior_hist[sample][Bin]->GetRMS());
1141  } // end loop over x
1142  } // end loop over y
1143  }
1144  } else {
1145  int nbinsx = hist->GetNbinsX();
1146  for (int i = 1; i <= nbinsx; ++i) {
1147  PostPred[sample]->SetBinContent(i, Posterior_hist[sample][i-1]->GetMean());
1148  PostPred[sample]->SetBinError(i, Posterior_hist[sample][i-1]->GetRMS());
1149  if (DebugHistograms) Posterior_hist[sample][i-1]->Write();
1150  }
1151  }
1152  if(WriteHist) PostPred[sample]->Write();
1153  } // end loop over samples
1154  return PostPred;
1155 }
std::vector< std::unique_ptr< TH1D > > PerBinHistogram(TH1 *hist, const int SampleId, const int Dim, const std::string &suffix) const
Create per-bin posterior histograms for a given sample.

◆ PerBinHistogram()

std::vector< std::unique_ptr< TH1D > > PredictiveThrower::PerBinHistogram ( TH1 *  hist,
const int  SampleId,
const int  Dim,
const std::string &  suffix 
) const
private

Create per-bin posterior histograms for a given sample.

For each analysis bin of the input histogram, this function allocates a new 1D histogram intended to accumulate the distribution of predicted event counts (e.g. across throws, toys, or posterior evaluations).

The number of output histograms therefore equals the number of physical bins:

  • TH1 → N histograms
  • TH2 → Nx × Ny histograms
  • TH2Poly → one histogram per polygon bin
Parameters
histInput histogram defining the bin structure for this sample.
SampleIdIndex identifying the sample in SampleInfo.
DimDimensionality of the original distribution.
suffixString appended to histogram names (e.g. to distinguish stages).

Definition at line 1005 of file PredictiveThrower.cpp.

1008  {
1009 // *************************
1010  std::vector<std::unique_ptr<TH1D>> PosteriorHistVec;
1011  constexpr int nBins = 100;
1012  const std::string Sample_Name = SampleInfo[SampleId].Name;
1013  if (Dim == 2) {
1014  if(std::string(hist->ClassName()) == "TH2Poly") {
1015  for (int i = 1; i <= static_cast<TH2Poly*>(hist)->GetNumberOfBins(); ++i) {
1016  std::string ProjName = fmt::format("{} {} Bin: {}",
1017  Sample_Name, suffix,
1018  GetBinName(hist, false, Dim, {i}));
1019  // KS: When a histogram is created with an axis lower limit greater or equal to its upper limit ROOT will automatically adjust histogram range
1020  // https://root.cern.ch/doc/master/classTH1.html#auto-bin
1021  auto PosteriorHist = std::make_unique<TH1D>(ProjName.c_str(), ProjName.c_str(), nBins, 1, -1);
1022  PosteriorHist->SetDirectory(nullptr);
1023  PosteriorHist->GetXaxis()->SetTitle("Events");
1024  PosteriorHistVec.push_back(std::move(PosteriorHist));
1025  } //end loop over bin
1026  } else {
1027  int nbinsx = hist->GetNbinsX();
1028  int nbinsy = hist->GetNbinsY();
1029  for (int iy = 1; iy <= nbinsy; ++iy) {
1030  for (int ix = 1; ix <= nbinsx; ++ix) {
1031  std::string ProjName = fmt::format("{} {} Bin: {}",
1032  Sample_Name, suffix,
1033  GetBinName(hist, true, Dim, {ix,iy}));
1034  //KS: When a histogram is created with an axis lower limit greater or equal to its upper limit ROOT will automatically adjust histogram range
1035  // https://root.cern.ch/doc/master/classTH1.html#auto-bin
1036  auto PosteriorHist = std::make_unique<TH1D>(ProjName.c_str(), ProjName.c_str(), nBins, 1, -1);
1037  PosteriorHist->SetDirectory(nullptr);
1038  PosteriorHist->GetXaxis()->SetTitle("Events");
1039  PosteriorHistVec.push_back(std::move(PosteriorHist));
1040  }
1041  }
1042  }
1043  } else {
1044  int nbinsx = hist->GetNbinsX();
1045  PosteriorHistVec.reserve(nbinsx);
1046  for (int i = 1; i <= nbinsx; ++i) {
1047  std::string ProjName = fmt::format("{} {} Bin: {}",
1048  Sample_Name, suffix,
1049  GetBinName(hist, true, Dim, {i}));
1050  //KS: When a histogram is created with an axis lower limit greater or equal to its upper limit ROOT will automatically adjust histogram range
1051  // https://root.cern.ch/doc/master/classTH1.html#auto-bin
1052  auto PosteriorHist = std::make_unique<TH1D>(ProjName.c_str(), ProjName.c_str(), nBins, 1, -1);
1053  PosteriorHist->SetDirectory(nullptr);
1054  PosteriorHist->GetXaxis()->SetTitle("Events");
1055  PosteriorHistVec.push_back(std::move(PosteriorHist));
1056  }
1057  }
1058  return PosteriorHistVec;
1059 }
std::string GetBinName(TH1 *hist, const bool uniform, const int Dim, const std::vector< int > &bins) const
Construct a human-readable label describing a specific analysis bin.

◆ PosteriorPredictivepValue()

void PredictiveThrower::PosteriorPredictivepValue ( const std::vector< std::unique_ptr< TH1 >> &  PostPred_mc,
const std::vector< TDirectory * > &  SampleDir 
)
private

Calculate Posterior Predictive $p$-value Compares observed data to toy datasets generated from:

  • fitted model fluctuations ("Draw")
  • posterior predictive distribution ("Pred")

Computes two discrepancy metrics: • Shape+Rate : bin-by-bin likelihood • Rate-only : total event normalization

TODO This can be multithreaded but be careful for Clone!!!

Definition at line 1361 of file PredictiveThrower.cpp.

1362  {
1363 // *************************
1364  // Step 1: Initialize per-toy accumulators once
1365  // [Sample] [Toys]
1366  auto make_matrix = [&](double init = 0.0) {
1367  return std::vector<std::vector<double>>(
1369  std::vector<double>(Ntoys, init));
1370  };
1371  auto chi2_dat = make_matrix();
1372  auto chi2_mc = make_matrix();
1373  auto chi2_pred = make_matrix();
1374  auto chi2_rate_dat = make_matrix();
1375  auto chi2_rate_mc = make_matrix();
1376  auto chi2_rate_pred = make_matrix();
1377 
1378  // 2. Add penalty terms to global bin
1379  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1380  chi2_dat[TotalNumberOfSamples][iToy] = PenaltyTerm[iToy];
1381  chi2_mc[TotalNumberOfSamples][iToy] = PenaltyTerm[iToy];
1382  chi2_pred[TotalNumberOfSamples][iToy] = PenaltyTerm[iToy];
1383 
1384  chi2_rate_dat[TotalNumberOfSamples][iToy] = PenaltyTerm[iToy];
1385  chi2_rate_mc[TotalNumberOfSamples][iToy] = PenaltyTerm[iToy];
1386  chi2_rate_pred[TotalNumberOfSamples][iToy] = PenaltyTerm[iToy];
1387  }
1388 
1390  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1391  auto SampleHandler = SampleInfo[iSample].SamHandler;
1392  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1393  // Clone histograms to avoid modifying originals
1394  auto DrawFluctHist = M3::Clone(MC_Hist_Toy[iSample][iToy].get());
1395  auto PredFluctHist = M3::Clone(PostPred_mc[iSample].get());
1396 
1397  // Apply fluctuations
1398  MakeFluctuatedHistogram(DrawFluctHist.get(), MC_Hist_Toy[iSample][iToy].get());
1399  MakeFluctuatedHistogram(PredFluctHist.get(), PostPred_mc[iSample].get());
1400 
1401  // I. SHAPE + RATE (bin-by-bin likelihood)
1402  chi2_dat[iSample][iToy] = CalcLLH(Data_Hist[iSample].get(), MC_Hist_Toy[iSample][iToy].get(), W2_Hist_Toy[iSample][iToy].get(), SampleHandler);
1403  chi2_mc[iSample][iToy] = CalcLLH(DrawFluctHist.get(), MC_Hist_Toy[iSample][iToy].get(), W2_Hist_Toy[iSample][iToy].get(), SampleHandler);
1404  chi2_pred[iSample][iToy] = CalcLLH(PredFluctHist.get(), MC_Hist_Toy[iSample][iToy].get(), W2_Hist_Toy[iSample][iToy].get(), SampleHandler);
1405 
1406  // II. RATE-ONLY (total normalization)
1407  chi2_rate_dat[iSample][iToy] = CalcLLH(Data_Hist[iSample]->Integral(), MC_Hist_Toy[iSample][iToy]->Integral(), W2_Hist_Toy[iSample][iToy]->Integral(), SampleHandler);
1408  chi2_rate_mc[iSample][iToy] = CalcLLH(DrawFluctHist->Integral(), MC_Hist_Toy[iSample][iToy]->Integral(), W2_Hist_Toy[iSample][iToy]->Integral(), SampleHandler);
1409  chi2_rate_pred[iSample][iToy] = CalcLLH(PredFluctHist->Integral(), MC_Hist_Toy[iSample][iToy]->Integral(), W2_Hist_Toy[iSample][iToy]->Integral(), SampleHandler);
1410 
1411  // III. accumulate global sums ---
1412  chi2_dat[TotalNumberOfSamples][iToy] += chi2_dat[iSample][iToy];
1413  chi2_mc[TotalNumberOfSamples][iToy] += chi2_mc[iSample][iToy];
1414  chi2_pred[TotalNumberOfSamples][iToy] += chi2_pred[iSample][iToy];
1415 
1416  chi2_rate_dat[TotalNumberOfSamples][iToy] += chi2_rate_dat[iSample][iToy];
1417  chi2_rate_mc[TotalNumberOfSamples][iToy] += chi2_rate_mc[iSample][iToy];
1418  chi2_rate_pred[TotalNumberOfSamples][iToy] += chi2_rate_pred[iSample][iToy];
1419  }
1420  }
1421 
1422  // 4. Produce pValue plots
1423  // Shape+rate posterior predictive checks
1424  MakeChi2Plots(chi2_mc, "-2LLH (Draw Fluc, Draw)", chi2_dat, "-2LLH (Data, Draw)", SampleDir, "_drawfluc_draw");
1425  MakeChi2Plots(chi2_pred, "-2LLH (Pred Fluc, Draw)", chi2_dat, "-2LLH (Data, Draw)", SampleDir, "_predfluc_draw");
1426 
1427  // Rate-only posterior predictive checks
1428  MakeChi2Plots(chi2_rate_mc, "-2LLH (Rate Draw Fluc, Draw)", chi2_rate_dat, "-2LLH (Rate Data, Draw)", SampleDir, "_rate_drawfluc_draw");
1429  MakeChi2Plots(chi2_rate_pred, "-2LLH (Rate Pred Fluc, Draw)", chi2_rate_dat, "-2LLH (Rate Data, Draw)", SampleDir, "_rate_predfluc_draw");
1430 }
void MakeFluctuatedHistogram(TH1 *FluctHist, TH1 *Hist)
Make Poisson fluctuation of TH1D hist.
void MakeChi2Plots(const std::vector< std::vector< double >> &Chi2_x, const std::string &Chi2_x_title, const std::vector< std::vector< double >> &Chi2_y, const std::string &Chi2_y_title, const std::vector< TDirectory * > &SampleDir, const std::string Title)
Produce Chi2 plot for a single sample based on which $p$-value is calculated.

◆ PredictiveLLH()

void PredictiveThrower::PredictiveLLH ( const std::vector< std::unique_ptr< TH1 >> &  Data_histogram,
const std::vector< std::unique_ptr< TH1 >> &  PostPred_mc,
const std::vector< std::unique_ptr< TH1 >> &  PostPred_w,
const std::vector< TDirectory * > &  SampleDir 
)
private

Calculate Posterior Predictive LLH.

Definition at line 1433 of file PredictiveThrower.cpp.

1436  {
1437 // *************************
1438  MACH3LOG_INFO("{:<55} {:<10} {:<10} {:<10}", "Sample", "DataInt", "MCInt", "-2LLH");
1439  MACH3LOG_INFO("{:-<55} {:-<10} {:-<10} {:-<10}", "", "", "", "");
1440  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1441  SampleDir[iSample]->cd();
1442  ExtractLLH(Data_histogram[iSample].get(), PostPred_mc[iSample].get(), PostPred_w[iSample].get(), SampleInfo[iSample].SamHandler);
1443  PostPred_mc[iSample]->Write();
1444  }
1445 }
void ExtractLLH(TH1 *DatHist, TH1 *MCHist, TH1 *W2Hist, const SampleHandlerInterface *SampleHandler) const
Calculate the LLH for TH1, set the LLH to title of MCHist.

◆ ProduceSpectra()

void PredictiveThrower::ProduceSpectra ( const std::vector< std::vector< std::vector< std::unique_ptr< TH1D >>>> &  Toys,
const std::vector< TDirectory * > &  Director,
const std::string  suffix,
const bool  DoSummary = true 
) const
private

Produce Violin style spectra.

Definition at line 877 of file PredictiveThrower.cpp.

880  {
881 // *************************
882  std::vector<std::vector<double>> MaxValue(TotalNumberOfSamples);
883 
884  // 1. Create Max value
885  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
886  const int nDims = SampleInfo[sample].Dimenstion;
887  MaxValue[sample].assign(nDims, 0);
888  }
889 
890  // 2. Find maximum entries over all toys
891  #ifdef MULTITHREAD
892  #pragma omp parallel for
893  #endif
894  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
895  for (int toy = 0; toy < Ntoys; ++toy) {
896  const int nDims = SampleInfo[sample].Dimenstion;
897  for (int dim = 0; dim < nDims; dim++) {
898  double max_val = Toys[sample][toy][dim]->GetMaximum();
899  MaxValue[sample][dim] = std::max(MaxValue[sample][dim], max_val);
900  }
901  }
902  }
903 
904  // 3. Make actual spectra histogram (this is because making ROOT histograms is not save)
905  // And we now have actual max values
906  std::vector<std::vector<std::unique_ptr<TH2D>>> Spectra(TotalNumberOfSamples);
907  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
908  const int nDims = SampleInfo[sample].Dimenstion;
909  Spectra[sample].resize(nDims);
910  for (int dim = 0; dim < nDims; dim++) {
911  // Get MC histogram x-axis binning
912  TH1D* refHist = Toys[sample][0][dim].get();
913 
914  const int n_bins_x = refHist->GetNbinsX();
915  std::vector<double> x_bin_edges(n_bins_x + 1);
916  for (int b = 0; b < n_bins_x; ++b) {
917  x_bin_edges[b] = refHist->GetXaxis()->GetBinLowEdge(b + 1);
918  }
919  x_bin_edges[n_bins_x] = refHist->GetXaxis()->GetBinUpEdge(n_bins_x);
920 
921  constexpr int n_bins_y = 400;
922  constexpr double y_min = 0.0;
923  const double y_max = MaxValue[sample][dim] * 1.05;
924 
925  // Create TH2D with variable binning on x axis
926  Spectra[sample][dim] = std::make_unique<TH2D>(
927  (SampleInfo[sample].Name + "_" + suffix + "_dim" + std::to_string(dim)).c_str(), // name
928  (SampleInfo[sample].Name + "_" + suffix + "_dim" + std::to_string(dim)).c_str(), // title
929  n_bins_x, x_bin_edges.data(), // x axis bins
930  n_bins_y, y_min, y_max // y axis bins
931  );
932 
933  Spectra[sample][dim]->GetXaxis()->SetTitle(refHist->GetXaxis()->GetTitle());
934  Spectra[sample][dim]->GetYaxis()->SetTitle("Events");
935 
936  Spectra[sample][dim]->SetDirectory(nullptr);
937  Spectra[sample][dim]->Sumw2(true);
938  }
939  }
940 
941  // 4. now we can actually fill our projections
942  #ifdef MULTITHREAD
943  #pragma omp parallel for collapse(2)
944  #endif
945  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
946  for (int toy = 0; toy < Ntoys; ++toy) {
947  const int nDims = SampleInfo[sample].Dimenstion;
948  for (int dim = 0; dim < nDims; dim++) {
949  FastViolinFill(Spectra[sample][dim].get(), Toys[sample][toy][dim].get());
950  }
951  }
952  }
953 
954  // 5. Save histograms which is not thread save
955  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
956  SampleDirectories[sample]->cd();
957  const int nDims = SampleInfo[sample].Dimenstion;
958  for (long unsigned int dim = 0; dim < Spectra[sample].size(); dim++) {
959  Spectra[sample][dim]->Write();
960  // For case of 2D make additional histograms
961  if(nDims == 2 && DoSummary) {
962  const std::string name = SampleInfo[sample].Name + "_" + suffix+ "_PostPred_dim" + std::to_string(dim);
963  auto Summary = MakeSummaryFromSpectra(Spectra[sample][dim].get(), name);
964  Summary->Write();
965  }
966  }
967  }
968 }

◆ ProduceToys()

void PredictiveThrower::ProduceToys ( )

Produce toys by throwing from MCMC.

KS: Names of parameter groups that will not be varied

KS: Index of parameters that will be varied

this store value of parameters sampled from a chain

Definition at line 478 of file PredictiveThrower.cpp.

478  {
479 // *************************
480  // If we found toys then skip process of making new toys
481  if(LoadToys()) return;
482 
484  std::vector<std::string> ParameterGroupsNotVaried;
486  std::unordered_set<int> ParameterOnlyToVary;
487  // For study where one would like to apply bounds
488  std::vector<const M3::float_t*> BoundValuePointer;
489  std::vector<std::pair<double, double>> ParamBounds;
490 
491  // Setup useful information for toy generation
492  SetupToyGeneration(ParameterGroupsNotVaried, ParameterOnlyToVary,
493  BoundValuePointer, ParamBounds);
494 
495  auto PosteriorFileName = Get<std::string>(fitMan->raw()["Predictive"]["PosteriorFile"], __FILE__, __LINE__);
496  auto ToyFileName = Get<std::string>(fitMan->raw()["Predictive"]["ToyFile"], __FILE__ , __LINE__);
497  auto ToyFile = M3::Open(ToyFileName, "RECREATE", __FILE__, __LINE__);
498 
499  MACH3LOG_INFO("Starting {}", __func__);
500 
501  ToyFile->cd();
502  double Penalty = 0, Weight = 1.;
503  int Draw = 0;
504 
505  TTree *ToyTree = new TTree("ToySummary", "ToySummary");
506  ToyTree->Branch("Penalty", &Penalty, "Penalty/D");
507  ToyTree->Branch("Weight", &Weight, "Weight/D");
508  ToyTree->Branch("Draw", &Draw, "Draw/I");
509  ToyTree->Branch("NModelParams", &NModelParams, "NModelParams/I");
510 
511  // KS: define branches so we can keep track of what params we are throwing
512  std::vector<double> ParamValues(NModelParams);
513  std::vector<const M3::float_t*> ParampPointers(NModelParams);
514  int ParamCounter = 0;
515  for (size_t iSys = 0; iSys < systematics.size(); iSys++)
516  {
517  for (int iPar = 0; iPar < systematics[iSys]->GetNumParams(); iPar++)
518  {
519  ParampPointers[ParamCounter] = systematics[iSys]->RetPointer(iPar);
520  std::string Name = systematics[iSys]->GetParFancyName(iPar);
521  //CW: Also strip out - signs because it messes up TBranches
522  while (Name.find("-") != std::string::npos) {
523  Name.replace(Name.find("-"), 1, std::string("_"));
524  }
525  ToyTree->Branch(Name.c_str(), &ParamValues[ParamCounter], (Name + "/D").c_str());
526  ParamCounter++;
527  }
528  }
529  TDirectory* ToyDirectory = ToyFile->mkdir("Toys");
530  ToyDirectory->cd();
531  int SampleCounter = 0;
532  for (size_t iPDF = 0; iPDF < samples.size(); iPDF++)
533  {
534  auto* MaCh3Sample = samples[iPDF];
535  for (int SampleIndex = 0; SampleIndex < MaCh3Sample->GetNSamples(); ++SampleIndex)
536  {
537  // Get nominal spectra and event rates
538  const TH1* DataHist = MaCh3Sample->GetDataHist(SampleIndex);
539  Data_Hist[SampleCounter] = M3::Clone(DataHist, MaCh3Sample->GetSampleTitle(SampleIndex) + "_data");
540  Data_Hist[SampleCounter]->Write((MaCh3Sample->GetSampleTitle(SampleIndex) + "_data").c_str());
541 
542  const TH1* MCHist = MaCh3Sample->GetMCHist(SampleIndex);
543  MC_Nom_Hist[SampleCounter] = M3::Clone(MCHist, MaCh3Sample->GetSampleTitle(SampleIndex) + "_mc");
544  MC_Nom_Hist[SampleCounter]->Write((MaCh3Sample->GetSampleTitle(SampleIndex) + "_mc").c_str());
545 
546  const TH1* W2Hist = MaCh3Sample->GetW2Hist(SampleIndex);
547  W2_Nom_Hist[SampleCounter] = M3::Clone(W2Hist, MaCh3Sample->GetSampleTitle(SampleIndex) + "_w2");
548  W2_Nom_Hist[SampleCounter]->Write((MaCh3Sample->GetSampleTitle(SampleIndex) + "_w2").c_str());
549  SampleCounter++;
550  }
551  }
552 
553  TDirectory* Toy_1DDirectory = ToyFile->mkdir("Toys_1DHistVar");
554  TDirectory* Toy_2DDirectory = ToyFile->mkdir("Toys_2DHistVar");
555  auto doByMode = GetFromManager<bool>(fitMan->raw()["Predictive"]["ByMode"], false, __FILE__, __LINE__);
556  TDirectory* ByModeDirectory = nullptr;
557  if(doByMode) ByModeDirectory = ToyFile->mkdir("Toys_ByMode");
558  auto ReweightNames = GetFromManager<std::vector<std::string>>(fitMan->raw()["Predictive"]["ReweightNames"],
559  {"Weight"}, __FILE__, __LINE__);
560  bool doReweight = false;
561  std::vector<double> reweight_weight(ReweightNames.size(), 1.0);
562 
564  std::vector<std::vector<double>> branch_vals(systematics.size());
565  std::vector<std::vector<std::string>> branch_name(systematics.size());
566 
567  TChain* PosteriorFile = nullptr;
568  unsigned int burn_in = 0;
569  unsigned int maxNsteps = 0;
570  unsigned int Step = 0;
571  if(!Is_PriorPredictive)
572  {
573  PosteriorFile = new TChain("posteriors");
574  PosteriorFile->Add(PosteriorFileName.c_str());
575 
576  PosteriorFile->SetBranchAddress("step", &Step);
577  doReweight = true;
578  for (size_t i = 0; i < ReweightNames.size(); ++i) {
579  const auto& name = ReweightNames[i];
580  if (PosteriorFile->GetBranch(name.c_str())) {
581  PosteriorFile->SetBranchStatus(name.c_str(), true);
582  PosteriorFile->SetBranchAddress(name.c_str(), &reweight_weight[i]);
583  } else {
584  MACH3LOG_WARN("Missing reweight branch '{}' -> disabling ALL reweighting", name);
585  doReweight = false;
586  }
587  }
588 
589  for (size_t s = 0; s < systematics.size(); ++s) {
590  auto fancy_names = GetStoredFancyName(systematics[s]);
591  systematics[s]->MatchMaCh3OutputBranches(PosteriorFile, branch_vals[s], branch_name[s], fancy_names);
592  }
593 
594  //Get the burn-in from the config
595  burn_in = Get<unsigned int>(fitMan->raw()["Predictive"]["BurnInSteps"], __FILE__, __LINE__);
596 
597  //DL: Adding sanity check for chains shorter than burn in
598  maxNsteps = static_cast<unsigned int>(PosteriorFile->GetMaximum("step"));
599  if(burn_in >= maxNsteps)
600  {
601  MACH3LOG_ERROR("You are running on a chain shorter than burn in cut");
602  MACH3LOG_ERROR("Maximal value of nSteps: {}, burn in cut {}", maxNsteps, burn_in);
603  MACH3LOG_ERROR("You will run into infinite loop");
604  MACH3LOG_ERROR("You can make new chain or modify burn in cut");
605  throw MaCh3Exception(__FILE__,__LINE__);
606  }
607  }
608 
609  TStopwatch TempClock;
610  TempClock.Start();
611  for(int i = 0; i < Ntoys; i++)
612  {
613  if(Ntoys >= 10 && i % (Ntoys/10) == 0) {
615  }
616  if(!Is_PriorPredictive){
617  int entry = 0;
618  Step = 0;
619  // KS This allow to set additional bounds like mass ordering
620  bool WithinBounds = false;
621  //YSP: Ensures you get an entry from the mcmc even when burn_in is set to zero (Although not advised :p ).
622  //Take 200k burn in steps, WP: Eb C in 1st peaky
623  // If we have combined chains by hadd need to check the step in the chain
624  // Note, entry is not necessarily same as step due to merged ROOT files, so can't choose entry in the range BurnIn - nEntries :(
625  while(Step < burn_in || !WithinBounds) {
626  entry = M3::rand::UniformInt(0, static_cast<int>(PosteriorFile->GetEntries()) - 1);
627  PosteriorFile->GetEntry(entry);
628  // KS: This might be bit hacky... but BoundValuePointer refer to values in ParameterHandler
629  // so we need to update them
630  if(BoundValuePointer.size() > 0) {
631  for (size_t s = 0; s < systematics.size(); ++s) {
632  systematics[s]->SetParameters(branch_vals[s]);
633  }
634  }
635  WithinBounds = CheckBounds(BoundValuePointer, ParamBounds);
636  }
637  Draw = entry;
638  }
639  for (size_t s = 0; s < systematics.size(); ++s)
640  {
641  //KS: Below line can help you get prior predictive distributions which are helpful for getting pre and post ND fit spectra
642  //YSP: If not set in the config, the code runs SK Posterior Predictive distributions by default. If true, then the code runs SK prior predictive.
643  if(Is_PriorPredictive) {
644  systematics[s]->ThrowParameters();
645  } else {
646  systematics[s]->SetParameters(branch_vals[s]);
647  }
648  }
649 
650  // This set some params to prior value this way you can evaluate errors from subset of errors
651  SetParamters(ParameterGroupsNotVaried, ParameterOnlyToVary);
652 
653  Penalty = 0.;
654  if(FullLLH) {
655  for (size_t s = 0; s < systematics.size(); ++s) {
656  //KS: do times 2 because banff reports chi2
657  Penalty += 2.0 * systematics[s]->GetLikelihood();
658  }
659  }
660 
661  PenaltyTerm[i] = Penalty;
662  Weight = 1.;
663  if(doReweight) {
664  for (size_t iWeight = 0; iWeight < reweight_weight.size(); ++iWeight) {
665  Weight *= reweight_weight[iWeight];
666  }
667  }
668  ReweightWeight[i] = Weight;
669 
670  for (size_t iPDF = 0; iPDF < samples.size(); iPDF++) {
671  samples[iPDF]->Reweight();
672  }
673  // Save histograms to file
674  WriteToy(ToyDirectory, Toy_1DDirectory, Toy_2DDirectory, i);
675  if(doByMode) WriteByModeToys(ByModeDirectory, i);
676 
677  // Fill parameter value so we know throw values
678  for (size_t iPar = 0; iPar < ParamValues.size(); iPar++) {
679  ParamValues[iPar] = *ParampPointers[iPar];
680  }
681 
682  ToyTree->Fill();
683  }//end of toys loop
684  TempClock.Stop();
685 
686  if(PosteriorFile) delete PosteriorFile;
687  ToyDirectory->Close(); delete ToyDirectory;
688  Toy_1DDirectory->Close(); delete Toy_1DDirectory;
689  Toy_2DDirectory->Close(); delete Toy_2DDirectory;
690  if(doByMode){
691  ByModeDirectory->Close();
692  delete ByModeDirectory;
693  }
694  ToyTree->Write(); delete ToyTree;
695  if(ToyFile) delete ToyFile;
696  outputFile->cd();
697 
698  MACH3LOG_INFO("{} took {:.2f}s to finish for {} toys", __func__, TempClock.RealTime(), Ntoys);
699 }
bool CheckBounds(const std::vector< const M3::float_t * > &BoundValuePointer, const std::vector< std::pair< double, double >> &ParamBounds)
TFile * outputFile
Output.
Definition: FitterBase.h:156
std::vector< SampleHandlerInterface * > samples
Sample holder.
Definition: FitterBase.h:141
std::vector< ParameterHandlerBase * > systematics
Systematic holder.
Definition: FitterBase.h:146
void WriteToy(TDirectory *ToyDirectory, TDirectory *Toy_1DDirectory, TDirectory *Toy_2DDirectory, const int iToy)
Save histograms for a single MCMC Throw/Toy.
bool LoadToys()
Load existing toys.
void WriteByModeToys(TDirectory *ByModeDirectory, const int iToy)
Save mode histograms for a single MCMC Throw/Toy.
void SetupToyGeneration(std::vector< std::string > &ParameterGroupsNotVaried, std::unordered_set< int > &ParameterOnlyToVary, std::vector< const M3::float_t * > &BoundValuePointer, std::vector< std::pair< double, double >> &ParamBounds)
Setup useful variables etc before stating toy generation.
std::vector< std::string > GetStoredFancyName(ParameterHandlerBase *Systematics) const
Get Fancy parameters stored in mcmc chains for passed ParameterHandler.
void SetParamters(std::vector< std::string > &ParameterGroupsNotVaried, std::unordered_set< int > &ParameterOnlyToVary)
This set some params to prior value this way you can evaluate errors from subset of errors.
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
Definition: Monitor.cpp:229
int UniformInt(const int min, const int max)
Generate a uniform random integer in [min, max].
Definition: Random.h:132

◆ RateAnalysis()

void PredictiveThrower::RateAnalysis ( const std::vector< std::vector< std::unique_ptr< TH1 >>> &  Toys,
const std::vector< TDirectory * > &  SampleDirectories 
) const
private

Produce distribution of number of events for each sample.

Definition at line 1750 of file PredictiveThrower.cpp.

1751  {
1752 // *************************
1753  std::vector<std::unique_ptr<TH1D>> EventHist(TotalNumberOfSamples+1);
1754  for (int iSample = 0; iSample < TotalNumberOfSamples+1; ++iSample) {
1755  std::string Title = "EventHist: ";
1756  if (iSample == TotalNumberOfSamples) {
1757  Title = "Total";
1758  } else {
1759  Title = SampleInfo[iSample].Name;
1760  }
1761  Title += "_sum";
1762  //KS: When a histogram is created with an axis lower limit greater or equal to its upper limit ROOT will automatically adjust histogram range
1763  // https://root.cern.ch/doc/master/classTH1.html#auto-bin
1764  EventHist[iSample] = std::make_unique<TH1D>(Title.c_str(), Title.c_str(), 100, 1, -1);
1765  EventHist[iSample]->SetDirectory(nullptr);
1766  EventHist[iSample]->GetXaxis()->SetTitle("Total event rate");
1767  EventHist[iSample]->GetYaxis()->SetTitle("Counts");
1768  EventHist[iSample]->SetLineWidth(2);
1769  }
1770 
1771  // First fill per-sample histograms
1772  #ifdef MULTITHREAD
1773  #pragma omp parallel for
1774  #endif
1775  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1776  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1777  double Count = Toys[iSample][iToy]->Integral();
1778  EventHist[iSample]->Fill(Count);
1779  }
1780  }
1781 
1782  // Now fill total histogram properly (per toy)
1783  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1784  double TotalCount = 0.0;
1785  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1786  TotalCount += Toys[iSample][iToy]->Integral();
1787  }
1788  EventHist[TotalNumberOfSamples]->Fill(TotalCount);
1789  }
1790 
1791  double DataRate = 0.0;
1792  std::vector<double> DataRates(TotalNumberOfSamples+1);
1793  #ifdef MULTITHREAD
1794  #pragma omp parallel for reduction(+:DataRate)
1795  #endif
1796  for (int i = 0; i < TotalNumberOfSamples; ++i) {
1797  DataRates[i] = Data_Hist[i]->Integral();
1798  DataRate += DataRates[i];
1799  }
1800  DataRates[TotalNumberOfSamples] = DataRate;
1801 
1802  for (int SampleNum = 0; SampleNum < TotalNumberOfSamples+1; ++SampleNum) {
1803  SampleDirectories[SampleNum]->cd();
1804  //Make fancy event rate histogram
1805  MakeCutEventRate(EventHist[SampleNum].get(), DataRates[SampleNum]);
1806  }
1807 }
void MakeCutEventRate(TH1D *Histogram, const double DataRate) const
Make the 1D Event Rate Hist.

◆ RunMCMC()

void PredictiveThrower::RunMCMC ( )
inlineoverridevirtual

This is not used in this class.

Implements FitterBase.

Definition at line 47 of file PredictiveThrower.h.

47  {
48  MACH3LOG_ERROR("{} is not supported in {}", __func__, GetName());
49  throw MaCh3Exception(__FILE__ , __LINE__ );
50  };
std::string GetName() const
Get name of class.
Definition: FitterBase.h:75

◆ RunPredictiveAnalysis()

void PredictiveThrower::RunPredictiveAnalysis ( )

Main routine responsible for producing posterior predictive distributions and $p$-value.

Definition at line 1159 of file PredictiveThrower.cpp.

1159  {
1160 // *************************
1161  // Remove not useful stuff
1162  SanitiseInputs();
1163 
1164  MACH3LOG_INFO("Starting {}", __func__);
1165  MACH3LOG_WARN("\033[0;31mCurrent Total RAM usage is {:.2f} GB\033[0m", M3::Utils::getValue("VmRSS") / 1048576.0);
1166  MACH3LOG_WARN("\033[0;31mOut of Total available RAM {:.2f} GB\033[0m", M3::Utils::getValue("MemTotal") / 1048576.0);
1167 
1168  TStopwatch TempClock;
1169  TempClock.Start();
1170 
1171  auto DebugHistograms = GetFromManager<bool>(fitMan->raw()["Predictive"]["DebugHistograms"], false, __FILE__, __LINE__);
1172  auto doByMode = GetFromManager<bool>(fitMan->raw()["Predictive"]["ByMode"], false, __FILE__, __LINE__);
1173 
1174  TDirectory* PredictiveDir = outputFile->mkdir("Predictive");
1175  std::vector<TDirectory*> SampleDirectories;
1176  SampleDirectories.resize(TotalNumberOfSamples+1);
1177 
1178  // open directory for every sample
1179  for (int sample = 0; sample < TotalNumberOfSamples+1; ++sample) {
1180  SampleDirectories[sample] = PredictiveDir->mkdir(SampleInfo[sample].Name.c_str());
1181  }
1182 
1183  // Produce Violin style spectra
1184  Study1DProjections(SampleDirectories);
1185  // Produce Post pred by each mode individually
1186  if(doByMode) StudyByMode1DProjections(SampleDirectories);
1187  // Produce posterior predictive distribution for mc
1188  auto PostPred_mc = MakePredictive(MC_Hist_Toy, SampleDirectories, "mc", DebugHistograms, false);
1189  // Produce posterior predictive distribution for w2
1190  auto PostPred_w2 = MakePredictive(W2_Hist_Toy, SampleDirectories, "w2", false, false);
1191  // Calculate Posterior Predictive LLH
1192  PredictiveLLH(Data_Hist, PostPred_mc, PostPred_w2, SampleDirectories);
1193  // Calculate Posterior Predictive $p$-value
1194  PosteriorPredictivepValue(PostPred_mc, SampleDirectories);
1195  // Check how number of events changed
1196  RateAnalysis(MC_Hist_Toy, SampleDirectories);
1197 
1198  // Close directories
1199  for (int sample = 0; sample < TotalNumberOfSamples+1; ++sample) {
1200  SampleDirectories[sample]->Close();
1201  delete SampleDirectories[sample];
1202  }
1203 
1204  auto StudyBeta = GetFromManager<bool>(fitMan->raw()["Predictive"]["StudyBetaParameters"], true, __FILE__, __LINE__);
1205  auto StudyInfoCriterion = GetFromManager<bool>(fitMan->raw()["Predictive"]["StudyInformationCriterion"], true, __FILE__, __LINE__);
1206  auto StudyCorr = GetFromManager<bool>(fitMan->raw()["Predictive"]["StudyCorrelations"], true, __FILE__, __LINE__);
1207 
1208  // Studying information criterion
1209  if(StudyInfoCriterion) StudyInformationCriterion(M3::kWAIC, PostPred_mc, PostPred_w2);
1210  // Study Prior/Posterior correlations between samples etc.
1211  if(StudyCorr) StudyCorrelations(PredictiveDir, MC_Hist_Toy, DebugHistograms);
1212  // Perform beta analysis for mc statical uncertainty
1213  if(StudyBeta) StudyBetaParameters(PredictiveDir);
1214 
1215  PredictiveDir->Close();
1216  delete PredictiveDir;
1217 
1218  outputFile->cd();
1219 
1220  TempClock.Stop();
1221  MACH3LOG_INFO("{} took {:.2f}s to finish for {} toys", __func__, TempClock.RealTime(), Ntoys);
1222 }
void SanitiseInputs()
Remove obsolete memory and make other checks before fit starts.
Definition: FitterBase.cpp:225
void StudyCorrelations(TDirectory *PredictiveDir, const std::vector< std::vector< std::unique_ptr< TH1 >>> &Toys, const bool DebugHistograms) const
Study Prior/Posterior correlations between samples etc.
void PosteriorPredictivepValue(const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< TDirectory * > &SampleDir)
Calculate Posterior Predictive $p$-value Compares observed data to toy datasets generated from:
void StudyInformationCriterion(M3::kInfCrit Criterion, const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w)
Information Criterion.
void StudyByMode1DProjections(const std::vector< TDirectory * > &SampleDirectories) const
Load 1D projections by mode and produce post pred for each.
void PredictiveLLH(const std::vector< std::unique_ptr< TH1 >> &Data_histogram, const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w, const std::vector< TDirectory * > &SampleDir)
Calculate Posterior Predictive LLH.
void RateAnalysis(const std::vector< std::vector< std::unique_ptr< TH1 >>> &Toys, const std::vector< TDirectory * > &SampleDirectories) const
Produce distribution of number of events for each sample.
void Study1DProjections(const std::vector< TDirectory * > &SampleDirectories) const
Load 1D projections and later produce violin plots for each.
void StudyBetaParameters(TDirectory *PredictiveDir)
Evaluate prior/post predictive distribution for beta parameters (used for evaluating impact MC statis...
std::vector< std::unique_ptr< TH1 > > MakePredictive(const std::vector< std::vector< std::unique_ptr< TH1 >>> &Toys, const std::vector< TDirectory * > &Director, const std::string &suffix, const bool DebugHistograms, const bool WriteHist)
Produce posterior predictive distribution.
int getValue(const std::string &Type)
CW: Get info like RAM.
Definition: Monitor.cpp:252
@ kWAIC
Watanabe-Akaike information criterion.

◆ SetParamters()

void PredictiveThrower::SetParamters ( std::vector< std::string > &  ParameterGroupsNotVaried,
std::unordered_set< int > &  ParameterOnlyToVary 
)
private

This set some params to prior value this way you can evaluate errors from subset of errors.

Have ability to not throw legacy matrices

Alternatively vary only selected params

Definition at line 53 of file PredictiveThrower.cpp.

54  {
55 // *************************
56  // WARNING This should be removed in the future
57  auto DoNotThrowLegacyCov = GetFromManager<std::vector<std::string>>(fitMan->raw()["Predictive"]["DoNotThrowLegacyCov"], {}, __FILE__, __LINE__);
59  for (size_t i = 0; i < DoNotThrowLegacyCov.size(); ++i) {
60  for (size_t s = 0; s < systematics.size(); ++s) {
61  if (systematics[s]->GetName() == DoNotThrowLegacyCov[i]) {
62  systematics[s]->SetParameters();
63  break;
64  }
65  }
66  }
67 
68  // Set groups to prefit values if they were set to not be varies
69  if(ModelSystematic && ParameterGroupsNotVaried.size() > 0) {
70  ModelSystematic->SetGroupOnlyParameters(ParameterGroupsNotVaried);
71  }
72 
74  if (ModelSystematic && !ParameterOnlyToVary.empty()) {
75  for (int i = 0; i < ModelSystematic->GetNumParams(); ++i) {
76  // KS: If parameter is in map then we are skipping this, otherwise for params that we don't want to vary we simply set it to prior
77  if (ParameterOnlyToVary.find(i) == ParameterOnlyToVary.end()) {
79  }
80  }
81  }
82 }
int GetNumParams() const
Get total number of parameters.
void SetParProp(const int i, const double val)
Set proposed parameter value.
double GetParPreFit(const int i) const
Get prior parameter value.
void SetGroupOnlyParameters(const std::string &Group, const std::vector< double > &Pars={})
KS Function to set to prior parameters of a given group or values from vector.

◆ SetupSampleInformation()

void PredictiveThrower::SetupSampleInformation ( )
private

Setup sample information.

Definition at line 85 of file PredictiveThrower.cpp.

85  {
86 // *************************
88  for (size_t iPDF = 0; iPDF < samples.size(); iPDF++) {
89  TotalNumberOfSamples += samples[iPDF]->GetNSamples();
90  }
91 
97 
99 
100 
101  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
102  MC_Hist_Toy[sample].resize(Ntoys);
103  W2_Hist_Toy[sample].resize(Ntoys);
104  }
105  int counter = 0;
106  for (size_t iPDF = 0; iPDF < samples.size(); iPDF++) {
107  for (int SampleIndex = 0; SampleIndex < samples[iPDF]->GetNSamples(); ++SampleIndex) {
108  SampleInfo[counter].Name = samples[iPDF]->GetSampleTitle(SampleIndex);
109  SampleInfo[counter].LocalId = SampleIndex;
110  SampleInfo[counter].SamHandler = samples[iPDF];
111  SampleInfo[counter].Dimenstion = SampleInfo[counter].SamHandler->GetNDim(SampleIndex);
112  counter++;
113  }
114  }
115  SampleInfo[TotalNumberOfSamples].Name= "Total";
116 }

◆ SetupToyGeneration()

void PredictiveThrower::SetupToyGeneration ( std::vector< std::string > &  ParameterGroupsNotVaried,
std::unordered_set< int > &  ParameterOnlyToVary,
std::vector< const M3::float_t * > &  BoundValuePointer,
std::vector< std::pair< double, double >> &  ParamBounds 
)
private

Setup useful variables etc before stating toy generation.

Let's ask the manager what are the file with covariance matrix

Definition at line 120 of file PredictiveThrower.cpp.

123  {
124 // *************************
125  int counter = 0;
126  for (size_t s = 0; s < systematics.size(); ++s) {
127  auto* MaCh3Params = dynamic_cast<ParameterHandlerGeneric*>(systematics[s]);
128  if(MaCh3Params) {
129  ModelSystematic = MaCh3Params;
130  counter++;
131  }
132  }
133 
135 
136  if(Is_PriorPredictive) {
137  MACH3LOG_INFO("You've chosen to run Prior Predictive Distribution");
138  } else {
139  auto PosteriorFileName = Get<std::string>(fitMan->raw()["Predictive"]["PosteriorFile"], __FILE__, __LINE__);
140  //KS: We use MCMCProcessor to get names of covariances that were actually used to produce given chain
141  MCMCProcessor Processor(PosteriorFileName);
142  Processor.Initialise();
143 
144  // For throwing FD predictions from ND-only chain we have to allow having different yaml configs
145  auto AllowDifferentConfigs = GetFromManager<bool>(fitMan->raw()["Predictive"]["AllowDifferentConfigs"], false, __FILE__, __LINE__);
146 
148  YAML::Node ConfigInChain = Processor.GetCovConfig(kModelPar);
149  if(ModelSystematic) {
150  YAML::Node ConfigNow = ModelSystematic->GetConfig();
151  if (!compareYAMLNodes(ConfigNow, ConfigInChain))
152  {
153  if(AllowDifferentConfigs){
154  MACH3LOG_WARN("Yaml configs used for your ParameterHandler for chain you want sample from ({}) and one currently initialised are different", PosteriorFileName);
155  } else {
156  MACH3LOG_ERROR("Yaml configs used for your ParameterHandler for chain you want sample from ({}) and one currently initialised are different", PosteriorFileName);
157  throw MaCh3Exception(__FILE__ , __LINE__ );
158  }
159  }
160  }
161  }
162  if(counter > 1) {
163  MACH3LOG_ERROR("Found {} ParmaterHandler inheriting from ParameterHandlerGeneric, I can accept at most 1", counter);
164  throw MaCh3Exception(__FILE__, __LINE__);
165  }
166 
167  for (size_t s = 0; s < systematics.size(); ++s) {
168  NModelParams += systematics[s]->GetNumParams();
169  }
170 
171  if (ModelSystematic) {
172  auto ThrowParamGroupOnly = GetFromManager<std::vector<std::string>>(fitMan->raw()["Predictive"]["ThrowParamGroupOnly"], {}, __FILE__, __LINE__);
173  auto UniqueParamGroup = ModelSystematic->GetUniqueParameterGroups();
174  auto ParameterOnlyToVaryString = GetFromManager<std::vector<std::string>>(fitMan->raw()["Predictive"]["ThrowSingleParams"], {}, __FILE__, __LINE__);
175 
176  if (!ThrowParamGroupOnly.empty() && !ParameterOnlyToVaryString.empty()) {
177  MACH3LOG_ERROR("Can't use ThrowParamGroupOnly and ThrowSingleParams at the same time");
178  throw MaCh3Exception(__FILE__, __LINE__);
179  }
180 
181  if (!ParameterOnlyToVaryString.empty()) {
182  MACH3LOG_INFO("I will throw only: {}", fmt::join(ParameterOnlyToVaryString, ", "));
183  std::vector<int> ParameterVary(ParameterOnlyToVaryString.size());
184 
185  for (size_t i = 0; i < ParameterOnlyToVaryString.size(); ++i) {
186  ParameterVary[i] = ModelSystematic->GetParIndex(ParameterOnlyToVaryString[i]);
187  if (ParameterVary[i] == M3::_BAD_INT_) {
188  MACH3LOG_ERROR("Can't proceed if param {} is missing", ParameterOnlyToVaryString[i]);
189  throw MaCh3Exception(__FILE__, __LINE__);
190  }
191  }
192  ParameterOnlyToVary = std::unordered_set<int>(ParameterVary.begin(), ParameterVary.end());
193  } else {
194  MACH3LOG_INFO("I have following parameter groups: {}", fmt::join(UniqueParamGroup, ", "));
195  if (ThrowParamGroupOnly.empty()) {
196  MACH3LOG_INFO("I will vary all");
197  } else {
198  std::unordered_set<std::string> throwOnlySet(ThrowParamGroupOnly.begin(), ThrowParamGroupOnly.end());
199  ParameterGroupsNotVaried.clear();
200 
201  for (const auto& group : UniqueParamGroup) {
202  if (throwOnlySet.find(group) == throwOnlySet.end()) {
203  ParameterGroupsNotVaried.push_back(group);
204  }
205  }
206 
207  MACH3LOG_INFO("I will vary: {}", fmt::join(ThrowParamGroupOnly, ", "));
208  MACH3LOG_INFO("Exclude: {}", fmt::join(ParameterGroupsNotVaried, ", "));
209  }
210  }
211  }
212 
213  auto paramNode = fitMan->raw()["Predictive"]["ParameterBounds"];
214  for (const auto& p : paramNode) {
215  // Extract name
216  auto name = Get<std::string>(p[0], __FILE__, __LINE__);
217 
218  // Extract bounds: min and max
219  auto minVal = Get<double>(p[1][0], __FILE__, __LINE__);
220  auto maxVal = Get<double>(p[1][1], __FILE__, __LINE__);
221  ParamBounds.emplace_back(minVal, maxVal);
222 
223  for (size_t s = 0; s < systematics.size(); ++s) {
224  for(int iPar = 0; iPar < systematics[s]->GetNParameters(); iPar++){
225  if(systematics[s]->GetParFancyName(iPar) == name){
226  BoundValuePointer.push_back(systematics[s]->RetPointer(iPar));
227  break;
228  }
229  }
230  }
231  if(ParamBounds.size() != BoundValuePointer.size()){
232  MACH3LOG_ERROR("Ddin't find paramter {}", name);
233  throw MaCh3Exception(__FILE__,__LINE__);
234  }
235  MACH3LOG_INFO("Parameter: {} with : [{}, {}]", name, minVal, maxVal);
236  }
237  if(Is_PriorPredictive && ParamBounds.size() > 0) {
238  MACH3LOG_ERROR("Additional bounds not supported by prior predictive right now");
239  throw MaCh3Exception(__FILE__,__LINE__);
240  }
241 }
@ kModelPar
Definition: MCMCProcessor.h:46
bool compareYAMLNodes(const YAML::Node &node1, const YAML::Node &node2, bool Mute=false)
Compare if yaml nodes are identical.
Definition: YamlHelper.h:185
Class responsible for processing MCMC chains, performing diagnostics, generating plots,...
Definition: MCMCProcessor.h:61
int GetParIndex(const std::string &name) const
Get index based on name.
YAML::Node GetConfig() const
Getter to return a copy of the YAML node.
Class responsible for handling of systematic error parameters with different types defined in the con...
std::vector< std::string > GetUniqueParameterGroups() const
KS: Get names of all unique parameter groups.
std::string join(const Container &values, std::string_view separator=" ")
Join all values in a container into a single string.
Definition: TablePrinter.h:36
constexpr static const int _BAD_INT_
Default value used for int initialisation.
Definition: Core.h:55

◆ Study1DProjections()

void PredictiveThrower::Study1DProjections ( const std::vector< TDirectory * > &  SampleDirectories) const
private

Load 1D projections and later produce violin plots for each.

Definition at line 702 of file PredictiveThrower.cpp.

702  {
703 // *************************
704  MACH3LOG_INFO("Starting {}", __func__);
705 
706  TDirectory * ogdir = gDirectory;
707  TDirectory* ToyDir = nullptr;
708 
709  auto ToyFileName = Get<std::string>(fitMan->raw()["Predictive"]["ToyFile"], __FILE__ , __LINE__);
710  // Open the ROOT file
711  int originalErrorWarning = gErrorIgnoreLevel;
712  gErrorIgnoreLevel = kFatal;
713  TFile* file = TFile::Open(ToyFileName.c_str(), "READ");
714  gErrorIgnoreLevel = originalErrorWarning;
715 
716  if (file == nullptr || file->IsZombie()) {
717  MACH3LOG_ERROR("Didn't find Toys_1DHistVar in toy file");
718  throw MaCh3Exception(__FILE__,__LINE__);
719  } else {
720  ToyDir = file->GetDirectory("Toys_1DHistVar");
721  }
722 
723  // [sample], [toy], [dim]
724  std::vector<std::vector<std::vector<std::unique_ptr<TH1D>>>> ProjectionToys(TotalNumberOfSamples);
725  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
726  ProjectionToys[sample].resize(Ntoys);
727  const int nDims = SampleInfo[sample].Dimenstion;
728  for (int iToy = 0; iToy < Ntoys; ++iToy) {
729  ProjectionToys[sample][iToy].resize(nDims);
730  }
731  }
732 
733  for (int iToy = 0; iToy < Ntoys; ++iToy) {
734  if (iToy % 100 == 0) MACH3LOG_INFO(" Loaded Projection toys {}", iToy);
735  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
736  const int nDims = SampleInfo[sample].Dimenstion;
737  for(int iDim = 0; iDim < nDims; iDim ++){
738  std::string ProjectionSuffix = "_1DProj" + std::to_string(iDim) + "_" + std::to_string(iToy);
739  TH1D* MCHist1D = static_cast<TH1D*>(ToyDir->Get((SampleInfo[sample].Name + ProjectionSuffix).c_str()));
740  ProjectionToys[sample][iToy][iDim] = M3::Clone(MCHist1D);
741  }
742  } // end loop over samples
743  } // end loop over toys
744  if(file) { file->Close(); delete file; }
745  if(ogdir){ ogdir->cd(); }
746 
747  ProduceSpectra(ProjectionToys, SampleDirectories, "mc");
748  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
749  const int nDims = SampleInfo[sample].Dimenstion;
750  // KS: We only care about doing projections for 2D, for 1D we have well 1D, for beyond 2D we have flattened TH1D
751  if(nDims == 2){
752  auto hist = Data_Hist[sample].get();
753  SampleDirectories[sample]->cd();
754 
755  std::string nameX = "Data_" + SampleInfo[sample].Name + "_Dim0";
756  std::string nameY = "Data_" + SampleInfo[sample].Name + "_Dim1";
757 
758  if(std::string(hist->ClassName()) == "TH2Poly") {
759  TAxis* xax = ProjectionToys[sample][0][0]->GetXaxis();
760  TAxis* yax = ProjectionToys[sample][0][1]->GetXaxis();
761 
762  std::vector<double> XBinning(xax->GetNbins()+1);
763  std::vector<double> YBinning(yax->GetNbins()+1);
764 
765  for(int i=0;i<=xax->GetNbins();++i)
766  XBinning[i] = xax->GetBinLowEdge(i+1);
767 
768  for(int i=0;i<=yax->GetNbins();++i)
769  YBinning[i] = yax->GetBinLowEdge(i+1);
770 
771  TH1D* ProjectionX = PolyProjectionX(static_cast<TH2Poly*>(hist), nameX.c_str(), XBinning, false);
772  TH1D* ProjectionY = PolyProjectionY(static_cast<TH2Poly*>(hist), nameY.c_str(), YBinning, false);
773 
774  auto x_var = SampleInfo[sample].SamHandler->GetKinVarName(SampleInfo[sample].LocalId, 0);
775  auto y_var = SampleInfo[sample].SamHandler->GetKinVarName(SampleInfo[sample].LocalId, 1);
776  ProjectionX->GetXaxis()->SetTitle(x_var.c_str());
777  ProjectionY->GetXaxis()->SetTitle(y_var.c_str());
778 
779  ProjectionX->SetDirectory(nullptr);
780  ProjectionY->SetDirectory(nullptr);
781 
782  ProjectionX->Write(nameX.c_str());
783  ProjectionY->Write(nameY.c_str());
784 
785  delete ProjectionX;
786  delete ProjectionY;
787  } else { //TH2D
788  TH1D* ProjectionX = static_cast<TH2D*>(hist)->ProjectionX(nameX.c_str());
789  TH1D* ProjectionY = static_cast<TH2D*>(hist)->ProjectionY(nameY.c_str());
790 
791  ProjectionX->SetDirectory(nullptr);
792  ProjectionY->SetDirectory(nullptr);
793 
794  ProjectionX->Write(nameX.c_str());
795  ProjectionY->Write(nameY.c_str());
796  delete ProjectionX;
797  delete ProjectionY;
798  }
799  }
800  }
801 }
void ProduceSpectra(const std::vector< std::vector< std::vector< std::unique_ptr< TH1D >>>> &Toys, const std::vector< TDirectory * > &Director, const std::string suffix, const bool DoSummary=true) const
Produce Violin style spectra.

◆ StudyBetaParameters()

void PredictiveThrower::StudyBetaParameters ( TDirectory *  PredictiveDir)
private

Evaluate prior/post predictive distribution for beta parameters (used for evaluating impact MC statistical uncertainty)

  1. Initialise Beta histogram
  2. Fill histograms, thread safe as all histograms are allocated before and we loop over samples

ROOT enumerates from 1 while MaCh3 from 0

  1. Write to file

Definition at line 1491 of file PredictiveThrower.cpp.

1491  {
1492 // *************************
1493  bool StudyBeta = GetFromManager<bool>(fitMan->raw()["Predictive"]["StudyBetaParameters"], true, __FILE__, __LINE__ );
1494  if (StudyBeta == false) return;
1495 
1496  MACH3LOG_INFO("Starting {}", __func__);
1497  TDirectory* BetaDir = PredictiveDir->mkdir("BetaParameters");
1498  std::vector<std::vector<std::unique_ptr<TH1D>>> BetaHist(TotalNumberOfSamples);
1499  std::vector<TDirectory *> DirBeta(TotalNumberOfSamples);
1500  // initialise directory for each sample
1501  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
1502  BetaDir->cd();
1503  DirBeta[sample] = BetaDir->mkdir(SampleInfo[sample].Name.c_str());
1504  }
1505 
1507  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1508  const int nDims = SampleInfo[iSample].Dimenstion;
1509  // Use any histogram that defines the binning structure
1510  TH1* RefHist = Data_Hist[iSample].get();
1511  BetaHist[iSample] = PerBinHistogram(RefHist, iSample, nDims, "Beta_Parameter");
1512  // Change x-axis title
1513  for (size_t i = 0; i < BetaHist[iSample].size(); ++i) {
1514  BetaHist[iSample][i]->GetXaxis()->SetTitle("beta parameter");
1515  }
1516  }
1517 
1519  #ifdef MULTITHREAD
1520  #pragma omp parallel for
1521  #endif
1522  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1523  const int nDims = SampleInfo[iSample].Dimenstion;
1524  const auto likelihood = SampleInfo[iSample].SamHandler->GetTestStatistic();
1525  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1526  if (nDims == 2) {
1527  if(std::string(Data_Hist[iSample]->ClassName()) == "TH2Poly") {
1528  for (int i = 1; i <= static_cast<TH2Poly*>(Data_Hist[iSample].get())->GetNumberOfBins(); ++i) {
1529  const double Data = Data_Hist[iSample]->GetBinContent(i);
1530  const double MC = MC_Hist_Toy[iSample][iToy]->GetBinContent(i);
1531  const double w2 = W2_Hist_Toy[iSample][iToy]->GetBinContent(i);
1532 
1533  const double BetaParam = GetBetaParameter(Data, MC, w2, likelihood);
1534  BetaHist[iSample][i-1]->Fill(BetaParam, ReweightWeight[iToy]);
1535  } // end loop over poly bins
1536  } else {
1537  const int nX = Data_Hist[iSample]->GetNbinsX();
1538  const int nY = Data_Hist[iSample]->GetNbinsY();
1539  for (int iy = 1; iy <= nY; ++iy) {
1540  for (int ix = 1; ix <= nX; ++ix) {
1541  const int FlatBin = (iy-1) * nX + (ix-1);
1542 
1543  const double Data = Data_Hist[iSample]->GetBinContent(ix, iy);
1544  const double MC = MC_Hist_Toy[iSample][iToy]->GetBinContent(ix, iy);
1545  const double w2 = W2_Hist_Toy[iSample][iToy]->GetBinContent(ix, iy);
1546 
1547  const double BetaParam = GetBetaParameter(Data, MC, w2, likelihood);
1548  BetaHist[iSample][FlatBin]->Fill(BetaParam, ReweightWeight[iToy]);
1549  }
1550  } // end loop over x
1551  } // end loop over y
1552  } else {
1553  int nbinsx = Data_Hist[iSample]->GetNbinsX();
1554  for (int ix = 1; ix <= nbinsx; ++ix) {
1556  const double Data = Data_Hist[iSample]->GetBinContent(ix);
1557  const double MC = MC_Hist_Toy[iSample][iToy]->GetBinContent(ix);
1558  const double w2 = W2_Hist_Toy[iSample][iToy]->GetBinContent(ix);
1559 
1560  const double BetaParam = GetBetaParameter(Data, MC, w2, likelihood);
1561  BetaHist[iSample][ix-1]->Fill(BetaParam, ReweightWeight[iToy]);
1562  } // end loop over bins
1563  }
1564  } // end loop over toys
1565  } // end loop over samples
1566 
1568  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1569  for (size_t iBin = 0; iBin < BetaHist[iSample].size(); iBin++) {
1570  DirBeta[iSample]->cd();
1571  BetaHist[iSample][iBin]->Write();
1572  }
1573  DirBeta[iSample]->Close();
1574  delete DirBeta[iSample];
1575  }
1576  BetaDir->Close();
1577  delete BetaDir;
1578 
1579  PredictiveDir->cd();
1580 }
double GetBetaParameter(const double data, const double mc, const double w2, const TestStatistic TestStat)
KS: Calculate Beta parameter which will be different based on specified test statistic.

◆ StudyBIC()

void PredictiveThrower::StudyBIC ( const std::vector< std::unique_ptr< TH1 >> &  PostPred_mc,
const std::vector< std::unique_ptr< TH1 >> &  PostPred_w 
)
private

Study Bayesian Information Criterion (BIC) The BIC is defined as:

\[ \mathrm{BIC} = -2 \log L + k \log(n) \]

where:

  • \(L\) is the likelihood evaluated at the fitted model
  • \(k\) is the number of model parameters
  • \(n\) is the number of observations

[15]

Definition at line 1841 of file PredictiveThrower.cpp.

1842  {
1843 // ****************
1844  //make fancy event rate histogram
1845  double DataRate = 0.0;
1846  double BinsRate = 0.0;
1847  double TotalLLH = 0.0;
1848  #ifdef MULTITHREAD
1849  #pragma omp parallel for reduction(+:DataRate, BinsRate, TotalLLH)
1850  #endif
1851  for (int i = 0; i < TotalNumberOfSamples; ++i)
1852  {
1853  auto SampleHandler = SampleInfo[i].SamHandler;
1854  auto* h = Data_Hist[i].get();
1855  DataRate += h->Integral();
1856  if (auto h1 = dynamic_cast<TH1D*>(h)) {
1857  BinsRate += h1->GetNbinsX();
1858  } else if (auto h2 = dynamic_cast<TH2D*>(h)) {
1859  BinsRate += h2->GetNbinsX() * h2->GetNbinsY();
1860  } else if (auto h2poly = dynamic_cast<TH2Poly*>(h)) {
1861  BinsRate += h2poly->GetNumberOfBins();
1862  } else {
1863  MACH3LOG_WARN("Unknown histogram type in DataHist[{}]", i);
1864  }
1865  TotalLLH += CalcLLH(Data_Hist[i].get(), PostPred_mc[i].get(), PostPred_w[i].get(), SampleHandler);
1866  }
1867 
1868  const double EventRateBIC = GetBIC(TotalLLH, DataRate, NModelParams);
1869  const double BinBasedBIC = GetBIC(TotalLLH, BinsRate, NModelParams);
1870  MACH3LOG_INFO("Calculated Bayesian Information Criterion using global number of events: {:.2f}", EventRateBIC);
1871  MACH3LOG_INFO("Calculated Bayesian Information Criterion using global number of bins: {:.2f}", BinBasedBIC);
1872  MACH3LOG_INFO("Additional info: NModelParams: {}, DataRate: {:.2f}, BinsRate: {:.2f}", NModelParams, DataRate, BinsRate);
1873 }
double GetBIC(const double llh, const int data, const int nPars)
Get the Bayesian Information Criterion (BIC) or Schwarz information criterion (also SIC,...

◆ StudyByMode1DProjections()

void PredictiveThrower::StudyByMode1DProjections ( const std::vector< TDirectory * > &  SampleDirectories) const
private

Load 1D projections by mode and produce post pred for each.

Todo:
KS: Here we assume each sample has same modes, this is because ProduceSpectra function, expects vector [sample], [toy], [dim], so we make ProjectionToys with [mode], [sample], [toy], [dim] so we can reuse this functionality

Definition at line 804 of file PredictiveThrower.cpp.

804  {
805 // *************************
806  MACH3LOG_INFO("Starting {}", __func__);
807 
808  TDirectory* ogdir = gDirectory;
809  TDirectory* ToyDir = nullptr;
810 
811  auto ToyFileName = Get<std::string>(fitMan->raw()["Predictive"]["ToyFile"], __FILE__ , __LINE__);
812  // Open the ROOT file
813  int originalErrorWarning = gErrorIgnoreLevel;
814  gErrorIgnoreLevel = kFatal;
815  TFile* file = TFile::Open(ToyFileName.c_str(), "READ");
816  gErrorIgnoreLevel = originalErrorWarning;
817 
818  if (file == nullptr || file->IsZombie()) {
819  MACH3LOG_ERROR("Didn't find Toys_ByMode in toy file");
820  throw MaCh3Exception(__FILE__,__LINE__);
821  } else {
822  ToyDir = file->GetDirectory("Toys_ByMode");
823  }
824 
828  auto* mode = SampleInfo[0].SamHandler->GetMaCh3Modes();
829  auto NModes = mode->GetNModes()+1;
830  // [mode], [sample], [toy], [dim]
831  std::vector<std::vector<std::vector<std::vector<std::unique_ptr<TH1D>>>>> ProjectionToys(NModes);
832  for(int iMode = 0; iMode < NModes; iMode++) {
833  ProjectionToys[iMode].resize(TotalNumberOfSamples);
834  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
835  ProjectionToys[iMode][sample].resize(Ntoys);
836  const int nDims = SampleInfo[sample].Dimenstion;
837  for (int iToy = 0; iToy < Ntoys; ++iToy) {
838  ProjectionToys[iMode][sample][iToy].resize(nDims);
839  }
840  }
841  }
842 
843  for (int iToy = 0; iToy < Ntoys; ++iToy) {
844  if (iToy % 100 == 0) MACH3LOG_INFO(" Loaded Projection toys {}", iToy);
845  for(int iMode = 0; iMode < NModes; iMode++) {
846  auto ModeName = mode->GetMaCh3ModeName(iMode);
847  for (int sample = 0; sample < TotalNumberOfSamples; ++sample) {
848  const int nDims = SampleInfo[sample].Dimenstion;
849  for(int iDim = 0; iDim < nDims; iDim ++) {
850  std::string ProjectionSuffix = "_1DProj" + std::to_string(iDim) + "_" + ModeName + "_" + std::to_string(iToy);
851  TH1D* MCHist1D = static_cast<TH1D*>(ToyDir->Get((SampleInfo[sample].Name + ProjectionSuffix).c_str()));
852  ProjectionToys[iMode][sample][iToy][iDim] = M3::Clone(MCHist1D);
853  }
854  }
855  } // end loop over samples
856  } // end loop over toys
857 
858  // ByMode directory
859  std::vector<TDirectory*> ModeDirectory(TotalNumberOfSamples);
860  for(int iSample = 0; iSample < TotalNumberOfSamples; iSample++) {
861  ModeDirectory[iSample] = SampleDirectories[iSample]->mkdir("ByMode");
862  }
863  // Produce By Mode Spectra
864  for(int iMode = 0; iMode < NModes; iMode++) {
865  auto ModeName = mode->GetMaCh3ModeName(iMode);
866  ProduceSpectra(ProjectionToys[iMode], ModeDirectory, ModeName, false);
867  }
868  for(int iSample = 0; iSample < TotalNumberOfSamples; iSample++) {
869  ModeDirectory[iSample]->Close();
870  delete ModeDirectory[iSample];
871  }
872  if(file){file->Close(); delete file;}
873  if(ogdir){ ogdir->cd(); }
874 }

◆ StudyCorrelations()

void PredictiveThrower::StudyCorrelations ( TDirectory *  PredictiveDir,
const std::vector< std::vector< std::unique_ptr< TH1 >>> &  Toys,
const bool  DebugHistograms 
) const
private

Study Prior/Posterior correlations between samples etc.

Definition at line 1584 of file PredictiveThrower.cpp.

1586  {
1587 // ****************
1588  MACH3LOG_INFO("Startin {}", __func__);
1589 
1590  // Make a new directory
1591  TDirectory *CorrDir = PredictiveDir->mkdir("Correlations");
1592  CorrDir->cd();
1593 
1594  std::vector<double> minVals(TotalNumberOfSamples, std::numeric_limits<double>::max());
1595  std::vector<double> maxVals(TotalNumberOfSamples, std::numeric_limits<double>::lowest());
1596  #ifdef MULTITHREAD
1597  #pragma omp parallel for
1598  #endif
1599  for (int i = 0; i < TotalNumberOfSamples; ++i)
1600  {
1601  for (const auto& toyHist : Toys[i])
1602  {
1603  const double val = toyHist->Integral();
1604  if (val < minVals[i]) minVals[i] = val;
1605  if (val > maxVals[i]) maxVals[i] = val;
1606  }
1607  }
1608  auto hSamCorr = std::make_unique<TH2D>("Sample Correlation", "Sample Correlation", TotalNumberOfSamples, 0,
1610  hSamCorr->SetDirectory(nullptr);
1611  hSamCorr->GetZaxis()->SetTitle("Correlation");
1612  hSamCorr->SetMinimum(-1);
1613  hSamCorr->SetMaximum(1);
1614  hSamCorr->GetXaxis()->SetLabelSize(0.015);
1615  hSamCorr->GetYaxis()->SetLabelSize(0.015);
1616  // Loop over the Covariance matrix entries
1617  for (int i = 0; i < TotalNumberOfSamples; ++i) {
1618  hSamCorr->SetBinContent(i+1, i+1, 1.0);
1619  hSamCorr->GetXaxis()->SetBinLabel(i+1, SampleInfo[i].Name.c_str());
1620  for (int j = 0; j < TotalNumberOfSamples; ++j) {
1621  hSamCorr->GetYaxis()->SetBinLabel(j+1, SampleInfo[j].Name.c_str());
1622  }
1623  }
1624 
1625  std::vector<std::vector<std::unique_ptr<TH2D>>> SamCorr(TotalNumberOfSamples);
1626  for (int i = 0; i < TotalNumberOfSamples; ++i)
1627  {
1628  SamCorr[i].resize(TotalNumberOfSamples);
1629  const double Min_i = minVals[i];
1630  const double Max_i = maxVals[i];
1631  for (int j = 0; j < TotalNumberOfSamples; ++j)
1632  {
1633  const double Min_j = minVals[j];
1634  const double Max_j = maxVals[j];
1635  // TH2D to hold the Correlation
1636  std::string name = "SamCorr_" + std::to_string(i) + "_" + std::to_string(j);
1637  SamCorr[i][j] = std::make_unique<TH2D>(name.c_str(), name.c_str(), 70, Min_i, Max_i, 70, Min_j, Max_j);
1638  SamCorr[i][j]->SetDirectory(nullptr);
1639  SamCorr[i][j]->SetMinimum(0);
1640  SamCorr[i][j]->GetXaxis()->SetTitle(SampleInfo[i].Name.c_str());
1641  SamCorr[i][j]->GetYaxis()->SetTitle(SampleInfo[j].Name.c_str());
1642  SamCorr[i][j]->GetZaxis()->SetTitle("Events");
1643  }
1644  }
1645 
1646  // Now we are sure we have the diagonal elements, let's make the off-diagonals
1647  #ifdef MULTITHREAD
1648  #pragma omp parallel for
1649  #endif
1650  for (int i = 0; i < TotalNumberOfSamples; ++i)
1651  {
1652  for (int j = 0; j <= i; ++j)
1653  {
1654  // Skip the diagonal elements which we've already done above
1655  if (j == i) continue;
1656 
1657  for (int iToy = 0; iToy < Ntoys; ++iToy)
1658  {
1659  SamCorr[i][j]->Fill(Toys[i][iToy]->Integral(), Toys[j][iToy]->Integral());
1660  }
1661  SamCorr[i][j]->Smooth();
1662 
1663  // The value of the Covariance
1664  const double corr = SamCorr[i][j]->GetCorrelationFactor();
1665  hSamCorr->SetBinContent(i+1, j+1, corr);
1666  hSamCorr->SetBinContent(j+1, i+1, corr);
1667  }// End j loop
1668  }// End i loop
1669 
1670  hSamCorr->Draw("colz");
1671  hSamCorr->Write("Sample_Corr");
1672 
1673  if(DebugHistograms) {
1674  for (int i = 0; i < TotalNumberOfSamples; ++i){
1675  for (int j = 0; j <= i; ++j) {
1676  // Skip the diagonal elements which we've already done above
1677  if (j == i) continue;
1678  SamCorr[i][j]->Write();
1679  }// End j loop
1680  }// End i loop
1681  } // end if debugHist
1682 
1683  PredictiveDir->cd();
1684 }

◆ StudyDIC()

void PredictiveThrower::StudyDIC ( const std::vector< std::unique_ptr< TH1 >> &  PostPred_mc,
const std::vector< std::unique_ptr< TH1 >> &  PostPred_w 
)
private

KS: Get the Deviance Information Criterion (DIC) The deviance is defined as:

\[ D(\theta) = -2 \log L(\theta) \]

The DIC statistic is then:

\[ \mathrm{DIC} = D(\hat{\theta}) + 2p_D \]

where:

\[ p_D = \bar{D} - D(\hat{\theta}) \]

is the effective number of parameters, and

\[ \bar{D} = E_{\theta|y}[D(\theta)] \]

[35] [37]

Definition at line 1877 of file PredictiveThrower.cpp.

1878  {
1879 // ****************
1880  //The posterior mean of the deviance
1881  double Dbar = 0.;
1882  double TotalLLH = 0.0;
1883 
1884  #ifdef MULTITHREAD
1885  #pragma omp parallel for reduction(+:Dbar)
1886  #endif
1887  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample)
1888  {
1889  auto SampleHandler = SampleInfo[iSample].SamHandler;
1890  TotalLLH += CalcLLH(Data_Hist[iSample].get(), PostPred_mc[iSample].get(), PostPred_w[iSample].get(), SampleHandler);
1891  double LLH_temp = 0.;
1892  for (int iToy = 0; iToy < Ntoys; ++iToy)
1893  {
1894  LLH_temp += CalcLLH(Data_Hist[iSample].get(), MC_Hist_Toy[iSample][iToy].get(), W2_Hist_Toy[iSample][iToy].get(), SampleHandler);
1895  }
1896  Dbar += LLH_temp;
1897  }
1898  Dbar = Dbar / Ntoys;
1899 
1900  // A point estimate of the deviance
1901  const double Dhat = TotalLLH;
1902 
1903  //Effective number of parameters
1904  const double p_D = std::fabs(Dbar - Dhat);
1905 
1906  //Actual test stat
1907  const double DIC_stat = Dhat + 2 * p_D;
1908  MACH3LOG_INFO("Effective number of parameters following DIC formalism is equal to: {:.2f}", p_D);
1909  MACH3LOG_INFO("DIC test statistic = {:.2f}", DIC_stat);
1910 }

◆ StudyInformationCriterion()

void PredictiveThrower::StudyInformationCriterion ( M3::kInfCrit  Criterion,
const std::vector< std::unique_ptr< TH1 >> &  PostPred_mc,
const std::vector< std::unique_ptr< TH1 >> &  PostPred_w 
)
private

Information Criterion.

Definition at line 1811 of file PredictiveThrower.cpp.

1813  {
1814 // ****************
1815  MACH3LOG_INFO("******************************");
1816  switch(Criterion) {
1817  case M3::kInfCrit::kBIC:
1818  // Study Bayesian Information Criterion
1819  StudyBIC(PostPred_mc, PostPred_w);
1820  break;
1821  case M3::kInfCrit::kDIC:
1822  // Study Deviance Information Criterion
1823  StudyDIC(PostPred_mc, PostPred_w);
1824  break;
1825  case M3::kInfCrit::kWAIC:
1826  // Study Watanabe-Akaike information criterion (WAIC)
1827  StudyWAIC();
1828  break;
1830  MACH3LOG_ERROR("kInfCrits is not a valid kInfCrit!");
1831  throw MaCh3Exception(__FILE__, __LINE__);
1832  default:
1833  MACH3LOG_ERROR("UNKNOWN Information Criterion SPECIFIED!");
1834  MACH3LOG_ERROR("You gave {}", static_cast<int>(Criterion));
1835  throw MaCh3Exception(__FILE__ , __LINE__ );
1836  }
1837  MACH3LOG_INFO("******************************");
1838 }
void StudyBIC(const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w)
Study Bayesian Information Criterion (BIC) The BIC is defined as:
void StudyWAIC()
KS: Get the Watanabe-Akaike information criterion (WAIC)
void StudyDIC(const std::vector< std::unique_ptr< TH1 >> &PostPred_mc, const std::vector< std::unique_ptr< TH1 >> &PostPred_w)
KS: Get the Deviance Information Criterion (DIC) The deviance is defined as:
@ kInfCrits
This only enumerates.
@ kBIC
Bayesian Information Criterion.
@ kDIC
Deviance Information Criterion.

◆ StudyWAIC()

void PredictiveThrower::StudyWAIC ( )
private

KS: Get the Watanabe-Akaike information criterion (WAIC)

WAIC is a fully Bayesian measure of model fit that estimates the predictive accuracy, taking into account the effective number of parameters in the model.

It is defined as:

\[ \text{WAIC} = -2 \left( \text{lppd} - p_\text{WAIC} \right), \]

where

\[ \text{lppd} = \sum_{i=1}^n \log \left( \frac{1}{S} \sum_{s=1}^S p(y_i \mid \theta_s) \right) \]

is the log pointwise predictive density and

\[ p_\text{WAIC} = \sum_{i=1}^n \text{Var}_{s=1,\dots,S} \left[ \log p(y_i \mid \theta_s) \right] \]

is the effective number of parameters (variance of log-likelihood over posterior samples).

[15] [20]

Definition at line 1948 of file PredictiveThrower.cpp.

1948  {
1949 // ****************
1950  // log pointwise predictive density
1951  double lppd = 0.;
1952  // effective number of parameters
1953  double p_WAIC = 0.;
1954 
1955  #ifdef MULTITHREAD
1956  #pragma omp parallel for reduction(+:lppd, p_WAIC)
1957  #endif
1958  for (int iSample = 0; iSample < TotalNumberOfSamples; ++iSample) {
1959  auto SampleHandler = SampleInfo[iSample].SamHandler;
1960  auto* hData = Data_Hist[iSample].get();
1961 
1962  if (auto h2poly = dynamic_cast<TH2Poly*>(hData)) {
1963  // TH2Poly: irregular bins, linear indexing
1964  for (int i = 1; i <= h2poly->GetNumberOfBins(); ++i) {
1965  const double data = Data_Hist[iSample]->GetBinContent(i);
1966  double mean_llh = 0.;
1967  double sum_exp_llh = 0;
1968  double mean_llh_squared = 0.;
1969 
1970  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1971  const double mc = MC_Hist_Toy[iSample][iToy]->GetBinContent(i);
1972  const double w2 = W2_Hist_Toy[iSample][iToy]->GetBinContent(i);
1973  // Get the -log-likelihood for this sample and bin
1974  double neg_LLH_temp = SampleHandler->GetTestStatLLH(data, mc, w2);
1975  AccumulateWAICToy(neg_LLH_temp, mean_llh, mean_llh_squared, sum_exp_llh);
1976  }
1977  AccumulateWAICBin(mean_llh, mean_llh_squared, sum_exp_llh, Ntoys, lppd, p_WAIC);
1978  }
1979  } else if (auto h2 = dynamic_cast<TH2D*>(hData)) {
1980  // TH2D: nested loops over X and Y
1981  for (int ix = 1; ix <= h2->GetNbinsX(); ++ix) {
1982  for (int iy = 1; iy <= h2->GetNbinsY(); ++iy) {
1983  const double data = hData->GetBinContent(ix, iy);
1984  double mean_llh = 0.;
1985  double mean_llh_squared = 0.;
1986  double sum_exp_llh = 0.;
1987  for (int iToy = 0; iToy < Ntoys; ++iToy) {
1988  const double mc = MC_Hist_Toy[iSample][iToy]->GetBinContent(ix, iy);
1989  const double w2 = W2_Hist_Toy[iSample][iToy]->GetBinContent(ix, iy);
1990  // Get the -log-likelihood for this sample and bin
1991  double neg_LLH_temp = SampleHandler->GetTestStatLLH(data, mc, w2);
1992  AccumulateWAICToy(neg_LLH_temp, mean_llh, mean_llh_squared, sum_exp_llh);
1993  }
1994  AccumulateWAICBin(mean_llh, mean_llh_squared, sum_exp_llh, Ntoys, lppd, p_WAIC);
1995  }
1996  }
1997  } else if (auto h1 = dynamic_cast<TH1D*>(hData)) {
1998  // TH1D: 1D histogram
1999  for (int iBin = 1; iBin <= h1->GetNbinsX(); ++iBin) {
2000  const double data = hData->GetBinContent(iBin);
2001  double mean_llh = 0.;
2002  double mean_llh_squared = 0.;
2003  double sum_exp_llh = 0.;
2004  for (int iToy = 0; iToy < Ntoys; ++iToy) {
2005  const double mc = MC_Hist_Toy[iSample][iToy]->GetBinContent(iBin);
2006  const double w2 = W2_Hist_Toy[iSample][iToy]->GetBinContent(iBin);
2007 
2008  // Get the -log-likelihood for this sample and bin
2009  double neg_LLH_temp = SampleHandler->GetTestStatLLH(data, mc, w2);
2010  AccumulateWAICToy(neg_LLH_temp, mean_llh, mean_llh_squared, sum_exp_llh);
2011  }
2012  AccumulateWAICBin(mean_llh, mean_llh_squared, sum_exp_llh, Ntoys, lppd, p_WAIC);
2013  }
2014  }
2015  }
2016 
2017  // Compute WAIC, see Eq. 13 in Gelman2014
2018  double WAIC = -2 * (lppd - p_WAIC);
2019  MACH3LOG_INFO("Effective number of parameters following WAIC formalism is equal to: {:.2f}", p_WAIC);
2020  MACH3LOG_INFO("WAIC = {:.2f}", WAIC);
2021 }
void AccumulateWAICToy(const double neg_LLH_temp, double &mean_llh, double &mean_llh_squared, double &sum_exp_llh)
void AccumulateWAICBin(double &mean_llh, double &mean_llh_squared, double &sum_exp_llh, const unsigned int Ntoys, double &lppd, double &p_WAIC)

◆ WriteByModeToys()

void PredictiveThrower::WriteByModeToys ( TDirectory *  ByModeDirectory,
const int  iToy 
)
private

Save mode histograms for a single MCMC Throw/Toy.

Definition at line 433 of file PredictiveThrower.cpp.

434  {
435 // *************************
436  for (size_t iPDF = 0; iPDF < samples.size(); iPDF++)
437  {
438  auto* SampleHandler = samples[iPDF];
439  auto* modes = SampleHandler->GetMaCh3Modes();
440  for (int iSample = 0; iSample < SampleHandler->GetNSamples(); ++iSample)
441  {
442  ByModeDirectory->cd();
443 
444  auto SampleName = SampleHandler->GetSampleTitle(iSample);
445  for (int iMode = 0; iMode < modes->GetNModes()+1; ++iMode) {
446  auto ModeName = modes->GetMaCh3ModeName(iMode);
447  for(int iDim = 0; iDim < SampleHandler->GetNDim(iSample); iDim++) {
448  std::string ProjectionName = SampleHandler->GetKinVarName(iSample, iDim);
449  std::string PlotSuffix = "_1DProj" + std::to_string(iDim) + "_" + ModeName + "_" + std::to_string(iToy);
450 
451  auto hist = SampleHandler->Get1DVarHistByModeAndChannel(iSample, ProjectionName, iMode);
452  hist->SetTitle((SampleName + PlotSuffix).c_str());
453  hist->SetName((SampleName + PlotSuffix).c_str());
454  hist->Write();
455  } // end loop over dimension
456  } // end loop over mode
457  } // end loop over sample
458  } // end loop over sample handler objects
459 }

◆ WriteToy()

void PredictiveThrower::WriteToy ( TDirectory *  ToyDirectory,
TDirectory *  Toy_1DDirectory,
TDirectory *  Toy_2DDirectory,
const int  iToy 
)
private

Save histograms for a single MCMC Throw/Toy.

Definition at line 375 of file PredictiveThrower.cpp.

378  {
379 // *************************
380  int SampleCounter = 0;
381  for (size_t iPDF = 0; iPDF < samples.size(); iPDF++)
382  {
383  auto* SampleHandler = samples[iPDF];
384  for (int iSample = 0; iSample < SampleHandler->GetNSamples(); ++iSample)
385  {
386  ToyDirectory->cd();
387 
388  auto SampleName = SampleHandler->GetSampleTitle(iSample);
389  const TH1* MCHist = SampleHandler->GetMCHist(iSample);
390  MC_Hist_Toy[SampleCounter][iToy] = M3::Clone(MCHist, SampleName + "_mc_" + std::to_string(iToy));
391  MC_Hist_Toy[SampleCounter][iToy]->Write();
392 
393  const TH1* W2Hist = SampleHandler->GetW2Hist(iSample);
394  W2_Hist_Toy[SampleCounter][iToy] = M3::Clone(W2Hist, SampleName + "_w2_" + std::to_string(iToy));
395  W2_Hist_Toy[SampleCounter][iToy]->Write();
396 
397  // now get 1D projection for every dimension
398  Toy_1DDirectory->cd();
399  for(int iDim = 0; iDim < SampleHandler->GetNDim(iSample); iDim++) {
400  std::string ProjectionName = SampleHandler->GetKinVarName(iSample, iDim);
401  std::string ProjectionSuffix = "_1DProj" + std::to_string(iDim) + "_" + std::to_string(iToy);
402 
403  auto hist = SampleHandler->Get1DVarHist(iSample, ProjectionName);
404  hist->SetTitle((SampleName + ProjectionSuffix).c_str());
405  hist->SetName((SampleName + ProjectionSuffix).c_str());
406  hist->Write();
407  }
408 
409  Toy_2DDirectory->cd();
410  // now get 2D projection for every combination
411  for(int iDim1 = 0; iDim1 < SampleHandler->GetNDim(iSample); iDim1++) {
412  for (int iDim2 = iDim1 + 1; iDim2 < SampleHandler->GetNDim(iSample); ++iDim2) {
413  // Get the names for the two dimensions
414  std::string XVarName = SampleHandler->GetKinVarName(iSample, iDim1);
415  std::string YVarName = SampleHandler->GetKinVarName(iSample, iDim2);
416 
417  // Get the 2D histogram for this pair
418  auto hist2D = SampleHandler->Get2DVarHist(iSample, XVarName, YVarName);
419 
420  // Write the histogram
421  std::string suffix2D = "_2DProj_" + std::to_string(iDim1) + "_vs_" + std::to_string(iDim2) + "_" + std::to_string(iToy);
422  hist2D->SetTitle((SampleName + suffix2D).c_str());
423  hist2D->SetName((SampleName + suffix2D).c_str());
424  hist2D->Write();
425  }
426  }
427  SampleCounter++;
428  }
429  }
430 }

Member Data Documentation

◆ Data_Hist

std::vector<std::unique_ptr<TH1> > PredictiveThrower::Data_Hist
private

Vector of Data histograms.

Definition at line 307 of file PredictiveThrower.h.

◆ FullLLH

bool PredictiveThrower::FullLLH
private

KS: Use Full LLH or only sample contribution based on discussion with Asher we almost always only want the sample likelihood.

Definition at line 288 of file PredictiveThrower.h.

◆ Is_PriorPredictive

bool PredictiveThrower::Is_PriorPredictive
private

Whether it is Prior or Posterior predictive.

Definition at line 292 of file PredictiveThrower.h.

◆ MC_Hist_Toy

std::vector<std::vector<std::unique_ptr<TH1> > > PredictiveThrower::MC_Hist_Toy
private

Vector of MC histograms per sample and toy experiment. Indexed as [sample][toy].

Definition at line 315 of file PredictiveThrower.h.

◆ MC_Nom_Hist

std::vector<std::unique_ptr<TH1> > PredictiveThrower::MC_Nom_Hist
private

Vector of MC histograms.

Definition at line 309 of file PredictiveThrower.h.

◆ ModelSystematic

ParameterHandlerGeneric* PredictiveThrower::ModelSystematic
private

Pointer to El Generico.

Definition at line 304 of file PredictiveThrower.h.

◆ NModelParams

int PredictiveThrower::NModelParams
private

KS: Count total number of model parameters which can be used for stuff like BIC.

Definition at line 290 of file PredictiveThrower.h.

◆ Ntoys

int PredictiveThrower::Ntoys
private

Number of toys we are generating analysing.

Definition at line 301 of file PredictiveThrower.h.

◆ PenaltyTerm

std::vector<double> PredictiveThrower::PenaltyTerm
private

Penalty term values for each toy by default 0.

Definition at line 323 of file PredictiveThrower.h.

◆ ReweightWeight

std::vector<double> PredictiveThrower::ReweightWeight
private

Reweighting factors applied for each toy, by default 1.

Definition at line 321 of file PredictiveThrower.h.

◆ SampleInfo

std::vector<PredictiveSample> PredictiveThrower::SampleInfo
private

Handy struct for all sample info.

Definition at line 298 of file PredictiveThrower.h.

◆ StandardFluctuation

bool PredictiveThrower::StandardFluctuation
private

KS: We have two methods for Poissonian fluctuation.

Definition at line 326 of file PredictiveThrower.h.

◆ TotalNumberOfSamples

int PredictiveThrower::TotalNumberOfSamples
private

Number of toys we are generating analysing.

Definition at line 295 of file PredictiveThrower.h.

◆ W2_Hist_Toy

std::vector<std::vector<std::unique_ptr<TH1> > > PredictiveThrower::W2_Hist_Toy
private

Vector of W² histograms per sample and toy experiment. Indexed as [sample][toy]

Definition at line 318 of file PredictiveThrower.h.

◆ W2_Nom_Hist

std::vector<std::unique_ptr<TH1> > PredictiveThrower::W2_Nom_Hist
private

Vector of W2 histograms.

Definition at line 311 of file PredictiveThrower.h.


The documentation for this class was generated from the following files: