CMS 3D CMS Logo

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