Go to the documentation of this file.00001 #ifndef PhysicsTools_Utilities_HistoChiSquare_h
00002 #define PhysicsTools_Utilities_HistoChiSquare_h
00003 #include "PhysicsTools/Utilities/interface/RootMinuitResultPrinter.h"
00004 #include <vector>
00005 #include "TH1.h"
00006 #include "TMath.h"
00007
00008 namespace fit {
00009 template<typename T>
00010 class HistoChiSquare {
00011 public:
00012 HistoChiSquare() { }
00013 HistoChiSquare(T & t, TH1 *histo, double rangeMin, double rangeMax):
00014 t_(&t), rangeMin_(rangeMin), rangeMax_(rangeMax) {
00015 nBins_ = histo->GetNbinsX();
00016 xMin_ = histo->GetXaxis()->GetXmin();
00017 xMax_ = histo->GetXaxis()->GetXmax();
00018 deltaX_ =(xMax_ - xMin_) / nBins_;
00019 for(size_t i = 0; i < nBins_; ++i) {
00020 cont_.push_back( histo->GetBinContent(i+1) );
00021 err_.push_back( histo->GetBinError(i+1) );
00022 }
00023 }
00024 double operator()() const {
00025 double chi2 = 0;
00026 for(size_t i = 0; i < nBins_; ++i) {
00027 double x = xMin_ + ( i +.5 ) * deltaX_;
00028 if((x > rangeMin_)&&(x < rangeMax_)&&(err_[i] > 0)) {
00029 double r = ( cont_[i] - (*t_)(x) )/err_[i];
00030 chi2 += (r * r);
00031 }
00032 }
00033 return chi2;
00034 }
00035 void setHistos(TH1 *histo) {
00036 nBins_ = histo->GetNbinsX();
00037 xMin_ = histo->GetXaxis()->GetXmin();
00038 xMax_ = histo->GetXaxis()->GetXmax();
00039 deltaX_ =(xMax_ - xMin_) / nBins_;
00040 }
00041 size_t numberOfBins() const {
00042 size_t fullBins = 0;
00043 for(size_t i = 0; i < nBins_; ++i) {
00044 double x = xMin_ + ( i +.5 ) * deltaX_;
00045 if((x > rangeMin_)&&(x < rangeMax_)&&(err_[i] > 0))
00046 fullBins++;
00047 }
00048 return fullBins;
00049 }
00050 T & function() { return * t_; }
00051 const T & function() const { return * t_; }
00052 private:
00053 T * t_;
00054 double rangeMin_, rangeMax_;
00055 size_t nBins_;
00056 double xMin_, xMax_, deltaX_;
00057 std::vector<double> cont_;
00058 std::vector<double> err_;
00059 };
00060
00061 template<typename T>
00062 struct RootMinuitResultPrinter<HistoChiSquare<T> > {
00063 static void print(double amin, unsigned int numberOfFreeParameters, const HistoChiSquare<T> & f) {
00064 unsigned int ndof = f.numberOfBins() - numberOfFreeParameters;
00065 std::cout << "chi-squared/n.d.o.f. = " << amin << "/" << ndof << " = " << amin/ndof
00066 << "; prob: " << TMath::Prob(amin, ndof)
00067 << std::endl;
00068 }
00069 };
00070 }
00071
00072 #endif