736 MACH3LOG_INFO(
"Max threads available: {}", omp_get_max_threads());
740 MACH3LOG_INFO(
"Loading configuration from: {}", config_file);
745 if (config.windows.empty() && !config.dynamic_files) {
746 MACH3LOG_ERROR(
"No windows defined in configuration and dynamic file loading is disabled.");
749 MACH3LOG_INFO(
"Variable of interest: {}", config.variable_of_interest);
754 std::vector<std::vector<double>> samples;
756 if (!config.dynamic_files) {
757 samples.resize(config.windows.size());
759 samples.resize(config.dynamic_n_windows);
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;
778 std::vector<std::vector<std::vector<double>>> window_cache =
buildWindowCache(config.windows, samples);
781 bool save_matrix =
true;
783 TFile *F_file =
nullptr;
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");
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++) {
820 if (iteration % config.print_frequency == 0 || iteration == 1) {
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()) /
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;
849 MACH3LOG_INFO(
"Iteration {:6}: z values: {}", iteration, z_values);
850 total_output_lines = 1;
852 last_print_time = current_time;
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);
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);
919 if (iteration == config.max_iterations - 1) {
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;
977 tree->SetBranchAddress(config.variable_of_interest.c_str(), &umbrella_variable);
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);
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);
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.
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).
int GetNThreads()
number of threads which we need for example for TRandom3