MaCh3  2.8.0
Reference Guide
Public Member Functions | Private Member Functions | Private Attributes | List of all members
M3::UmbrellaModule Class Reference

Module for performing Umbrella sampling. More...

#include <CLI/Modules/UmbrellaModule.hpp>

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

Public Member Functions

virtual ~UmbrellaModule ()
 Destructor. More...
 
MaCh3ArgumentParser * get_parser () override
 Get the argument parser for this module. More...
 
int Run () override
 Execute the Umbrella sampling. More...
 
- Public Member Functions inherited from M3::PluginBase
virtual ~PluginBase ()=default
 
- Public Member Functions inherited from M3::IPlugin
virtual ~IPlugin ()=default
 

Private Member Functions

UmbrellaConfig parseYAMLConfig (const std::string &filename)
 YAML-based config parser using yaml-cpp library. More...
 
double gaussianWindow (double x, double center, double width)
 
double vonMisesWindow (double x, double center, double kappa)
 
double generalisedGaussian2 (double x, double mean, double width)
 
double GetMulticanonicalWeightGenGaussian (double deltacp, double mean, double width, double multicanonicalBeta)
 
double summedWindowsWeighted (double x, const std::vector< WindowConfig > &windows, const std::vector< double > &z_values)
 
size_t calculateWindowCacheSizeBytes (const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples)
 
std::vector< std::vector< std::vector< double > > > buildWindowCache (const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples)
 
std::vector< std::vector< double > > calcFmatrix (const std::vector< double > &z_current, const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples, const std::vector< std::vector< std::vector< double >>> &window_cache)
 
std::vector< double > zSolver (const std::vector< double > &z_current, const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples, const std::vector< std::vector< std::vector< double >>> &window_cache, [[maybe_unused]] bool verbose=false, [[maybe_unused]] int *total_lines=nullptr)
 
bool checkConvergence (const std::vector< double > &z_current, const std::vector< double > &z_prev, double tolerance)
 A few different convergence checks. More...
 
std::vector< double > getZDiffs (const std::vector< double > &z_current, const std::vector< double > &z_prev)
 
bool checkConvergenceStalled (const std::vector< double > &z_current, const std::vector< double > &z_prev, double tolerance)
 
void LoadFiles (std::vector< std::vector< double >> &samples, UmbrellaConfig &config, std::vector< TFile * > &input_files, std::vector< TTree * > &input_trees)
 
void DiagnoseUmbrella (const UmbrellaConfig &config, TFile *output_file, const std::vector< std::vector< double >> &z_evolution, TTree *combined_tree)
 
void UmbrellaSolver (const std::string &config_file)
 

Private Attributes

std::unique_ptr< MaCh3ArgumentParser > m_default_parser
 
UmbrellaPlotModule m_plotModule
 

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 Umbrella sampling.

This module provides functionality for performing Umbrella sampling, a technique used to enhance sampling of rare events in MCMC simulations.

Definition at line 52 of file UmbrellaModule.hpp.

Constructor & Destructor Documentation

◆ ~UmbrellaModule()

M3::UmbrellaModule::~UmbrellaModule ( )
virtualdefault

Destructor.

Member Function Documentation

◆ buildWindowCache()

std::vector< std::vector< std::vector< double > > > M3::UmbrellaModule::buildWindowCache ( const std::vector< WindowConfig > &  windows,
const std::vector< std::vector< double >> &  samples 
)
private

Definition at line 179 of file UmbrellaModule.cpp.

180  {
181  TStopwatch clock;
182  clock.Start();
183  int n_windows = static_cast<int>(windows.size());
184  const size_t cache_size_bytes = calculateWindowCacheSizeBytes(windows, samples);
185  const double cache_size_gb = static_cast<double>(cache_size_bytes) / (1024.0 * 1024.0 * 1024.0);
186  if (cache_size_gb > 10.0) {
187  MACH3LOG_WARN("Window cache size: {:.2f} GB", cache_size_gb);
188  } else {
189  MACH3LOG_INFO("Window cache size: {:.2f} GB", cache_size_gb);
190  }
191 
192  std::vector<std::vector<std::vector<double>>> cache(n_windows);
193  for (int i = 0; i < n_windows; i++) {
194  cache[i].resize(n_windows);
195  for (int j = 0; j < n_windows; j++) {
196  cache[i][j].resize(samples[i].size());
197  }
198  }
199  MACH3LOG_INFO("Window cache built successfully.");
200 
201  #ifdef MULTITHREAD
202  #pragma omp parallel for collapse(2) schedule(dynamic)
203  #endif
204  for (int i = 0; i < n_windows; i++) {
205  for (int j = 0; j < n_windows; j++) {
206  for (size_t s = 0; s < samples[i].size(); s++) {
207  if (windows[j].umbrellaBiasFunction == M3::BiasFunction::kVonMises) {
208  cache[i][j][s] = vonMisesWindow(samples[i][s], windows[j].center, windows[j].vonMises_kappa);
209  } else if (windows[j].umbrellaBiasFunction == M3::BiasFunction::kGaussian) {
210  cache[i][j][s] = gaussianWindow(samples[i][s], windows[j].center, windows[j].width);
211  } else if (windows[j].umbrellaBiasFunction == M3::BiasFunction::kGeneralisedGaussian) {
212  cache[i][j][s] = GetMulticanonicalWeightGenGaussian(samples[i][s], windows[j].center, windows[j].width, windows[j].multicanonical_beta);
213  } else {
214  MACH3LOG_ERROR("Unrecognised BiasFunction!!");
215  throw MaCh3Exception(__FILE__, __LINE__);
216  }
217  }
218  }
219  }
220 
221  if (debug_mode) { // this should be TH1D of cache against sample value in the
222  // variable of interest for each window, to check the cache
223  // is being built correctly and the windows look correct
224  // across the range of samples
225  // TODO break this into a standalone function
226  // first print the size in memory of the cache to check it is reasonable and
227  // not being built incorrectly with an extra dimension or something
228  TFile *cache_file = TFile::Open("window_cache_debug_histograms.root", "RECREATE");
229  for (int i = 0; i < n_windows; i++) {
230  for (int j = 0; j < n_windows; j++) {
231  std::string hist_name = "Sample" + std::to_string(i) + "_window" + std::to_string(j);
232  TH1D *window_cache_hist = new TH1D(hist_name.c_str(), hist_name.c_str(), 100, -3.1415, 3.1415);
233  for (size_t s = 0; s < cache[i][j].size(); s++) {
234  window_cache_hist->AddBinContent(window_cache_hist->FindBin(samples[i][s]));
235  }
236  window_cache_hist->Write();
237  }
238  }
239 
240  // additionally save a TH2D of the values in the cache against the sample
241  // values for a specific window to check the shape of the windows is correct
242  // across the range of samples
243  for (int i = 0; i < n_windows; i++) {
244  for (int j = 0; j < n_windows; j++) {
245  std::string hist_name = "Sample" + std::to_string(i) + "_window" + std::to_string(j) + "_cache_2D";
246  TH2D *window_cache_2D_hist = new TH2D(hist_name.c_str(), hist_name.c_str(), 100, -3.1415, 3.1415, 100, -1000, 10);
247  for (size_t s = 0; s < cache[i][j].size(); s++) {
248  // take the log of the likelihood values
249  window_cache_2D_hist->Fill(samples[i][s], log(cache[i][j][s]));
250  }
251  // show overflow numbers on the hist
252  window_cache_2D_hist->SetStats(1);
253  window_cache_2D_hist->Write();
254  }
255  }
256  cache_file->Close();
257  }
258 
259  clock.Stop();
260  MACH3LOG_INFO("Finished building window cache, it took {:.2f}s to finish", clock.RealTime());
261  return cache;
262 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
size_t calculateWindowCacheSizeBytes(const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples)
double GetMulticanonicalWeightGenGaussian(double deltacp, double mean, double width, double multicanonicalBeta)
double vonMisesWindow(double x, double center, double kappa)
double gaussianWindow(double x, double center, double width)
Custom exception class used throughout MaCh3.
bool debug_mode
@ kGaussian
Assumes gaussian prior.

◆ calcFmatrix()

std::vector< std::vector< double > > M3::UmbrellaModule::calcFmatrix ( const std::vector< double > &  z_current,
const std::vector< WindowConfig > &  windows,
const std::vector< std::vector< double >> &  samples,
const std::vector< std::vector< std::vector< double >>> &  window_cache 
)
private

Definition at line 265 of file UmbrellaModule.cpp.

268  {
269  int n_windows = static_cast<int>(windows.size());
270  std::vector<std::vector<double>> F(n_windows, std::vector<double>(n_windows, 0.0));
271 
272  std::vector<double> z_inv = z_current; // make a copy to avoid modifying the original z_current
273  for (size_t i = 0; i < z_current.size(); i++) {
274  if (z_current[i] > 0) {
275  z_inv[i] = 1.0 / z_current[i];
276  } else {
277  z_inv[i] = 0.0; // Handle zero or negative z values gracefully
278  if (debug_mode) {
279  MACH3LOG_WARN("Warning: z_current[{}] is non-positive ({}). Setting its inverse to 0 in F matrix calculation.", i, z_current[i]);
280  }
281  }
282  }
283  #ifdef MULTITHREAD
284  #pragma omp parallel for schedule(dynamic)
285  #endif
286  for (int i = 0; i < n_windows; i++) {
287  std::vector<double> denominator_cache(samples[i].size(), 0.0);
288  for (size_t s = 0; s < samples[i].size(); s++) {
289  double denominator = 0.0;
290  for (int k = 0; k < n_windows; k++) {
291  denominator += window_cache[i][k][s] * z_inv[k];
292  }
293  denominator_cache[s] = 1 / denominator;
294  }
295 
296  for (int j = 0; j < n_windows; j++) {
297  double sum = 0.0;
298  int count = 0;
299 
300  for (size_t s = 0; s < samples[i].size(); s++) {
301  double sample = samples[i][s];
302  double window_j = window_cache[i][j][s];
303  double denominator = denominator_cache[s];
304 
305  if (denominator > 0) {
306  double integrand = (window_j * z_inv[i]) * denominator;
307  sum += integrand;
308  count++;
309  } else if (debug_mode) {
310  MACH3LOG_WARN("Denominator is zero for sample {} in window {}, skipping...", sample, i);
311  }
312  }
313 
314  if (debug_mode) {
315  MACH3LOG_INFO("F[{}][{}] sum: {}, count: {}", i, j, sum, count);
316  }
317 
318  if (count > 0) {
319  F[i][j] = sum / count;
320  }
321  }
322  }
323  return F;
324 }

◆ calculateWindowCacheSizeBytes()

size_t M3::UmbrellaModule::calculateWindowCacheSizeBytes ( const std::vector< WindowConfig > &  windows,
const std::vector< std::vector< double >> &  samples 
)
private

Definition at line 167 of file UmbrellaModule.cpp.

167  {
168  const size_t n_windows = windows.size();
169  size_t total_samples = 0;
170  for (const auto &sample_set : samples) {
171  total_samples += sample_set.size();
172  }
173  return n_windows * total_samples * sizeof(double);
174 }

◆ checkConvergence()

bool M3::UmbrellaModule::checkConvergence ( const std::vector< double > &  z_current,
const std::vector< double > &  z_prev,
double  tolerance 
)
private

A few different convergence checks.

Definition at line 377 of file UmbrellaModule.cpp.

377  {
378  double sum_diffs = 0.0;
379  for (size_t i = 0; i < z_current.size(); i++) {
380  // if (std::abs(z_current[i] - z_prev[i]) > tolerance *
381  // std::max(std::abs(z_current[i]), std::abs(z_prev[i]))) { // intention
382  // here: is the difference between any of the z elements more than the
383  // tolerance*the magnitude of the largest element in z? in this way the
384  // tolerance sets the number of decimal points below the largest element we
385  // are targeting.
386  // return false;
387  // }
388  sum_diffs += std::abs(z_current[i] - z_prev[i]);
389  // check the average difference across all elements instead
390  // of requiring every element to meet the condition, this
391  // should be more robust to individual elements fluctuating
392  // around their target value while the overall z
393  // distribution is still converging
394  if (sum_diffs / static_cast<double>(z_current.size()) > tolerance) {
395  return false;
396  }
397  }
398  return true;
399 }

◆ checkConvergenceStalled()

bool M3::UmbrellaModule::checkConvergenceStalled ( const std::vector< double > &  z_current,
const std::vector< double > &  z_prev,
double  tolerance 
)
private

Definition at line 411 of file UmbrellaModule.cpp.

411  {
412  (void)z_prev;
413 
414  static std::deque<std::vector<double>> z_history;
415  static std::vector<double> previous_moving_average;
416  static int stagnant_iterations = 0;
417 
418  constexpr int moving_average_window = 500;
419  constexpr int stagnant_required = 500;
420  const double bound = tolerance;
421 
422  if (z_current.empty()) {
423  return false;
424  }
425 
426  // Reset state safely if number of windows changes between solver runs.
427  if (!z_history.empty() && z_history.front().size() != z_current.size()) {
428  z_history.clear();
429  previous_moving_average.clear();
430  stagnant_iterations = 0;
431  }
432 
433  z_history.push_back(z_current);
434  if (static_cast<int>(z_history.size()) > moving_average_window) {
435  z_history.pop_front();
436  }
437 
438  // Wait until the moving-average window is fully populated.
439  if (static_cast<int>(z_history.size()) < moving_average_window) {
440  return false;
441  }
442 
443  std::vector<double> moving_average(z_current.size(), 0.0);
444  for (const auto &z_vec : z_history) {
445  for (size_t i = 0; i < z_vec.size(); i++) {
446  moving_average[i] += z_vec[i];
447  }
448  }
449  for (size_t i = 0; i < moving_average.size(); i++) {
450  moving_average[i] /= moving_average_window;
451  }
452 
453  if (previous_moving_average.empty()) {
454  previous_moving_average = moving_average;
455  return false;
456  }
457 
458  bool all_within_bound = true;
459  for (size_t i = 0; i < moving_average.size(); i++) {
460  if (std::abs(moving_average[i] - previous_moving_average[i]) > bound) {
461  all_within_bound = false;
462  break;
463  }
464  }
465 
466  if (all_within_bound) {
467  stagnant_iterations++;
468  } else {
469  stagnant_iterations = 0;
470  }
471 
472  previous_moving_average = moving_average;
473 
474  if (stagnant_iterations == stagnant_required) {
475  MACH3LOG_WARN("Convergence appears stalled: moving-average change stayed within {} for {} iterations.",
476  bound, stagnant_required);
477  }
478 
479  return stagnant_iterations >= stagnant_required;
480 }

◆ DiagnoseUmbrella()

void M3::UmbrellaModule::DiagnoseUmbrella ( const UmbrellaConfig &  config,
TFile *  output_file,
const std::vector< std::vector< double >> &  z_evolution,
TTree *  combined_tree 
)
private

Definition at line 665 of file UmbrellaModule.cpp.

666  {
667  TDirectory* UmbrellaDir = output_file->mkdir("Umbrella");
668  UmbrellaDir->cd();
669 
670  TCanvas c1("c1", "Z Evolution", 800, 600);
671  std::vector<std::unique_ptr<TGraph>> z_graphs(config.windows.size());
672  TLegend legend(0.7, 0.7, 0.9, 0.9);
673 
674  double ymax = 0.0;
675  double ymin = std::numeric_limits<double>::max();
676 
677  for (size_t i = 0; i < config.windows.size(); i++) {
678  std::vector<double> iterations, z_vals;
679  for (size_t j = 0; j < z_evolution.size(); j++) {
680  iterations.push_back(static_cast<int>(j));
681  z_vals.push_back(z_evolution[j][i]);
682  }
683 
684  for (double val : z_vals) {
685  if (val > ymax)
686  ymax = val;
687  if (val < ymin)
688  ymin = val;
689  }
690 
691  z_graphs[i] = std::make_unique<TGraph>((iterations.size()), &iterations[0], &z_vals[0]);
692  z_graphs[i]->SetLineColor(static_cast<Color_t>(i + 1));
693  z_graphs[i]->SetLineWidth(2);
694  z_graphs[i]->SetName(Form("z_evolution_window_%lu", i));
695  z_graphs[i]->SetTitle("Evolution of Z Values");
696  z_graphs[i]->GetXaxis()->SetTitle("Iteration");
697  z_graphs[i]->GetYaxis()->SetTitle("Z Value");
698 
699  if (i == 0) {
700  z_graphs[i]->Draw("AL");
701  } else {
702  z_graphs[i]->Draw("L SAME");
703  }
704 
705  legend.AddEntry(z_graphs[i].get(), Form("Window %lu", i), "l");
706  z_graphs[i]->Write();
707  }
708 
709  legend.Draw();
710  z_graphs[0]->SetMaximum(ymax);
711  z_graphs[0]->SetMinimum(ymin);
712  c1.Update();
713  c1.SetLogy();
714  c1.Write();
715 
716  // Create summary histogram of umbrella_variable distribution
717  TH1D *h_delta_cp = new TH1D("h_delta_cp_weighted", "Weighted Delta CP Distribution", 100, -TMath::Pi(), TMath::Pi());
718  TH1D *h_delta_cp_unweighted = new TH1D("h_delta_cp_unweighted", "Unweighted Delta CP Distribution", 100, -TMath::Pi(), TMath::Pi());
719 
720  const std::string& variable = config.variable_of_interest;
721  combined_tree->Draw((variable + ">>h_delta_cp_weighted").c_str(), "umbrella_weight", "goff");
722  combined_tree->Draw((variable + ">>h_delta_cp_unweighted").c_str(), "", "goff");
723 
724  h_delta_cp->Write();
725  h_delta_cp_unweighted->Write();
726 
727  UmbrellaDir->Close();
728  delete UmbrellaDir;
729 }

◆ gaussianWindow()

double M3::UmbrellaModule::gaussianWindow ( double  x,
double  center,
double  width 
)
private

Definition at line 106 of file UmbrellaModule.cpp.

106  {
107  return exp(-0.5 * pow((x - center) / width, 2)) / (width * sqrt(2 * TMath::Pi()));
108 }

◆ generalisedGaussian2()

double M3::UmbrellaModule::generalisedGaussian2 ( double  x,
double  mean,
double  width 
)
private

Definition at line 126 of file UmbrellaModule.cpp.

126  {
127  constexpr int n = 2; // this controls the tightness of the gaussian fixed at 2
128  // for now due to normalisation
129  const double normFactor = 1 / ((M3::UmbrellaGaussianNormFactor) * 2 * std::sqrt(2) * width); // the normalisation is a little ugly (uses gamma functions),
130  // im just going to hardcode them for now
131  double likelihood = normFactor * std::exp(-std::pow((std::pow(x - mean, 2) / (2 * std::pow(width, 2))), n));
132  return likelihood;
133 }
constexpr double UmbrellaGaussianNormFactor

◆ get_parser()

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

Get the argument parser for this module.

Returns
Pointer to the configured MaCh3ArgumentParser

Implements M3::IPlugin.

Definition at line 16 of file UmbrellaModule.cpp.

16  {
17  m_parser = std::make_unique<MaCh3ArgumentParser>("umbrellasolver", "1.0", argparse::default_arguments::help);
18  m_default_parser = std::make_unique<MaCh3ArgumentParser>("umbrellasolver__default__", "1.0", argparse::default_arguments::help);
19  m_default_parser->set_suppress(true);
20  m_parser->add_subparser(*m_default_parser.get());
21  auto* plotParser = m_plotModule.get_parser();
22  m_parser->add_subparser(*plotParser);
23  m_parser->set_default_subcommand(m_default_parser->name());
24  m_parser->add_description("Tool for calculating umbrella weight based on several chains.");
25  m_default_parser->add_argument("config")
26  .help("Config file.")
27  .metavar("CONFIG")
28  .default_value("umbrella_config.yaml");
29  m_default_parser->add_epilog("Optional subcommands:\n " + plotParser->name() + " " + plotParser->description());
30  return m_parser.get();
31 }
std::unique_ptr< MaCh3ArgumentParser > m_parser
Argument parser for this plugin.
Definition: plugin.hpp:47
UmbrellaPlotModule m_plotModule
std::unique_ptr< MaCh3ArgumentParser > m_default_parser
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.

◆ GetMulticanonicalWeightGenGaussian()

double M3::UmbrellaModule::GetMulticanonicalWeightGenGaussian ( double  deltacp,
double  mean,
double  width,
double  multicanonicalBeta 
)
private
Todo:
modify this to instead use atan2 implementation for wrapping
Todo:
modify this to instead use atan2 implementation for wrapping

Definition at line 136 of file UmbrellaModule.cpp.

136  {
137  // implementation of the generalised gaussian as a bias function
138  // for now with a fixed n = 2 for simplicity
139 
140  double g0 = generalisedGaussian2(deltacp, mean, width);
141  double g1 = generalisedGaussian2(deltacp, mean - 2 * TMath::Pi(),width); // these two repeats are required for wrapping the gaussian around -+pi
142  double g2 = generalisedGaussian2(deltacp, mean + 2 * TMath::Pi(), width);
143  return (g0 + g1 + g2) * (multicanonicalBeta);
144 }
double generalisedGaussian2(double x, double mean, double width)

◆ getZDiffs()

std::vector< double > M3::UmbrellaModule::getZDiffs ( const std::vector< double > &  z_current,
const std::vector< double > &  z_prev 
)
private

Definition at line 401 of file UmbrellaModule.cpp.

401  {
402  std::vector<double> diffs(z_current.size(), 0.0);
403  for (size_t i = 0; i < z_current.size(); i++) {
404  diffs[i] = std::abs(z_current[i] - z_prev[i]);
405  }
406  return diffs;
407 }

◆ LoadFiles()

void M3::UmbrellaModule::LoadFiles ( std::vector< std::vector< double >> &  samples,
UmbrellaConfig &  config,
std::vector< TFile * > &  input_files,
std::vector< TTree * > &  input_trees 
)
private

Definition at line 482 of file UmbrellaModule.cpp.

482  {
483  TStopwatch clock;
484  clock.Start();
485  if (!config.dynamic_files) {
486  MACH3LOG_INFO("Using static input files from configuration.");
487  for (size_t i = 0; i < config.windows.size(); i++) {
488  MACH3LOG_INFO("Loading file: {}", config.windows[i].input_file);
489  TFile *file = M3::Open(config.windows[i].input_file.c_str(), "READ", __FILE__, __LINE__);
490 
491  TTree *tree = static_cast<TTree*>(file->Get("posteriors"));
492  if (!tree) {
493  MACH3LOG_ERROR("Cannot find 'posteriors' tree in {}", config.windows[i].input_file);
494  file->Close();
495  continue;
496  }
497 
498  input_files.push_back(file);
499  input_trees.push_back(tree);
500  }
501  } else {
502  MACH3LOG_INFO("Dynamic file loading enabled. Searching for files in directory: {}", config.dynamic_pattern);
503  // Use ROOT's TSystem to find all files in the directory
504  TSystemDirectory dir("", config.dynamic_pattern.c_str());
505  TList *files = dir.GetListOfFiles();
506  int file_count = 0;
507  if (files) {
508  TIter next(files);
509  TSystemFile *file;
510  while ((file = static_cast<TSystemFile*>(next()))) {
511  std::string filename = file->GetName();
512  if (filename.find(".root") == std::string::npos) {
513  MACH3LOG_DEBUG("Skipping non-root file: {}", filename);
514  continue;
515  }
516 
517  std::string full_path = config.dynamic_pattern + "/" + filename;
518  MACH3LOG_DEBUG("Found file: {}", full_path);
519 
520  TFile *root_file = M3::Open(full_path, "READ", __FILE__, __LINE__);
521 
522  TTree *tree = static_cast<TTree*>(root_file->Get("posteriors"));
523  if (!tree) {
524  MACH3LOG_ERROR("Cannot find 'posteriors' tree in {}", full_path);
525  root_file->Close();
526  throw MaCh3Exception(__FILE__, __LINE__, "Missing 'posteriors' tree in file: " + full_path);
527  }
528  file_count++;
529 
530  input_files.push_back(root_file);
531  input_trees.push_back(tree);
532  MACH3LOG_DEBUG("Loaded tree 'posteriors' from file: {}", full_path);
533  }
534  } else {
535  MACH3LOG_ERROR("No files found matching pattern: {}", config.dynamic_pattern);
536  throw MaCh3Exception(__FILE__, __LINE__, "No files found matching pattern: " + config.dynamic_pattern);
537  }
538 
539  if (file_count != config.dynamic_n_windows) {
540  MACH3LOG_ERROR("Number of files found ({}) does not match expected dynamic_n_windows ({}).",
541  file_count, config.dynamic_n_windows);
542  throw MaCh3Exception(__FILE__, __LINE__, "File count mismatch for dynamic loading.");
543  }
544  }
545 
546  for (size_t i = 0; i < input_trees.size(); i++) {
547  TTree *tree = input_trees[i];
548  TFile *file = input_files[i];
549 
550  MACH3LOG_DEBUG("Processing file {}/{}: {}", i + 1, input_trees.size(), file->GetName());
551  TMacro *macro = static_cast<TMacro*>(file->Get("MaCh3_Config"));
552  if (macro) {
553  MACH3LOG_DEBUG("Found MaCh3_Config macro in file.");
554 
555  // Convert TMacro to YAML: concatenate all lines and parse
556  std::stringstream yaml_text;
557  TList *lines = macro->GetListOfLines();
558  for (int iline = 0; iline < lines->GetEntries(); ++iline) {
559  TObjString *line = static_cast<TObjString*>(lines->At(iline));
560  yaml_text << line->GetString().Data() << "\n";
561  }
562 
563  try {
564  YAML::Node macro_yaml = YAML::Load(yaml_text.str());
565  YAML::Node umbrellaConfig =
566  macro_yaml["General"]["MCMC"]["Multicanonical"];
567  // Extract window parameters
568  config.windows[i].center = Get<double>(umbrellaConfig["Umbrella"]["UmbrellaMean"], __FILE__, __LINE__);
569  MACH3LOG_DEBUG("Window {} center updated to {}", i, config.windows[i].center);
570 
571  config.variable_of_interest = Get<std::string>(umbrellaConfig["VariableName"], __FILE__, __LINE__);
572  config.windows[i].multicanonical_beta = Get<double>(umbrellaConfig["Beta"], __FILE__, __LINE__);
573 
574  // Check if using von Mises distribution
575  auto biasString = Get<std::string>(umbrellaConfig["Umbrella"]["UmbrellaBiasFunction"], __FILE__, __LINE__);
576  M3::BiasFunction biasMode = M3::ParseBiasFunction(biasString);
577  config.windows[i].umbrellaBiasFunction = biasMode;
578 
579  if (config.windows[i].umbrellaBiasFunction == M3::BiasFunction::kVonMises) {
580  // Extract von Mises sigma and compute kappa
581  double vonMises_sigma = Get<double>(umbrellaConfig["Umbrella"]["UmbrellaWidth"], __FILE__, __LINE__);
582  config.windows[i].vonMises_kappa = 1.0 / (vonMises_sigma * vonMises_sigma);
583  config.windows[i].width = vonMises_sigma; // Store sigma in width for reference
584  MACH3LOG_DEBUG("Window {} using von Mises: sigma = {}, kappa = {}",
585  i, vonMises_sigma, config.windows[i].vonMises_kappa);
586  } else {
587  // Extract Gaussian sigma
588  config.windows[i].width = Get<double>(umbrellaConfig["Umbrella"]["UmbrellaWidth"], __FILE__, __LINE__);
589  config.windows[i].vonMises_kappa = -1.0; // Not using von Mises
590  MACH3LOG_DEBUG("Window {} using Gaussian: width = {}", i, config.windows[i].width);
591  }
592  } catch (const std::exception &e) {
593  MACH3LOG_WARN("Could not parse macro as YAML: {}", e.what());
594  }
595  } else{
596  MACH3LOG_ERROR("Found MaCh3 chain without embedded config, this can't be right");
597  throw MaCh3Exception(__FILE__, __LINE__);
598  }
599 
600  double var_value;
601 
602  tree->SetBranchStatus("*", false);
603  const auto* branch = tree->GetBranch(config.variable_of_interest.c_str());
604  if (branch == nullptr) {
605  MACH3LOG_ERROR("Branch '{}' does not exist in the TTree.", config.variable_of_interest);
606  throw MaCh3Exception(__FILE__, __LINE__);
607  }
608  tree->SetBranchStatus(config.variable_of_interest.c_str(), true);
609  tree->SetBranchAddress(config.variable_of_interest.c_str(), &var_value);
610  Long64_t nentries = tree->GetEntries();
611  MACH3LOG_DEBUG("Window {}: {} entries", i, nentries);
612  samples[i].resize(nentries);
613  for (Long64_t entry = 0; entry < nentries; entry++) {
614  tree->GetEntry(entry);
615  samples[i][entry] = var_value;
616  }
617  // need to set all to true so later part of the code don't produce bonkers results
618  tree->SetBranchStatus("*", true);
619  }
620 
621  // Sort by window center and keep all per-window containers aligned.
622  // The final weighting stage loops over input_trees by index, so those indices
623  // must track the same sorted window order used by z_current.
624  for (size_t i = 0; i < config.windows.size(); i++) {
625  for (size_t j = i + 1; j < config.windows.size(); j++) {
626  if (config.windows[i].center > config.windows[j].center) {
627  std::swap(config.windows[i], config.windows[j]);
628  std::swap(samples[i], samples[j]);
629  std::swap(input_trees[i], input_trees[j]);
630  std::swap(input_files[i], input_files[j]);
631  }
632  }
633  }
634  clock.Stop();
635  MACH3LOG_INFO("Finished loading samples, it took {:.2f}s to finish", clock.RealTime());
636 
637  // verify the order and file associations after sorting
638  MACH3LOG_INFO("Final window configurations after sorting:");
639 
641  {"#", 5, 5, M3::Utils::Alignment::Right},
642  {"Filename", 10, 50, M3::Utils::Alignment::Left},
643  {"Center", 10, 15, M3::Utils::Alignment::Right},
644  {"Width", 10, 15, M3::Utils::Alignment::Right},
645  {"BiasFunction", 15, 30, M3::Utils::Alignment::Left},
646  {"Samples", 10, 20, M3::Utils::Alignment::Right},
647  });
648 
649  for (size_t i = 0; i < config.windows.size(); ++i) {
650  const auto& window = config.windows[i];
651  TFile* file = input_files[i];
652 
653  table.AddRow(i, file->GetName(),
654  M3::Utils::Cell(window.center, "{:.2f}"),
655  M3::Utils::Cell(window.width, "{:.2f}"),
656  M3::BiasFunction_ToString(window.umbrellaBiasFunction),
657  samples[i].size());
658  }
659 
660  for (const auto& line : table.Render()) {
661  MACH3LOG_INFO("{}", line);
662  }
663 }
#define MACH3LOG_DEBUG
Definition: MaCh3Logger.h:34
Creates fancy formatted text tables for terminal output.
Definition: TablePrinter.h:50
void AddRow(Args &&... args)
Add a row to the table.
Definition: TablePrinter.h:57
static std::string Cell(T &&value, std::string_view format)
Format a value using a runtime fmt format string.
Definition: TablePrinter.h:44
@ Right
Align text to the right.
@ Left
Align text to the left.
M3::BiasFunction ParseBiasFunction(const std::string &biasFunctionName)
std::string BiasFunction_ToString(const M3::BiasFunction &biasFunction)

◆ parseYAMLConfig()

UmbrellaConfig M3::UmbrellaModule::parseYAMLConfig ( const std::string &  filename)
private

YAML-based config parser using yaml-cpp library.

Definition at line 49 of file UmbrellaModule.cpp.

49  {
50  UmbrellaConfig config;
51 
52  try {
53  YAML::Node yaml_diag_config = YAML::LoadFile(filename);
54  YAML::Node yaml_config = yaml_diag_config["UmbrellaSolver"];
55 
56  // Parse other configuration
57  config.output_file = Get<std::string>(yaml_config["output_file"], __FILE__ , __LINE__);
58  config.max_iterations = Get<int>(yaml_config["max_iterations"], __FILE__ , __LINE__);
59  config.tolerance = Get<double>(yaml_config["tolerance"], __FILE__ , __LINE__);
60  config.print_frequency = GetFromManager<int>(yaml_config["print_frequency"], 0, __FILE__ , __LINE__);
61  config.dynamic_files = GetFromManager<bool>(yaml_config["dynamic_files"], false, __FILE__ , __LINE__);
62  config.dynamic_pattern = Get<std::string>(yaml_config["dynamic_pattern"], __FILE__ , __LINE__);
63  config.dynamic_n_windows = Get<int>(yaml_config["dynamic_n_windows"], __FILE__ , __LINE__);
64 
65  if (!config.dynamic_files) {
66  // TODO: these are mostly redundant now that the MaCh3_Config macro is
67  // being parsed, work out if its safe to remove them at somepoint!!! Parse
68  // windows
69  if (yaml_config["windows"]) {
70  const YAML::Node &windows = yaml_config["windows"];
71  for (size_t i = 0; i < windows.size(); i++) {
72  WindowConfig window;
73  window.name = Get<std::string>(windows[i]["name"], __FILE__, __LINE__);
74  window.center = Get<double>(windows[i]["center"], __FILE__, __LINE__);
75  window.width = Get<double>(windows[i]["width"], __FILE__, __LINE__);
76  config.windows.push_back(window);
77  }
78  }
79 
80  // Parse input files
81  if (yaml_config["input_files"]) {
82  const YAML::Node &input_files = yaml_config["input_files"];
83  for (size_t i = 0; i < input_files.size() && i < config.windows.size(); i++) {
84  config.windows[i].input_file = Get<std::string>(input_files[i], __FILE__, __LINE__);
85  }
86  }
87  } else {
88  // set up placeholders to be filled later
89  for (int i = 0; i < config.dynamic_n_windows; i++) {
90  WindowConfig window;
91  window.name = "Window_" + std::to_string(i);
92  window.center = 0.0; // Placeholder, will be updated from MaCh3_Config macro
93  window.width = 1.0; // Placeholder, will be updated from MaCh3_Config macro
94  config.windows.push_back(window);
95  }
96  }
97  } catch (const YAML::Exception &e) {
98  MACH3LOG_ERROR("Error parsing YAML file {}: {}", filename, e.what());
99  throw MaCh3Exception(__FILE__, __LINE__);
100  }
101 
102  return config;
103 }

◆ Run()

int M3::UmbrellaModule::Run ( )
overridevirtual

Execute the Umbrella sampling.

Returns
Exit code (0 on success)

Implements M3::IPlugin.

Definition at line 34 of file UmbrellaModule.cpp.

34  {
35  if (m_parser->is_subcommand_used("plot")) return m_plotModule.Run();
37  std::string config_file = m_default_parser->get<std::string>("config");
38  try {
39  UmbrellaSolver(config_file);
40  } catch (const std::exception &e) {
41  MACH3LOG_ERROR("Error: {}", e.what());
42  return 1;
43  }
44 
45  return 0;
46 }
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Definition: MaCh3Logger.h:60
void UmbrellaSolver(const std::string &config_file)
int Run() override
Execute the Umbrella sampling plot analysis.

◆ summedWindowsWeighted()

double M3::UmbrellaModule::summedWindowsWeighted ( double  x,
const std::vector< WindowConfig > &  windows,
const std::vector< double > &  z_values 
)
private

Definition at line 148 of file UmbrellaModule.cpp.

148  {
149  double sum = 0.0;
150  for (size_t k = 0; k < windows.size(); k++) {
151  double window_val;
152  if (windows[k].umbrellaBiasFunction == M3::BiasFunction::kVonMises) {
153  window_val = vonMisesWindow(x, windows[k].center, windows[k].vonMises_kappa);
154  } else if (windows[k].umbrellaBiasFunction == M3::BiasFunction::kGaussian) {
155  window_val = gaussianWindow(x, windows[k].center, windows[k].width);
156  } else if (windows[k].umbrellaBiasFunction == M3::BiasFunction::kGeneralisedGaussian) {
157  window_val = GetMulticanonicalWeightGenGaussian(x, windows[k].center, windows[k].width, windows[k].multicanonical_beta);
158  } else {
159  MACH3LOG_ERROR("Unrecognised BiasFunction!!");
160  throw MaCh3Exception(__FILE__, __LINE__);
161  }
162  sum += window_val / z_values[k];
163  }
164  return sum;
165 }

◆ UmbrellaSolver()

void M3::UmbrellaModule::UmbrellaSolver ( const std::string &  config_file)
private

Definition at line 732 of file UmbrellaModule.cpp.

732  {
733  MACH3LOG_INFO("=== Umbrella Sampling Z-Factor Solver ===");
734 
735  #ifdef MULTITHREAD
736  MACH3LOG_INFO("Max threads available: {}", omp_get_max_threads());
737  #else
738  MACH3LOG_WARN("OpenMP not available");
739  #endif
740  MACH3LOG_INFO("Loading configuration from: {}", config_file);
741 
742  // Parse configuration
743  UmbrellaConfig config = parseYAMLConfig(config_file);
744 
745  if (config.windows.empty() && !config.dynamic_files) {
746  MACH3LOG_ERROR("No windows defined in configuration and dynamic file loading is disabled.");
747  throw MaCh3Exception(__FILE__, __LINE__);
748  }
749  MACH3LOG_INFO("Variable of interest: {}", config.variable_of_interest);
750  MACH3LOG_INFO("Output file: {}", config.output_file);
751 
752  // Load data from input files
753  // Declare here to ensure it exists in the scope of the entire function
754  std::vector<std::vector<double>> samples;
755 
756  if (!config.dynamic_files) {
757  samples.resize(config.windows.size());
758  } else {
759  samples.resize(config.dynamic_n_windows);
760  }
761  std::vector<TFile*> input_files;
762  std::vector<TTree*> input_trees;
763 
764  LoadFiles(samples, config, input_files, input_trees);
765 
766  // Initialize z values
767  std::vector<double> z_current(config.windows.size(), 1.0);
768  std::vector<double> z_prev(config.windows.size(), 1.0);
769  std::vector<std::vector<double>> z_evolution;
770 
771  MACH3LOG_INFO("Starting iterative z-solver...");
772  int max_threads = M3::GetNThreads();
773  MACH3LOG_INFO("Max threads reported: {}", max_threads);
774 
775  MACH3LOG_INFO("Precomputing window cache...");
776  // TODO: this is slow as hell and causes massive memory usage, what's a smarter
777  // way to do this? break out to a file? RDataFrame?
778  std::vector<std::vector<std::vector<double>>> window_cache = buildWindowCache(config.windows, samples);
779 
780  // TFile to hold the F matrix evolution for the first 15 iterations if needed
781  bool save_matrix = true; // Set to true to enable saving F matrix evolution
782  // Create F_file here to avoid reopening it multiple times in the loop
783  TFile *F_file = nullptr;
784  if (save_matrix) {
785  size_t pos = config.output_file.find(".root");
786  std::string base_name = (pos != std::string::npos) ? config.output_file.substr(0, pos) : config.output_file;
787  F_file = TFile::Open((base_name + "_matrix_evolution.root").c_str(), "RECREATE"); // use name from config with .root subtracted with _matrix_evolution suffix added
788  if (!F_file || F_file->IsZombie()) {
789  MACH3LOG_ERROR("Cannot create file {}", base_name + "_matrix_evolution.root");
790  save_matrix = false; // Disable saving if file cannot be created
791  }
792  // add an initial FMatrix with the initial z values for reference
793  std::vector<std::vector<double>> initial_F = calcFmatrix(z_current, config.windows, samples, window_cache);
794  int n_windows = static_cast<int>(config.windows.size());
795  TH2D initial_F_TH2D("F_matrix_initial", "Initial F matrix;Window j;Window i", n_windows, 0, n_windows, n_windows, 0, n_windows);
796  for (int i = 0; i < n_windows; i++) {
797  for (int j = 0; j < n_windows; j++) {
798  initial_F_TH2D.SetBinContent(j + 1, i + 1, initial_F[i][j]); // Note the order of i and j for correct axis labeling
799  }
800  }
801  F_file->cd();
802  MACH3LOG_INFO("Saving initial F matrix to file...");
803  initial_F_TH2D.Write();
804  }
805 
806  // Timing variables
807  auto start_time = std::chrono::high_resolution_clock::now();
808  auto last_print_time = start_time;
809 
810  bool converged_robustness_check = false; // Flag to indicate if convergence check has been passed at least
811  // once, used to control when to start checking for stalled
812  // convergence
813 
814  if (!converged_robustness_check) {
815  MACH3LOG_INFO("Starting iterative solver with convergence checks...");
816  }
817  // Iterative solver
818  int total_output_lines = 0; // Track total lines printed for clearing
819  for (int iteration = 0; iteration < config.max_iterations; iteration++) {
820  if (iteration % config.print_frequency == 0 || iteration == 1) {
821  auto current_time = std::chrono::high_resolution_clock::now();
822  // Calculate average relative change (precision metric)
823  double avg_relative_change = 0.0;
824  if (iteration > 0) {
825  for (size_t i = 0; i < z_current.size(); i++) {
826  double rel_change = std::abs(z_current[i] - z_prev[i]) / std::max(std::abs(z_current[i]), 1e-10);
827  avg_relative_change += rel_change;
828  }
829  avg_relative_change /= static_cast<double>(z_current.size());
830  }
831 
832  // Print z-values
833  std::string z_values = "[";
834  for (size_t i = 0; i < z_current.size(); i++) {
835  z_values += fmt::format("{:10.5f}", z_current[i]);
836  if (i < z_current.size() - 1) {
837  z_values += ", ";
838  }
839  }
840  z_values += "]";
841  if (iteration > 0) {
842  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(current_time - last_print_time);
843  double avg_time_per_iteration = static_cast<double>(duration.count()) /
844  static_cast<double>(config.print_frequency);
845  MACH3LOG_INFO("Iteration {:6}: z values: {} (avg: {:6.1f} ms/iter)", iteration, z_values, avg_time_per_iteration);
846  MACH3LOG_INFO("Avg relative change: {:.3e} (target: {:.3e})", avg_relative_change, config.tolerance);
847  total_output_lines = 2;
848  } else {
849  MACH3LOG_INFO("Iteration {:6}: z values: {}", iteration, z_values);
850  total_output_lines = 1;
851  }
852  last_print_time = current_time;
853  }
854 
855  z_prev = z_current;
856  z_current = zSolver(z_current, config.windows, samples, window_cache, iteration % config.print_frequency == 0, &total_output_lines);
857  z_evolution.push_back(z_current);
858 
859  // save the first 15 iterations of the F matrix to check convergence
860  // behaviour and debug if needed should be a root file with Th2D for easy
861  // plotting in root, with axes of iteration number and window index, and the
862  // value being the F matrix element
863  if (save_matrix && (iteration < 15 || iteration % config.print_frequency == 0)) {
864  std::vector<std::vector<double>> F_matrix = calcFmatrix(z_current, config.windows, samples, window_cache);
865  // convert F_matrix to Th2D for saving to root file
866  int n_windows = static_cast<int>(config.windows.size());
867  TH2D F_TH2D(Form("F_matrix_iter_%02d", iteration),Form("F matrix at iteration %02d;Window j;Window i", iteration), n_windows, 0, n_windows, n_windows, 0, n_windows);
868  for (int i = 0; i < n_windows; i++) {
869  for (int j = 0; j < n_windows; j++) {
870  F_TH2D.SetBinContent(j + 1, i + 1, F_matrix[i][j]); // Note the order of i and j for correct axis labeling
871  }
872  }
873  // for the purposes of picking back up a solve after it has been
874  // interrupted also save the std::vector of z_current. You can put this into hacky start to pick up
875  TTree *z_tree = new TTree(Form("z_saved_iter_%02d", iteration), Form("Z vector at iteration %02d", iteration));
876  z_tree->Branch("z_saved", &z_current);
877  z_tree->Fill();
878  F_file->cd();
879  MACH3LOG_INFO("Saving F matrix for iteration {} to file...", iteration);
880  F_TH2D.Write();
881  z_tree->Write();
882  }
883  // if (save_matrix && iteration == 15) {
884  // F_file->Close();
885  // }
886 
887  // after the first convergence check has been passed, randomly perturb the z
888  // values to see if they return to the same values, this is a robustness
889  // check to see if the solution is stable or if it is just meeting the
890  // convergence criteria by chance due to small changes in z values
891  bool apply_robustness_check = true;
892  if (iteration % 100 == 0 &&
893  (checkConvergence(z_current, z_prev, config.tolerance) || checkConvergenceStalled(z_current, z_prev, config.tolerance))) {
894  if (!converged_robustness_check && apply_robustness_check) {
895  MACH3LOG_INFO("Convergence check passed at iteration {}. Starting robustness check with random perturbation...", iteration);
896  converged_robustness_check = true;
897 
898  // Apply random perturbation to z_current
899  std::vector<double> z_perturbed = z_current;
900  for (size_t i = 0; i < z_perturbed.size(); i++) {
901  // Random perturbation up to 10 times the tolerance
902  double perturbation = M3::rand::Uniform(-0.5, 0.5) * z_perturbed[i];
903  z_perturbed[i] += perturbation;
904  if (z_perturbed[i] < 0) {
905  z_perturbed[i] = abs(z_perturbed[i]); // Ensure no negative values
906  }
907  MACH3LOG_INFO("z[{:2}] | Original: {:.6e} | Perturbation: {:+.6e} | Updated: {:.6e}",
908  i, z_current[i], perturbation, z_perturbed[i]);
909  }
910  z_current = z_perturbed;
911  MACH3LOG_INFO("Applied random perturbation to z values for robustness check.");
912  } else {
913  if (checkConvergence(z_current, z_prev, config.tolerance)) {
914  MACH3LOG_INFO("Convergence achieved at iteration {}", iteration);
915  } else {
916  MACH3LOG_WARN("Convergence appears to be stalled at iteration {}", iteration);
917  }
918 
919  if (iteration == config.max_iterations - 1) {
920  MACH3LOG_WARN("Reached maximum iterations without convergence.");
921  }
922 
923  auto end_time = std::chrono::high_resolution_clock::now();
924  auto total_duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
925  double avg_time_total = static_cast<double>(total_duration.count()) /
926  static_cast<double>(iteration + 1);
927  if (save_matrix) {
928  F_file->Close();
929  }
930  MACH3LOG_INFO("Terminating at iteration {}", iteration);
931  MACH3LOG_INFO("Average time per iteration: {:.6f} ms", avg_time_total);
932  break;
933  }
934  }
935  }
936 
937  std::ostringstream oss;
938  oss << "Final z values: [";
939  for (size_t i = 0; i < z_current.size(); i++) {
940  oss << std::fixed << std::setprecision(5) << z_current[i];
941  if (i < z_current.size() - 1)
942  oss << ", ";
943  }
944  oss << "]";
945  MACH3LOG_INFO("{}", oss.str());
946 
947  std::filesystem::copy_file(input_files[0]->GetName(), config.output_file,
948  std::filesystem::copy_options::overwrite_existing);
949  // Create output file
950  TFile *output_file = M3::Open(config.output_file.c_str(), "UPDATE", __FILE__, __LINE__);
951  output_file->cd();
952 
953  TTree *input_tree = dynamic_cast<TTree*>(output_file->Get("posteriors"));
954  // Create combined tree with weights
955  TTree *combined_tree = input_tree->CloneTree(0);
956 
957  // Variables for the combined tree
958  double umbrella_weight;
959  int window_id;
960  double umbrella_variable;
961 
962  combined_tree->Branch("umbrella_weight", &umbrella_weight, "umbrella_weight/D");
963  combined_tree->Branch("window_id", &window_id, "window_id/I");
964 
965  // Fill combined tree
966  for (size_t i = 0; i < input_trees.size(); i++) {
967  TTree *tree = input_trees[i];
968 
969  Long64_t nentries = tree->GetEntries();
970 
971  // KS: This is to avoid warnings about missing umbrella branches...
972  int oldLevel = gErrorIgnoreLevel;
973  gErrorIgnoreLevel = kError;
974  combined_tree->CopyAddresses(tree);
975  gErrorIgnoreLevel = oldLevel;
976 
977  tree->SetBranchAddress(config.variable_of_interest.c_str(), &umbrella_variable);
978  // KS: SetBranchAddress above decouples the input branch address, so update the
979  // copied output branch address to use the current umbrella_variable value.
980  combined_tree->GetBranch(config.variable_of_interest.c_str())->SetAddress(&umbrella_variable);
981  if (z_current[i] == 0) {
982  MACH3LOG_WARN("Z value for window {} is zero, skipping weighting for this window to avoid division by zero.", i);
983  }
984  window_id = static_cast<int>(i);
985 
986  for (Long64_t entry = 0; entry < nentries; entry++) {
987  tree->GetEntry(entry);
988 
989  if (z_current[i] == 0) {
990  umbrella_weight = 0.0; // If z is zero, we cannot apply the umbrella weight, so we set it to 0 (completely downweigh this window's contribution)
991  } else {
992  // Calculate umbrella weight for this event
993  // The umbrella weight corrects for the bias introduced by the window function Weight is 1 / sum of all window contributions (equation 4 from paper)
994  double denominator = 1 / summedWindowsWeighted(umbrella_variable, config.windows, z_current);
995 
996  // umbrella_weight = z_current[i] / denominator; // with or without z_current[i] / denominator? why did I have this originally
997  umbrella_weight = denominator; // This is the correct form based on the paper - the z_current[i] factor is already included in the summedWindowsWeighted function
998  }
999 
1000  if (combined_tree->Fill() < 0) {
1001  MACH3LOG_WARN("Failed writing output tree. Check disk quota/space and write permissions for: {}", config.output_file);
1002  throw MaCh3Exception(__FILE__, __LINE__);
1003  }
1004  }
1005  }
1006  // Write final results
1007  combined_tree->Write(input_tree->GetName(), TObject::kOverwrite);
1008 
1009  // Save diagnostics
1010  DiagnoseUmbrella(config, output_file, z_evolution, combined_tree);
1011 
1012  // Get entry count before closing the file
1013  Long64_t total_entries = combined_tree->GetEntries();
1014 
1015  output_file->cd();
1016 
1017  YAML::Node yaml_config = M3OpenConfig(config_file);
1018  YAML::Node umbrella_config;
1019  umbrella_config["UmbrellaSolver"] = yaml_config["UmbrellaSolver"];
1020 
1021  // Convert YAML -> TMacro
1022  TMacro UmbrellaHeader = YAMLtoTMacro(umbrella_config, "Umbrella_Config");
1023  UmbrellaHeader.Write();
1024 
1025  output_file->Close();
1026 
1027  // Close input files
1028  for (TFile *file : input_files) {
1029  file->Close();
1030  }
1031 
1032  MACH3LOG_INFO("Umbrella sampling outputs created (make sure to check for convergence issues)!");
1033  MACH3LOG_INFO("Output written to: {}", config.output_file);
1034  MACH3LOG_INFO("Combined tree contains {} entries with umbrella weights.", total_entries);
1035 }
TMacro YAMLtoTMacro(const YAML::Node &yaml_node, const std::string &name)
Convert a YAML node to a ROOT TMacro object.
Definition: YamlHelper.h:166
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:589
bool checkConvergence(const std::vector< double > &z_current, const std::vector< double > &z_prev, double tolerance)
A few different convergence checks.
std::vector< std::vector< double > > calcFmatrix(const std::vector< double > &z_current, const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples, const std::vector< std::vector< std::vector< double >>> &window_cache)
std::vector< double > zSolver(const std::vector< double > &z_current, const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples, const std::vector< std::vector< std::vector< double >>> &window_cache, [[maybe_unused]] bool verbose=false, [[maybe_unused]] int *total_lines=nullptr)
void DiagnoseUmbrella(const UmbrellaConfig &config, TFile *output_file, const std::vector< std::vector< double >> &z_evolution, TTree *combined_tree)
bool checkConvergenceStalled(const std::vector< double > &z_current, const std::vector< double > &z_prev, double tolerance)
void LoadFiles(std::vector< std::vector< double >> &samples, UmbrellaConfig &config, std::vector< TFile * > &input_files, std::vector< TTree * > &input_trees)
UmbrellaConfig parseYAMLConfig(const std::string &filename)
YAML-based config parser using yaml-cpp library.
double summedWindowsWeighted(double x, const std::vector< WindowConfig > &windows, const std::vector< double > &z_values)
std::vector< std::vector< std::vector< double > > > buildWindowCache(const std::vector< WindowConfig > &windows, const std::vector< std::vector< double >> &samples)
double Uniform(const double min=0.0, const double max=1.0)
Generate a uniform random number in [min, max).
Definition: Random.h:116
int GetNThreads()
number of threads which we need for example for TRandom3
Definition: Monitor.cpp:372

◆ vonMisesWindow()

double M3::UmbrellaModule::vonMisesWindow ( double  x,
double  center,
double  kappa 
)
private

Definition at line 111 of file UmbrellaModule.cpp.

111  {
112  // von Mises PDF: exp(kappa * cos(x - center)) / (2*pi*I0(kappa))
113  // For numerical stability, compute in log space when possible
114  if (kappa > 700) {
115  // Use asymptotic approximation for large kappa to avoid overflow
116  // log(I0(kappa)) ≈ kappa - 0.5*log(2*pi*kappa)
117  double log_I0 = kappa - 0.5 * log(2 * TMath::Pi() * kappa);
118  return exp(kappa * cos(x - center) - log_I0 - log(2 * TMath::Pi()));
119  } else {
120  double I0_kappa = TMath::BesselI0(kappa);
121  return exp(kappa * cos(x - center)) / (2 * TMath::Pi() * I0_kappa);
122  }
123 }

◆ zSolver()

std::vector< double > M3::UmbrellaModule::zSolver ( const std::vector< double > &  z_current,
const std::vector< WindowConfig > &  windows,
const std::vector< std::vector< double >> &  samples,
const std::vector< std::vector< std::vector< double >>> &  window_cache,
[[maybe_unused] ] bool  verbose = false,
[[maybe_unused] ] int *  total_lines = nullptr 
)
private

Normalize z to prevent scale drift and maintain sum(z)=1

Todo:
: try this with magnitude = 1, the absolute scale doesn't matter but maybee this condition is preventing elements meeting their required values? also just try completely disabled double z_sum = 0.0; for (int i = 0; i < n_windows; i++) { z_sum += z_new[i]; } if (z_sum > 0) { for (int i = 0; i < n_windows; i++) { z_new[i] /= z_sum; }

Definition at line 327 of file UmbrellaModule.cpp.

332  {
333  int n_windows = static_cast<int>(windows.size());
334 
335  // F matrix and update z values
336  std::vector<std::vector<double>> F = calcFmatrix(z_current, windows, samples, window_cache);
337  // Compute z_new = z_current * F
338  // could do faster matrix multiplication here?
339  std::vector<double> z_new(n_windows, 0.0);
340  for (int i = 0; i < n_windows; i++) {
341  for (int j = 0; j < n_windows; j++) {
342  z_new[i] += z_current[j] * F[j][i];
343  }
344  }
345 
358  //}
359 
360  // normalise the z values so that magnitude of the vector is 1
361  double z_magnitude = 0.0;
362  for (int i = 0; i < n_windows; i++) {
363  z_magnitude += z_new[i] * z_new[i];
364  }
365  z_magnitude = sqrt(z_magnitude);
366  if (z_magnitude > 0) {
367  for (int i = 0; i < n_windows; i++) {
368  z_new[i] /= z_magnitude;
369  }
370  }
371 
372  return z_new;
373 }

Member Data Documentation

◆ m_default_parser

std::unique_ptr<MaCh3ArgumentParser> M3::UmbrellaModule::m_default_parser
private

Definition at line 121 of file UmbrellaModule.hpp.

◆ m_plotModule

UmbrellaPlotModule M3::UmbrellaModule::m_plotModule
private

Definition at line 122 of file UmbrellaModule.hpp.


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