MaCh3  2.8.0
Reference Guide
Public Member Functions | List of all members
M3::ReweightModule Class Reference

Module for performing reweighting analysis on MCMC chains. More...

#include <CLI/Modules/ReweightModule.hpp>

Inheritance diagram for M3::ReweightModule:
[legend]
Collaboration diagram for M3::ReweightModule:
[legend]

Public Member Functions

virtual ~ReweightModule ()
 Destructor. More...
 
double Graph_interpolateNO (TGraph2D *graph, double theta13, double dm32)
 Function to interpolate 2D graph for Normal Ordering. More...
 
double Graph_interpolateIO (TGraph2D *graph, double theta13, double dm32)
 Function to interpolate 2D graph for Inverted Ordering. More...
 
double Graph_interpolate1D (TGraph *graph, double theta13)
 Function to interpolate 1D graph. More...
 
bool GetParameterInfo (MCMCProcessor *processor, const std::string &paramName, double &mean, double &sigma, bool &isFlat)
 Get parameter information from MCMCProcessor. More...
 
void LoadReweightingSettings (std::vector< ReweightConfig > &reweightConfigs, const YAML::Node &reweight_settings)
 Load reweighting setting like 1D or 2D from YAML config. More...
 
double Get1DWeight (const ReweightConfig &rwConfig, const std::map< std::string, double > &paramValues)
 Calculate 1D weight. More...
 
double Get2DWeight (const ReweightConfig &rwConfig, const std::map< std::string, double > &paramValues)
 Calculate 2D weight. More...
 
void ReweightMCMC (const std::string &configFile, const std::string &inputFile)
 Main executable responsible for reweighting MCMC chains. More...
 
MaCh3ArgumentParser * get_parser () override
 Get the argument parser for this module. More...
 
int Run () override
 Execute the MCMC reweighting analysis. More...
 
- Public Member Functions inherited from M3::PluginBase
virtual ~PluginBase ()=default
 
- Public Member Functions inherited from M3::IPlugin
virtual ~IPlugin ()=default
 

Additional Inherited Members

- Protected Attributes inherited from M3::PluginBase
std::unique_ptr< MaCh3ArgumentParser > m_parser
 Argument parser for this plugin. More...
 

Detailed Description

Module for performing reweighting analysis on MCMC chains.

This module provides diagnostics such as convergence tests, autocorrelation analysis, and batch means calculations to assess the quality of MCMC samples.

Definition at line 67 of file ReweightModule.hpp.

Constructor & Destructor Documentation

◆ ~ReweightModule()

M3::ReweightModule::~ReweightModule ( )
virtualdefault

Destructor.

Member Function Documentation

◆ Get1DWeight()

double M3::ReweightModule::Get1DWeight ( const ReweightConfig &  rwConfig,
const std::map< std::string, double > &  paramValues 
)

Calculate 1D weight.

Warning
Big limitation is that code only works for uncorrelated parameters :(

Definition at line 291 of file ReweightModule.cpp.

291  {
292  double weight = 1.;
293  if(rwConfig.type == M3::kGaussian) {
294  auto& paramNames = rwConfig.paramNames;
295  //KS: Calculate reweight weight. Weights are multiplicative so we can do several reweights at once.
297  for (unsigned int j = 0; j < paramNames.size(); ++j)
298  {
299  auto name = rwConfig.paramNames.at(j);
300  // Extract means and sigmas from the prior pairs
301  auto newPriorPair = rwConfig.newPriorValues[j];
302  double NewCentral = newPriorPair[0]; // mean
303  double NewError = newPriorPair[1]; // sigma
304 
305  double new_chi = (paramValues.at(name) - NewCentral)/NewError;
306  double new_prior = std::exp(-0.5 * new_chi * new_chi);
307 
308  double old_chi = -1;
309  double old_prior = -1;
310  if(rwConfig.flatPrior[j]) {
311  old_prior = 1.0;
312  } else {
313  auto oldPriorPair = rwConfig.oldPriorValues[j];
314  double OldCentral = newPriorPair[0]; // mean
315  double OldError = newPriorPair[1]; // sigma
316 
317  old_chi = (paramValues.at(name) - OldCentral)/OldError;
318  old_prior = std::exp(-0.5 * old_chi * old_chi);
319  }
320  weight *= new_prior/old_prior;
321  }
322  } else if (rwConfig.type == M3::kTGraph) {
323  double paramValue = paramValues.at(rwConfig.paramNames.at(0));
324  weight = Graph_interpolate1D(rwConfig.graph_1D.get(), paramValue);
325  }
326  return weight;
327 }
double Graph_interpolate1D(TGraph *graph, double theta13)
Function to interpolate 1D graph.
@ kTGraph
Calculates Likelihood based on TGraph.
@ kGaussian
Assumes gaussian prior.

◆ Get2DWeight()

double M3::ReweightModule::Get2DWeight ( const ReweightConfig &  rwConfig,
const std::map< std::string, double > &  paramValues 
)

Calculate 2D weight.

Definition at line 330 of file ReweightModule.cpp.

330  {
331  double weight = 1.;
332  if (rwConfig.type == M3::kTGraph2D) {
333  double dm32 = paramValues.at(rwConfig.paramNames.at(0));
334  double theta13 = paramValues.at(rwConfig.paramNames.at(1));
335  if (dm32 > 0) {
336  // Normal Ordering
337  if (rwConfig.graph_NO) {
338  weight = Graph_interpolateNO(rwConfig.graph_NO.get(), theta13, dm32);
339  } else {
340  MACH3LOG_ERROR("NO graph not available for {}", rwConfig.key);
341  weight = 0.0;
342  }
343  } else {
344  // Inverted Ordering
345  if (rwConfig.graph_IO) {
346  weight = Graph_interpolateIO(rwConfig.graph_IO.get(), theta13, dm32);
347  } else {
348  MACH3LOG_ERROR("IO graph not available for {}", rwConfig.key);
349  weight = 0.0;
350  }
351  }
352  }
353  return weight;
354 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
double Graph_interpolateIO(TGraph2D *graph, double theta13, double dm32)
Function to interpolate 2D graph for Inverted Ordering.
double Graph_interpolateNO(TGraph2D *graph, double theta13, double dm32)
Function to interpolate 2D graph for Normal Ordering.
@ kTGraph2D
Calculates Likelihood based on TGraph2D.

◆ get_parser()

MaCh3ArgumentParser * M3::ReweightModule::get_parser ( )
overridevirtual

Get the argument parser for this module.

Returns
Pointer to the configured MaCh3ArgumentParser

Implements M3::IPlugin.

Definition at line 540 of file ReweightModule.cpp.

540  {
541  m_parser = std::make_unique<MaCh3ArgumentParser>("reweight", "1.0", argparse::default_arguments::help);
542  m_parser->add_description("Tool for MCMC reweighting.");
543  m_parser->add_argument("config")
544  .help("Config file.")
545  .metavar("CONFIG")
546  .required();
547  m_parser->add_argument("mcmc-output")
548  .help("MCMC chain root file.")
549  .metavar("MCMC_CHAIN")
550  .required();
551  return m_parser.get();
552 }
std::unique_ptr< MaCh3ArgumentParser > m_parser
Argument parser for this plugin.
Definition: plugin.hpp:47

◆ GetParameterInfo()

bool M3::ReweightModule::GetParameterInfo ( MCMCProcessor *  processor,
const std::string &  paramName,
double &  mean,
double &  sigma,
bool &  isFlat 
)

Get parameter information from MCMCProcessor.

Definition at line 88 of file ReweightModule.cpp.

88  {
89  // Try to find the parameter index
90  int paramIndex = processor->GetParamIndexFromName(paramName);
91 
92  if (paramIndex == M3::_BAD_INT_) { // This indicate parameter not found
93  return false;
94  }
95 
96  // Get parameter information
97  TString title;
98  processor->GetNthParameter(paramIndex, mean, sigma, title);
99  isFlat = processor->GetParamFlat(paramIndex);
100 
101  return true;
102 }
bool isFlat(TSpline3_red *&spl)
CW: Helper function used in the constructor, tests to see if the spline is flat.
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.
constexpr static const int _BAD_INT_
Default value used for int initialisation.
Definition: Core.h:55

◆ Graph_interpolate1D()

double M3::ReweightModule::Graph_interpolate1D ( TGraph *  graph,
double  theta13 
)

Function to interpolate 1D graph.

Todo:
double check implementation of TGraph interpolation for 1D

Definition at line 59 of file ReweightModule.cpp.

59  {
61  if (!graph) {
62  MACH3LOG_ERROR("Graph pointer is null");
63  throw MaCh3Exception(__FILE__, __LINE__);
64  }
65 
66  double xmax = -999999999;
67  double xmin = 999999999;
68 
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;
73  }
74 
75  double chiSquared, prior;
76 
77  if (theta13 < xmax && theta13 > xmin) {
78  chiSquared = graph->Eval(theta13);
79  prior = std::exp(-0.5 * chiSquared);
80  } else {
81  prior = 0.0;
82  }
83 
84  return prior;
85 }
Custom exception class used throughout MaCh3.

◆ Graph_interpolateIO()

double M3::ReweightModule::Graph_interpolateIO ( TGraph2D *  graph,
double  theta13,
double  dm32 
)

Function to interpolate 2D graph for Inverted Ordering.

Definition at line 33 of file ReweightModule.cpp.

33  {
34  if (!graph) {
35  MACH3LOG_ERROR("Graph pointer is null");
36  throw MaCh3Exception(__FILE__, __LINE__);
37  }
38 
39  double xmax = graph->GetXmax();
40  double xmin = graph->GetXmin();
41  double ymax = graph->GetYmax();
42  double ymin = graph->GetYmin();
43 
44  // The dm32 value is positive for in the TGraph2D so we should compare the abs value of the -delM32 values to get the chisq
45  double mod_dm32 = std::abs(dm32);
46  double chiSquared, prior;
47 
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);
51  } else {
52  prior = 0.0;
53  }
54 
55  return prior;
56 }

◆ Graph_interpolateNO()

double M3::ReweightModule::Graph_interpolateNO ( TGraph2D *  graph,
double  theta13,
double  dm32 
)

Function to interpolate 2D graph for Normal Ordering.

Definition at line 9 of file ReweightModule.cpp.

9  {
10  if (!graph) {
11  MACH3LOG_ERROR("Graph pointer is null");
12  throw MaCh3Exception(__FILE__, __LINE__);
13  }
14 
15  double xmax = graph->GetXmax();
16  double xmin = graph->GetXmin();
17  double ymin = graph->GetYmin();
18  double ymax = graph->GetYmax();
19 
20  double chiSquared, prior;
21 
22  if (theta13 < xmax && theta13 > xmin && dm32 < ymax && dm32 > ymin) {
23  chiSquared = graph->Interpolate(theta13, dm32);
24  prior = std::exp(-0.5 * chiSquared);
25  } else {
26  prior = 0.0;
27  }
28 
29  return prior;
30 }

◆ LoadReweightingSettings()

void M3::ReweightModule::LoadReweightingSettings ( std::vector< ReweightConfig > &  reweightConfigs,
const YAML::Node &  reweight_settings 
)

Load reweighting setting like 1D or 2D from YAML config.

Definition at line 105 of file ReweightModule.cpp.

105  {
106  // iterate through the keys in the reweighting yaml creating and storing the ReweightConfig as we go
107  for (const auto& reweight : reweight_settings) {
108  const std::string& reweightKey = reweight.first.as<std::string>();
109  const YAML::Node& reweightConfigNode = reweight.second;
110 
111  // Check if this particular reweight is enabled !!! Currently only support one reweight at a time so this defaults to enabled
112  if (!GetFromManager<bool>(reweightConfigNode["Enabled"], true, __FILE__ , __LINE__)) {
113  MACH3LOG_INFO("Skipping disabled reweight: {}", reweightKey);
114  continue;
115  }
116 
117  ReweightConfig reweightConfig;
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__);
122 
123  reweightConfig.weightBranchName = reweightKey;
124  reweightConfig.enabled = true;
125 
126  auto paramNames = Get<std::vector<std::string>>(reweightConfigNode["ReweightVar"], __FILE__ , __LINE__);
127  reweightConfig.paramNames = paramNames;
128  reweightConfig.oldPriorValues.resize(paramNames.size());
129  reweightConfig.flatPrior.resize(paramNames.size());
130 
131  // Handle different reweight types as they fill different members
132  if (reweightConfig.dimension == 1) {
133  if (ReweightType == "Gaussian") {
134  reweightConfig.type = M3::kGaussian;
135  // For Gaussian reweights, we need the parameter name(s) and prior values (mean, sigma pairs)
136  // Get prior values - handle both single [mean, sigma] pair and list of pairs for safety
137  auto priorNode = reweightConfigNode["ReweightPrior"];
138  std::vector<std::vector<double>> allPriorValues;
139 
140  if (priorNode.IsSequence() && priorNode.size() > 0) {
141  // Check if first element is a number (single [mean, sigma] pair) or sequence (list of pairs)
142  if (priorNode[0].IsScalar()) {
143  // Single [mean, sigma] pair - convert to list format
144  auto newPriorValues = Get<std::vector<double>>(priorNode, __FILE__ , __LINE__);
145  if (newPriorValues.size() == 2) {
146  allPriorValues.push_back(newPriorValues);
147  }
148  }
149  else {
150  // List of [mean, sigma] pairs
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);
155  }
156  }
157  }
158  }
159 
160  reweightConfig.newPriorValues = allPriorValues;
161 
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());
164  continue;
165  }
166  }
167  else if (ReweightType == "TGraph") {
168  reweightConfig.type = M3::kTGraph;
169  // For TGraph reweights, we need the parameter name and the TGraph file and name
170  auto fileName = Get<std::string>(reweightConfigNode["ReweightPrior"]["file"], __FILE__ , __LINE__);
171  auto graphName = Get<std::string>(reweightConfigNode["ReweightPrior"]["graph_name"], __FILE__ , __LINE__);
172  reweightConfig.fileName = fileName;
173  reweightConfig.graphName = graphName;
174 
175  if (paramNames.empty() || paramNames.size() != 1 || fileName.empty() || graphName.empty()) {
176  MACH3LOG_ERROR("Invalid TGraph reweight configuration for {}", reweightKey);
177  continue;
178  }
179 
180  // Load the 1D graph
181  MACH3LOG_INFO("Loading 1D constraint from file: {} (graph: {})", reweightConfig.fileName, reweightConfig.graphName);
182  auto constraintFile = std::unique_ptr<TFile>(TFile::Open(reweightConfig.fileName.c_str(), "READ"));
183  if (!constraintFile || constraintFile->IsZombie()) {
184  MACH3LOG_ERROR("Failed to open constraint file: {}", reweightConfig.fileName);
185  continue;
186  }
187 
188  std::unique_ptr<TGraph> graph(constraintFile->Get<TGraph>(reweightConfig.graphName.c_str()));
189  if (graph) {
190  // Create a completely independent copy
191  auto cloned_graph = static_cast<TGraph*>(graph->Clone());
192  cloned_graph->SetBit(kCanDelete, true); // Allow ROOT to delete it when we're done
193  reweightConfig.graph_1D = std::unique_ptr<TGraph>(cloned_graph);
194  MACH3LOG_INFO("Loaded 1D graph: {}", reweightConfig.graphName);
195  }
196  else {
197  MACH3LOG_ERROR("Failed to load graph: {}", reweightConfig.graphName);
198  continue;
199  }
200  }
201  else {
202  MACH3LOG_ERROR("Unknown 1D reweight type: {} for {}", ReweightType, reweightKey);
203  throw MaCh3Exception(__FILE__, __LINE__);
204  }
205  }
206  else if (reweightConfig.dimension == 2) {
207  // 2D reweights need 2 parameter names
208  if (paramNames.size() != 2) {
209  MACH3LOG_ERROR("2D reweighting requires exactly 2 parameter names for {}", reweightKey);
210  continue;
211  }
212 
213  if (ReweightType == "TGraph2D") {
214  reweightConfig.type = M3::kTGraph2D;
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__);
219 
220  if (reweightConfig.fileName.empty() || reweightConfig.graphName.empty()) {
221  MACH3LOG_ERROR("Invalid TGraph2D configuration for {}", reweightKey);
222  continue;
223  }
224 
225  // Load the 2D graphs
226  MACH3LOG_INFO("Loading 2D constraint from file: {} (graph: {})", reweightConfig.fileName, reweightConfig.graphName);
227  auto constraintFile = std::unique_ptr<TFile>(TFile::Open(reweightConfig.fileName.c_str(), "READ"));
228  if (!constraintFile || constraintFile->IsZombie()) {
229  MACH3LOG_ERROR("Failed to open constraint file: {}", reweightConfig.fileName);
230  continue;
231  }
232 
233  // Load both NO and IO graphs if hierarchy is auto
234  if (reweightConfig.hierarchyType == "auto" || reweightConfig.hierarchyType == "NO") {
235  std::string graphName_NO = reweightConfig.graphName + "_NO";
236  MACH3LOG_INFO("Loading NO graph: {}", graphName_NO);
237 
238  std::unique_ptr<TGraph2D> graph_NO(constraintFile->Get<TGraph2D>(graphName_NO.c_str()));
239  if (graph_NO) {
240  // Create a completely independent copy
241  auto cloned_graph = static_cast<TGraph2D*>(graph_NO->Clone());
242  cloned_graph->SetDirectory(nullptr); // Detach from file
243  cloned_graph->SetBit(kCanDelete, true); // Allow ROOT to delete it when we're done
244  reweightConfig.graph_NO = std::unique_ptr<TGraph2D>(cloned_graph);
245  MACH3LOG_INFO("Loaded NO graph: {}", graphName_NO);
246  } else {
247  MACH3LOG_ERROR("Failed to load NO graph: {}", graphName_NO);
248  }
249  }
250 
251  if (reweightConfig.hierarchyType == "auto" || reweightConfig.hierarchyType == "IO") {
252  std::string graphName_IO = reweightConfig.graphName + "_IO";
253  MACH3LOG_INFO("Loading IO graph: {}", graphName_IO);
254  std::unique_ptr<TGraph2D> graph_IO(constraintFile->Get<TGraph2D>(graphName_IO.c_str()));
255  if (graph_IO) {
256  // Create a completely independent copy
257  auto cloned_graph = static_cast<TGraph2D*>(graph_IO->Clone());
258  cloned_graph->SetDirectory(nullptr); // Detach from file
259  cloned_graph->SetBit(kCanDelete, true); // Allow ROOT to delete it when we're done
260  reweightConfig.graph_IO = std::unique_ptr<TGraph2D>(cloned_graph);
261  MACH3LOG_INFO("Loaded IO graph: {}", graphName_IO);
262  }
263  else {
264  MACH3LOG_ERROR("Failed to load IO graph: {}", graphName_IO);
265  }
266  }
267 
268  constraintFile->Close();
269  }
270  else {
271  MACH3LOG_ERROR("Unknown 2D reweight type: {} for {}", ReweightType, reweightKey);
272  continue;
273  }
274  }
275  else {
276  MACH3LOG_ERROR("Unsupported reweight dimension: {} for {}", reweightConfig.dimension, reweightKey);
277  continue;
278  } // end check over dimensions
279 
280  reweightConfigs.push_back(std::move(reweightConfig));
281  MACH3LOG_INFO("Added reweight configuration: {} ({}D, type: {})", reweightConfigs.back().name, reweightConfigs.back().dimension, ReweightType);
282  } // end loop o er settings
283 
284  if (reweightConfigs.empty()) {
285  MACH3LOG_ERROR("No valid reweight configurations found in config file");
286  throw MaCh3Exception(__FILE__, __LINE__);
287  }
288 }
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35

◆ ReweightMCMC()

void M3::ReweightModule::ReweightMCMC ( const std::string &  configFile,
const std::string &  inputFile 
)

Main executable responsible for reweighting MCMC chains.

Parameters
inputFileMCMC Chain file path
configFileConfig file with reweighting settings
Author
David Riley
Evan Goodman
Todo:
add a generic 2D reweight that is not dm32 and theta13 specific DWR
Parameters
inputFileMCMC Chain file path
configFileConfig file with reweighting settings
Author
David Riley
Evan Goodman
Todo:
add a generic 2D reweight that is not dm32 and theta13 specific DWR
Todo:
Get list only of unique parameters, this is repeating unnecessarily when adding more than 1 weight DWR
Todo:
Finish Asimov shifting implementation, for now just warn that Asimovs are not being properly handled
Todo:
add tracking for how many events are outside the graph ranges for diagnostics DWR

Definition at line 362 of file ReweightModule.cpp.

362  {
363  MACH3LOG_INFO("File for reweighting: {} with config {}", inputFile, configFile);
364  // Load configuration
365  YAML::Node reweight_yaml = M3OpenConfig(configFile);
366  YAML::Node reweight_settings = reweight_yaml["ReweightMCMC"];
367 
368  // Parse all reweight configurations first
369  std::vector<ReweightConfig> reweightConfigs;
370 
371  LoadReweightingSettings(reweightConfigs, reweight_settings);
372 
373  // Create MCMCProcessor to get parameter information
374  auto processor = std::make_unique<MCMCProcessor>(inputFile);
375  processor->Initialise();
376 
377  // Validate that all required parameters exist in the chain
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);
383  if (paramIndex == M3::_BAD_INT_) {
384  MACH3LOG_ERROR("Parameter {} not found in MCMC chain", paramName);
385  throw MaCh3Exception(__FILE__, __LINE__);
386  }
387  MACH3LOG_INFO("Parameter {} found in chain", paramName);
388 
389  double mean, sigma;
390  bool isFlat;
391  GetParameterInfo(processor.get(), paramName, mean, sigma, isFlat);
392 
393  rwConfig.oldPriorValues[i] = {mean, sigma};
394  rwConfig.flatPrior[i] = isFlat;
395  }
396  }
397 
399  // Get the settings for the MCMC
400  auto TempFile = std::unique_ptr<TFile>(TFile::Open(inputFile.c_str(), "READ"));
401  if (!TempFile || TempFile->IsZombie()) {
402  MACH3LOG_ERROR("Cannot open MCMC file: {}", inputFile);
403  throw MaCh3Exception(__FILE__ , __LINE__ );
404  }
405  std::unique_ptr<TMacro> Config(TempFile->Get<TMacro>("MaCh3_Config"));
406  if (!Config) {
407  MACH3LOG_ERROR("Didn't find MaCh3_Config tree in MCMC file! {}", inputFile.c_str());
408  TempFile->ls();
409  throw MaCh3Exception(__FILE__ , __LINE__ );
410  }
411  MACH3LOG_INFO("Loading YAML config from MCMC chain");
412  YAML::Node Settings = TMacroToYAML(*Config);
413  bool asimovfit = GetFromManager<bool>(Settings["General"]["Asimov"], false, __FILE__ , __LINE__);
414  if (asimovfit) {
415  MACH3LOG_WARN("MCMC chain was produced from an Asimov fit");
416  MACH3LOG_WARN("ReweightMCMC does not currently handle Asimov shifting, results may be incorrect!");
417  } else {
418  MACH3LOG_INFO("Not an Asimov fit, proceeding with reweighting");
419  }
420 
421  // Open input file and get tree
422  auto inFile = std::unique_ptr<TFile>(TFile::Open(inputFile.c_str(), "READ"));
423  if (!inFile || inFile->IsZombie()) {
424  MACH3LOG_ERROR("Cannot open input file: {}", inputFile);
425  throw MaCh3Exception(__FILE__, __LINE__);
426  }
427 
428  std::unique_ptr<TTree> inTree(inFile->Get<TTree>("posteriors"));
429  if (!inTree) {
430  MACH3LOG_ERROR("Cannot find 'posteriors' tree in input file");
431  throw MaCh3Exception(__FILE__, __LINE__);
432  }
433 
434  // Create output file
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()) {
439  MACH3LOG_ERROR("Cannot create output file: {}", outputFile);
440  throw MaCh3Exception(__FILE__, __LINE__);
441  }
442 
443  MACH3LOG_INFO("Output file will be: {}", outputFile);
444 
445  // Copy all the remaining objects into the out file (i.e. all but posteriors tree)
446  TIter next(inFile->GetListOfKeys());
447  while (TKey* key = dynamic_cast<TKey*>(next())) {
448  inFile->cd();
449  std::unique_ptr<TObject> obj(key->ReadObj());
450  if (obj->IsA()->InheritsFrom(TDirectory::Class())) {
451  // It's a folder, create and copy its contents
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())) {
456  srcDir->cd();
457  std::unique_ptr<TObject> subObj(subKey->ReadObj());
458  destDir->cd();
459  subObj->Write();
460  }
461  } else if (std::string(key->GetName()) != "posteriors") {
462  // Regular object, skip "posteriors" tree
463  outFile->cd();
464  obj->Write();
465  }
466  }
467 
468  // Clone the tree structure
469  outFile->cd();
470  std::unique_ptr<TTree> outTree(inTree->CloneTree(0));
471 
472  // Set up parameter reading
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;
478  // KS: Params other than Osc have branch like Param_, so we need to match it
479  auto idx = processor->GetParamIndexFromName(paramName);
480  auto BranchName = processor->GetBranchNames()[idx];
481  inTree->SetBranchAddress(BranchName, &paramValues[paramName]);
482  }
483  }
484  }
485 
486  // Add weight branches
487  std::map<std::string, double> weights;
488  std::map<std::string, TBranch*> weightBranches;
489 
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);
494  }
495 
496  // For 2D reweight and non-gaussian (ie TGraph) 1D reweight we need to do it ourselves
497  // Process all entries
498  Long64_t nEntries = inTree->GetEntries();
499  MACH3LOG_INFO("Processing {} entries", nEntries);
500 
502  for (Long64_t i = 0; i < nEntries; ++i) {
503  if(i % (nEntries/20) == 0) M3::Utils::PrintProgressBar(i, nEntries);
504 
505  inTree->GetEntry(i);
506 
507  // Calculate weights for all configurations
508  for (const auto& rwConfig : reweightConfigs) {
509  double weight = 1.0;
510  if (rwConfig.dimension == 1) {
511  weight = Get1DWeight(rwConfig, paramValues);
512  } else if (rwConfig.dimension == 2) {
513  weight = Get2DWeight(rwConfig, paramValues);
514  }
515  weights[rwConfig.weightBranchName] = weight;
516  }
517  // Fill the output tree
518  outTree->Fill();
519  } // end loop over entries
520 
521  // Write and close
522  outFile->cd();
523  outTree->Write();
524 
525  // once we have finished the reweight save its configuration (reweightConfigNode) to the root file as a macro
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();
533 
534  MACH3LOG_INFO("Reweighting completed successfully!");
535  MACH3LOG_INFO("Final reweighted file is: {}", outputFile);
536 }
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
YAML::Node TMacroToYAML(const TMacro &macro)
KS: Convert a ROOT TMacro object to a YAML node.
Definition: YamlHelper.h:151
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:589
double Get1DWeight(const ReweightConfig &rwConfig, const std::map< std::string, double > &paramValues)
Calculate 1D weight.
double Get2DWeight(const ReweightConfig &rwConfig, const std::map< std::string, double > &paramValues)
Calculate 2D weight.
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 &paramName, double &mean, double &sigma, bool &isFlat)
Get parameter information from MCMCProcessor.
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
Definition: Monitor.cpp:229

◆ Run()

int M3::ReweightModule::Run ( )
overridevirtual

Execute the MCMC reweighting analysis.

Returns
Exit code (0 on success)

Implements M3::IPlugin.

Definition at line 554 of file ReweightModule.cpp.

554  {
556 
557  std::string filename = m_parser->get<std::string>("mcmc-output");
558  std::string config = m_parser->get<std::string>("config");
559 
560  ReweightMCMC(config, filename);
561 
562  return 0;
563 }
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Definition: MaCh3Logger.h:60
void ReweightMCMC(const std::string &configFile, const std::string &inputFile)
Main executable responsible for reweighting MCMC chains.

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