Crombie Tools
old/SkimmingTools/interface/Correction.h
Go to the documentation of this file.
1 #ifndef CROMBIE_CORRECTION_H
2 #define CROMBIE_CORRECTION_H 1
3 
4 #include <map>
5 #include <string>
6 
7 #include "TFile.h"
8 #include "TH2.h"
9 
10 // ROOT won't let us open files, load histograms, and close files peacefully,
11 // but at least we can avoid opening files multiple times
12 namespace {
13 
14  class Files : public std::map<std::string, TFile*> {
15  public:
16  ~Files () {
17  // Fuck ROOT
18  /* for (auto& file : *this) */
19  /* file.second->Close(); */
20  }
21  };
22 
23  Files files {};
24 
25 }
26 
27 /**
28  @ingroup skimminggroup
29  @class Correction
30  @brief A rewrite of the Corrector that allows easy standalone correction application
31 
32  @param H The type of the histogram to read
33 */
34 
35 template<typename H>
36 class Correction {
37  public:
38  /**
39  Reads in one or two histograms from a file.
40 
41  Both histograms must have the same binning.
42  If two histograms are given the corrector applies the first histogram divided by the second.
43  */
44  Correction(std::string filename, const char* histname, const char* denom = 0);
45  ~Correction() { /* delete hist; */ }
46 
47  /// Get the correction value from the histogram
48  double GetCorrection(const double xval, const double yval);
49  double GetCorrection(const double xval);
50 
51  private:
52  H* hist;
53  double get(const int bin);
54  using minmax = std::pair<double, double>;
55  minmax xminmax {};
56  minmax yminmax {};
57 
58  double Filter(const minmax& mm, double val);
59 
60 };
61 
62 template<typename H>
63 Correction<H>::Correction(std::string filename, const char* histname, const char* denom)
64 {
65  if (files.find(filename) == files.end())
66  files[filename] = TFile::Open(filename.data());
67 
68  auto& in = files[filename];
69 
70  hist = static_cast<H*>(in->Get(histname)->Clone());
71  if (denom)
72  hist->Divide(static_cast<H*>(in->Get(denom)));
73 
74  auto* axis = hist->GetXaxis();
75  xminmax.first = axis->GetBinCenter(axis->GetFirst());
76  xminmax.second = axis->GetBinCenter(axis->GetLast());
77 
78  if (dynamic_cast<const TH2*>(hist)) {
79  axis = hist->GetYaxis();
80  yminmax.first = axis->GetBinCenter(axis->GetFirst());
81  yminmax.second = axis->GetBinCenter(axis->GetLast());
82  }
83 }
84 
85 template<typename H>
86 double Correction<H>::GetCorrection(const double xval, const double yval) {
87  return get(hist->FindBin(Filter(xminmax, xval), Filter(yminmax, yval)));
88 };
89 
90 template<typename H>
91 double Correction<H>::GetCorrection(const double xval) {
92  return get(hist->FindBin(Filter(xminmax, xval)));
93 };
94 
95 template<typename H>
96 double Correction<H>::get(const int bin) {
97  return hist->GetBinContent(bin);
98 };
99 
100 template<typename H>
101 double Correction<H>::Filter(const Correction::minmax& mm, double val) {
102  return std::max(mm.first, std::min(mm.second, val));
103 }
104 
105 #endif