15 double xmax = graph->GetXmax();
16 double xmin = graph->GetXmin();
17 double ymin = graph->GetYmin();
18 double ymax = graph->GetYmax();
20 double chiSquared, prior;
22 if (theta13 < xmax && theta13 > xmin && dm32 < ymax && dm32 > ymin) {
23 chiSquared = graph->Interpolate(theta13, dm32);
24 prior = std::exp(-0.5 * chiSquared);
39 double xmax = graph->GetXmax();
40 double xmin = graph->GetXmin();
41 double ymax = graph->GetYmax();
42 double ymin = graph->GetYmin();
45 double mod_dm32 = std::abs(dm32);
46 double chiSquared, prior;
48 if (theta13 < xmax && theta13 > xmin && mod_dm32 < ymax && mod_dm32 > ymin) {
49 chiSquared = graph->Interpolate(theta13, mod_dm32);
50 prior = std::exp(-0.5 * chiSquared);
66 double xmax = -999999999;
67 double xmin = 999999999;
69 for (
int i = 0; i < graph->GetN(); i++) {
70 double x = graph->GetX()[i];
71 if (x > xmax) xmax = x;
72 if (x < xmin) xmin = x;
75 double chiSquared, prior;
77 if (theta13 < xmax && theta13 > xmin) {
78 chiSquared = graph->Eval(theta13);
79 prior = std::exp(-0.5 * chiSquared);
107 for (
const auto& reweight : reweight_settings) {
108 const std::string& reweightKey = reweight.first.as<std::string>();
109 const YAML::Node& reweightConfigNode = reweight.second;
112 if (!GetFromManager<bool>(reweightConfigNode[
"Enabled"],
true, __FILE__ , __LINE__)) {
113 MACH3LOG_INFO(
"Skipping disabled reweight: {}", reweightKey);
118 reweightConfig.
key = reweightKey;
119 reweightConfig.
name = Get<std::string>(reweightConfigNode[
"ReweightName"], __FILE__ , __LINE__);
120 auto ReweightType = Get<std::string>(reweightConfigNode[
"ReweightType"], __FILE__ , __LINE__);
121 reweightConfig.
dimension = Get<int>(reweightConfigNode[
"ReweightDim"], __FILE__ , __LINE__);
126 auto paramNames = Get<std::vector<std::string>>(reweightConfigNode[
"ReweightVar"], __FILE__ , __LINE__);
129 reweightConfig.
flatPrior.resize(paramNames.size());
133 if (ReweightType ==
"Gaussian") {
137 auto priorNode = reweightConfigNode[
"ReweightPrior"];
138 std::vector<std::vector<double>> allPriorValues;
140 if (priorNode.IsSequence() && priorNode.size() > 0) {
142 if (priorNode[0].IsScalar()) {
144 auto newPriorValues = Get<std::vector<double>>(priorNode, __FILE__ , __LINE__);
145 if (newPriorValues.size() == 2) {
146 allPriorValues.push_back(newPriorValues);
151 for (
const auto& priorPair : priorNode) {
152 auto newPriorValues = Get<std::vector<double>>(priorPair, __FILE__ , __LINE__);
153 if (newPriorValues.size() == 2) {
154 allPriorValues.push_back(newPriorValues);
162 if (paramNames.empty() || allPriorValues.empty() || paramNames.size() != allPriorValues.size()) {
163 MACH3LOG_ERROR(
"Invalid Gaussian reweight configuration for {}: {} parameters, {} prior pairs", reweightKey, paramNames.size(), allPriorValues.size());
167 else if (ReweightType ==
"TGraph") {
170 auto fileName = Get<std::string>(reweightConfigNode[
"ReweightPrior"][
"file"], __FILE__ , __LINE__);
171 auto graphName = Get<std::string>(reweightConfigNode[
"ReweightPrior"][
"graph_name"], __FILE__ , __LINE__);
175 if (paramNames.empty() || paramNames.size() != 1 || fileName.empty() || graphName.empty()) {
176 MACH3LOG_ERROR(
"Invalid TGraph reweight configuration for {}", reweightKey);
182 auto constraintFile = std::unique_ptr<TFile>(TFile::Open(reweightConfig.
fileName.c_str(),
"READ"));
183 if (!constraintFile || constraintFile->IsZombie()) {
188 std::unique_ptr<TGraph> graph(constraintFile->Get<TGraph>(reweightConfig.
graphName.c_str()));
191 auto cloned_graph =
static_cast<TGraph*
>(graph->Clone());
192 cloned_graph->SetBit(kCanDelete,
true);
193 reweightConfig.
graph_1D = std::unique_ptr<TGraph>(cloned_graph);
202 MACH3LOG_ERROR(
"Unknown 1D reweight type: {} for {}", ReweightType, reweightKey);
206 else if (reweightConfig.
dimension == 2) {
208 if (paramNames.size() != 2) {
209 MACH3LOG_ERROR(
"2D reweighting requires exactly 2 parameter names for {}", reweightKey);
213 if (ReweightType ==
"TGraph2D") {
215 auto priorConfig = reweightConfigNode[
"ReweightPrior"];
216 reweightConfig.
fileName = Get<std::string>(priorConfig[
"file"], __FILE__ , __LINE__);
217 reweightConfig.
graphName = Get<std::string>(priorConfig[
"graph_name"], __FILE__ , __LINE__);
218 reweightConfig.
hierarchyType = GetFromManager<std::string>(priorConfig[
"hierarchy"],
"auto", __FILE__ , __LINE__);
221 MACH3LOG_ERROR(
"Invalid TGraph2D configuration for {}", reweightKey);
227 auto constraintFile = std::unique_ptr<TFile>(TFile::Open(reweightConfig.
fileName.c_str(),
"READ"));
228 if (!constraintFile || constraintFile->IsZombie()) {
235 std::string graphName_NO = reweightConfig.
graphName +
"_NO";
238 std::unique_ptr<TGraph2D> graph_NO(constraintFile->Get<TGraph2D>(graphName_NO.c_str()));
241 auto cloned_graph =
static_cast<TGraph2D*
>(graph_NO->Clone());
242 cloned_graph->SetDirectory(
nullptr);
243 cloned_graph->SetBit(kCanDelete,
true);
244 reweightConfig.
graph_NO = std::unique_ptr<TGraph2D>(cloned_graph);
252 std::string graphName_IO = reweightConfig.
graphName +
"_IO";
254 std::unique_ptr<TGraph2D> graph_IO(constraintFile->Get<TGraph2D>(graphName_IO.c_str()));
257 auto cloned_graph =
static_cast<TGraph2D*
>(graph_IO->Clone());
258 cloned_graph->SetDirectory(
nullptr);
259 cloned_graph->SetBit(kCanDelete,
true);
260 reweightConfig.
graph_IO = std::unique_ptr<TGraph2D>(cloned_graph);
268 constraintFile->Close();
271 MACH3LOG_ERROR(
"Unknown 2D reweight type: {} for {}", ReweightType, reweightKey);
280 reweightConfigs.push_back(std::move(reweightConfig));
281 MACH3LOG_INFO(
"Added reweight configuration: {} ({}D, type: {})", reweightConfigs.back().name, reweightConfigs.back().dimension, ReweightType);
284 if (reweightConfigs.empty()) {
285 MACH3LOG_ERROR(
"No valid reweight configurations found in config file");
297 for (
unsigned int j = 0; j < paramNames.size(); ++j)
302 double NewCentral = newPriorPair[0];
303 double NewError = newPriorPair[1];
305 double new_chi = (paramValues.at(name) - NewCentral)/NewError;
306 double new_prior = std::exp(-0.5 * new_chi * new_chi);
309 double old_prior = -1;
314 double OldCentral = newPriorPair[0];
315 double OldError = newPriorPair[1];
317 old_chi = (paramValues.at(name) - OldCentral)/OldError;
318 old_prior = std::exp(-0.5 * old_chi * old_chi);
320 weight *= new_prior/old_prior;
323 double paramValue = paramValues.at(rwConfig.
paramNames.at(0));
333 double dm32 = paramValues.at(rwConfig.
paramNames.at(0));
334 double theta13 = paramValues.at(rwConfig.
paramNames.at(1));
363 MACH3LOG_INFO(
"File for reweighting: {} with config {}", inputFile, configFile);
366 YAML::Node reweight_settings = reweight_yaml[
"ReweightMCMC"];
369 std::vector<ReweightConfig> reweightConfigs;
374 auto processor = std::make_unique<MCMCProcessor>(inputFile);
375 processor->Initialise();
379 for (
auto& rwConfig : reweightConfigs) {
380 for (
size_t i = 0; i < rwConfig.paramNames.size(); ++i) {
381 const auto& paramName = rwConfig.paramNames[i];
382 int paramIndex = processor->GetParamIndexFromName(paramName);
384 MACH3LOG_ERROR(
"Parameter {} not found in MCMC chain", paramName);
393 rwConfig.oldPriorValues[i] = {mean, sigma};
394 rwConfig.flatPrior[i] =
isFlat;
400 auto TempFile = std::unique_ptr<TFile>(TFile::Open(inputFile.c_str(),
"READ"));
401 if (!TempFile || TempFile->IsZombie()) {
405 std::unique_ptr<TMacro> Config(TempFile->Get<TMacro>(
"MaCh3_Config"));
407 MACH3LOG_ERROR(
"Didn't find MaCh3_Config tree in MCMC file! {}", inputFile.c_str());
413 bool asimovfit = GetFromManager<bool>(Settings[
"General"][
"Asimov"],
false, __FILE__ , __LINE__);
416 MACH3LOG_WARN(
"ReweightMCMC does not currently handle Asimov shifting, results may be incorrect!");
418 MACH3LOG_INFO(
"Not an Asimov fit, proceeding with reweighting");
422 auto inFile = std::unique_ptr<TFile>(TFile::Open(inputFile.c_str(),
"READ"));
423 if (!inFile || inFile->IsZombie()) {
428 std::unique_ptr<TTree> inTree(inFile->Get<TTree>(
"posteriors"));
435 std::string configString = configFile.substr(configFile.find_last_of(
'/') + 1, configFile.find_last_of(
'.') - configFile.find_last_of(
'/') - 1);
436 std::string outputFile = inputFile.substr(0, inputFile.find_last_of(
'.')) +
"_reweighted_" + configString +
".root";
437 auto outFile = std::unique_ptr<TFile>(TFile::Open(outputFile.c_str(),
"RECREATE"));
438 if (!outFile || outFile->IsZombie()) {
446 TIter next(inFile->GetListOfKeys());
447 while (TKey* key =
dynamic_cast<TKey*
>(next())) {
449 std::unique_ptr<TObject> obj(key->ReadObj());
450 if (obj->IsA()->InheritsFrom(TDirectory::Class())) {
452 TDirectory* srcDir =
static_cast<TDirectory*
>(obj.get());
453 TDirectory* destDir = outFile->mkdir(srcDir->GetName());
454 TIter nextSubKey(srcDir->GetListOfKeys());
455 while (TKey* subKey =
dynamic_cast<TKey*
>(nextSubKey())) {
457 std::unique_ptr<TObject> subObj(subKey->ReadObj());
461 }
else if (std::string(key->GetName()) !=
"posteriors") {
470 std::unique_ptr<TTree> outTree(inTree->CloneTree(0));
473 std::map<std::string, double> paramValues;
474 for (
const auto& rwConfig : reweightConfigs) {
475 for (
const auto& paramName : rwConfig.paramNames) {
476 if (paramValues.find(paramName) == paramValues.end()) {
477 paramValues[paramName] = 0.0;
479 auto idx = processor->GetParamIndexFromName(paramName);
480 auto BranchName = processor->GetBranchNames()[idx];
481 inTree->SetBranchAddress(BranchName, ¶mValues[paramName]);
487 std::map<std::string, double> weights;
488 std::map<std::string, TBranch*> weightBranches;
490 for (
const auto& rwConfig : reweightConfigs) {
491 weights[rwConfig.weightBranchName] = 1.0;
492 weightBranches[rwConfig.weightBranchName] = outTree->Branch(rwConfig.weightBranchName.c_str(), &weights[rwConfig.weightBranchName], (rwConfig.weightBranchName +
"/D").c_str());
493 MACH3LOG_INFO(
"Added weight branch: {}", rwConfig.weightBranchName);
498 Long64_t nEntries = inTree->GetEntries();
502 for (Long64_t i = 0; i < nEntries; ++i) {
508 for (
const auto& rwConfig : reweightConfigs) {
510 if (rwConfig.dimension == 1) {
512 }
else if (rwConfig.dimension == 2) {
515 weights[rwConfig.weightBranchName] = weight;
526 TMacro reweightMacro;
527 reweightMacro.SetName(
"Reweight_Config");
528 reweightMacro.SetTitle(
"ReweightMCMC configuration");
529 std::stringstream ss;
530 ss << reweight_settings;
531 reweightMacro.AddLine(ss.str().c_str());
532 reweightMacro.Write();
541 m_parser = std::make_unique<MaCh3ArgumentParser>(
"reweight",
"1.0", argparse::default_arguments::help);
542 m_parser->add_description(
"Tool for MCMC reweighting.");
544 .help(
"Config file.")
547 m_parser->add_argument(
"mcmc-output")
548 .help(
"MCMC chain root file.")
549 .metavar(
"MCMC_CHAIN")
557 std::string filename =
m_parser->get<std::string>(
"mcmc-output");
558 std::string config =
m_parser->get<std::string>(
"config");
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Module for MCMC reweighting analysis.
bool isFlat(TSpline3_red *&spl)
CW: Helper function used in the constructor, tests to see if the spline is flat.
YAML::Node TMacroToYAML(const TMacro ¯o)
KS: Convert a ROOT TMacro object to a YAML node.
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Extended ArgumentParser with MaCh3-specific functionality.
std::unique_ptr< MaCh3ArgumentParser > m_parser
Argument parser for this plugin.
void ReweightMCMC(const std::string &configFile, const std::string &inputFile)
Main executable responsible for reweighting MCMC chains.
double Get1DWeight(const ReweightConfig &rwConfig, const std::map< std::string, double > ¶mValues)
Calculate 1D weight.
double Graph_interpolateIO(TGraph2D *graph, double theta13, double dm32)
Function to interpolate 2D graph for Inverted Ordering.
double Get2DWeight(const ReweightConfig &rwConfig, const std::map< std::string, double > ¶mValues)
Calculate 2D weight.
double Graph_interpolate1D(TGraph *graph, double theta13)
Function to interpolate 1D graph.
void LoadReweightingSettings(std::vector< ReweightConfig > &reweightConfigs, const YAML::Node &reweight_settings)
Load reweighting setting like 1D or 2D from YAML config.
bool GetParameterInfo(MCMCProcessor *processor, const std::string ¶mName, double &mean, double &sigma, bool &isFlat)
Get parameter information from MCMCProcessor.
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
virtual ~ReweightModule()
Destructor.
double Graph_interpolateNO(TGraph2D *graph, double theta13, double dm32)
Function to interpolate 2D graph for Normal Ordering.
int Run() override
Execute the MCMC reweighting analysis.
Class responsible for processing MCMC chains, performing diagnostics, generating plots,...
void GetNthParameter(const int param, double &Prior, double &PriorError, TString &Title) const
Get properties of parameter by passing it number.
bool GetParamFlat(const int iParam) const
Get whether param has flat prior or not.
int GetParamIndexFromName(const std::string &Name) const
Get parameter number based on name.
Custom exception class used throughout MaCh3.
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
Main namespace for MaCh3 software.
constexpr static const int _BAD_INT_
Default value used for int initialisation.
@ kTGraph
Calculates Likelihood based on TGraph.
@ kGaussian
Assumes gaussian prior.
@ kTGraph2D
Calculates Likelihood based on TGraph2D.
Structure to hold reweight configuration.
std::vector< std::vector< double > > newPriorValues
new [mean, sigma] pairs
std::unique_ptr< TGraph2D > graph_IO
Inverted Ordering graph.
std::string key
The YAML key for this reweight.
std::vector< std::string > paramNames
Parameter names.
M3::kReweightType type
"Gaussian", "TGraph2D"
std::string graphName
Graph name in the ROOT file.
std::vector< bool > flatPrior
std::string fileName
ROOT file containing graph data.
std::unique_ptr< TGraph > graph_1D
1D interpolation graph.
std::vector< std::vector< double > > oldPriorValues
new [mean, sigma] pairs
std::unique_ptr< TGraph2D > graph_NO
Normal Ordering graph.
std::string weightBranchName
Output weight branch name.
std::string hierarchyType
"NO", "IO", or "auto"