CMS 3D CMS Logo

HistoPoissonLikelihoodRatio.h
Go to the documentation of this file.
1 #ifndef PhysicsTools_Utilities_HistoPoissonLikelihoodRatio_h
2 #define PhysicsTools_Utilities_HistoPoissonLikelihoodRatio_h
4 #include <vector>
5 #include <cmath>
6 #include "TH1.h"
7 #include "TMath.h"
8 
9 namespace fit {
10  template <typename T>
12  public:
14  HistoPoissonLikelihoodRatio(T &t, TH1 *histo, double rangeMin, double rangeMax)
15  : t_(&t), rangeMin_(rangeMin), rangeMax_(rangeMax) {
16  nBins_ = histo->GetNbinsX();
17  xMin_ = histo->GetXaxis()->GetXmin();
18  xMax_ = histo->GetXaxis()->GetXmax();
19  deltaX_ = (xMax_ - xMin_) / nBins_;
20  for (size_t i = 0; i < nBins_; ++i) {
21  cont_.push_back(histo->GetBinContent(i + 1));
22  }
23  }
24  double operator()() const {
25  double chi2lambda = 0;
26  for (size_t i = 0; i < nBins_; ++i) {
27  double x = xMin_ + (i + .5) * deltaX_;
28  if ((x > rangeMin_) && (x < rangeMax_)) {
29  double nu = (*t_)(x);
30  if (nu > 0 && cont_[i] > 0)
31  chi2lambda += nu - cont_[i] + cont_[i] * log(cont_[i] / nu);
32  }
33  }
34  chi2lambda *= 2;
35  return chi2lambda;
36  }
37  void setHistos(TH1 *histo) {
38  nBins_ = histo->GetNbinsX();
39  xMin_ = histo->GetXaxis()->GetXmin();
40  xMax_ = histo->GetXaxis()->GetXmax();
41  deltaX_ = (xMax_ - xMin_) / nBins_;
42  }
43  size_t numberOfBins() const {
44  size_t fullBins = 0;
45  for (size_t i = 0; i < nBins_; ++i) {
46  double x = xMin_ + (i + .5) * deltaX_;
47  if ((x > rangeMin_) && (x < rangeMax_))
48  fullBins++;
49  }
50  return fullBins;
51  }
52  T &function() { return *t_; }
53  const T &function() const { return *t_; }
54 
55  private:
56  T *t_;
58  size_t nBins_;
59  double xMin_, xMax_, deltaX_;
60  std::vector<double> cont_;
61  };
62 
63  template <typename T>
65  static void print(double amin, unsigned int numberOfFreeParameters, const HistoPoissonLikelihoodRatio<T> &f) {
66  unsigned int ndof = f.numberOfBins() - numberOfFreeParameters;
67  std::cout << "chi-squared/n.d.o.f. = " << amin << "/" << ndof << " = " << amin / ndof
68  << "; prob: " << TMath::Prob(amin, ndof) << std::endl;
69  }
70  };
71 } // namespace fit
72 
73 #endif
double f[11][100]
float x
HistoPoissonLikelihoodRatio(T &t, TH1 *histo, double rangeMin, double rangeMax)
long double T
static void print(double amin, unsigned int numberOfFreeParameters, const HistoPoissonLikelihoodRatio< T > &f)