MaCh3  2.8.0
Reference Guide
LLHMapModule.cpp
Go to the documentation of this file.
1 // MaCh3 includes
3 #include "Manager/Manager.h"
4 
10 namespace M3 {
11 LLHMapModule::~LLHMapModule() = default;
12 
14  m_parser = std::make_unique<MaCh3ArgumentParser>("llhmap", "1.0", argparse::default_arguments::help);
15  m_parser->add_description("Process LLHMap outputs and generate 1D and 2D profiled likelihoods as defined in the config");
16  m_parser->add_argument("config")
17  .help("Config file.")
18  .metavar("CONFIG")
19  .required();
20  m_parser->add_argument("inputfile")
21  .help("LLHMap outputs root files to process")
22  .metavar("INPUTFILE")
23  .nargs(argparse::nargs_pattern::at_least_one)
24  .required();
25  return m_parser.get();
26 }
27 
28 // *******************
29 // Process the parameters as given by the config file and present in the input LLHMap
30 std::vector<std::string> LLHMapModule::GetParams(std::vector<std::string> &PoIs, ROOT::RDataFrame Map) {
31 // *******************
32  std::vector<std::string> PtPs;
33 
34  if(PoIs.empty())
35  MACH3LOG_INFO("No parameters requested, processing all parameters found in the LLHMap!");
36 
37  // First, filter out all non-parametric (LLH) columns of LLHMap
38  for(auto p : Map.GetColumnNames())
39  {
40  if(p.find("_LLH") != std::string::npos) continue;
41  PtPs.push_back(p);
42  }
43 
44  // Check if the parameters user wants to plot, actually live in the LLHMap
45  // Remove from the list if not
46  for(auto pit = PoIs.begin(); pit != PoIs.end();)
47  {
48  if(std::find(PtPs.begin(), PtPs.end(), *pit) != PtPs.end())
49  {
50  ++pit;
51  } else {
52  MACH3LOG_WARN("Parameter {} not found in the LLHMap!", *pit);
53  pit = PoIs.erase(pit);
54  }
55  }
56 
57 // Check what LLHMap parameters the user wants to plot
58 // Remove from the list if not
59 for(auto pit = PtPs.begin(); pit != PtPs.end();)
60 {
61  if(std::find(PoIs.begin(), PoIs.end(), *pit) != PoIs.end() || PoIs.empty()){
62  ++pit;
63  } else {
64  pit = PtPs.erase(pit);
65  }
66  }
67 
68  // Return the vector of parameters we are about to plot
69  return PtPs;
70 }
71 
72 // *******************
73 // Extract binning
74 std::pair<bool,std::vector<double>> LLHMapModule::ExtractBinning(std::string param, YAML::Node Settings, ROOT::RDataFrame Map) {
75 // *******************
76  // Expected number of bins based on the config
77  unsigned int nExpBins = GetFromManager<unsigned int>(Settings["LLHScan"]["LLHScanPoints"], 20, __FILE__, __LINE__);
78  if(CheckNodeExists(Settings,"LLHScan","ScanPoints"))
79  nExpBins = GetFromManager<unsigned int>(Settings["LLHScan"]["ScanPoints"][param], nExpBins, __FILE__, __LINE__);
80 
81 
82  // Preparing a histogram.
83  auto values = Map.Take<double>(param.c_str());
84 
85  // remove duplicates
86  std::set<double> unique(values->begin(), values->end());
87 
88  MACH3LOG_INFO("There are {} values (bins) for parameter {} inside LLHMap.", unique.size(), param);
89 
90  if(nExpBins != static_cast<unsigned int>(unique.size())) {
91  MACH3LOG_WARN("The config expects different number of {} bins for parameter {} than {} values included in LLHMap!", nExpBins, param, unique.size());
92  nExpBins = static_cast<unsigned int>(unique.size());
93  }
94 
95  // Extract minimum and maximum
96  double minx = *unique.begin();
97  double maxx = *unique.rbegin();
98 
99  // What is the minimal difference between two unique values to construct a bin width
100  double minDiff = maxx - minx;
101 
102  for (auto it = std::next(unique.begin()); it != unique.end(); ++it) {
103  auto prev = std::prev(it);
104  minDiff = std::min(minDiff, *it - *prev);
105  }
106 
107  if (unique.size() > 1) {
108  unsigned int bins = static_cast<unsigned int>( 1 + std::abs(maxx-minx) / minDiff );
109  if (nExpBins != bins) {
110  MACH3LOG_WARN("The scan is not uniform! Instead, we will use bins based on unique scan values and minimal {:.3e} distance between them!", minDiff);
111  nExpBins = 0;
112  }
113  }
114 
115  double half_w = std::max(1e-12*minx, .5*minDiff);
116  minx = minx-half_w;
117  maxx = maxx+half_w;
118 
119  std::vector<double> binning = {minx, maxx};
120  if (nExpBins == 0) {
121  for (auto it = std::next(unique.begin()); std::next(it) != unique.end(); ++it)
122  {
123  // first, insert next edge
124  double next_edge = *it + half_w;
125  binning.insert(binning.end()-1, next_edge);
126 
127  // now check, if it aligns with the next unique value
128  auto next = std::next(it);
129  if ( std::abs((next_edge - *next + half_w) / (next_edge + *next - half_w )) < 1e-12 ) {
130  continue;
131  } else {
132  binning.insert(binning.end()-1, *next-half_w);
133  }
134  }
135  } else {
136  for (auto it = unique.begin(); std::next(it) != unique.end(); ++it)
137  binning.insert(binning.end()-1, *it + half_w);
138  }
139  return std::make_pair(nExpBins>0, binning);
140 }
141 
142 // *******************
144 // *******************
147 
148  std::string configfile = m_parser->get<std::string>("config");
149  std::vector<std::string> inputfilelist = m_parser->get<std::vector<std::string>>("inputfile");
150  if (inputfilelist.size() < 2){
151  MACH3LOG_ERROR("At least two input files are required!");
152  throw MaCh3Exception(__FILE__ , __LINE__ );
153  }
154 
155  // Open the settings and output file
156  YAML::Node Settings = M3OpenConfig(configfile);
157  auto OutFileName = GetFromManager<std::string>(Settings["General"]["OutputFile"], "LLHMap.root", __FILE__, __LINE__);
158  auto Plot2D = GetFromManager<bool>(Settings["LLHScan"]["Plot2D"], false, __FILE__, __LINE__);
159 
160  auto OutFile = new TFile(OutFileName.c_str(),"UPDATE");
161  OutFile->cd();
162 
163  // Prepare dirs for profiled LLHs
164  TDirectory* DirProfile1D = OutFile->mkdir("Profiled1D_LLH", "profile1D", true);
165  TDirectory* DirProfile2D = nullptr;
166  if (Plot2D) DirProfile2D = OutFile->mkdir("Profiled2D_LLH", "profile2D", true);
167 
168  TDirectory* DirMarginal1D = OutFile->mkdir("Marginal1D_L", "marginal1D", true);
169  TDirectory* DirMarginal2D = nullptr;
170  if (Plot2D) DirMarginal2D = OutFile->mkdir("Marginal2D_L", "marginal2D", true);
171 
172 
173  // Read the llhmap trees from the input files
174  auto Map = ROOT::RDataFrame("llhmap", inputfilelist);
175 
176  // Now prepare the L column
177  // TODO: Let the user choose whether they want the Total_LLH or something else... but why?
178  auto LLHMap = Map.Define("L", "exp(-0.5*Total_LLH)");
179 
180  // Process what parameters to plot
181  auto ParamsOfInterest = GetFromManager<std::vector<std::string>>(Settings["LLHScan"]["LLHParameters"],{}, __FILE__, __LINE__);
182  std::vector<std::string> ParamsToProfile = GetParams(ParamsOfInterest, Map);
183 
184  MACH3LOG_INFO("... Starting generating 1D profiled and marginalized likelihoods ...");
185  MACH3LOG_WARN("!!! LLHMap numerical marginalization assumes uncorrelated priors !!!");
186 
187  std::map<std::string, std::unique_ptr<TH1D>> hProfiles1d;
188  std::map<std::string, std::unique_ptr<TH1D>> hMarginals1d;
189  for(auto p = ParamsToProfile.begin(); p != ParamsToProfile.end(); ++p)
190  {
191  // Find the binning for the histograms.
192  // ExtractBinning gives a pair of bool, bin_edges.
193  // The bool denotes whether binning is uniform or not.
194  std::pair<bool, std::vector<double>> binning = ExtractBinning(*p, Settings, Map);
195 
196  std::string hProfTitle = *p+" profiled -2LogL";
197  std::string hProfName = *p+"_LLHProf1D";
198  std::string hMargTitle = *p+" marginalized L";
199  std::string hMargName = *p+"_LMarg1D";
200 
201  // Prepare histograms and detach from ROOT
202  auto hprof1d = std::make_unique<TH1D>(hProfName.c_str(), hProfTitle.c_str(), int(binning.second.size()-1), binning.second.data());
203  hprof1d->SetDirectory(nullptr);
204 
205  auto hmarg1d = std::make_unique<TH1D>(hMargName.c_str(), hMargTitle.c_str(), int(binning.second.size()-1), binning.second.data());
206  hmarg1d->SetDirectory(nullptr);
207 
208  if (binning.first)
209  {
210  MACH3LOG_INFO("Initializing 1D profiled -2LogL and marginalized L histograms for {} of {} bins from {:.3e} to {:.3e} (bin center at {:.3e} and {:.3e})", *p, hprof1d->GetNbinsX(), hprof1d->GetXaxis()->GetXmin(), hprof1d->GetXaxis()->GetXmax(), hprof1d->GetBinCenter(1), hprof1d->GetBinCenter(hprof1d->GetNbinsX()));
211  } else {
212  std::string binnies;
213  // TN: Waiting for C++ 20 std::format() function
214  for (auto binnie : binning.second)
215  {
216  std::ostringstream os;
217  os << std::scientific << std::setprecision(4) << binnie;
218  binnies += " "+os.str();
219  }
220 
221  MACH3LOG_INFO("Initializing 1D profiled -2LogL and marginalized L histograms of {} bins with edges{}.", binning.second.size(), binnies);
222  }
223 
224  hProfiles1d[*p] = std::move(hprof1d);
225  hMarginals1d[*p] = std::move(hmarg1d);
226  }
227 
228  for(auto p = ParamsToProfile.begin(); p != ParamsToProfile.end(); ++p)
229  {
230  // Now loop over the bins. For each bin, find the minimal Total_LLH over the rest of the parameter space.
231  // TODO: Switch between different LLHs (sample, xsec, etc.)
232  const int count = hProfiles1d[*p]->GetNbinsX() > 5 ? int(double(hProfiles1d[*p]->GetNbinsX())/double(5)) : 1;
233 
234  // Profile over the rest of the parameters
235  MACH3LOG_INFO("Profiling 1D -2LogL and numerically profiling 1D L for parameter {}!", *p);
236  for(int bidx = 1; bidx < hProfiles1d[*p]->GetNbinsX() + 1; ++bidx)
237  {
238  if (bidx % count == 0)
239  M3::Utils::PrintProgressBar(bidx, hProfiles1d[*p]->GetNbinsX());
240 
241  auto b_lo = hProfiles1d[*p]->GetXaxis()->GetBinLowEdge(bidx);
242  auto b_hi = b_lo + hProfiles1d[*p]->GetXaxis()->GetBinWidth(bidx);
243 
244  double llhmin = LLHMap.Filter(*p+">"+std::to_string(b_lo)+"&&"+*p+"<"+std::to_string(b_hi)).Min("Total_LLH").GetValue();
245 
246  // Rather store a non-sensensical value if out of bounds
247  if(llhmin >= M3::_LARGE_LOGL_) llhmin = -12345;
248  hProfiles1d[*p]->SetBinContent(bidx, llhmin);
249 
250  auto L = LLHMap.Filter(*p+">"+std::to_string(b_lo)+"&&"+*p+"<"+std::to_string(b_hi)).Sum("L");
251 
252  hMarginals1d[*p]->SetBinContent(bidx, *L);
253  }
254 
255  // Save the 1D histograms
256  DirProfile1D->cd();
257  hProfiles1d[*p]->Write(hProfiles1d[*p]->GetName(), TObject::kOverwrite);
258 
259  DirMarginal1D->cd();
260  hMarginals1d[*p]->Scale(1./hMarginals1d[*p]->Integral());
261  hMarginals1d[*p]->Write(hMarginals1d[*p]->GetName(), TObject::kOverwrite);
262  }
263 
264 
265  if (Plot2D)
266  {
267  MACH3LOG_INFO("... Starting generating 2D profiled and marginalized likelihoods ...");
268  MACH3LOG_WARN("!!! THIS MIGHT TAKE QUITE A WHILE !!!");
269  MACH3LOG_WARN("!!! LLHMap numerical marginalization assumes uncorrelated priors !!!");
270 
271  std::vector<std::string> Keys2D;
272  std::vector<std::string> ParamsFiltered;
273  std::map<std::string, std::unique_ptr<TH2D>> hProfiles2d;
274  std::map<std::string, std::unique_ptr<TH2D>> hMarginals2d;
275 
276  for(auto p : ParamsToProfile)
277  {
278  auto h = DirProfile1D->Get<TH1D>((p+"_LLHProf1D").c_str());
279  if(h->GetNbinsX()<2)
280  {
281  MACH3LOG_WARN("There is less than 2 bins for {}, 2D is equivalent to 1D! Removing from 2D plots ...", p);
282  } else {
283  ParamsFiltered.push_back(p);
284  }
285  }
286 
287  // Similar as with 1D profiles, but looping over parameters twice
288  for(auto p1 = ParamsFiltered.begin(); p1 != ParamsFiltered.end(); ++p1)
289  {
290  for(auto p2 = std::next(p1); p2 != ParamsFiltered.end(); ++p2)
291  {
292  auto h1 = DirProfile1D->Get<TH1D>((*p1+"_LLHProf1D").c_str());
293  auto h2 = DirProfile1D->Get<TH1D>((*p2+"_LLHProf1D").c_str());
294 
295  std::string key = *p1+"_"+*p2;
296  Keys2D.push_back(key);
297 
298  MACH3LOG_INFO("Initializing 2D profiled -2LogL and marginalized L histograms for {} vs. {} based on previously generated 1D histograms.", *p1, *p2);
299 
300  std::string hProfTitle = *p1+" vs. "+*p2+" profiled -2LogL";
301  std::string hProfName = key+"_LLHProf2D";
302  auto hprof2d = std::make_unique<TH2D>(
303  hProfName.c_str(), hProfTitle.c_str(),
304  h1->GetXaxis()->GetNbins(), h1->GetXaxis()->GetXbins()->GetArray(),
305  h2->GetXaxis()->GetNbins(), h2->GetXaxis()->GetXbins()->GetArray()
306  );
307  hprof2d->SetDirectory(nullptr);
308 
309  hProfiles2d[key] = std::move(hprof2d);
310 
311  std::string hMargTitle = *p1+" vs. "+*p2+" marginalized L";
312  std::string hMargName = key+"_LMarg1D";
313  auto hmarg2d = std::make_unique<TH2D>(
314  hMargName.c_str(), hMargTitle.c_str(),
315  h1->GetXaxis()->GetNbins(), h1->GetXaxis()->GetXbins()->GetArray(),
316  h2->GetXaxis()->GetNbins(), h2->GetXaxis()->GetXbins()->GetArray()
317  );
318  hmarg2d->SetDirectory(nullptr);
319 
320  hMarginals2d[key] = std::move(hmarg2d);
321  }
322  }
323 
324  for(auto p1 = ParamsFiltered.begin(); p1 != ParamsFiltered.end(); ++p1)
325  {
326  for(auto p2 = std::next(p1); p2 != ParamsFiltered.end(); ++p2)
327  {
328  std::string key = *p1+"_"+*p2;
329 
330  MACH3LOG_INFO("Numerically profiling 2D -2LogL and marginalizing 2D L for parameters {} and {}!",*p1, *p2);
331  const Long64_t nBinsX = static_cast<Long64_t>(hProfiles2d[key]->GetNbinsX());
332  const Long64_t nBinsY = static_cast<Long64_t>(hProfiles2d[key]->GetNbinsY());
333 
334  const Long64_t TotalBins = nBinsX * nBinsY;
335  const int count = TotalBins > 5 ? int(double(TotalBins)/double(5)) : 1;
336 
337  for(int bidx = 1; bidx < nBinsX + 1; ++bidx)
338  {
339  for(int bidy = 1; bidy < nBinsY + 1; ++bidy)
340  {
341  if ( ((bidx-1)*hProfiles2d[key]->GetNbinsY() + bidy) % count == 0)
342  M3::Utils::PrintProgressBar((bidx-1)*hProfiles2d[key]->GetNbinsY() + bidy, TotalBins);
343 
344  auto bx_lo = hProfiles2d[key]->GetXaxis()->GetBinLowEdge(bidx);
345  auto bx_hi = bx_lo + hProfiles2d[key]->GetXaxis()->GetBinWidth(bidx);
346 
347  auto by_lo = hProfiles2d[key]->GetYaxis()->GetBinLowEdge(bidy);
348  auto by_hi = by_lo + hProfiles2d[key]->GetYaxis()->GetBinWidth(bidy);
349 
350  // TODO: Think how to do this smarter and faster
351  double llhmin = LLHMap.Filter(*p1+">"+std::to_string(bx_lo)+"&&"+*p1+"<"+std::to_string(bx_hi)+"&&"+*p2+">"+std::to_string(by_lo)+"&&"+*p2+"<"+std::to_string(by_hi)).Min("Total_LLH").GetValue();
352 
353  // Rather store a non-sensical value if out of bounds
354  if(llhmin >= M3::_LARGE_LOGL_) llhmin = -12345;
355  hProfiles2d[key]->SetBinContent(bidx, bidy, llhmin);
356 
357  auto L = LLHMap.Filter(*p1+">"+std::to_string(bx_lo)+"&&"+*p1+"<"+std::to_string(bx_hi)
358  +"&&"+*p2+">"+std::to_string(by_lo)+"&&"+*p2+"<"+std::to_string(by_hi)).Sum("L");
359 
360  hMarginals2d[key]->SetBinContent(bidx,bidy, *L);
361  } // end bins y loop
362  } // end bins x loop
363 
364  // Save the 2D histograms
365  DirProfile2D->cd();
366  hProfiles2d[key]->Write(hProfiles2d[key]->GetName(), TObject::kOverwrite);
367 
368  DirMarginal2D->cd();
369  hMarginals2d[key]->Scale(1./hMarginals2d[key]->Integral());
370  hMarginals2d[key]->Write(hMarginals2d[key]->GetName(), TObject::kOverwrite);
371  } // end p2 loop
372  } // end p1 loop
373  } // end 2D plot
374  OutFile->Close();
375  return 0;
376 }
377 }
Module for processing LLHMap outputs.
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
void SetMaCh3LoggerFormat()
Set messaging format of the logger.
Definition: MaCh3Logger.h:60
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
bool CheckNodeExists(const YAML::Node &node, Args... args)
KS: Wrapper function to call the recursive helper.
Definition: YamlHelper.h:59
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:589
virtual ~LLHMapModule()
Destructor.
std::vector< std::string > GetParams(std::vector< std::string > &PoIs, ROOT::RDataFrame Map)
Process the parameters as given by the config file and present in the input LLHMap.
std::pair< bool, std::vector< double > > ExtractBinning(std::string param, YAML::Node Settings, ROOT::RDataFrame Map)
Extract the binning for a given parameter from the LLHMap.
MaCh3ArgumentParser * get_parser() override
Get the argument parser for this module.
int Run() override
Execute the MCMC diagnostics.
Extended ArgumentParser with MaCh3-specific functionality.
Definition: m3argparse.hpp:17
std::unique_ptr< MaCh3ArgumentParser > m_parser
Argument parser for this plugin.
Definition: plugin.hpp:47
Custom exception class used throughout MaCh3.
void PrintProgressBar(const Long64_t Done, const Long64_t All)
KS: Simply print progress bar.
Definition: Monitor.cpp:229
void MaCh3Welcome()
KS: Prints welcome message with MaCh3 logo.
Definition: Monitor.cpp:13
Main namespace for MaCh3 software.
constexpr static const double _LARGE_LOGL_
Large Likelihood is used it parameter go out of physical boundary, this indicates in MCMC that such s...
Definition: Core.h:80