ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/Jeng/scripts/fitRelIso_Data.C
Revision: 1.1
Committed: Thu Jun 24 02:16:25 2010 UTC (14 years, 10 months ago) by jengbou
Content type: text/plain
Branch: MAIN
Log Message:
Add file

File Contents

# User Rev Content
1 jengbou 1.1 #include <vector>
2     #include <TROOT.h>
3     #include <TChain.h>
4     #include <TFile.h>
5     #include <TTree.h>
6     #include <TH1.h>
7     #include <TH2.h>
8     #include <THStack.h>
9     #include <TStyle.h>
10     #include <TCanvas.h>
11     #include <TMath.h>
12     #include <TMultiGraph.h>
13     #include <TGraphErrors.h>
14     #include <TLegend.h>
15     #include <TPaveStats.h>
16     #include <TLatex.h>
17     #include "Math/GSLIntegrator.h"
18     #include "Math/WrappedTF1.h"
19     #include "map.h"
20     #include <sstream>
21     #include <fstream>
22    
23     using namespace std;
24    
25     double sf_mc = 1.;
26    
27     // Dynamic(true) or static(false) range
28     bool dynamic = true;
29     TString isoname = "New";
30     TString s0 = "fuser";
31     TString fitOpt = "QLM0";
32     bool debug = true;
33     double yMax = 0.;
34     bool DrawOverFlow = true;
35     bool drawtail = false;
36     double wxmin = 1.;
37     double wxmax = 1.;
38     double plot_xMax = 1.4; // max of x axis for output plots; 1.0 for Old reliso
39    
40     map<TString,TCanvas*> cvs; // map of usual histogram
41    
42     double round(double num, int places)
43     {
44     double temp, mult;
45     mult = pow(10.0, places);
46     temp = floor(num * mult + 0.5);
47     temp = temp / mult;
48     return temp;
49     }
50    
51     double stdDev(int data[], int n, double mean)
52     {
53     double dev = 0;
54     double sum2 = 0;
55    
56     for ( int i = 0; i < n; i++ ) {
57     sum2 += pow((data[i] - mean),2);
58     }
59     dev = sqrt(sum2/(n - 1));
60     return dev;
61     }
62    
63     void cmsPrel(double intLumi){
64     TLatex latex;
65     latex.SetNDC();
66     latex.SetTextSize(0.05);
67    
68     latex.SetTextAlign(31); // align right
69     latex.DrawLatex(0.98,0.945,"#sqrt{s} = 7 TeV");
70     if (intLumi > 0.) {
71     latex.SetTextAlign(31); // align right
72     latex.DrawLatex(0.98,0.68,Form("#int #font[12]{L}dt = %.1fnb^{-1}",intLumi));
73     }
74     latex.SetTextAlign(11); // align left
75     latex.DrawLatex(0.02,0.945,"#font[22]{CMS preliminary 2010}");
76     return;
77     }
78    
79     void fitRelIso_Data()
80     {
81     //New RelIso
82     if (isoname == "New") {
83     s0 = "landau";
84     wxmin = 10.;
85     wxmax = wxmin/3.;
86     // Select fitting function:
87     }
88     //Old RelIso
89     if (isoname == "Old") {
90     s0 = "gaus"; // for old
91     wxmin = 1.;
92     wxmax = 1./3.;
93     DrawOverFlow = false;
94     plot_xMax = 1.;
95     }
96    
97     gROOT->SetStyle("CMS");
98    
99     cout << " =========================== " << endl;
100     cout << " = Start fitting = " << endl;
101     cout << " =========================== " << endl;
102    
103     // Input fileName
104     TString infile1 = "skimmed361p3_20100623/Data_Incl_NewRelIso_wErrors_TandL_3";
105     TString infile2 = "skimmed361p3_20100623/MC_ppMuX_Incl_NewRelIso_wErrors_TandL_3";
106     TString infile3 = "skimmed361p3_20100623/MC_Wjets_Incl_NewRelIso_wErrors_TandL_3";
107     // TString infile1 = "skimmed361p3_20100623/Data_Incl_OldRelIso_wErrors_TandL_3";
108     // TString infile2 = "skimmed361p3_20100623/MC_ppMuX_Incl_OldRelIso_wErrors_TandL_3";
109     // TString infile3 = "skimmed361p3_20100623/MC_Wjets_Incl_OldRelIso_wErrors_TandL_3";
110    
111     // Output file
112     TString outFile = "Plots/20100623/QCD_data_LandauFit_3_";
113     // TString outFile = "Plots/20100623/QCD_data_GaussFit_3_";
114     ofstream outTxtFile;
115     outTxtFile.open(TString(outFile+"Results.txt"));
116    
117     double binwidth[5] = {0.05,0.02,0.01,0.005,0.002};
118     int res_nbkg[5] = {0,0,0,0,0};
119     int res_nsig[5] = {0,0,0,0,0};
120     int nfiles = sizeof(binwidth)/sizeof(double);
121     for(int ibin = 0; ibin < nfiles ; ++ibin) {
122     TString plotFile = outFile;
123     gStyle->SetOptFit(100);
124     cout << " =========================== " << endl;
125     cout << " = Bin width = " << binwidth[ibin] << endl;
126     cout << " =========================== " << endl;
127    
128     map<TString,TFile*> fs;
129     map<TString,TH1*> hs; // map of usual histogram
130     map<TString,TH1*> hso; // map of histo with overflow bin drawn
131     map<TString,std::pair<TString,double> > m_fs;
132     map<TString,THStack*> hst; // map of stacked histogram
133    
134     ostringstream suffix1,suffix2;
135     suffix1 << binwidth[ibin];
136     suffix2 << ibin;
137    
138     // Input files
139     // Data
140     m_fs["Data"] = pair<TString,double>(TString(infile1+"_"+suffix1.str()+".root"),1.);
141     // MC
142     m_fs["QCD"] = pair<TString,double>(TString(infile2+"_"+suffix1.str()+".root"),0.154166);
143     m_fs["WJets"] = pair<TString,double>(TString(infile3+"_"+suffix1.str()+".root"),0.0000369);
144    
145     // User fit function
146     TF1 *fuser = new TF1("fuser","[0]*TMath::Landau(x,[1],[2],0)",0.,2.);
147     fuser->SetParameters(1.,0.5,1.);
148     fuser->SetParLimits(2,0.125,1.);
149     fuser->SetParLimits(3,0.,0.5);
150    
151     // File type
152     TString fileName = m_fs["Data"].first;
153     //cout << fileName << endl;
154    
155     Int_t jbin;
156     Double_t na[3],na1[3];
157     int j = 0;
158     for (std::map<TString,pair<TString,double> >::iterator itFile = m_fs.begin();
159     itFile != m_fs.end(); ++itFile, ++j) {
160     cout << (*itFile).first << "; " << ((*itFile).second).first << endl;
161     fs[(*itFile).first] = TFile::Open(((*itFile).second).first,"READ");
162     hs[(*itFile).first] = (TH1D*) fs[(*itFile).first]->Get("histos/h_RelIso_all");
163     TTree *tree = (TTree*) fs[(*itFile).first]->Get("myTree");
164     tree->SetBranchAddress("na",&na[j]);
165     if (fileName.Contains("TandL"))
166     tree->SetBranchAddress("na1",&na1[j]);
167     if ((*itFile).first == "Data") {
168     tree->SetBranchAddress("jbin",&jbin);
169     sf_mc = hs[(*itFile).first]->Integral();
170     // sf_mc = hs[(*itFile).first]->GetEntries();
171     cout << ">>>>> Total events of data = " << sf_mc << " <<<<<<<<<<<<<<<<" << endl;
172     }
173     else
174     hs[(*itFile).first]->Scale(((*itFile).second).second);
175     tree->GetEntry(0);
176     }
177    
178     // Calculate scale factor for MC; normalized to total number of events from data
179     hs["MCBKG"] = (TH1D*) hs["QCD"]->Clone();
180     hs["MCBKG"]->Add((TH1D*) hs["WJets"]->Clone());
181     double nTotMC = hs["MCBKG"]->Integral();
182     cout << ">>>>> Total weighted MC BKG = " << nTotMC << " <<<<<<<<<<<<<<<<" << endl;
183     //double nTotMC = hs["QCD"]->GetEntries()*m_fs["QCD"].second + hs["WJets"]->GetEntries()*m_fs["WJets"].second;
184     //cout << ">>>>> Total weighted MC BKG = " << nTotMC << " <<<<<<<<<<<<<<<<" << endl;
185     sf_mc /= nTotMC;
186     cout << ">>>>> Scale factor for MC (sf_mc) = " << sf_mc << " <<<<<<<<<<<<<<<<" << endl;
187    
188     hs["QCD"]->Scale(sf_mc);
189     hs["WJets"]->Scale(sf_mc);
190    
191     // define fit region:
192     double ax0 = 0.0;
193     double axf = 0.0;
194     double bx0 = 0.0;
195     double bxf = 0.0;
196     double loosecut = 0.;
197    
198     cout<<">>>>> Use "<<isoname<<" RelIso"<<endl;
199    
200     if ( isoname.Contains("Old") ) {
201     // old
202     loosecut = 10./11.; // 0.9
203     ax0 = 20./21.; // 0.95
204     axf = 1.0 + binwidth[ibin];
205     bx0 = 0.3; // Must be smaller than x at peak
206     bxf = 0.9; // Should not overlap signal region
207     }
208     else if ( isoname.Contains("New") ) {
209     // new
210     ax0 = 0.0;
211     axf = 0.05; // 1./19. = old 0.95
212     loosecut = 0.125; // 1./9. = old 0.9
213     bx0 = 0.2;
214     bxf = 1.2;
215     }
216    
217     int niter = 1;
218     double pass[3] = {0.,0.,0.};
219     double bound[2] = {0.,0.};
220     double ns_tight[3] = {0.,0.,0.};
221     double ns_loose[3] = {0.,0.,0.};
222     double ns2 = 0.;
223    
224     // Fit QCD in background region
225     cout<<">>>>> Fitting with "<<s0<<" function!"<<endl;
226     hs["data_all_clone"] = (TH1D*) hs["Data"]->Clone();
227     hs["data_all_clone"]->SetLineWidth(2);
228     hs["data_all_clone"]->SetMinimum(0);
229     hs["mc_qcd_clone"] = (TH1D*) hs["QCD"]->Clone();
230     hs["mc_wj_clone"] = (TH1D*) hs["WJets"]->Clone();
231    
232     // Get num of bin at peak and bin width
233     Int_t nbxMax = hs["data_all_clone"]->GetXaxis()->FindBin(2.0);
234     hs["data_all_clone"]->GetXaxis()->SetRange(2,hs["data_all_clone"]->GetXaxis()->FindBin(bxf));
235     Int_t nbMax = hs["data_all_clone"]->GetMaximumBin();
236     cout << ">>>>> Bin number at peak = " << nbMax << endl;
237     hs["data_all_clone"]->GetXaxis()->SetRange(1,nbxMax);
238     TAxis *axis0 = hs["data_all_clone"]->GetXaxis();
239     double bwidth = axis0->GetBinWidth(nbMax);
240     cout << ">>>>> Histo bin width = " << bwidth << endl;
241    
242     TString title = "RelIso";
243     if ( jbin == -1 )
244     title += " (inclusive)";
245     else if ( jbin == 4 )
246     title += " (#geq 4 jets)";
247     else if ( jbin == 1 ) {
248     title += " (";
249     title += jbin;
250     title += " jet)";
251     }
252     else if ( jbin < 4 ) {
253     title += " (";
254     title += jbin;
255     title += " jets)";
256     hs["data_all_clone"]->SetTitle(title);
257     }
258     else if ( jbin == 5 ) {
259     hs["data_all_clone"]->SetTitle( isoname+" RelIso distribution (#geq 1 jets (up to 3 jets))");
260     }
261     else {
262     cout<<"Don't mess around!!! jbin should be less than 6!"<<endl;
263     return;
264     }
265    
266     cvs[TString("cv"+suffix2.str())] = new TCanvas(TString("cv"+suffix2.str()),TString("cv"+suffix2.str()),600,600);
267     cvs[TString("cv"+suffix2.str())]->cd();
268    
269     // Data
270     hs["data_all_clone"]->GetXaxis()->SetTitle(title);
271     hs["data_all_clone"]->GetXaxis()->SetLabelFont(42);
272     hs["data_all_clone"]->GetXaxis()->SetLabelSize(0.03);
273     hs["data_all_clone"]->GetXaxis()->SetTitleFont(42);
274     hs["data_all_clone"]->GetXaxis()->SetTitleSize(0.035);
275     hs["data_all_clone"]->GetXaxis()->SetTitleOffset(1.2);
276    
277     hs["data_all_clone"]->GetYaxis()->SetTitle("Number of Events");
278     hs["data_all_clone"]->GetYaxis()->SetLabelFont(42);
279     hs["data_all_clone"]->GetYaxis()->SetLabelSize(0.03);
280     hs["data_all_clone"]->GetYaxis()->SetTitleFont(42);
281     hs["data_all_clone"]->GetYaxis()->SetTitleSize(0.035);
282     hs["data_all_clone"]->GetYaxis()->SetTitleOffset(1.4);
283     hs["data_all_clone"]->GetXaxis()->SetRangeUser(0.,plot_xMax);
284     hs["data_all_clone"]->SetMarkerStyle(20);
285     hs["data_all_clone"]->SetMarkerSize(0.8);
286     hs["data_tmp_clone"] = (TH1D*) hs["data_all_clone"]->Clone(); // for zoomed in plot
287    
288     if (DrawOverFlow) { // store histo with overflow bin drawn
289     int nbins_ = hs["data_all_clone"]->GetXaxis()->FindBin(plot_xMax);
290     for (std::map<TString,TH1*>::iterator itHS = hs.begin();
291     itHS != hs.end(); ++itHS) {
292     hso[(*itHS).first] = (TH1D*) ((*itHS).second)->Clone();
293     hso[(*itHS).first]->SetBins(nbins_,0.,plot_xMax+bwidth);
294     double v_ovf = 0.;
295     for (int i=0; i < ((*itHS).second)->GetNbinsX()+1 ; i++) {
296     if (i < nbins_) {
297     hso[(*itHS).first]->SetBinContent(i+1,hs[(*itHS).first]->GetBinContent(i+1));
298     hso[(*itHS).first]->SetBinError(i+1,hs[(*itHS).first]->GetBinError(i+1));
299     }
300     else {
301     v_ovf += hs[(*itHS).first]->GetBinContent(i+1);
302     }
303     }
304     hso[(*itHS).first]->SetBinContent(nbins_,v_ovf);
305     hso[(*itHS).first]->SetBinError(nbins_,TMath::Sqrt(v_ovf));
306     }
307     }
308    
309     hst[TString("Data"+suffix2.str())] = new THStack(TString("Data"+suffix2.str()),TString("Data"+suffix2.str()+"stacked"));
310     if (DrawOverFlow) {
311     hso["mc_qcd_clone"]->SetStats(0);
312     hso["mc_qcd_clone"]->SetLineWidth(2);
313     hso["mc_qcd_clone"]->SetLineColor(40);
314     hso["mc_qcd_clone"]->SetFillStyle(3018);
315     hso["mc_qcd_clone"]->SetFillColor(38);
316    
317     hso["mc_wj_clone"]->SetStats(0);
318     hso["mc_wj_clone"]->SetLineWidth(2);
319     hso["mc_wj_clone"]->SetLineColor(8);
320     //hso["mc_wj_clone"]->SetFillStyle(3001);
321     hso["mc_wj_clone"]->SetFillColor(3);
322     hst[TString("Data"+suffix2.str())]->Add(hso["mc_qcd_clone"]);
323     hst[TString("Data"+suffix2.str())]->Add(hso["mc_wj_clone"]);
324     }
325     else {
326     hs["mc_qcd_clone"]->SetStats(0);
327     hs["mc_qcd_clone"]->SetLineWidth(2);
328     hs["mc_qcd_clone"]->SetLineColor(40);
329     hs["mc_qcd_clone"]->SetFillStyle(3018);
330     hs["mc_qcd_clone"]->SetFillColor(38);
331    
332     hs["mc_wj_clone"]->SetStats(0);
333     hs["mc_wj_clone"]->SetLineWidth(2);
334     hs["mc_wj_clone"]->SetLineColor(8);
335     //hs["mc_wj_clone"]->SetFillStyle(3001);
336     hs["mc_wj_clone"]->SetFillColor(3);
337    
338     hst[TString("Data"+suffix2.str())]->Add(hs["mc_qcd_clone"]);
339     hst[TString("Data"+suffix2.str())]->Add(hs["mc_wj_clone"]);
340     }
341    
342     // Find good y range first
343     if (isoname == "New") {
344     if ((hs["data_all_clone"]->GetBinContent(1) + hs["data_all_clone"]->GetBinError(1))*1.05 > yMax)
345     yMax = (hs["data_all_clone"]->GetBinContent(1) + hs["data_all_clone"]->GetBinError(1))*1.05;
346     if ((hs["mc_qcd_clone"]->GetBinContent(1)+hs["mc_wj_clone"]->GetBinContent(1))*1.05 > yMax)
347     yMax = (hs["mc_qcd_clone"]->GetBinContent(1)+hs["mc_wj_clone"]->GetBinContent(1))*1.05;
348     }
349     if (isoname == "Old") {
350     if ((hs["data_all_clone"]->GetBinContent(nbMax) + hs["data_all_clone"]->GetBinError(nbMax))*1.05 > yMax)
351     yMax = (hs["data_all_clone"]->GetBinContent(nbMax) + hs["data_all_clone"]->GetBinError(nbMax))*1.05;
352     if ((hs["mc_qcd_clone"]->GetBinContent(nbMax)+hs["mc_wj_clone"]->GetBinContent(nbMax))*1.05 > yMax)
353     yMax = (hs["mc_qcd_clone"]->GetBinContent(nbMax)+hs["mc_wj_clone"]->GetBinContent(nbMax))*1.05;
354     }
355    
356     cout << " ===============> YMax = " << yMax << endl;
357     //hs["data_all_clone"]->GetYaxis()->SetRangeUser(0.,yMax);
358     hs["data_all_clone"]->Draw("e");
359    
360     cout << "\n =========================== " << endl;
361     cout << " = Iteration step: "<< niter << endl;
362     cout << " =========================== " << endl;
363     cout << ">>>>> Start fitting control region: " << bx0 << " to " << bxf << endl;
364    
365     // Very first fit
366     hs["data_all_clone"]->Fit(s0,fitOpt,"",bx0,bxf);
367    
368     // Very first fit function
369     TF1 *f0 = (TF1*) hs["data_all_clone"]->GetFunction(s0)->Clone();
370     Int_t npar = f0->GetNpar();
371     Double_t chi2 = f0->GetChisquare();
372     Int_t ndof = f0->GetNDF();
373     pass[0] = chi2/ndof; // Very first fit norm chi2. Fixed range.
374     cout << ">>> Norm chi2 = " << pass[0] << endl;
375     if (!dynamic)
376     pass[1] = pass[0];
377     else
378     pass[1] = 999.; // require at least 2 iterations
379    
380     cout << " >> Peak at " << f0->GetMaximumX(bx0,bxf) << endl;
381    
382     double * par0 = new double [npar];
383     double * parErr0 = new double [npar];
384    
385     cout << " >> Parameters of initial fit: " << endl;
386     for (Int_t i=0;i<npar;i++) {
387     printf(" >> %s = %g +- %g\n",
388     f0->GetParName(i),
389     f0->GetParameter(i),
390     f0->GetParError(i)
391     );
392     par0[i] = f0->GetParameter(i);
393     parErr0[i] = f0->GetParError(i);
394     }
395     if(dynamic) {
396     bx0 = f0->GetParameter(1) - wxmin*f0->GetParameter(2);
397     bxf = f0->GetParameter(1) + wxmax*f0->GetParameter(2);
398     }
399     if (isoname == "New") {
400     bx0 = ( bx0 <= loosecut ? loosecut : bx0 );
401     bxf = ( bxf >= hs["data_all_clone"]->GetXaxis()->GetXmax() ?
402     hs["data_all_clone"]->GetXaxis()->GetXmax() :
403     ( bxf > bx0 ? bxf :
404     (bx0 + wxmax*f0->GetParameter(2) >= 2. ? 2. : bx0 + wxmax*f0->GetParameter(2) ) ) );
405     }
406     if (isoname == "Old") {
407     bxf = ( bxf > loosecut ? loosecut : bxf );
408     bx0 = ( bx0 < 0. ? 0. : bx0 );
409     }
410     bound[0] = bx0;
411     bound[1] = bxf;
412     if (dynamic) {
413     cout << ">>> Range for next iteration (bx0, bxf) = (" << bx0;
414     cout << ", " << bxf << ")" << endl;
415     }
416    
417     double delta = pass[1]-pass[2];
418    
419     while (dynamic && niter <= 20 && abs(delta) > 0.000001 && ndof >= 4) {
420     if (niter > 1)
421     pass[1] = pass[2];
422     if (delta != 0){
423     niter++;
424     cout << "\n =========================== " << endl;
425     cout << " = Iteration step: "<< niter << endl;
426     cout << " =========================== " << endl;
427     cout << ">>>>> Previous step norm. chi2 = " << pass[1];
428     if (niter == 2)
429     cout << "; pass[0] = " << pass[0];
430    
431     cout << "\n>>> Start fitting new range (bx0, bxf) = (" << bx0
432     << ", " << bxf << ")" << endl;
433    
434     hs["data_all_clone"]->Fit(s0,fitOpt,"",bx0,bxf);
435     TF1 *fi = (TF1*) hs["data_all_clone"]->GetFunction(s0)->Clone();
436     cout << " >> fi->GetChisquare() = " << fi->GetChisquare() << "; fi->GetNDF() = " << fi->GetNDF() << endl;
437     if ( fi->GetNDF() > 0 ) pass[2] = fi->GetChisquare()/fi->GetNDF();
438     else pass[2] = 999.;
439     cout << " >> Current step norm. chi2 = " << pass[2] << endl;
440     delta = pass[1]-pass[2];
441     cout << " >> Delta = " << delta << endl;
442    
443     if (delta > 0 && bx0 >= loosecut && bxf <= hs["data_all_clone"]->GetXaxis()->GetXmax() && bx0 < bxf) {
444     bound[0] = bx0;
445     bound[1] = bxf;
446     printf(" >> Function has %i parameters. Chisquare = %g\n",
447     npar,
448     fi->GetChisquare());
449     for (Int_t i=0;i<npar;i++) {
450     printf(" >> %s = %g +- %g\n",
451     fi->GetParName(i),
452     fi->GetParameter(i),
453     fi->GetParError(i)
454     );
455     par0[i] = fi->GetParameter(i);
456     parErr0[i] = fi->GetParError(i);
457     // cout<<"Par["<<i<<"]="<<par0[i]<<"; Error="<<parErr0[i]<<endl;
458     }
459     bx0 = fi->GetParameter(1) - wxmin*fi->GetParameter(2);
460     bxf = fi->GetParameter(1) + wxmax*fi->GetParameter(2);
461     if (isoname == "New") {
462     bx0 = ( bx0 < loosecut ? loosecut : bx0 );
463     bxf = ( bxf > 2. ? 2. : ( bxf > bx0 ? bxf : 1.1*bx0 ) );
464     }
465     if (isoname == "Old") {
466     bxf = ( bxf > loosecut ? loosecut : bxf );
467     bxf = ( bx0 < 0. ? 0. : bx0 );
468     }
469     cout << ">>> Range for next iteration (bx0, bxf) = (" << bx0;
470     cout << ", " << bxf << ")" << endl;
471     }
472     else if (delta < 0) {
473     cout << ">>> Use previous fit parameters for extrapolation fit" << endl;
474     delta = 0;
475     }
476     else { // delta == 0
477     cout << ">> Fit converges." << endl;
478     cout << ">> Best fitting region = (" << bound[0];
479     cout << ", " << bound[1] << ")" << endl;
480     }
481     if (niter == 2)
482     pass[0]=pass[2]; // First dynamic fit norm. chi2
483     } // delta != 0
484     } // End while
485     if(debug){
486     cout << ">>> First dynamic fit norm. chi2 = " << pass[0] << endl;
487     cout << ">>> Min dynamic norm. chi2 = " << pass[1] << endl;
488     cout << ">>> Last fitting region (bx0, bxf) = (" << bx0 << ", " << bxf << ")"<< endl;
489     cout << ">>> Best fitting region (bx0, bxf) = (" << bound[0] << ", ";
490     cout << bound[1] << ")"<< endl;
491     }
492    
493     // Get number of events within fitted region
494     TAxis *axis = hs["data_all_clone"]->GetXaxis();
495     int bmin = axis->FindBin(bound[0]);
496     int bmax = axis->FindBin(bound[1]);
497     double nfac1 = hs["data_all_clone"]->Integral(bmin,bmax);
498     cout << ">>> Initial Nfac = " << nfac1 << endl;
499     nfac1 -= (hs["data_all_clone"]->GetBinContent(bmin))*(bound[0]-axis->GetBinLowEdge(bmin))/axis->GetBinWidth(bmin);
500     nfac1 -= (hs["data_all_clone"]->GetBinContent(bmax))*(axis->GetBinUpEdge(bmax)-bound[1])/axis->GetBinWidth(bmax);
501     cout << ">>> Final Nfac = " << nfac1 << endl;
502    
503     // ////////////////////////
504     // Histos and extrapolation
505     // ////////////////////////
506    
507     if (DrawOverFlow) {
508     hso["data_all_clone"]->GetYaxis()->SetRangeUser(0.,yMax);
509     hso["data_all_clone"]->Draw("esame");
510     }
511    
512     hst[TString("Data"+suffix2.str())]->Draw("sames hist");
513    
514     TF1 *f1 = (TF1*) f0->Clone();
515     f1->SetRange(bound[0],bound[1]);
516    
517     cout << ">>> Parameters used for " << s0 << " function: " << endl;
518     for (int i=0;i<npar;i++) {
519     cout << " >> Par[" << i << "] = " << par0[i] << "; Error = " << parErr0[i] << endl;
520     f1->SetParameter(i,par0[i]);
521     }
522     f1->SetLineColor(2);
523    
524     // Draw on top of everything
525     gStyle->SetErrorX(0.5);
526     if (DrawOverFlow) {
527     hso["data_all_clone"]->Draw("esame");
528     }
529     else {
530     hs["data_all_clone"]->Draw("esame"); // Draw on top of others
531     }
532     //f1->SetLineWidth(3.5);
533     f1->Draw("same");
534    
535     // Connect fitted and extrapolated region
536     TF1 *fin = (TF1*) f1->Clone();
537     if (isoname == "New") {
538     fin->SetRange(axf,bound[0]);
539     fin->SetLineStyle(2);
540     fin->SetLineColor(9);
541     fin->SetLineWidth(3.5);
542     fin->Draw("same");
543    
544     if (drawtail){
545     TF1 *fine = (TF1*) f1->Clone();
546     fine->SetRange(bound[1],2.0);
547     fine->SetLineStyle(2);
548     fine->SetLineColor(9);
549     fine->SetLineWidth(3.5);
550     fine->Draw("same");
551     }
552     }
553     if (isoname == "Old") {
554     fin->SetRange(bound[1],axf);
555     fin->SetLineStyle(2);
556     fin->SetLineColor(9);
557     fin->SetLineWidth(3.5);
558     fin->Draw("same");
559    
560     if (drawtail){
561     TF1 *fine = (TF1*) f1->Clone();
562     fine->SetRange(0.,bound[0]);
563     fine->SetLineStyle(2);
564     fine->SetLineColor(9);
565     fine->SetLineWidth(3.5);
566     fine->Draw("same");
567     }
568     }
569    
570     TF1 *f2 = (TF1*) f1->Clone();
571     f2->SetRange(ax0,axf);
572     f2->SetLineColor(4);
573     //f2->SetLineWidth(3.5);
574     f2->Draw("same");
575    
576     // ////////////////////////
577     // Extract number of qcd events
578     // ////////////////////////
579     // Method 1: Ratio
580     int np = 100;
581     double *x=new double[np];
582     double *w=new double[np];
583     f2->CalcGaussLegendreSamplingPoints(np,x,w,1e-15);
584    
585     double nfac0 = 0.;
586     if (fileName.Contains("0053") ||
587     fileName.Contains("TandL") ||
588     fileName.Contains("Tight")) {
589     ns_tight[0] = f2->IntegralFast(np,x,w,ax0,axf);
590     nfac0 = f2->Integral(bound[0],bound[1]);
591     cout << " >> Area of signal region = " << ns_tight[0] << endl;
592     cout << " >> Area of control region = " << nfac0 << endl;
593     ns_tight[0]/=nfac0;
594     ns_tight[0]*=nfac1;
595     }
596     else if (fileName.Contains("011") ||
597     fileName.Contains("Loose")) {
598     ns_tight[0] = f2->IntegralFast(np,x,w,ax0,loosecut);
599     nfac0 = f2->Integral(bound[0],bound[1]);
600     ns_tight[0]/=nfac0;
601     ns_tight[0]*=nfac1;
602     }
603    
604     ns_loose[0] = f2->IntegralFast(np,x,w,ax0,loosecut);
605     ns_loose[0]/=(f2->Integral(bound[0],bound[1]));
606     ns_loose[0]*=nfac1;
607    
608     cout << ">>> Tight Ns by usual integral = " << ns_tight[0] << endl;
609     if (fileName.Contains("TandL") || fileName.Contains("011"))
610     cout << ">>> Loose Ns by usual integral = " << ns_loose[0] << endl;
611    
612     delete [] x;
613     delete [] w;
614    
615     // Another way to do integration
616     TF1 *g = (TF1*)f1->Clone();
617     ROOT::Math::GSLIntegrator ig(1.E-8,1.E-8,1000);
618     ROOT::Math::WrappedTF1 wf(*g);
619     ig.SetFunction(wf);
620     if (fileName.Contains("0053") ||
621     fileName.Contains("TandL") ||
622     fileName.Contains("Tight"))
623     ns2 = ig.Integral(ax0,axf);
624     else if (fileName.Contains("011") ||
625     fileName.Contains("Loose"))
626     ns2 = ig.Integral(ax0,loosecut);
627    
628     ns2/=(g->Integral(bound[0],bound[1]));
629     ns2*=nfac1;
630     cout<<">>> Ns by MathMore integral = "<<ns2<<endl;
631    
632     // Method 2: area of trapezoid
633     ns_tight[1] = (TMath::Landau(ax0,par0[1],par0[2],kFALSE)*par0[0] + TMath::Landau(axf,par0[1],par0[2],kFALSE)*par0[0])
634     * fabs(axf-ax0)/(2*bwidth);
635     ns_loose[1] = (TMath::Landau(ax0,par0[1],par0[2],kFALSE)*par0[0] + TMath::Landau(loosecut,par0[1],par0[2],kFALSE)*par0[0])
636     * fabs(loosecut-ax0)/(2*bwidth);
637     // Method 3: area of Landau function
638     ns_tight[2] = f2->Integral(ax0,axf)/bwidth;
639     ns_loose[2] = f2->Integral(ax0,loosecut)/bwidth;
640    
641     // Stats box
642     TPaveStats * tps1;
643     if(!dynamic){
644     cvs[TString("cv"+suffix2.str())]->Update();
645     tps1 = (TPaveStats*) cvs[TString("cv"+suffix2.str())]->GetPrimitive("stats");
646     }
647     else {
648     hs["data_all_clone"]->Fit(s0,fitOpt,"",bound[0],bound[1]);
649     cvs[TString("cv"+suffix2.str())]->Update();
650     tps1 = (TPaveStats*) cvs[TString("cv"+suffix2.str())]->GetPrimitive("stats");
651     }
652    
653     tps1->SetName(TString("Landau fit"+suffix2.str()));
654    
655    
656     TList *list = tps1->GetListOfLines();
657     // TText *tconst = tps1->GetLineWith("Constant");
658     // list->Remove(tconst);
659     TLatex *myt = new TLatex(0,0,"Landau Fit");
660     //TLatex *myt = new TLatex(0,0,"#font[22]{Landau Fit}");
661     list->AddFirst(myt);
662     hs["data_all_clone"]->SetStats(0);
663     gStyle->SetOptFit(0);
664     cvs[TString("cv"+suffix2.str())]->Modified();
665    
666     tps1->SetTextFont(42);
667     tps1->SetTextSize(0.03);
668     tps1->SetFillColor(0);
669     tps1->SetFillStyle(0);
670     tps1->SetBorderSize(0);
671     tps1->SetX1NDC(0.63);
672     tps1->SetX2NDC(0.88);
673     tps1->SetY1NDC(0.74);
674     tps1->SetY2NDC(0.87);
675     cvs[TString("cv"+suffix2.str())]->cd();
676     gPad->Update();
677    
678     //cmsPrel(13);
679     // Label histo
680     TLegend * leg1 = new TLegend(0.18,0.47,0.45,0.87);
681     leg1->SetHeader("#font[22]{CMS preliminary 2010 #sqrt{s} = 7 TeV }");
682     leg1->SetTextSize(0.03);
683     leg1->SetFillColor(0);
684     leg1->SetFillStyle(0);
685     if (DrawOverFlow) {
686     leg1->AddEntry(hso["data_all_clone"],"Data #int#font[12]{L}dt = 13 nb^{-1}","p");
687     leg1->AddEntry(f1,"Fit of all events in control region","l");
688     leg1->AddEntry(f2,"Extrapolation to signal region","l");
689     leg1->AddEntry(hso["mc_qcd_clone"],"QCD","f");
690     leg1->AddEntry(hso["mc_wj_clone"],"W+Jets","f");
691     }
692     else {
693     leg1->AddEntry(hs["data_all_clone"],"Data #int#font[12]{L}dt = 13 nb^{-1}","p");
694     leg1->AddEntry(f1,"Fit of all events in control region","l");
695     leg1->AddEntry(f2,"Extrapolation to signal region","l");
696     leg1->AddEntry(hs["mc_qcd_clone"],"QCD","f");
697     leg1->AddEntry(hs["mc_wj_clone"],"W+Jets","f");
698     }
699     leg1->Draw();
700    
701     plotFile = plotFile + suffix1.str() + ".pdf";
702     //cvs[TString("cv"+suffix2.str())]->Print(plotFile);
703    
704     // Print results
705     cout << "\n";
706     cout << " =========================== " << endl;
707     cout << " = Results = " << endl;
708     cout << " =========================== " << endl;
709    
710     if ( jbin == -1 )
711     cout << ">>>>> Inclusive jet bin " << ":" << endl;
712     else
713     cout << ">>>>> Jet bin " << jbin << ":" << endl;
714     cout << ">>>>> Bin number at peak = " << nbMax << endl;
715     cout << ">>>>> Bin width = " << bwidth << endl;
716     if (dynamic) {
717     cout << ">>>>> First dynamic fit norm. chi2 = " << pass[0] << endl;
718     cout << ">>>>> Min dynamic fit norm. chi2 = " << pass[1] << endl;
719     cout << ">>>>> Last fitting region (bx0, bxf) = (" << bx0 << ", " << bxf << ")"<< endl;
720     cout << ">>>>> Best fitting region (bx0, bxf) = (" << bound[0] << ", " << bound[1] << ")"<< endl;
721     }
722     cout << ">>>>> Calculated Ns (ratio) = " << ns_tight[0] << endl;
723     cout << ">>>>> Calculated Ns (trapezoid) = " << ns_tight[1] << endl;
724     cout << ">>>>> Calculated Ns (integral) = " << ns_tight[2] << endl;
725     cout << ">>>>> Total events expected Na = " << na[0] << endl;
726     cout << ">>>>> Num of Signal events = " << na[0] - round(ns_tight[2],0) << endl;
727    
728     res_nbkg[ibin] = round(ns_tight[2],0);
729     res_nsig[ibin] = na[0]-round(ns_tight[2],0);
730    
731     // if (fileName.Contains("TandL")) {
732     // cout << "====================================" << endl;
733     // cout << ">>>>> Calculated Loose Ns (ratio) = " << ns_loose[0] << endl;
734     // cout << ">>>>> Calculated Loose Ns (trapezoid) = " << ns_loose[1] << endl;
735     // cout << ">>>>> Calculated Loose Ns (integral) = " << ns_loose[2] << endl;
736     // cout << ">>>>> Total expected events Loose Na = " << na1[0] << endl;
737     // cout << ">>>>> Num of Signal events = " << na1[0] - round(ns_loose[2],0) << endl;
738     // }
739    
740     // cout << "Landau(0.05) = " << TMath::Landau(0.05,par0[1],par0[2],kFALSE)*par0[0] << endl;
741     // cout << "Landau(0.1) = " << TMath::Landau(0.1,par0[1],par0[2],kFALSE)*par0[0] << endl;
742     cout << " ===========================\n\n " << endl;
743    
744     outTxtFile << "===========================" << endl;
745     outTxtFile << ">>>>> Bin width = " << bwidth << endl;
746     //outTxtFile << ">>>>> Calculated Ns (ratio) = " << ns_tight[0] << endl;
747     //outTxtFile << ">>>>> Calculated Ns (trapezoid) = " << ns_tight[1] << endl;
748     outTxtFile << ">>>>> Total number of events = " << na[0] << endl;
749     outTxtFile << ">>>>> Calculated bkg (integral) = " << round(ns_tight[2],0) << endl;
750     outTxtFile << ">>>>> Num of Signal events = " << na[0] - round(ns_tight[2],0) << endl;
751     outTxtFile << ">>>>> Total MC QCD expected = " << round(na[1]*((m_fs["QCD"]).second)*sf_mc,0) << endl;
752     outTxtFile << ">>>>> Total MC WJets expected = " << round(na[2]*((m_fs["WJets"]).second)*sf_mc,0) << endl;
753     outTxtFile << "===========================\n\n " << endl;
754    
755    
756     cvs[TString("cv1"+suffix2.str())] = new TCanvas(TString("cv1"+suffix2.str()),TString("cv1"+suffix2.str()),600,600);
757     cvs[TString("cv1"+suffix2.str())]->cd();
758     if (isoname == "New")
759     hs["data_tmp_clone"]->GetXaxis()->SetRangeUser(0.,0.1);
760     if (isoname == "Old")
761     hs["data_tmp_clone"]->GetXaxis()->SetRangeUser(0.9,axf);
762     hs["data_tmp_clone"]->GetYaxis()->SetRangeUser(0.,yMax);
763     hs["data_tmp_clone"]->Draw("e");
764     hst[TString("Data"+suffix2.str())]->Draw("sames hist");
765     hs["data_tmp_clone"]->Draw("esame");
766    
767     TLegend * leg2 = new TLegend(0.38,0.6,0.65,0.85);
768     leg2->SetHeader("#font[22]{CMS preliminary 2010 #sqrt{s} = 7 TeV }");
769     leg2->SetTextSize(0.03);
770     leg2->SetFillColor(0);
771     leg2->SetFillStyle(0);
772     if (DrawOverFlow) {
773     leg2->AddEntry(hso["data_all_clone"],"Data #int#font[12]{L}dt = 13 nb^{-1}","p");
774     leg2->AddEntry(hso["mc_qcd_clone"],"QCD","f");
775     leg2->AddEntry(hso["mc_wj_clone"],"W+Jets","f");
776     }
777     else {
778     leg2->AddEntry(hs["data_all_clone"],"Data #int#font[12]{L}dt = 13 nb^{-1}","p");
779     leg2->AddEntry(hs["mc_qcd_clone"],"QCD","f");
780     leg2->AddEntry(hs["mc_wj_clone"],"W+Jets","f");
781     }
782     leg2->Draw();
783    
784     // TF1 *fb2 = new TF1("fa3","[0]*TMath::Landau(x,[1],[2],0)",ax0,axf);
785     // fb2->SetParameters(par0[0],par0[1],par0[2]);
786     // fb2->SetLineColor(5);
787     // fb2->Draw("same");
788    
789     plotFile = plotFile(0,plotFile.Length()-4) + "_zoomed.pdf";
790     //cvs[TString("cv1"+suffix2.str())]->Print(plotFile);
791    
792     hs.clear();
793     hso.clear();
794     fs.clear();
795     m_fs.clear();
796     }
797     // Calculate errors:
798    
799     float sum[2] = {0.,0.};
800     float average[2] = {0.,0.};
801     float errors = 0.;
802    
803     int nmax = sizeof(res_nbkg)/sizeof(int);
804     for (int ii=0; ii<nmax; ii++) {
805     sum[0] += res_nbkg[ii];
806     sum[1] += res_nsig[ii];
807     }
808     average[0] = round(sum[0] / nmax,0);
809     average[1] = round(sum[1] / nmax,0);
810     errors = stdDev(res_nbkg,nmax,average[0]);
811    
812     cout << "Mean bkg estimated = " << average[0] << endl;
813     cout << "Mean sig estimated = " << average[1] << endl;
814     cout << "Standard deviation = " << errors << endl;
815     cout << "Uncertainties = " << errors/average[0]*100. << "% " << endl;
816    
817     outTxtFile << "Estimated bkg = ";
818     for (int jj=0; jj<nmax;++jj)
819     outTxtFile << res_nbkg[jj] << " ";
820     outTxtFile << endl;
821     outTxtFile << "Mean bkg estimated = " << average[0] << endl;
822     outTxtFile << "Mean sig estimated = " << average[1] << endl;
823     outTxtFile << "Standard deviation = " << errors << endl;
824     outTxtFile << "Uncertainties = " << errors/average[0]*100. << "% " << endl;
825    
826     outTxtFile.close();
827     }