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);
22 m_parser->add_subparser(*plotParser);
24 m_parser->add_description(
"Tool for calculating umbrella weight based on several chains.");
28 .default_value(
"umbrella_config.yaml");
29 m_default_parser->add_epilog(
"Optional subcommands:\n " + plotParser->name() +
" " + plotParser->description());
40 }
catch (
const std::exception &e) {
53 YAML::Node yaml_diag_config = YAML::LoadFile(filename);
54 YAML::Node yaml_config = yaml_diag_config[
"UmbrellaSolver"];
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__);
69 if (yaml_config[
"windows"]) {
70 const YAML::Node &windows = yaml_config[
"windows"];
71 for (
size_t i = 0; i < windows.size(); i++) {
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);
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__);
91 window.
name =
"Window_" + std::to_string(i);
94 config.
windows.push_back(window);
97 }
catch (
const YAML::Exception &e) {
98 MACH3LOG_ERROR(
"Error parsing YAML file {}: {}", filename, e.what());
107 return exp(-0.5 * pow((x - center) / width, 2)) / (width * sqrt(2 * TMath::Pi()));
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()));
120 double I0_kappa = TMath::BesselI0(kappa);
121 return exp(kappa * cos(x - center)) / (2 * TMath::Pi() * I0_kappa);
131 double likelihood = normFactor * std::exp(-std::pow((std::pow(x - mean, 2) / (2 * std::pow(width, 2))), n));
143 return (g0 + g1 + g2) * (multicanonicalBeta);
150 for (
size_t k = 0; k < windows.size(); k++) {
153 window_val =
vonMisesWindow(x, windows[k].center, windows[k].vonMises_kappa);
155 window_val =
gaussianWindow(x, windows[k].center, windows[k].width);
162 sum += window_val / z_values[k];
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();
173 return n_windows * total_samples *
sizeof(double);
180 const std::vector<std::vector<double>> &samples) {
183 int n_windows =
static_cast<int>(windows.size());
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);
189 MACH3LOG_INFO(
"Window cache size: {:.2f} GB", cache_size_gb);
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());
202 #pragma omp parallel for collapse(2) schedule(dynamic)
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++) {
208 cache[i][j][s] =
vonMisesWindow(samples[i][s], windows[j].center, windows[j].vonMises_kappa);
210 cache[i][j][s] =
gaussianWindow(samples[i][s], windows[j].center, windows[j].width);
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]));
236 window_cache_hist->Write();
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++) {
249 window_cache_2D_hist->Fill(samples[i][s], log(cache[i][j][s]));
252 window_cache_2D_hist->SetStats(1);
253 window_cache_2D_hist->Write();
260 MACH3LOG_INFO(
"Finished building window cache, it took {:.2f}s to finish", clock.RealTime());
266 const std::vector<WindowConfig> &windows,
267 const std::vector<std::vector<double>> &samples,
268 const std::vector<std::vector<std::vector<double>>> &window_cache) {
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));
272 std::vector<double> z_inv = 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];
279 MACH3LOG_WARN(
"Warning: z_current[{}] is non-positive ({}). Setting its inverse to 0 in F matrix calculation.", i, z_current[i]);
284 #pragma omp parallel for schedule(dynamic)
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];
293 denominator_cache[s] = 1 / denominator;
296 for (
int j = 0; j < n_windows; j++) {
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];
305 if (denominator > 0) {
306 double integrand = (window_j * z_inv[i]) * denominator;
310 MACH3LOG_WARN(
"Denominator is zero for sample {} in window {}, skipping...", sample, i);
315 MACH3LOG_INFO(
"F[{}][{}] sum: {}, count: {}", i, j, sum, count);
319 F[i][j] = sum / count;
328 const std::vector<WindowConfig> &windows,
329 const std::vector<std::vector<double>> &samples,
330 const std::vector<std::vector<std::vector<double>>> &window_cache,
331 [[maybe_unused]]
bool verbose,
332 [[maybe_unused]]
int *total_lines) {
333 int n_windows =
static_cast<int>(windows.size());
336 std::vector<std::vector<double>> F =
calcFmatrix(z_current, windows, samples, window_cache);
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];
361 double z_magnitude = 0.0;
362 for (
int i = 0; i < n_windows; i++) {
363 z_magnitude += z_new[i] * z_new[i];
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;
378 double sum_diffs = 0.0;
379 for (
size_t i = 0; i < z_current.size(); i++) {
388 sum_diffs += std::abs(z_current[i] - z_prev[i]);
394 if (sum_diffs /
static_cast<double>(z_current.size()) > tolerance) {
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]);
414 static std::deque<std::vector<double>> z_history;
415 static std::vector<double> previous_moving_average;
416 static int stagnant_iterations = 0;
418 constexpr
int moving_average_window = 500;
419 constexpr
int stagnant_required = 500;
420 const double bound = tolerance;
422 if (z_current.empty()) {
427 if (!z_history.empty() && z_history.front().size() != z_current.size()) {
429 previous_moving_average.clear();
430 stagnant_iterations = 0;
433 z_history.push_back(z_current);
434 if (
static_cast<int>(z_history.size()) > moving_average_window) {
435 z_history.pop_front();
439 if (
static_cast<int>(z_history.size()) < moving_average_window) {
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];
449 for (
size_t i = 0; i < moving_average.size(); i++) {
450 moving_average[i] /= moving_average_window;
453 if (previous_moving_average.empty()) {
454 previous_moving_average = moving_average;
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;
466 if (all_within_bound) {
467 stagnant_iterations++;
469 stagnant_iterations = 0;
472 previous_moving_average = moving_average;
474 if (stagnant_iterations == stagnant_required) {
475 MACH3LOG_WARN(
"Convergence appears stalled: moving-average change stayed within {} for {} iterations.",
476 bound, stagnant_required);
479 return stagnant_iterations >= stagnant_required;
486 MACH3LOG_INFO(
"Using static input files from configuration.");
487 for (
size_t i = 0; i < config.
windows.size(); i++) {
489 TFile *file = M3::Open(config.
windows[i].input_file.c_str(),
"READ", __FILE__, __LINE__);
491 TTree *tree =
static_cast<TTree*
>(file->Get(
"posteriors"));
498 input_files.push_back(file);
499 input_trees.push_back(tree);
505 TList *files = dir.GetListOfFiles();
510 while ((file =
static_cast<TSystemFile*
>(next()))) {
511 std::string filename = file->GetName();
512 if (filename.find(
".root") == std::string::npos) {
520 TFile *root_file = M3::Open(full_path,
"READ", __FILE__, __LINE__);
522 TTree *tree =
static_cast<TTree*
>(root_file->Get(
"posteriors"));
526 throw MaCh3Exception(__FILE__, __LINE__,
"Missing 'posteriors' tree in file: " + full_path);
530 input_files.push_back(root_file);
531 input_trees.push_back(tree);
532 MACH3LOG_DEBUG(
"Loaded tree 'posteriors' from file: {}", full_path);
540 MACH3LOG_ERROR(
"Number of files found ({}) does not match expected dynamic_n_windows ({}).",
542 throw MaCh3Exception(__FILE__, __LINE__,
"File count mismatch for dynamic loading.");
546 for (
size_t i = 0; i < input_trees.size(); i++) {
547 TTree *tree = input_trees[i];
548 TFile *file = input_files[i];
550 MACH3LOG_DEBUG(
"Processing file {}/{}: {}", i + 1, input_trees.size(), file->GetName());
551 TMacro *macro =
static_cast<TMacro*
>(file->Get(
"MaCh3_Config"));
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";
564 YAML::Node macro_yaml = YAML::Load(yaml_text.str());
565 YAML::Node umbrellaConfig =
566 macro_yaml[
"General"][
"MCMC"][
"Multicanonical"];
568 config.
windows[i].center = Get<double>(umbrellaConfig[
"Umbrella"][
"UmbrellaMean"], __FILE__, __LINE__);
571 config.
variable_of_interest = Get<std::string>(umbrellaConfig[
"VariableName"], __FILE__, __LINE__);
572 config.
windows[i].multicanonical_beta = Get<double>(umbrellaConfig[
"Beta"], __FILE__, __LINE__);
575 auto biasString = Get<std::string>(umbrellaConfig[
"Umbrella"][
"UmbrellaBiasFunction"], __FILE__, __LINE__);
577 config.
windows[i].umbrellaBiasFunction = biasMode;
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;
584 MACH3LOG_DEBUG(
"Window {} using von Mises: sigma = {}, kappa = {}",
585 i, vonMises_sigma, config.
windows[i].vonMises_kappa);
588 config.
windows[i].width = Get<double>(umbrellaConfig[
"Umbrella"][
"UmbrellaWidth"], __FILE__, __LINE__);
589 config.
windows[i].vonMises_kappa = -1.0;
592 }
catch (
const std::exception &e) {
593 MACH3LOG_WARN(
"Could not parse macro as YAML: {}", e.what());
596 MACH3LOG_ERROR(
"Found MaCh3 chain without embedded config, this can't be right");
602 tree->SetBranchStatus(
"*",
false);
604 if (branch ==
nullptr) {
610 Long64_t nentries = tree->GetEntries();
612 samples[i].resize(nentries);
613 for (Long64_t entry = 0; entry < nentries; entry++) {
614 tree->GetEntry(entry);
615 samples[i][entry] = var_value;
618 tree->SetBranchStatus(
"*",
true);
624 for (
size_t i = 0; i < config.
windows.size(); i++) {
625 for (
size_t j = i + 1; j < config.
windows.size(); 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]);
635 MACH3LOG_INFO(
"Finished loading samples, it took {:.2f}s to finish", clock.RealTime());
649 for (
size_t i = 0; i < config.
windows.size(); ++i) {
650 const auto& window = config.
windows[i];
651 TFile* file = input_files[i];
653 table.AddRow(i, file->GetName(),
660 for (
const auto& line : table.Render()) {
666 TTree *combined_tree) {
667 TDirectory* UmbrellaDir = output_file->mkdir(
"Umbrella");
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);
675 double ymin = std::numeric_limits<double>::max();
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]);
684 for (
double val : z_vals) {
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");
700 z_graphs[i]->Draw(
"AL");
702 z_graphs[i]->Draw(
"L SAME");
705 legend.AddEntry(z_graphs[i].get(), Form(
"Window %lu", i),
"l");
706 z_graphs[i]->Write();
710 z_graphs[0]->SetMaximum(ymax);
711 z_graphs[0]->SetMinimum(ymin);
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());
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");
725 h_delta_cp_unweighted->Write();
727 UmbrellaDir->Close();
736 MACH3LOG_INFO(
"Max threads available: {}", omp_get_max_threads());
740 MACH3LOG_INFO(
"Loading configuration from: {}", config_file);
746 MACH3LOG_ERROR(
"No windows defined in configuration and dynamic file loading is disabled.");
754 std::vector<std::vector<double>> samples;
757 samples.resize(config.
windows.size());
761 std::vector<TFile*> input_files;
762 std::vector<TTree*> input_trees;
764 LoadFiles(samples, config, input_files, input_trees);
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;
781 bool save_matrix =
true;
783 TFile *F_file =
nullptr;
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");
788 if (!F_file || F_file->IsZombie()) {
789 MACH3LOG_ERROR(
"Cannot create file {}", base_name +
"_matrix_evolution.root");
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]);
803 initial_F_TH2D.Write();
807 auto start_time = std::chrono::high_resolution_clock::now();
808 auto last_print_time = start_time;
810 bool converged_robustness_check =
false;
814 if (!converged_robustness_check) {
815 MACH3LOG_INFO(
"Starting iterative solver with convergence checks...");
818 int total_output_lines = 0;
819 for (
int iteration = 0; iteration < config.
max_iterations; iteration++) {
821 auto current_time = std::chrono::high_resolution_clock::now();
823 double avg_relative_change = 0.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;
829 avg_relative_change /=
static_cast<double>(z_current.size());
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) {
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()) /
845 MACH3LOG_INFO(
"Iteration {:6}: z values: {} (avg: {:6.1f} ms/iter)", iteration, z_values, avg_time_per_iteration);
847 total_output_lines = 2;
849 MACH3LOG_INFO(
"Iteration {:6}: z values: {}", iteration, z_values);
850 total_output_lines = 1;
852 last_print_time = current_time;
857 z_evolution.push_back(z_current);
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);
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]);
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);
879 MACH3LOG_INFO(
"Saving F matrix for iteration {} to file...", iteration);
891 bool apply_robustness_check =
true;
892 if (iteration % 100 == 0 &&
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;
899 std::vector<double> z_perturbed = z_current;
900 for (
size_t i = 0; i < z_perturbed.size(); i++) {
903 z_perturbed[i] += perturbation;
904 if (z_perturbed[i] < 0) {
905 z_perturbed[i] = abs(z_perturbed[i]);
907 MACH3LOG_INFO(
"z[{:2}] | Original: {:.6e} | Perturbation: {:+.6e} | Updated: {:.6e}",
908 i, z_current[i], perturbation, z_perturbed[i]);
910 z_current = z_perturbed;
911 MACH3LOG_INFO(
"Applied random perturbation to z values for robustness check.");
914 MACH3LOG_INFO(
"Convergence achieved at iteration {}", iteration);
916 MACH3LOG_WARN(
"Convergence appears to be stalled at iteration {}", iteration);
920 MACH3LOG_WARN(
"Reached maximum iterations without convergence.");
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);
931 MACH3LOG_INFO(
"Average time per iteration: {:.6f} ms", avg_time_total);
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)
947 std::filesystem::copy_file(input_files[0]->GetName(), config.
output_file,
948 std::filesystem::copy_options::overwrite_existing);
950 TFile *output_file = M3::Open(config.
output_file.c_str(),
"UPDATE", __FILE__, __LINE__);
953 TTree *input_tree =
dynamic_cast<TTree*
>(output_file->Get(
"posteriors"));
955 TTree *combined_tree = input_tree->CloneTree(0);
958 double umbrella_weight;
960 double umbrella_variable;
962 combined_tree->Branch(
"umbrella_weight", &umbrella_weight,
"umbrella_weight/D");
963 combined_tree->Branch(
"window_id", &window_id,
"window_id/I");
966 for (
size_t i = 0; i < input_trees.size(); i++) {
967 TTree *tree = input_trees[i];
969 Long64_t nentries = tree->GetEntries();
972 int oldLevel = gErrorIgnoreLevel;
973 gErrorIgnoreLevel = kError;
974 combined_tree->CopyAddresses(tree);
975 gErrorIgnoreLevel = oldLevel;
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);
984 window_id =
static_cast<int>(i);
986 for (Long64_t entry = 0; entry < nentries; entry++) {
987 tree->GetEntry(entry);
989 if (z_current[i] == 0) {
990 umbrella_weight = 0.0;
997 umbrella_weight = denominator;
1000 if (combined_tree->Fill() < 0) {
1001 MACH3LOG_WARN(
"Failed writing output tree. Check disk quota/space and write permissions for: {}", config.
output_file);
1007 combined_tree->Write(input_tree->GetName(), TObject::kOverwrite);
1013 Long64_t total_entries = combined_tree->GetEntries();
1018 YAML::Node umbrella_config;
1019 umbrella_config[
"UmbrellaSolver"] = yaml_config[
"UmbrellaSolver"];
1022 TMacro UmbrellaHeader =
YAMLtoTMacro(umbrella_config,
"Umbrella_Config");
1023 UmbrellaHeader.Write();
1025 output_file->Close();
1028 for (TFile *file : input_files) {
1032 MACH3LOG_INFO(
"Umbrella sampling outputs created (make sure to check for convergence issues)!");
1034 MACH3LOG_INFO(
"Combined tree contains {} entries with umbrella weights.", total_entries);
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
TMacro YAMLtoTMacro(const YAML::Node &yaml_node, const std::string &name)
Convert a YAML node to a ROOT TMacro object.
#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.
bool checkConvergence(const std::vector< double > &z_current, const std::vector< double > &z_prev, double tolerance)
A few different convergence checks.
double generalisedGaussian2(double x, double mean, double width)
void UmbrellaSolver(const std::string &config_file)
size_t calculateWindowCacheSizeBytes(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)
void DiagnoseUmbrella(const UmbrellaConfig &config, TFile *output_file, const std::vector< std::vector< double >> &z_evolution, TTree *combined_tree)
double GetMulticanonicalWeightGenGaussian(double deltacp, double mean, double width, double multicanonicalBeta)
bool checkConvergenceStalled(const std::vector< double > &z_current, const std::vector< double > &z_prev, double tolerance)
UmbrellaPlotModule m_plotModule
void LoadFiles(std::vector< std::vector< double >> &samples, UmbrellaConfig &config, std::vector< TFile * > &input_files, std::vector< TTree * > &input_trees)
int Run() override
Execute the Umbrella sampling.
std::unique_ptr< MaCh3ArgumentParser > m_default_parser
std::vector< double > getZDiffs(const std::vector< double > &z_current, const std::vector< double > &z_prev)
double vonMisesWindow(double x, double center, double kappa)
virtual ~UmbrellaModule()
Destructor.
double gaussianWindow(double x, double center, double width)
UmbrellaConfig parseYAMLConfig(const std::string &filename)
YAML-based config parser using yaml-cpp library.
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
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)
int Run() override
Execute the Umbrella sampling plot analysis.
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
Creates fancy formatted text tables for terminal output.
Custom exception class used throughout MaCh3.
static std::string Cell(T &&value, std::string_view format)
Format a value using a runtime fmt format string.
@ Right
Align text to the right.
@ Left
Align text to the left.
double Uniform(const double min=0.0, const double max=1.0)
Generate a uniform random number in [min, max).
Main namespace for MaCh3 software.
M3::BiasFunction ParseBiasFunction(const std::string &biasFunctionName)
std::string BiasFunction_ToString(const M3::BiasFunction &biasFunction)
int GetNThreads()
number of threads which we need for example for TRandom3
constexpr double UmbrellaGaussianNormFactor
@ kGaussian
Assumes gaussian prior.
std::string variable_of_interest
std::vector< WindowConfig > windows
std::string dynamic_pattern