ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/Development/Plotting/Modules/GeneralToolBox.C
Revision: 1.42
Committed: Fri May 3 09:04:24 2013 UTC (12 years ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.41: +56 -0 lines
Log Message:
Moved functions to produce yields for low mass region to general toolbox

File Contents

# User Rev Content
1 buchmann 1.1 #include <iostream>
2     #include <iomanip>
3     #include <sstream>
4     #include <fstream>
5     #include <vector>
6     #include <stdio.h>
7     #include <stdlib.h>
8     #include <sys/types.h>
9     #include <sys/stat.h>
10     #include <limits>
11     #include <time.h>
12     #include <sys/types.h>
13     #include <dirent.h>
14     #include <cstdlib>
15     #include <sys/types.h>
16     #include <sys/socket.h>
17     #include <netdb.h>
18     #include <stdio.h>
19     #include <string.h>
20 buchmann 1.8 #include <assert.h>
21 buchmann 1.1
22     #include <TFile.h>
23     #include <TTree.h>
24     #include <TCut.h>
25     #include <TLegend.h>
26     #include <TLatex.h>
27     #include <TText.h>
28     #include <TGraph.h>
29     #include <TH1.h>
30     #include <TF1.h>
31     #include <TMath.h>
32     #include <THStack.h>
33     #include <TColor.h>
34     #include <TStyle.h>
35     #include <TCanvas.h>
36     #include <TError.h>
37     #include <TVirtualPad.h>
38     #include <TGraphAsymmErrors.h>
39     #include <TPaveText.h>
40     #include <TRandom.h>
41     #include <TGraphErrors.h>
42 buchmann 1.15 #include <TROOT.h>
43 buchmann 1.24 #include <TPolyLine.h>
44    
45 buchmann 1.1 #ifndef Verbosity
46     #define Verbosity 0
47     #endif
48    
49    
50     /*
51     #ifndef SampleClassLoaded
52     #include "SampleClass.C"
53     #endif
54     */
55     #define GeneralToolBoxLoaded
56    
57     using namespace std;
58    
59     namespace PlottingSetup {
60     string cbafbasedir="";
61     string basedirectory="";
62     vector<float> global_ratio_binning;
63     int publicmode=0;
64     int PaperMode=0; // PaperMode=true will suppress "Preliminary" in DrawPrelim()
65 buchmann 1.6 int Approved=0; // Approved=true will only plot approved plots
66 buchmann 1.10 bool is2012=true;
67 fronga 1.18 bool is53reco=true;
68 buchmann 1.20 bool openBox = true;
69 buchmann 1.28 vector<TH1F*> FakeHistoHeap;
70 buchmann 1.38 bool DrawMetSignalRegionMllLines=false; // whether to draw the lines in mll plots for the MET signal region
71     float ConsideredZWidth=20;
72 buchmann 1.1 }
73    
74     bool dopng=false;
75     bool doC=false;
76     bool doeps=false;
77     bool dopdf=false;
78     bool doroot=false;
79     float generaltoolboxlumi;
80    
81     TLegend* make_legend(string title, float posx1, float posy1, bool drawleg, float posx2, float posy2);
82     TText* write_title(bool, string);
83     TText* write_title_low(string title);
84    
85     TText* write_text(float xpos,float ypos,string title);
86     float computeRatioError(float a, float da, float b, float db);
87     float computeProductError(float a, float da, float b, float db);
88     TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning);
89     void setlumi(float l);
90     void DrawPrelim(float writelumi);
91     void CompleteSave(TCanvas *can, string filename, bool feedback);
92     void CompleteSave(TVirtualPad *can, string filename, bool feedback);
93     void write_warning(string funcname, string text);
94     void write_error(string funcname, string text);
95     void write_info(string funcname, string text);
96     string get_directory();
97     bool Contains(string wholestring, string findme);
98 buchmann 1.38 TH1F* CollapseStack(THStack stack,TString hname);
99 buchmann 1.42 TH1F* CollapseStack(THStack* stack,TString hname);
100 buchmann 1.1 //-------------------------------------------------------------------------------------
101    
102     template<typename U>
103     inline bool isanyinf(U value)
104     {
105     return !(value >= std::numeric_limits<U>::min() && value <=
106     std::numeric_limits<U>::max());
107     }
108    
109     stringstream warningsummary;
110     stringstream infosummary;
111     stringstream errorsummary;
112    
113     template<class A>
114     string any2string(const A& a){
115     ostringstream out;
116     out << a;
117     return out.str();
118     }
119    
120     void do_png(bool s) { dopng=s;}
121     void do_eps(bool s) { doeps=s;}
122     void do_C(bool s) { doC=s;}
123     void do_pdf(bool s) { dopdf=s;}
124     void do_root(bool s){ doroot=s;}
125    
126     string topdir(string child) {
127     string tempdirectory=child;
128     if(tempdirectory.substr(tempdirectory.length()-1,1)=="/") tempdirectory=tempdirectory.substr(0,tempdirectory.length());
129     //we now have a directory without the trailing slash so we can just look for the last non-slash character :-)
130     for(int ichar=tempdirectory.length()-1;ichar>=0;ichar--) {
131     if(tempdirectory.substr(ichar,1)=="/") {
132     return tempdirectory.substr(0,ichar);
133     }
134     }
135 buchmann 1.7 return "TOPDIRFAILURE";
136 buchmann 1.1 }
137    
138     template < typename CHAR_TYPE,
139     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
140    
141     struct basic_teebuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
142     {
143     typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
144     typedef typename TRAITS_TYPE::int_type int_type ;
145    
146     basic_teebuf( streambuf_type* buff_a, streambuf_type* buff_b )
147     : first(buff_a), second(buff_b) {}
148    
149     protected:
150     virtual int_type overflow( int_type c )
151     {
152     const int_type eof = TRAITS_TYPE::eof() ;
153     if( TRAITS_TYPE::eq_int_type( c, eof ) )
154     return TRAITS_TYPE::not_eof(c) ;
155     else
156     {
157     const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(c) ;
158     if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
159     TRAITS_TYPE::eq_int_type( second->sputc(ch), eof ) )
160     return eof ;
161     else return c ;
162     }
163     }
164    
165     virtual int sync()
166     { return !first->pubsync() && !second->pubsync() ? 0 : -1 ; }
167    
168     private:
169     streambuf_type* first ;
170     streambuf_type* second ;
171     };
172    
173     template < typename CHAR_TYPE,
174     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
175     struct basic_teestream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
176     {
177     typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
178     typedef basic_teebuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;
179    
180     basic_teestream( stream_type& first, stream_type& second )
181     : stream_type( &stmbuf), stmbuf( first.rdbuf(), second.rdbuf() ) {}
182    
183     ~basic_teestream() { stmbuf.pubsync() ; }
184    
185     private: streambuff_type stmbuf ;
186     };
187    
188     typedef basic_teebuf<char> teebuf ;
189     typedef basic_teestream<char> teestream ;
190    
191     std::ofstream file("LOG.txt",ios::app) ;
192     std::ofstream texfile("Tex.txt") ;
193     std::ofstream efile("LOGerr.txt",ios::app) ;
194     teestream dout( file, std::cout ) ; // double out
195     teestream eout( efile, std::cout ) ; // double out (errors)
196    
197     template < typename CHAR_TYPE,
198     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
199    
200     struct basic_tripbuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
201     {
202     typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
203     typedef typename TRAITS_TYPE::int_type int_type ;
204    
205     basic_tripbuf( streambuf_type* buff_a, streambuf_type* buff_b, streambuf_type* buff_c )
206     : first(buff_a), second(buff_b), third(buff_c) {}
207    
208     protected:
209     virtual int_type overflow( int_type d )
210     {
211     const int_type eof = TRAITS_TYPE::eof() ;
212     if( TRAITS_TYPE::eq_int_type( d, eof ) )
213     return TRAITS_TYPE::not_eof(d) ;
214     else
215     {
216     const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(d) ;
217     if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
218     TRAITS_TYPE::eq_int_type( second->sputc(ch), eof )||
219     TRAITS_TYPE::eq_int_type( third->sputc(ch), eof ) )
220     return eof ;
221     else return d ;
222     }
223     }
224    
225     virtual int sync()
226     { return !first->pubsync() && !second->pubsync() && !third->pubsync() ? 0 : -1 ; }
227    
228     private:
229     streambuf_type* first ;
230     streambuf_type* second ;
231     streambuf_type* third ;
232     };
233    
234     template < typename CHAR_TYPE,
235     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
236     struct basic_tripstream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
237     {
238     typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
239     typedef basic_tripbuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;
240    
241     basic_tripstream( stream_type& first, stream_type& second, stream_type& third )
242     : stream_type( &stmbuf), stmbuf( first.rdbuf(), second.rdbuf(), third.rdbuf() ) {}
243    
244     ~basic_tripstream() { stmbuf.pubsync() ; }
245    
246     private: streambuff_type stmbuf ;
247     };
248    
249     //typedef basic_tripbuf<char> teebuf ;
250     typedef basic_tripstream<char> tripplestream ;
251    
252     tripplestream tout( file, texfile , std::cout ) ; // tripple out
253    
254     void ensure_directory_exists(string thisdirectory) {
255     struct stat st;
256     if(stat(thisdirectory.c_str(),&st) == 0) {
257     if(Verbosity>0) dout << "Directory " << thisdirectory << " exists!" << endl;
258     }
259     else {
260     if(Verbosity>0) dout << "Directory " << thisdirectory << " does not exist. Need to create it!" << endl;
261     ensure_directory_exists(topdir(thisdirectory));
262     if (mkdir(thisdirectory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
263     if(Verbosity>0) dout << "Created the directory " << thisdirectory << endl;
264     }
265     }
266    
267 buchmann 1.28 void DeleteStack(THStack mcstack) {
268     TH1F* h;
269     TIter nextHist(mcstack.GetHists());
270     while ( h = (TH1F*)nextHist() ) {
271     h->Delete();
272     }
273     delete h;
274     }
275    
276    
277 buchmann 1.15 void DeadEnd(string message) {
278     dout << endl;
279     dout << "\033[1;31m _ _ _ " << endl;
280     dout << "\033[1;31m __| | ___ __ _ __| | ___ _ __ __| | " << endl;
281     dout << "\033[1;31m / _` |/ _ \\/ _` |/ _` | / _ \\ '_ \\ / _` | " << endl;
282     dout << "\033[1;31m| (_| | __/ (_| | (_| | | __/ | | | (_| | " << endl;
283     dout << "\033[1;31m \\__,_|\\___|\\__,_|\\__,_| \\___|_| |_|\\__,_| " << endl;
284     dout << "\033[1;31m " << endl;
285     dout << "" << endl;
286     dout << " A totally fatal error has occurred: " << endl;
287     dout << " " << message << endl;
288     dout << endl;
289     dout << "If you do not know how to deal with this error message please call Customer Support Mumbai (or Zurich...) \033[0m" << endl;
290     dout << " ... aborting now ... " << endl;
291     assert(0);
292     }
293    
294    
295     void SanityChecks() {
296     //this function gets called whenever samples are initialized (see ActiveSamples.C)
297     //whatever is necessary for the code to run should be put here.
298    
299     if(gROOT->GetVersionInt()<53200) {
300     DeadEnd("ROOT version outdated, you are using "+any2string(gROOT->GetVersionInt())+" but the earliest recommended version is 5.32.00");
301     }
302    
303    
304     }
305    
306 buchmann 1.1 void initialize_log() {
307     if(!PlottingSetup::publicmode) {
308     dout << "____________________________________________________________" << endl;
309     dout << endl;
310     dout << " " << endl;
311     dout << " JJJJJJJJJJJZZZZZZZZZZZZZZZZZZZBBBBBBBBBBBBBBBBB " << endl;
312     dout << " J:::::::::JZ:::::::::::::::::ZB::::::::::::::::B " << endl;
313     dout << " J:::::::::JZ:::::::::::::::::ZB::::::BBBBBB:::::B " << endl;
314     dout << " JJ:::::::JJZ:::ZZZZZZZZ:::::Z BB:::::B B:::::B" << endl;
315     dout << " J:::::J ZZZZZ Z:::::Z B::::B B:::::B" << endl;
316     dout << " J:::::J Z:::::Z B::::B B:::::B" << endl;
317     dout << " J:::::J Z:::::Z B::::BBBBBB:::::B " << endl;
318     dout << " J:::::j Z:::::Z B:::::::::::::BB " << endl;
319     dout << " J:::::J Z:::::Z B::::BBBBBB:::::B " << endl;
320     dout << "JJJJJJJ J:::::J Z:::::Z B::::B B:::::B" << endl;
321     dout << "J:::::J J:::::J Z:::::Z B::::B B:::::B" << endl;
322     dout << "J::::::J J::::::J ZZZ:::::Z ZZZZZ B::::B B:::::B" << endl;
323     dout << "J:::::::JJJ:::::::J Z::::::ZZZZZZZZ:::ZBB:::::BBBBBB::::::B" << endl;
324     dout << " JJ:::::::::::::JJ Z:::::::::::::::::ZB:::::::::::::::::B " << endl;
325     dout << " JJ:::::::::JJ Z:::::::::::::::::ZB::::::::::::::::B " << endl;
326     dout << " JJJJJJJJJ ZZZZZZZZZZZZZZZZZZZBBBBBBBBBBBBBBBBB " << endl;
327     dout << " " << endl;
328     dout << endl << endl;
329     dout << "____________________________________________________________" << endl;
330     } else {
331     dout << " PUBLIC MODE " << endl;
332     }
333     time_t rawtime;
334     time ( &rawtime );
335     dout << " Analysis run on " << asctime (localtime ( &rawtime ));
336     dout << "____________________________________________________________" << endl;
337     dout << " Results saved in : " << get_directory() << endl << endl;
338     }
339    
340     void extract_cbaf_dir(string curpath) {
341     int position=curpath.find("/Plotting");
342     if(position<0) position=curpath.find("/DistributedModelCalculations");
343     if(position<0) position=curpath.find("/various_assignments");
344 buchmann 1.4 if(position<0) position=curpath.find("/exchange");
345 buchmann 1.1 PlottingSetup::cbafbasedir=curpath.substr(0,position);
346     }
347    
348     void set_directory(string basedir="") {
349     if(basedir.substr(0,1)=="/") basedir=basedir.substr(1,basedir.length()-1);
350     if(basedir.substr(basedir.length()-1,1)!="/") basedir+="/";
351     char currentpath[1024];
352 buchmann 1.7 getcwd(currentpath,1024);
353 buchmann 1.1 PlottingSetup::basedirectory=(string)currentpath+"/Plots/"+basedir;
354     ensure_directory_exists(PlottingSetup::basedirectory);
355     initialize_log();
356     extract_cbaf_dir(currentpath);
357     }
358    
359     string get_directory() {
360     return PlottingSetup::basedirectory;
361     }
362    
363     string extract_directory(string savethis) {
364     bool foundslash=false;
365     int position=savethis.length();
366     while(!foundslash&&position>0) {
367     position--;
368     if(savethis.substr(position,1)=="/") foundslash=true;
369     }
370     if(position>0) return savethis.substr(0,position+1);
371     else return "";
372     }
373    
374     string extract_root_dir(string name) {
375     int position = -1;
376     if(name.substr(0,1)=="/") name=name.substr(1,name.length()-1);
377 buchmann 1.7 for(int ipos=0;ipos<(int)name.length();ipos++) {
378 buchmann 1.1 if(name.substr(ipos,1)=="/") position=ipos;
379     }
380     if(position==-1) return "";
381     return name.substr(0,position);
382     }
383    
384     string extract_root_filename(string name) {
385     int position = -1;
386     if(name.substr(0,1)=="/") name=name.substr(1,name.length()-1);
387 buchmann 1.7 for(int ipos=0;ipos<(int)name.length();ipos++) {
388 buchmann 1.1 if(name.substr(ipos,1)=="/") position=ipos;
389     }
390     return name.substr(position+1,name.length()-position-1);
391     }
392    
393     void SaveToRoot(TCanvas *can, string name) {
394     can->Update();
395     TFile *fout = new TFile((TString(PlottingSetup::basedirectory)+TString("allplots.root")),"UPDATE");
396     fout->cd();
397     string directory=extract_root_dir(name);
398     string filename=extract_root_filename(name);
399     if(directory!="") {
400     if(fout->GetDirectory(directory.c_str())) {
401     fout->cd(directory.c_str());
402     can->Write(filename.c_str());
403     }else {
404     fout->mkdir(directory.c_str());
405     fout->cd(directory.c_str());
406     can->Write(filename.c_str());
407     }
408     } else {
409     can->Write(filename.c_str());
410     }
411     fout->cd();
412     fout->Close();
413     }
414    
415     void CompleteSave(TCanvas *can, string filename, bool feedback=false, bool redraw=true) {
416     //any change you make here should also be done below in the CompleteSave function for virtual pads
417     Int_t currlevel=gErrorIgnoreLevel;
418     if(!feedback) gErrorIgnoreLevel=1001;
419     if(redraw) can->RedrawAxis();
420     ensure_directory_exists(extract_directory(PlottingSetup::basedirectory+filename));
421     if(dopng) can->SaveAs((PlottingSetup::basedirectory+filename+".png").c_str());
422     if(doeps) can->SaveAs((PlottingSetup::basedirectory+filename+".eps").c_str());
423     if(dopdf) can->SaveAs((PlottingSetup::basedirectory+filename+".pdf").c_str());
424     if(doC) can->SaveAs((PlottingSetup::basedirectory+filename+".C").c_str());
425     if(doroot) SaveToRoot(can,filename);
426     gErrorIgnoreLevel=currlevel;
427     dout << "Saved " << filename << " in all requested formats" << endl;
428     }
429    
430     void CompleteSave(TVirtualPad *can, string filename, bool feedback=false, bool redraw=true) {
431     Int_t currlevel=gErrorIgnoreLevel;
432     if(!feedback) gErrorIgnoreLevel=1001;
433     if(redraw) can->RedrawAxis();
434     ensure_directory_exists(extract_directory(PlottingSetup::basedirectory+filename));
435     if(dopng) can->SaveAs((PlottingSetup::basedirectory+filename+".png").c_str());
436     if(doeps) can->SaveAs((PlottingSetup::basedirectory+filename+".eps").c_str());
437     if(dopdf) can->SaveAs((PlottingSetup::basedirectory+filename+".pdf").c_str());
438     if(doC) can->SaveAs((PlottingSetup::basedirectory+filename+".C").c_str());
439     gErrorIgnoreLevel=currlevel;
440     dout << "Saved " << filename << " in all requested formats" << endl;
441     }
442    
443    
444     void setlumi(float l) {
445 buchmann 1.28 generaltoolboxlumi=l;
446 buchmann 1.1 }
447    
448     int write_first_line(vector<vector<string> > &entries) {
449     if(entries.size()>0) {
450     vector<string> firstline = entries[0];
451     int ncolumns=firstline.size();
452     int ndividers=ncolumns+1;
453     int cellwidth=(int)(((float)(60-ndividers))/(ncolumns));
454     dout << " |";
455     for(int idiv=0;idiv<ncolumns;idiv++) {
456     for(int isig=0;isig<cellwidth;isig++) dout << "-";
457     dout << "|";
458     }
459     dout << endl;
460     return ncolumns;
461     } else {
462     return 0;
463     }
464     }
465    
466     void write_entry(string entry,int width,int iline=0,int ientry=0) {
467     int currwidth=entry.size();
468     while(currwidth<width) {
469     entry=" "+entry;
470 buchmann 1.7 if((int)entry.size()<width) entry=entry+" ";
471 buchmann 1.1 currwidth=entry.size();
472     }
473     bool do_special=false;
474     if(iline==1&&ientry==1) { dout << "\033[1;32m" << entry << "\033[0m|";do_special=true;}//observed
475     if(iline==1&&ientry==2) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
476     if(iline==2&&ientry==1) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
477     if(iline==2&&ientry==2) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
478     if(!do_special) dout << entry << "|";
479     }
480    
481     void make_nice_table(vector<vector <string> > &entries) {
482     int ncolumns=write_first_line(entries);
483     int cellwidth=(int)(((float)(60-(ncolumns+1)))/(ncolumns));
484 buchmann 1.7 for(int iline=0;iline<(int)entries.size();iline++) {
485 buchmann 1.1 vector<string> currline = entries[iline];
486     dout << " |";
487 buchmann 1.7 for(int ientry=0;ientry<(int)currline.size();ientry++) {
488 buchmann 1.1 write_entry(currline[ientry],cellwidth);
489     }
490     dout << endl;
491     if(iline==0) write_first_line(entries);
492     }
493     write_first_line(entries);
494     }
495    
496     void make_nice_jzb_table(vector<vector <string> > &entries) {
497     int ncolumns=write_first_line(entries);
498     int cellwidth=(int)(((float)(60-(ncolumns+1)))/(ncolumns));
499 buchmann 1.7 for(int iline=0;iline<(int)entries.size();iline++) {
500 buchmann 1.1 vector<string> currline = entries[iline];
501     dout << " |";
502 buchmann 1.7 for(int ientry=0;ientry<(int)currline.size();ientry++) {
503 buchmann 1.1 write_entry(currline[ientry],cellwidth,iline,ientry);
504     }
505     dout << endl;
506     if(iline==0) write_first_line(entries);
507     }
508     write_first_line(entries);
509     }
510    
511    
512     void write_warning(string funcname, string text) {
513     string colid="[1;35m";
514     char hostname[1023];
515     gethostname(hostname,1023);
516     if(!Contains((string)hostname,"t3")) colid="[1;33m";
517     eout << endl << endl;
518     eout << "\033"<<colid<<"" << " _ " << endl;
519     eout << "\033"<<colid<<"" << " (_) " << endl;
520     eout << "\033"<<colid<<"" << "__ ____ _ _ __ _ __ _ _ __ __ _ " << endl;
521     eout << "\033"<<colid<<"" << "\\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` |" << endl;
522     eout << "\033"<<colid<<"" << " \\ V V / (_| | | | | | | | | | | (_| |" << endl;
523     eout << "\033"<<colid<<"" << " \\_/\\_/ \\__,_|_| |_| |_|_|_| |_|\\__, |" << endl;
524     eout << "\033"<<colid<<"" << " __/ |" << endl;
525     eout << "\033"<<colid<<"" << " |___/ " << endl;
526     eout << endl;
527     eout << "\033"<<colid<<" [" << funcname << "] " << text << " \033[0m" << endl;
528     eout << endl << endl;
529     warningsummary << "[" << funcname << "] " << text << endl;
530     }
531    
532     void write_error(string funcname, string text) {
533     eout << endl << endl;
534     eout << "\033[1;31m ___ _ __ _ __ ___ _ __ " << endl;
535     eout << "\033[1;31m / _ \\ __| __/ _ \\| '__|" << endl;
536     eout << "\033[1;31m| __/ | | | | (_) | | " << endl;
537     eout << "\033[1;31m \\___|_| |_| \\___/|_| " << endl;
538     eout << endl;
539     eout << "\033[1;31m [" << funcname << "] " << text << " \033[0m" << endl;
540     eout << endl << endl;
541     errorsummary << "[" << funcname << "] " << text << endl;
542     }
543    
544     void write_info(string funcname, string text) {
545     dout << endl << endl;
546     dout << "\033[1;34m _____ __ " << endl;
547     dout << "\033[1;34m |_ _| / _| " << endl;
548     dout << "\033[1;34m | | _ __ | |_ ___ " << endl;
549     dout << "\033[1;34m | | | '_ \\| _/ _ \\ " << endl;
550     dout << "\033[1;34m _| |_| | | | || (_) | " << endl;
551     dout << "\033[1;34m |_____|_| |_|_| \\___/ " << endl;
552     dout << endl;
553     dout << "\033[1;34m [" << funcname << "] " << text << " \033[0m" << endl;
554     dout << endl << endl;
555     infosummary << "[" << funcname << "] " << text << endl;
556     }
557    
558     TText* write_text(float xpos,float ypos,string title)
559     {
560     TLatex* titlebox = new TLatex (xpos,ypos,title.c_str());
561     titlebox->SetNDC(true);
562     titlebox->SetTextFont(42);
563     titlebox->SetTextSize(0.04);
564     titlebox->SetTextAlign(21);
565     return titlebox;
566     }
567    
568     TText* write_title(string title)
569     {
570     TText* titlebox = write_text(0.5,0.945,title);
571     return titlebox;
572     }
573    
574     TText* write_cut_on_canvas(string cut) {
575     // TLatex *normbox = new TLatex(0.96,0.5,cut.c_str());
576     TLatex *normbox = new TLatex(0.96,0.5,"");//currently deactivated
577     normbox->SetNDC(true);
578     normbox->SetTextFont(42);
579     normbox->SetTextSize(0.01);
580     normbox->SetTextAlign(21);
581     normbox->SetTextAngle(270);
582     return normbox;
583     }
584    
585     TText* write_title_low(string title)
586     {
587     TText* titlebox = write_text(0.5,0.94,title);
588     return titlebox;
589     }
590    
591     void DrawPrelim(float writelumi=generaltoolboxlumi,bool isMC=false) {
592     string barn="pb";
593     if(writelumi>=1000)
594     {
595     writelumi/=1000;
596     barn="fb";
597     }
598    
599     stringstream prelimtext;
600     string prel=" Preliminary";
601     if(PlottingSetup::PaperMode) prel="";
602     //prelimtext << "CMS Preliminary 2011 , #sqrt{s}= 7 TeV, L= O(1) fb^{-1}"; //temporary replacement
603 buchmann 1.37 // if(PlottingSetup::is53reco) prel += " 53X";
604 buchmann 1.9 string energy="7 TeV";
605     if(PlottingSetup::is2012) energy="8 TeV";
606 buchmann 1.1 if(writelumi == 0) {
607 buchmann 1.9 if(isMC) prelimtext << "CMS Simulation, #sqrt{s} = " << energy;
608     else prelimtext << "CMS" << prel << ", #sqrt{s} = " << energy;
609 buchmann 1.1 } else {
610 buchmann 1.40 if(isMC) prelimtext << "CMS Simulation, #sqrt{s} = " << energy << ", #scale[0.6]{#int}L dt = " << std::setprecision(3) <<writelumi<<" "<<barn<<"^{-1}";
611     else prelimtext << "CMS" << prel << ", #sqrt{s} = " << energy << ", #scale[0.6]{#int}L dt = " << std::setprecision(3) <<writelumi<<" "<<barn<<"^{-1}";
612 buchmann 1.1 }
613     TPaveText *eventSelectionPaveText = new TPaveText(0.27, 0.93,0.77, 1.0,"blNDC");
614     eventSelectionPaveText->SetFillStyle(4000);
615     eventSelectionPaveText->SetBorderSize(0);
616     eventSelectionPaveText->SetFillColor(kWhite);
617     eventSelectionPaveText->SetTextFont(42);
618 buchmann 1.6 //eventSelectionPaveText->SetTextFont(62); // paper style
619 buchmann 1.1 eventSelectionPaveText->SetTextSize(0.042);
620     eventSelectionPaveText->AddText(prelimtext.str().c_str());
621     eventSelectionPaveText->Draw();
622     }
623    
624     void DrawMCPrelim(float writelumi=generaltoolboxlumi) {
625     DrawPrelim(writelumi,true);
626     }
627    
628     TLegend* make_legend(string title="", float posx1=0.6, float posy1=0.55, bool drawleg=true, float posx2 = 0.89, float posy2 = 0.89 )
629     {
630     gStyle->SetTextFont(42);
631     TLegend *leg = new TLegend(posx1,posy1,posx2,posy2);
632     if(title!="") leg->SetHeader(title.c_str());
633     leg->SetTextFont(42);
634     leg->SetTextSize(0.04);
635     leg->SetFillColor(kWhite);
636     leg->SetBorderSize(0);
637     leg->SetLineColor(kWhite);
638     if(drawleg) DrawPrelim();
639     return leg;
640     }
641    
642     TLegend* make_legend(bool drawleg, string title) {
643     return make_legend(title,0.6,0.55,drawleg);
644     }
645    
646     TGraph* make_nice_ratio(int nbins,float binning[],TH1F* histo)
647     {
648     float errorsquared[nbins];
649     float errors[nbins];
650     float bincontent[nbins];
651     for (int i=0;i<nbins;i++) {
652     errorsquared[i]=0;
653     bincontent[i]=0;
654     errors[i]=0;
655     }
656 buchmann 1.7 // float currlimit=binning[0];
657 buchmann 1.1 int currtoplim=1;
658     for(int ibin=1;ibin<=histo->GetNbinsX();ibin++)
659     {
660     if(binning[currtoplim]<histo->GetBinCenter(ibin)) currtoplim++;
661     dout << "Bin i=" << ibin << " with bin center " << histo->GetBinCenter(ibin) << " contains " << histo->GetBinContent(ibin) << " is within " << binning[currtoplim-1] << " and " << binning[currtoplim] << endl;
662    
663     }
664    
665     return 0;
666     }
667    
668     float statErrorN(float x){return x - 0.5*TMath::ChisquareQuantile(0.3173/2,2*x);}
669     float statErrorP(float x){return 0.5*TMath::ChisquareQuantile(1-0.3173/2,2*(x+1))-x;}
670     float lowLimit(float a, float x){return 0.5*TMath::ChisquareQuantile(a,2*x);}
671     float highLimit(float a,float x){return 0.5*TMath::ChisquareQuantile(1-a,2*(x+1));}
672    
673     float computeRatioError(float a, float da, float b, float db)
674     {
675     float val=0.;
676     float errorSquare = (a/b)*(a/b)*( (da/a)*(da/a) + (db/b)*(db/b));
677     val = TMath::Sqrt(errorSquare);
678     return val;
679    
680     }
681     float computeProductError(float a, float da, float b, float db)
682     {
683     float val=0.;
684     float errorSquare = (a*b)*(a*b)*( (da/a)*(da/a) + (db/b)*(db/b));
685     val = TMath::Sqrt(errorSquare);
686     return val;
687     }
688    
689 buchmann 1.13 TGraphAsymmErrors *SysAndStatRatio(TH1F *h1,TH1F *h2, TH1F *sys, int id, vector<float>binning, bool precise=false) {
690     int absJZBbinsNumber = binning.size()-1;
691     TGraphAsymmErrors* graph = new TGraphAsymmErrors(absJZBbinsNumber);
692     for(int i=0;i<absJZBbinsNumber;i++)
693     {
694     float xCenter=h1->GetBinCenter(i+1);
695     float xWidth=(h1->GetBinWidth(i+1))*0.5;
696     float nominatorError = h1->GetBinError(i+1);
697     float nominator=h1->GetBinContent(i+1);
698     float denominatorError=h2->GetBinError(i+1);
699     float denominator=h2->GetBinContent(i+1);
700     float errorN = 0;
701     float errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
702     float syserr=sys->GetBinContent(i+1);
703     float errorsys=0;
704     if(id==1) // (is data)
705     {
706     if(!precise) errorP = computeRatioError(nominator,statErrorP(nominator),denominator,statErrorP(denominator));
707     else errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
708     errorsys=computeRatioError(nominator,syserr,denominator,0);
709     errorP = TMath::Sqrt(errorsys*errorsys+errorP*errorP);
710     errorN = errorP; // symmetrize using statErrorP
711     } else {
712     errorN = computeRatioError(nominator,nominatorError,denominator,denominatorError);
713     errorsys=computeRatioError(nominator,syserr,denominator,0);
714     errorN = TMath::Sqrt(errorsys*errorsys+errorP*errorP);
715     errorP = errorN; // symmetrize using statErrorP
716     }
717     if(denominator!=0) {
718     graph->SetPoint(i, xCenter, nominator/denominator);
719     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
720     }
721     else {
722     graph->SetPoint(i, xCenter, -999);
723     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
724     }
725     }
726     return graph;
727     }
728    
729    
730 buchmann 1.1 TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning, bool precise=false)
731     {
732     int absJZBbinsNumber = binning.size()-1;
733     TGraphAsymmErrors* graph = new TGraphAsymmErrors(absJZBbinsNumber);
734    
735 buchmann 1.7 for(int i=0;i<absJZBbinsNumber;i++)
736 buchmann 1.1 {
737     float xCenter=h1->GetBinCenter(i+1);
738     float xWidth=(h1->GetBinWidth(i+1))*0.5;
739     float nominatorError = h1->GetBinError(i+1);
740     float nominator=h1->GetBinContent(i+1);
741     float denominatorError=h2->GetBinError(i+1);
742     float denominator=h2->GetBinContent(i+1);
743     float errorN = 0;
744     float errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
745     if(id==1) // (is data)
746     {
747     if(!precise) errorP = computeRatioError(nominator,statErrorP(nominator),denominator,statErrorP(denominator));
748     else errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
749     errorN = errorP; // symmetrize using statErrorP
750     } else {
751     errorN = computeRatioError(nominator,nominatorError,denominator,denominatorError);
752     errorP = errorN;
753     }
754     if(denominator!=0) {
755     graph->SetPoint(i, xCenter, nominator/denominator);
756     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
757     }
758     else {
759     graph->SetPoint(i, xCenter, -999);
760     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
761     }
762     }
763     return graph;
764     }
765    
766     string print_range(float cent, float down, float up) {//note that up&down can be flipped, we don't care, but the central value needs to come 1st!
767     float uperr=0,downerr=0;
768     if(down>up&&down>cent) uperr=down-cent;
769     if(up>down&&up>cent) uperr=up-cent;
770     if(down<cent&&down<up) downerr=cent-down;
771     if(up<cent&&up<down) downerr=cent-up;
772     if(cent>up&&cent>down&&(up!=0&&down!=0)) write_error("print_range"," WATCH OUT: THE CENTRAL VALUE SEEMS TO BE LARGER THAN BOTH UP&DOWN!");
773     if(cent<up&&cent<down&&(up!=0&&down!=0)) write_error("print_range"," WATCH OUT: THE CENTRAL VALUE SEEMS TO BE SMALLER THAN BOTH UP&DOWN!");
774     stringstream result;
775     result << cent << " + " << uperr << " - " << downerr;
776     return result.str();
777     }
778    
779     void bubbleSort ( int arr [ ], int size, int order [ ]) // nice way to sort an array (called arr) which is currently in a random order (indices in (order")
780     {
781     int last = size - 2;
782     int isChanged = 1;
783    
784     while ( last >= 0 && isChanged )
785     {
786     isChanged = 0;
787     for ( int k = 0; k <= last; k++ )
788     if ( arr[k] > arr[k+1] )
789     {
790     swap ( arr[k], arr[k+1] );
791     isChanged = 1;
792     int bkp=order[k];
793     order[k]=order[k+1];
794     order[k+1]=bkp;
795     }
796     last--;
797     }
798     }
799    
800     void swapvec(vector<float> &vec,int j, int k) {
801     float bkp=vec[j];
802     vec[j]=vec[k];
803     vec[k]=bkp;
804     }
805    
806     void bubbleSort ( vector<float> &arr , vector<int> &order) // nice way to sort an array (called arr) which is currently in a random order (indices in (order")
807     {
808     int last = arr.size() - 2;
809     int isChanged = 1;
810    
811     while ( last >= 0 && isChanged )
812     {
813     isChanged = 0;
814     for ( int k = 0; k <= last; k++ )
815     if ( arr[k] > arr[k+1] )
816     {
817     swapvec (arr,k,k+1);
818     isChanged = 1;
819     int bkp=order[k];
820     order[k]=order[k+1];
821     order[k+1]=bkp;
822     }
823     last--;
824     }
825     }
826    
827     int numerichistoname=0;
828     bool givingnumber=false;
829     string GetNumericHistoName() {
830     while(givingnumber) sleep(1);
831     givingnumber=true;
832     stringstream b;
833     b << "h_" << numerichistoname;
834     numerichistoname++;
835     givingnumber=false;
836     return b.str();
837     }
838    
839     //********************** BELOW : CUT INTERPRETATION **************************//
840     void splitupcut(string incut, vector<string> &partvector)
841     {
842     //idea: go thru the string called incut; if a parantheses is opened, then the cut cannot be split up until the parantheses is closed.
843     //ok anyway screw the parantheses.
844     int paranthesis_open=0;
845     int substr_start=0;
846     string currchar="";
847 buchmann 1.7 for (int ichar=0;ichar<(int)incut.length();ichar++)
848 buchmann 1.1 {
849     currchar=incut.substr(ichar,1);
850     // if(currchar=="(") paranthesis_open++;
851     // if(currchar==")") paranthesis_open--;
852     if(currchar=="&"&&incut.substr(ichar+1,1)=="&"&&paranthesis_open==0) {
853     partvector.push_back(incut.substr(substr_start,ichar-substr_start));
854     substr_start=ichar+2;
855     }
856     }
857     partvector.push_back(incut.substr(substr_start,incut.length()-substr_start));
858     if(Verbosity>1) {
859     dout << "[ splitupcut() ] : The cut vector now contains the following elements: "<< endl;
860 buchmann 1.7 for (int ipart=0;ipart<(int)partvector.size();ipart++)
861 buchmann 1.1 {
862     dout << " - " << partvector[ipart] << endl;
863     }
864     }
865     }
866    
867     int atleastvalue(string expression, int &morethanlessthan) // takes in an expression such as ">2" or ">=3" and returns e.g. 3 (in both examples)
868     {
869 buchmann 1.7 // int retval=0;
870 buchmann 1.1 if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
871     // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
872     morethanlessthan=1;
873     return atoi(expression.substr(2,1).c_str());
874     }
875     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
876     // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
877     morethanlessthan=0;
878     return atoi(expression.substr(1,1).c_str());
879     }
880     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
881     // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
882     morethanlessthan=-1;
883     return 1+atoi(expression.substr(1,1).c_str());
884     }
885     if(expression.substr(0,1)==">") {
886     // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
887     morethanlessthan=1;
888     return 1+atoi(expression.substr(2,1).c_str());
889     }
890     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
891     // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
892     morethanlessthan=-1;
893     return 1+atoi(expression.substr(2,1).c_str());
894     }
895 buchmann 1.7
896     return -1234567;
897 buchmann 1.1 }
898    
899     int do_jet_cut(string incut, int *nJets) {
900     string expression=(incut.substr(12,incut.size()-12));
901     dout << "Going to analyze the jet cut : " << expression << " with 0,1 being " << expression.substr(0,1) << " and 1,1 being " << expression.substr(1,1) << endl;
902     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
903     int nJet=atoi(expression.substr(2,1).c_str());
904     for(int i=nJet+1;i<20;i++) nJets[i]=0;
905     dout << "Is of type <=" << endl;
906     return 0;
907     }
908     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
909     int nJet=atoi(expression.substr(2,1).c_str());
910     for(int i=0;i<20&&i!=nJet;i++) nJets[i]=0;
911     dout << "Is of type ==" << endl;
912     return 0;
913     }
914     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
915     int nJet=atoi(expression.substr(2,1).c_str());
916     for(int i=0;i<nJet&&i!=nJet;i++) nJets[i]=0;
917     dout << "Is of type >=" << endl;
918     return 0;
919     }
920     if(expression.substr(0,1)=="<") {
921     int nJet=atoi(expression.substr(1,1).c_str());
922     for(int i=nJet;i<20;i++) nJets[i]=0;
923     dout << "Is of type <" << endl;
924     return 0;
925     }
926     if(expression.substr(0,1)==">") {
927     int nJet=atoi(expression.substr(1,1).c_str());
928     for(int i=0;i<nJet+1&&i!=nJet;i++) nJets[i]=0;
929     dout << "Is of type >" << endl;
930     return 0;
931     }
932 buchmann 1.7 return -12345;
933 buchmann 1.1 }
934    
935     string interpret_cut(string incut, bool &isJetCut, int *permittednJets)
936     {
937     // isJetCut=false;nJets=-1;
938     if(incut=="()") return "";
939     while(incut.substr(0,1)=="(") incut=incut.substr(1,incut.length()-1);
940     while(incut.length()>0&&incut.substr(incut.length()-1,1)==")") incut=incut.substr(0,incut.length()-1);
941     // if(incut.substr(0,1)=="("&&incut.substr(incut.length()-1,1)==")") incut=incut.substr(1,incut.length()-2); //this is to make (cut) to cut.
942    
943     if(Verbosity>0) {
944     dout << "Now interpreting cut " << incut << endl;
945     }
946     /*
947     if(incut=="ch1*ch2<0") return "OS";
948     if(incut=="id1==id2") return "SF";
949     if(incut=="id1!=id2") return "OF";
950     */
951     if(incut=="ch1*ch2<0") return "";
952     if(incut=="(mll>55&&mll<70)||(mll>112&&mll<160)") return "SB";
953     if(incut=="(mll>61&&mll<70)||(mll>112&&mll<190)") return "SB'";
954     if(incut=="id1==id2") return "";
955     if(incut=="id1!=id2") return "";
956     if(incut=="mll>2") return "";
957    
958     if(incut=="mll>0") return ""; // my typical "fake cut"
959    
960     if(incut=="passed_triggers||!is_data") return "Triggers";
961     if(incut=="pfjzb[0]>-998") return "";
962    
963    
964     if(incut=="id1==0") return "ee";
965     if(incut=="id1==1") return "#mu#mu";
966 buchmann 1.20 if(incut=="abs(mll-91)<10") return "|m_{l^{+}l^{-}}-m_{Z}|<10";
967 buchmann 1.1 if(incut=="pfJetGoodID[0]") return "";
968     if(incut=="pfJetGoodID[1]") return "";
969     if((int)incut.find("pfJetGoodNum")>-1) {
970     //do_jet_cut(incut,permittednJets);
971     stringstream result;
972     result << "nJets" << incut.substr(12,incut.size()-12);
973     /* dout << "Dealing with a jet cut: " << incut << endl;
974     stringstream result;
975     result << "nJets" << incut.substr(12,incut.size()-12);
976     isJetCut=true;
977     if(exactjetcut(incut,nJets))
978     // nJets=atleastvalue((incut.substr(12,incut.size()-12)),morethanlessthan);
979     return result.str();*/
980     return result.str();
981     }
982     return incut;
983     }
984    
985     string interpret_nJet_range(int *nJets) {
986     for (int i=0;i<20;i++) dout << i << " : " << nJets[i] << endl;
987     return "hello";
988     }
989    
990     string interpret_cuts(vector<string> &cutparts)
991     {
992     stringstream nicecut;
993     int nJets;
994     bool isJetCut;
995     int finalJetCut=-1;
996     int permittednJets[20];
997     for(int ijet=0;ijet<20;ijet++) permittednJets[ijet]=1;
998 buchmann 1.7 // int morethanlessthan=0;//-1: less than, 0: exactly, 1: more than
999     for(int icut=0;icut<(int)cutparts.size();icut++)
1000 buchmann 1.1 {
1001     if(icut==0) nicecut<<interpret_cut(cutparts[icut],isJetCut,permittednJets);
1002     else {
1003     string nice_this_cut = interpret_cut(cutparts[icut],isJetCut,permittednJets);//blublu
1004     if(nice_this_cut.length()>0&&nicecut.str().length()>0) {
1005     if(!isJetCut) nicecut<<"&&"<<nice_this_cut;
1006     else {
1007     if(nJets>finalJetCut) finalJetCut=nJets;
1008     }
1009     }
1010     if(nice_this_cut.length()>0&&nicecut.str().length()==0) {
1011     if(!isJetCut) {
1012     nicecut<<nice_this_cut;
1013     }
1014     else {
1015     if(nJets>finalJetCut) finalJetCut=nJets;
1016     }
1017     }
1018     }
1019     }
1020     if(finalJetCut>-1) {
1021     if(nicecut.str().length()==0) {
1022     nicecut << "nJets#geq" << finalJetCut;
1023     }
1024     else
1025     {
1026     nicecut << "&&nJets#geq " << finalJetCut;
1027     }
1028     }
1029    
1030     // dout << "The nJet allowed range is given by: " << interpret_nJet_range(permittednJets) << endl;
1031    
1032     return nicecut.str();
1033     }
1034    
1035     string decipher_cut(TCut originalcut,TCut ignorethispart)
1036     {
1037     string incut=(const char*)originalcut;
1038     string ignore=(const char*)ignorethispart;
1039    
1040     if(ignore.length()>0 && incut.find(ignore)!=string::npos) incut=incut.replace(incut.find(ignore),ignore.length(),"");
1041    
1042     vector<string>cutparts;
1043     splitupcut(incut,cutparts);
1044     string write_cut=interpret_cuts(cutparts);
1045     return write_cut;
1046     }
1047    
1048     //********************** ABOVE : CUT INTERPRETATION **************************//
1049    
1050     Double_t GausRandom(Double_t mu, Double_t sigma) {
1051     return gRandom->Gaus(mu,sigma);// real deal
1052     //return mu;//debugging : no smearing.
1053     }
1054    
1055     int functionalhistocounter=0;
1056     TH1F * makehistofromfunction(TF1 *f1,TH1F *model) {
1057     TH1F *histo = (TH1F*)model->Clone();
1058     functionalhistocounter++;
1059     stringstream histoname;
1060     histoname << "histo_based_on_function_" << f1->GetName() << "__"<<functionalhistocounter;
1061     histo->SetTitle(histoname.str().c_str());
1062     histo->SetName(histoname.str().c_str());
1063     int nbins=histo->GetNbinsX();
1064 buchmann 1.7 // float low=histo->GetBinLowEdge(1);
1065     // float hi=histo->GetBinLowEdge(histo->GetNbinsX())+histo->GetBinWidth(histo->GetNbinsX());
1066 buchmann 1.1
1067     for(int i=0;i<=nbins;i++) {
1068     histo->SetBinContent(i,(f1->Integral(histo->GetBinLowEdge(i),histo->GetBinLowEdge(i)+histo->GetBinWidth(i)))/histo->GetBinWidth(i));
1069     histo->SetBinError(i,TMath::Sqrt(histo->GetBinContent(i)));
1070     }
1071    
1072     return histo;
1073     }
1074    
1075     float hintegral(TH1 *histo, float low, float high) {
1076     float sum=0;
1077     for(int i=1;i<histo->GetNbinsX();i++) {
1078     if((histo->GetBinLowEdge(i)>=low)&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))<=high) sum+=histo->GetBinContent(i);
1079     //now on to the less clear cases!
1080     if(histo->GetBinLowEdge(i)<low&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>low) {
1081     //need to consider this case still ... the bin is kind of in range but not sooooo much.
1082     }
1083     if(histo->GetBinLowEdge(i)<high&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>high) {
1084     //need to consider this case still ... the bin is kind of in range but not sooooo much.
1085     }
1086    
1087     }
1088     return sum;
1089     }
1090    
1091     string newjzbexpression(string oldexpression,float shift) {
1092     stringstream ss;
1093     if(shift>0) ss<<"("<<oldexpression<<"+"<<shift<<")";
1094     if(shift<0) ss<<"("<<oldexpression<<shift<<")";
1095     if(shift==0) ss<<oldexpression;
1096     return ss.str();
1097     }
1098    
1099     float Round(float num, unsigned int dig)
1100     {
1101     num *= pow((double)10, (double)dig);
1102     if (num >= 0)
1103     num = floor(num + 0.5);
1104     else
1105     num = ceil(num - 0.5);
1106     num/= pow((double)10, (double)dig);
1107     return num;
1108     }
1109    
1110     float SigDig(double number, float N) {
1111     int exp=0;
1112     while(number<pow(10,N-1)) {
1113     number*=10;
1114     exp+=1;
1115     }
1116     while(number>pow(10,N)) {
1117     number/=10;
1118     exp-=1;
1119     }
1120     number=int(number+0.5);
1121     return number/pow((double)10,(double)exp);
1122     }
1123    
1124     // The two functions below are for distributed processing
1125    
1126     int get_job_number(float ipoint, float Npoints,float Njobs) {
1127     float pointposition=(ipoint/Npoints);
1128     int njob=(int)floor(pointposition*Njobs);
1129     if(njob>=Njobs) njob--;
1130     // cout << "Looking at point " << ipoint << " out of " << Npoints << " which is at position " << pointposition << " corresponding to " << pointposition*Njobs << " --> JOB " << njob << endl;
1131     return njob;
1132     }
1133    
1134    
1135     bool do_this_point(int ipoint, int Npoints, int jobnumber, int Njobs) {
1136     if(get_job_number(ipoint,Npoints,Njobs)==jobnumber) return true;
1137     return false;
1138     }
1139    
1140     Double_t DoIntegral(TH1F *histo, Int_t binx1, Int_t binx2, Int_t biny1, Int_t biny2, Int_t binz1, Int_t binz2, Double_t & error ,
1141     Option_t *option, Bool_t doError)
1142     {
1143     // internal function compute integral and optionally the error between the limits
1144     // specified by the bin number values working for all histograms (1D, 2D and 3D)
1145    
1146     Int_t nbinsx = histo->GetNbinsX();
1147     if (binx1 < 0) binx1 = 0;
1148     if (binx2 > nbinsx+1 || binx2 < binx1) binx2 = nbinsx+1;
1149     if (histo->GetDimension() > 1) {
1150     Int_t nbinsy = histo->GetNbinsY();
1151     if (biny1 < 0) biny1 = 0;
1152     if (biny2 > nbinsy+1 || biny2 < biny1) biny2 = nbinsy+1;
1153     } else {
1154     biny1 = 0; biny2 = 0;
1155     }
1156     if (histo->GetDimension() > 2) {
1157     Int_t nbinsz = histo->GetNbinsZ();
1158     if (binz1 < 0) binz1 = 0;
1159     if (binz2 > nbinsz+1 || binz2 < binz1) binz2 = nbinsz+1;
1160     } else {
1161     binz1 = 0; binz2 = 0;
1162     }
1163    
1164     // - Loop on bins in specified range
1165     TString opt = option;
1166     opt.ToLower();
1167     Bool_t width = kFALSE;
1168     if (opt.Contains("width")) width = kTRUE;
1169    
1170    
1171     Double_t dx = 1.;
1172     Double_t dy = 1.;
1173     Double_t dz = 1.;
1174     Double_t integral = 0;
1175     Double_t igerr2 = 0;
1176     for (Int_t binx = binx1; binx <= binx2; ++binx) {
1177     if (width) dx = histo->GetXaxis()->GetBinWidth(binx);
1178     for (Int_t biny = biny1; biny <= biny2; ++biny) {
1179     if (width) dy = histo->GetYaxis()->GetBinWidth(biny);
1180     for (Int_t binz = binz1; binz <= binz2; ++binz) {
1181     if (width) dz = histo->GetZaxis()->GetBinWidth(binz);
1182     Int_t bin = histo->GetBin(binx, biny, binz);
1183     if (width) integral += histo->GetBinContent(bin)*dx*dy*dz;
1184     else integral += histo->GetBinContent(bin);
1185     if (doError) {
1186     if (width) igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin)*dx*dx*dy*dy*dz*dz;
1187     else igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin);
1188     }
1189     }
1190     }
1191     }
1192    
1193     if (doError) error = TMath::Sqrt(igerr2);
1194     return integral;
1195     }
1196    
1197     Double_t IntegralAndError(TH1F *histo, Int_t binx1, Int_t binx2, Double_t & error, Option_t *option)
1198     {
1199     //Return integral of bin contents in range [binx1,binx2] and its error
1200     // By default the integral is computed as the sum of bin contents in the range.
1201     // if option "width" is specified, the integral is the sum of
1202     // the bin contents multiplied by the bin width in x.
1203     // the error is computed using error propagation from the bin errors assumming that
1204     // all the bins are uncorrelated
1205     return DoIntegral(histo,binx1,binx2,0,-1,0,-1,error,option,kTRUE);
1206     }
1207    
1208     void print_usage() {
1209     cout << "Some distributed model calculations call Create_All_Plots.exec with the argument \"1\" to calculate some basic quantities, such as the peak position in MC and data, observed and predicted, and so on. If you want to test this, you can just run this program with argument 1 yourself :-) " << endl;
1210     }
1211    
1212    
1213     string format_number( int value )
1214     {
1215     if( value == 0 ) return "00";
1216     if( value < 10 ) return "0"+any2string(value);
1217     return any2string(value);
1218     }
1219    
1220     string seconds_to_time(int seconds) {
1221     const static unsigned int SECONDS_IN_AN_HOUR = 3600;
1222     const static unsigned int SECONDS_IN_A_MINUTE = 60;
1223     stringstream answer;
1224     if( seconds > 0 )
1225     {
1226     answer << format_number( (unsigned int)(seconds / SECONDS_IN_AN_HOUR) ) << ":";
1227     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE) ) << ":";
1228     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) % (SECONDS_IN_A_MINUTE)) );
1229     }
1230     else
1231     {
1232     answer << "00:00:00";
1233     }
1234     return answer.str();
1235     }
1236    
1237     bool Contains(string wholestring, string findme) {
1238     if((int)wholestring.find(findme)>-1) return true;
1239     else return false;
1240     }
1241    
1242 buchmann 1.35
1243 buchmann 1.1 //////////////////////////////////////////////////////////////////////////////
1244     //
1245     // http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
1246     // process_mem_usage(double &, double &) - takes two doubles by reference,
1247     // attempts to read the system-dependent data for a process' virtual memory
1248     // size and resident set size, and return the results in KB.
1249     //
1250     // On failure, returns 0.0, 0.0
1251    
1252     /* usage:
1253     double vm2, rss2;
1254     process_mem_usage(vm2, rss2);
1255 buchmann 1.35 cout << "Memory usage: VM: " << vm2 << "; RSS: " << rss2 << endl;
1256 buchmann 1.1 */
1257    
1258     void process_mem_usage(double& vm_usage, double& resident_set)
1259     {
1260     using std::ios_base;
1261     using std::ifstream;
1262     using std::string;
1263    
1264     vm_usage = 0.0;
1265     resident_set = 0.0;
1266    
1267     // 'file' stat seems to give the most reliable results
1268     //
1269     ifstream stat_stream("/proc/self/stat",ios_base::in);
1270    
1271     // dummy vars for leading entries in stat that we don't care about
1272     //
1273     string pid, comm, state, ppid, pgrp, session, tty_nr;
1274     string tpgid, flags, minflt, cminflt, majflt, cmajflt;
1275     string utime, stime, cutime, cstime, priority, nice;
1276     string O, itrealvalue, starttime;
1277    
1278     // the two fields we want
1279     //
1280     unsigned long vsize;
1281     long rss;
1282    
1283     stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
1284     >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
1285     >> utime >> stime >> cutime >> cstime >> priority >> nice
1286     >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
1287    
1288     stat_stream.close();
1289    
1290     long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
1291     vm_usage = vsize / 1024.0;
1292     resident_set = rss * page_size_kb;
1293     }
1294    
1295     TGraphAsymmErrors* produce_ratio_graph(TH1F *baseratio) {
1296     int nbins=baseratio->GetNbinsX();
1297     double x[nbins];
1298     double y[nbins];
1299     double ex[nbins];
1300     double ey[nbins];
1301    
1302     for(int ibin=1;ibin<=nbins;ibin++) {
1303     x[ibin-1]=baseratio->GetBinCenter(ibin);
1304     y[ibin-1]=baseratio->GetBinContent(ibin);
1305     ex[ibin-1]=0.5*baseratio->GetBinWidth(ibin);
1306     ey[ibin-1]=baseratio->GetBinError(ibin);
1307     }
1308    
1309     TGraphAsymmErrors *result = new TGraphAsymmErrors(nbins, x,y,ex,ex,ey,ey);
1310     return result;
1311     }
1312    
1313    
1314 buchmann 1.38 TLatex* WriteSelection(int njets) {
1315 buchmann 1.33 string sel="Loose selection";
1316 buchmann 1.39 if(njets==3) sel="Low E_{T}^{miss} selection";
1317 buchmann 1.33 assert(njets==2||njets==3);
1318 buchmann 1.38 TLatex *sele = new TLatex(0.97,0.135,sel.c_str());
1319 buchmann 1.33 sele->SetNDC(true);
1320     sele->SetTextColor(TColor::GetColor("#848484"));
1321     sele->SetTextFont(42);
1322     sele->SetTextAlign(32);
1323     sele->SetTextSize(0.03);
1324     sele->SetTextAngle(270);
1325     return sele;
1326     }
1327    
1328 buchmann 1.1 Double_t MarcosChi2TestX(const TH1* h1, const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option)
1329     {
1330    
1331     TString opt = option;
1332     opt.ToUpper();
1333    
1334     Double_t prob = h1->Chi2TestX(h2,chi2,ndf,igood,option);
1335    
1336     if(opt.Contains("P")) {
1337     printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1338     }
1339     if(opt.Contains("CHI2/NDF")) {
1340     if (ndf == 0) return 0;
1341     return chi2/ndf;
1342     }
1343     if(opt.Contains("CHI2")) {
1344     return chi2;
1345     }
1346    
1347     return prob;
1348     }
1349    
1350 buchmann 1.32 void Save_With_Ratio(TH1F *nominator, TH1F *denominator, TVirtualPad *orig_canvas, string savemeas, bool do_bpred_ratio=false, bool extendrange=false, string yaxistitle="ratio",TH1F *syshisto=NULL) {
1351 buchmann 1.1 //this function saves the pad being passed as well as a new one including the ratio.
1352 buchmann 1.32
1353 buchmann 1.33 orig_canvas->cd();
1354     orig_canvas->Update();
1355     CompleteSave(orig_canvas,savemeas);
1356     TVirtualPad *canvas = (TVirtualPad*) orig_canvas->Clone("TempCanvas");//otherwise the Ratio_main_canvas will own our pad and destroy it upon deletion
1357 buchmann 1.31
1358 buchmann 1.1 float bottommargin=gStyle->GetPadBottomMargin();
1359     float canvas_height=gStyle->GetCanvasDefH();
1360     float canvas_width=gStyle->GetCanvasDefW();
1361     float ratiospace=0.25;// space the ratio should take up (relative to original pad)
1362    
1363     float ratiobottommargin=0.3;
1364     float ratiotopmargin=0.1;
1365    
1366     float xstretchfactor=((1-ratiospace)*(1-gStyle->GetPadTopMargin()))/((1)*ratiospace);
1367    
1368 buchmann 1.33 TCanvas *Ratio_main_canvas = new TCanvas("Ratio_main_canvas","Ratio_main_canvas",(Int_t)canvas_width,(Int_t)(canvas_height*(1+ratiospace)));
1369 buchmann 1.1 TPad *mainpad = new TPad("mainpad","mainpad",0,1-(1.0/(1+ratiospace)),1,1);//top (main) pad
1370     TPad *coverpad = new TPad("coverpad","coverpad",gStyle->GetPadLeftMargin()-0.008,1-(1.0/(1+ratiospace))-0.04,1,1-(1.0/(1+ratiospace))+0.103);//pad covering up the x scale
1371     TPad *bottompad = new TPad("bottompad", "Ratio Pad",0,0,1,(1-(1-bottommargin)/(1+ratiospace))-0.015); //bottom pad
1372    
1373 buchmann 1.33 Ratio_main_canvas->Range(0,0,1,1);
1374     Ratio_main_canvas->SetBorderSize(0);
1375     Ratio_main_canvas->SetFrameFillColor(0);
1376 buchmann 1.1 mainpad->Draw();
1377     mainpad->cd();
1378     mainpad->Range(0,0,1,1);
1379     mainpad->SetFillColor(kWhite);
1380     mainpad->SetBorderSize(0);
1381     mainpad->SetFrameFillColor(0);
1382     canvas->Range(0,0,1,1);
1383     canvas->Draw("same");
1384     mainpad->Modified();
1385 buchmann 1.33 Ratio_main_canvas->cd();
1386 buchmann 1.1 coverpad->Draw();
1387     coverpad->cd();
1388     coverpad->Range(0,0,1,1);
1389     coverpad->SetFillColor(kWhite);
1390     coverpad->SetBorderSize(0);
1391     coverpad->SetFrameFillColor(0);
1392     coverpad->Modified();
1393 buchmann 1.33 Ratio_main_canvas->cd();
1394 buchmann 1.1 bottompad->SetTopMargin(ratiotopmargin);
1395     bottompad->SetBottomMargin(ratiobottommargin);
1396     bottompad->Draw();
1397     bottompad->cd();
1398     bottompad->Range(0,0,1,1);
1399     bottompad->SetFillColor(kWhite);
1400     TH1F *ratio = (TH1F*)nominator->Clone(GetNumericHistoName().c_str());
1401     ratio->Divide(denominator);
1402     TGraphAsymmErrors *eratio;
1403 buchmann 1.14 TH1F *SystDown;
1404     TH1F *SystUp;
1405    
1406 buchmann 1.1 if(!do_bpred_ratio) eratio = produce_ratio_graph(ratio);
1407     else {
1408     bool using_data=false;
1409     if((int)savemeas.find("Data")>0) using_data=true;
1410     eratio = histRatio(nominator,denominator,using_data,PlottingSetup::global_ratio_binning,false);
1411 buchmann 1.13 if(syshisto!=0) {
1412 buchmann 1.14 SystDown = (TH1F*)syshisto->Clone("SystDown");
1413     SystUp = (TH1F*)syshisto->Clone("SystUp");
1414     for(int i=1;i<=syshisto->GetNbinsX();i++) {
1415     SystDown->SetBinContent(i,1-syshisto->GetBinContent(i));
1416     SystUp->SetBinContent(i,1+syshisto->GetBinContent(i));
1417     }
1418     SystDown->SetLineColor(TColor::GetColor("#006DE1"));
1419     SystUp->SetLineColor(TColor::GetColor("#006DE1"));
1420 buchmann 1.13 }
1421 buchmann 1.1 for(int i=1;i<=ratio->GetNbinsX();i++) {
1422     ratio->SetBinContent(i,0);
1423     ratio->SetBinError(i,0);
1424     }
1425 buchmann 1.13
1426 buchmann 1.1 }
1427 buchmann 1.25
1428     if(syshisto && !do_bpred_ratio) {
1429     SystDown = (TH1F*)syshisto->Clone("SystDown");
1430     SystUp = (TH1F*)syshisto->Clone("SystUp");
1431     for(int i=1;i<=syshisto->GetNbinsX();i++) {
1432     SystDown->SetBinContent(i,1-syshisto->GetBinContent(i));
1433     SystUp->SetBinContent(i,1+syshisto->GetBinContent(i));
1434     }
1435     SystDown->SetLineColor(TColor::GetColor("#006DE1"));
1436     SystUp->SetLineColor(TColor::GetColor("#006DE1"));
1437     }
1438 buchmann 1.1 eratio->SetFillColor(TColor::GetColor("#00ADE1"));
1439     ratio->SetTitle("");
1440 buchmann 1.21 ratio->GetYaxis()->SetRangeUser(0.0,2.0);
1441 buchmann 1.1 if(do_bpred_ratio) ratio->GetYaxis()->SetRangeUser(0.0,2.0);
1442     if(extendrange) ratio->GetYaxis()->SetRangeUser(0.0,4.0);
1443     ratio->GetXaxis()->SetTitle(nominator->GetXaxis()->GetTitle());
1444     ratio->GetXaxis()->CenterTitle();
1445     ratio->GetYaxis()->SetTitle(yaxistitle.c_str());
1446     ratio->GetYaxis()->SetTitleOffset(0.4);
1447     ratio->GetYaxis()->CenterTitle();
1448     ratio->SetStats(0);
1449     ratio->GetXaxis()->SetLabelSize(xstretchfactor*ratio->GetXaxis()->GetLabelSize());
1450     ratio->GetYaxis()->SetLabelSize(xstretchfactor*ratio->GetYaxis()->GetLabelSize());
1451     ratio->GetXaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1452     ratio->GetYaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1453     ratio->GetYaxis()->SetNdivisions(502,false);
1454     ratio->SetFillColor(TColor::GetColor("#58D3F7"));
1455     ratio->SetMarkerSize(0);
1456 buchmann 1.41 ratio->Draw("e20");
1457 buchmann 1.28
1458     TGraphAsymmErrors *ratio_center = (TGraphAsymmErrors*)eratio->Clone("ratio_center");
1459     for(int i=0;i<ratio_center->GetN();i++) {
1460     ratio_center->SetPointError(i,ratio_center->GetErrorXlow(i),ratio_center->GetErrorXhigh(i),0.005,0.005);
1461     }
1462     ratio_center->SetFillColor(TColor::GetColor("#006381"));
1463    
1464 buchmann 1.13 if(syshisto!=0) {
1465     // sysratio->Draw("2");
1466     // eratio->Draw("2,same");
1467 buchmann 1.41 eratio->Draw("20");
1468 buchmann 1.14 SystDown->Draw("histo,same");
1469     SystUp->Draw("histo,same");
1470 buchmann 1.13 } else {
1471 buchmann 1.41 eratio->Draw("20");
1472 buchmann 1.13 }
1473 buchmann 1.41 ratio_center->Draw("20");
1474 buchmann 1.1 ratio->Draw("same,axis");
1475     TLine *oneline = new TLine(ratio->GetXaxis()->GetBinLowEdge(1),1,ratio->GetXaxis()->GetBinLowEdge(ratio->GetNbinsX())+ratio->GetXaxis()->GetBinWidth(ratio->GetNbinsX()),1);
1476     oneline->SetLineStyle(2);
1477     oneline->SetLineColor(kBlue);
1478     oneline->Draw("same");
1479 buchmann 1.38 if(PlottingSetup::DrawMetSignalRegionMllLines) {
1480     cout << "Drawing extra lines in ratio this time around ... " << endl;
1481     float RatioYMax=2.0;
1482     if(extendrange) RatioYMax=4.0;
1483    
1484     TLine *SRline = new TLine(70,0,70,RatioYMax);
1485     TLine *ZLowLine = new TLine(91.2-PlottingSetup::ConsideredZWidth,0,91.2-PlottingSetup::ConsideredZWidth,RatioYMax);
1486     TLine *ZHiLine = new TLine(91.2+PlottingSetup::ConsideredZWidth,0,91.2+PlottingSetup::ConsideredZWidth,RatioYMax);
1487    
1488     SRline->SetLineStyle(2);
1489     ZLowLine->SetLineStyle(2);
1490     ZHiLine->SetLineStyle(2);
1491     SRline->SetLineColor(kGray+2);
1492     ZLowLine->SetLineColor(kGray+2);
1493     ZHiLine->SetLineColor(kGray+2);
1494     SRline->Draw();
1495     ZLowLine->Draw();
1496     ZHiLine->Draw();
1497     }
1498    
1499 buchmann 1.33 Ratio_main_canvas->cd();
1500     Ratio_main_canvas->Modified();
1501     Ratio_main_canvas->cd();
1502     Ratio_main_canvas->SetSelected(Ratio_main_canvas);
1503 buchmann 1.1
1504 buchmann 1.33 CompleteSave(Ratio_main_canvas,savemeas+"_withratio");
1505 buchmann 1.1 bottompad->cd();
1506    
1507     Double_t chi2;
1508     Int_t ndf,igood;
1509 buchmann 1.7 // Double_t res=0.0;
1510 buchmann 1.1 Double_t chi2prob = MarcosChi2TestX(nominator,denominator,chi2,ndf,igood,"UW");
1511    
1512     stringstream Chi2text;
1513     Chi2text << "#chi^{2} / ndf: " << chi2 << " / " << ndf;
1514     stringstream Chi2probtext;
1515     Chi2probtext << "#chi^{2} prob: " << chi2prob;
1516     TText* chi2box = write_text(0.02,0.11,Chi2text.str());
1517     chi2box->SetTextSize(0.08);
1518     chi2box->SetTextAlign(11);
1519     chi2box->Draw();
1520     TText* chi2probbox = write_text(0.02,0.04,Chi2probtext.str());
1521     chi2probbox->SetTextSize(0.08);
1522     chi2probbox->SetTextAlign(11);
1523     chi2probbox->Draw();
1524 buchmann 1.11
1525     stringstream CompRatio;
1526     CompRatio << "Ratio: " << nominator->Integral() << " / " << denominator->Integral() << " \n " << nominator->Integral()/denominator->Integral();
1527     TText *CompleteRatio = write_text(0.98,0.04,CompRatio.str());
1528     CompleteRatio->SetTextSize(0.08);
1529     CompleteRatio->SetTextAlign(31);
1530     CompleteRatio->Draw();
1531    
1532 buchmann 1.33 CompleteSave(Ratio_main_canvas,savemeas+"_withratio_and_Chi2");
1533 buchmann 1.1
1534     // float KS = nominator->KolmogorovTest(denominator);
1535     // stringstream KStext;
1536     // Chi2text << "KS = " << KS << endl;
1537     //cout << "Found : " << KStext.str() << endl;
1538    
1539 buchmann 1.31 delete eratio;
1540     delete ratio_center;
1541     delete ratio;
1542 buchmann 1.33 delete Ratio_main_canvas;
1543 buchmann 1.1 }
1544    
1545 buchmann 1.38 void Save_With_Ratio_And_Line(TH1F *nominator, TH1F *denominator, TVirtualPad *orig_canvas, string savemeas, bool do_bpred_ratio=false, bool extendrange=false, string yaxistitle="ratio",TH1F *syshisto=NULL) {
1546     PlottingSetup::ConsideredZWidth=10.0;
1547     PlottingSetup::DrawMetSignalRegionMllLines=true;
1548     Save_With_Ratio(nominator, denominator, orig_canvas, savemeas, do_bpred_ratio, extendrange, yaxistitle,syshisto);
1549     PlottingSetup::DrawMetSignalRegionMllLines=false;
1550     }
1551    
1552     void Save_With_Ratio_And_Line(TH1F *nominator, THStack denominator, TVirtualPad *canvas, string savemeas, bool do_bpred_ratio=false) {
1553     TH1F *denominator_histo = (TH1F*) CollapseStack(denominator,"TemporaryStack");
1554     Save_With_Ratio_And_Line(nominator, denominator_histo, canvas, savemeas, do_bpred_ratio);
1555     delete denominator_histo;
1556     }
1557    
1558     void save_with_ratio_and_sys_band(float ConsideredZWidth, TH1F *nominator, TH1F *denominator, TVirtualPad *orig_canvas, string savemeas, bool do_bpred_ratio=false, bool extendrange=false, string yaxistitle="ratio",TH1F *syshisto=NULL) {
1559 buchmann 1.19 //this function saves the pad being passed as well as a new one including the SysRatio.
1560 buchmann 1.33 orig_canvas->cd();
1561     orig_canvas->Update();
1562     CompleteSave(orig_canvas,savemeas);
1563    
1564     TVirtualPad *canvas = (TVirtualPad*) orig_canvas->Clone("TempCanvas");//otherwise the Ratio_main_canvas will own our pad and destroy it upon deletion
1565 buchmann 1.19
1566     float bottommargin=gStyle->GetPadBottomMargin();
1567     float canvas_height=gStyle->GetCanvasDefH();
1568     float canvas_width=gStyle->GetCanvasDefW();
1569 buchmann 1.25 float ratiospace=0.25;// space the ratio should take up (relative to original pad)
1570    
1571     float ratiobottommargin=0.3;
1572     float ratiotopmargin=0.1;
1573 buchmann 1.19
1574 buchmann 1.25 float xstretchfactor=((1-ratiospace)*(1-gStyle->GetPadTopMargin()))/((1)*ratiospace);
1575    
1576 buchmann 1.33 TCanvas *Ratio_main_canvas = new TCanvas("Ratio_main_canvas","Ratio_main_canvas",(Int_t)canvas_width,(Int_t)(canvas_height*(1+ratiospace)));
1577 buchmann 1.25 TPad *mainpad = new TPad("mainpad","mainpad",0,1-(1.0/(1+ratiospace)),1,1);//top (main) pad
1578     TPad *coverpad = new TPad("coverpad","coverpad",gStyle->GetPadLeftMargin()-0.008,1-(1.0/(1+ratiospace))-0.04,1,1-(1.0/(1+ratiospace))+0.103);//pad covering up the x scale
1579     TPad *bottompad = new TPad("bottompad", "Ratio Pad",0,0,1,(1-(1-bottommargin)/(1+ratiospace))-0.015); //bottom pad
1580 buchmann 1.19
1581 buchmann 1.33 Ratio_main_canvas->Range(0,0,1,1);
1582     Ratio_main_canvas->SetBorderSize(0);
1583     Ratio_main_canvas->SetFrameFillColor(0);
1584 buchmann 1.19
1585 buchmann 1.25 mainpad->Draw();
1586     mainpad->cd();
1587     mainpad->Range(0,0,1,1);
1588     mainpad->SetFillColor(kWhite);
1589     mainpad->SetBorderSize(0);
1590     mainpad->SetFrameFillColor(0);
1591 buchmann 1.19 canvas->Range(0,0,1,1);
1592     canvas->Draw("same");
1593 buchmann 1.25 mainpad->Modified();
1594 buchmann 1.33 Ratio_main_canvas->cd();
1595 buchmann 1.25 coverpad->Draw();
1596     coverpad->cd();
1597     coverpad->Range(0,0,1,1);
1598     coverpad->SetFillColor(kWhite);
1599     coverpad->SetBorderSize(0);
1600     coverpad->SetFrameFillColor(0);
1601     coverpad->Modified();
1602 buchmann 1.33 Ratio_main_canvas->cd();
1603 buchmann 1.25 bottompad->SetTopMargin(ratiotopmargin);
1604     bottompad->SetBottomMargin(ratiobottommargin);
1605     bottompad->Draw();
1606     bottompad->cd();
1607     bottompad->Range(0,0,1,1);
1608     bottompad->SetFillColor(kWhite);
1609     TH1F *ratio = (TH1F*)nominator->Clone(GetNumericHistoName().c_str());
1610     ratio->Divide(denominator);
1611 buchmann 1.19
1612    
1613 buchmann 1.25 TGraphAsymmErrors *eratio;
1614     TGraphAsymmErrors *SysEnvelope = new TGraphAsymmErrors();
1615    
1616     if(syshisto && !do_bpred_ratio) {
1617     for(int i=1;i<=syshisto->GetNbinsX();i++) {
1618 buchmann 1.26 float dx=syshisto->GetBinWidth(i)/2.0;
1619     float dy=syshisto->GetBinContent(i);
1620     if(dy<0.01) dy=0.07;
1621 buchmann 1.25 SysEnvelope->SetPoint(i-1,syshisto->GetBinCenter(i),1.0);
1622 buchmann 1.26 SysEnvelope->SetPointError(i-1,dx,dx,dy,dy);
1623 buchmann 1.25 }
1624     SysEnvelope->SetFillColor(TColor::GetColor("#006DE1"));
1625     }
1626 buchmann 1.19
1627 buchmann 1.25 ratio->SetTitle("");
1628     ratio->GetYaxis()->SetRangeUser(0.0,2.0);
1629     if(do_bpred_ratio) ratio->GetYaxis()->SetRangeUser(0.0,2.0);
1630     if(extendrange) ratio->GetYaxis()->SetRangeUser(0.0,4.0);
1631     ratio->GetXaxis()->SetTitle(nominator->GetXaxis()->GetTitle());
1632     ratio->GetXaxis()->CenterTitle();
1633     ratio->GetYaxis()->SetTitle(yaxistitle.c_str());
1634     ratio->GetYaxis()->SetTitleOffset(0.4);
1635     ratio->GetYaxis()->CenterTitle();
1636     ratio->SetStats(0);
1637     ratio->GetXaxis()->SetLabelSize(xstretchfactor*ratio->GetXaxis()->GetLabelSize());
1638     ratio->GetYaxis()->SetLabelSize(xstretchfactor*ratio->GetYaxis()->GetLabelSize());
1639     ratio->GetXaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1640     ratio->GetYaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1641     ratio->GetYaxis()->SetNdivisions(502,false);
1642     ratio->SetFillColor(TColor::GetColor("#58D3F7"));
1643 buchmann 1.39 ratio->Draw("e0");
1644 buchmann 1.19
1645 buchmann 1.25 if(syshisto!=0) {
1646     SysEnvelope->SetFillColor(TColor::GetColor("#FE9A2E"));
1647 buchmann 1.41 SysEnvelope->Draw("2,0,same");
1648 buchmann 1.39 ratio->Draw("e0,same");
1649 buchmann 1.25 } else {
1650 buchmann 1.39 eratio->Draw("0");
1651 buchmann 1.25 }
1652     ratio->Draw("same,axis");
1653     TLine *oneline = new TLine(ratio->GetXaxis()->GetBinLowEdge(1),1,ratio->GetXaxis()->GetBinLowEdge(ratio->GetNbinsX())+ratio->GetXaxis()->GetBinWidth(ratio->GetNbinsX()),1);
1654 buchmann 1.19 oneline->SetLineStyle(2);
1655     oneline->SetLineColor(kBlue);
1656     oneline->Draw("same");
1657 buchmann 1.38
1658    
1659    
1660     if(ConsideredZWidth>0.1) {
1661     cout << "Drawing extra lines in ratio this time around ... " << endl;
1662     float RatioYMax=2.0;
1663     if(extendrange) RatioYMax=4.0;
1664    
1665     TLine *SRline = new TLine(70,0,70,RatioYMax);
1666     TLine *ZLowLine = new TLine(91.2-ConsideredZWidth,0,91.2-ConsideredZWidth,RatioYMax);
1667     TLine *ZHiLine = new TLine(91.2+ConsideredZWidth,0,91.2+ConsideredZWidth,RatioYMax);
1668    
1669     SRline->SetLineStyle(2);
1670     ZLowLine->SetLineStyle(2);
1671     ZHiLine->SetLineStyle(2);
1672     SRline->SetLineColor(kGray+2);
1673     ZLowLine->SetLineColor(kGray+2);
1674     ZHiLine->SetLineColor(kGray+2);
1675     SRline->Draw();
1676     ZLowLine->Draw();
1677     ZHiLine->Draw();
1678     }
1679 buchmann 1.19
1680 buchmann 1.33 Ratio_main_canvas->cd();
1681     Ratio_main_canvas->Modified();
1682     Ratio_main_canvas->cd();
1683     Ratio_main_canvas->SetSelected(Ratio_main_canvas);
1684 buchmann 1.25
1685 buchmann 1.33 CompleteSave(Ratio_main_canvas,savemeas+"_withSysRatio");
1686 buchmann 1.25 bottompad->cd();
1687    
1688     Double_t chi2;
1689     Int_t ndf,igood;
1690     Double_t chi2prob = MarcosChi2TestX(nominator,denominator,chi2,ndf,igood,"UW");
1691    
1692     stringstream Chi2text;
1693     Chi2text << "#chi^{2} / ndf: " << chi2 << " / " << ndf;
1694     stringstream Chi2probtext;
1695     Chi2probtext << "#chi^{2} prob: " << chi2prob;
1696     TText* chi2box = write_text(0.02,0.11,Chi2text.str());
1697     chi2box->SetTextSize(0.08);
1698     chi2box->SetTextAlign(11);
1699     chi2box->Draw();
1700     TText* chi2probbox = write_text(0.02,0.04,Chi2probtext.str());
1701     chi2probbox->SetTextSize(0.08);
1702     chi2probbox->SetTextAlign(11);
1703     chi2probbox->Draw();
1704    
1705     stringstream CompRatio;
1706     CompRatio << "Ratio: " << nominator->Integral() << " / " << denominator->Integral() << " \n " << nominator->Integral()/denominator->Integral();
1707     TText *CompleteRatio = write_text(0.98,0.04,CompRatio.str());
1708     CompleteRatio->SetTextSize(0.08);
1709     CompleteRatio->SetTextAlign(31);
1710     CompleteRatio->Draw();
1711    
1712 buchmann 1.33 CompleteSave(Ratio_main_canvas,savemeas+"_withSysRatio_and_Chi2");
1713     delete Ratio_main_canvas;
1714 buchmann 1.31 delete ratio;
1715 buchmann 1.19 }
1716 buchmann 1.1
1717 buchmann 1.31 TH1F* CollapseStack(THStack stack,TString hname="CollapsedStack") {
1718 buchmann 1.1 TH1F *bhist = ((TH1F*)((stack.GetHists())->At(0)));
1719 fronga 1.22 TH1F *basehisto = (TH1F*)bhist->Clone(hname);
1720 buchmann 1.1 TIter next(stack.GetHists());
1721     TH1F *h;
1722     int counter=0;
1723     while ((h=(TH1F*)next())) {
1724     counter++;
1725     if(counter==1) continue;
1726     basehisto->Add(h);
1727     }
1728     return basehisto;
1729     }
1730    
1731 buchmann 1.42 TH1F* CollapseStack(THStack *stack,TString hname="CollapsedStack") {
1732     TH1F *bhist = ((TH1F*)((stack->GetHists())->At(0)));
1733     TH1F *basehisto = (TH1F*)bhist->Clone(hname);
1734     TIter next(stack->GetHists());
1735     TH1F *h;
1736     int counter=0;
1737     while ((h=(TH1F*)next())) {
1738     counter++;
1739     if(counter==1) continue;
1740     basehisto->Add(h);
1741     }
1742     return basehisto;
1743     }
1744    
1745 buchmann 1.32 void Save_With_Ratio(TH1F *nominator, THStack denominator, TVirtualPad *canvas, string savemeas, bool do_bpred_ratio=false) {
1746     TH1F *denominator_histo = (TH1F*) CollapseStack(denominator);
1747     Save_With_Ratio(nominator, denominator_histo, canvas, savemeas, do_bpred_ratio);
1748 buchmann 1.31 delete denominator_histo;
1749 buchmann 1.1 }
1750    
1751     void flag_this_change(string function, int line, int checked=0) {
1752     stringstream peakmodificationwarning;
1753     if(checked==0) peakmodificationwarning << "There's been a change on line " << line << " in function " << function << " that affects the functionality you're using. If you've checked that it works well please change the function call to flag_this_change(..,..,true) so this will only be an info instead of a warning :-) ";
1754     if(checked==1) peakmodificationwarning << "There's been a change on line " << line << " in function " << function << " that affects the functionality you're using. This modification has already been checked. Please produce the corresponding plot manually and then mark this as done (i.e. flag_this_change(..,..,2)";
1755     if(checked==2) peakmodificationwarning << "Xchecked: There's been a change on line " << line << " in function " << function << " that affects the functionality you're using. This modification has been checked and crosschecked.";
1756    
1757    
1758     if(checked==0) write_warning(function,peakmodificationwarning.str());
1759     // if(checked==1) write_info(function,peakmodificationwarning.str());
1760     peakmodificationwarning << " This modification has been checked and the changes have been reproduced. Checks completed.";
1761     if(checked==2) write_info(function,peakmodificationwarning.str());
1762     }
1763    
1764 buchmann 1.8 void write_analysis_type(bool isonpeak, bool dobtag) {
1765 buchmann 1.1 //http://www.network-science.de/ascii/, ogre
1766     if(!PlottingSetup::publicmode) {
1767     if(isonpeak) {
1768 buchmann 1.8 //font: big
1769 buchmann 1.1 dout << "\033[1;34m" << endl;
1770 buchmann 1.8 dout << " _ __________ " << endl;
1771     dout << " | |___ / _ \\ " << endl;
1772     dout << " /\\ ___ | | / /| |_) | " << endl;
1773     dout << " / \\ / _|_ | | / / | _ < " << endl;
1774     dout << " / \\ | (_| |__| |/ /__| |_) | " << endl;
1775     dout << " \\___|\\____//_____|____/ " << endl;
1776 buchmann 1.1 } else {
1777 buchmann 1.8 //font: big
1778 buchmann 1.1 dout << "\033[1;33m" << endl;
1779 buchmann 1.5 dout << " _ _ __________ " << endl;
1780     dout << " (_) | |___ / _ \\ " << endl;
1781     dout << " /\\ _ | | / /| |_) | " << endl;
1782     dout << " /\\/ \\ | |_ | | / / | _ < " << endl;
1783     dout << " / \\ | | |__| |/ /__| |_) | " << endl;
1784     dout << " |_|\\____//_____|____/ " << endl;
1785 buchmann 1.1 }
1786 buchmann 1.8
1787     if(dobtag) {
1788     //font: big
1789     dout << "\033[1;32m \\ / " << endl;
1790     dout << " \\ o ^ o / " << endl;
1791     dout << " \\ ( ) / " << endl;
1792     dout << " ____________(%%%%%%%)____________ _ _ __________ " << endl;
1793     dout << " ( / / )%%%%%%%( \\ \\ ) | | | |___ / _ \\ " << endl;
1794     dout << " (___/___/__/ \\__\\___\\___) | |__ | | / /| |_) | " << endl;
1795     dout << " ( / /(%%%%%%%)\\ \\ ) | '_ \\ _ | | / / | _ < " << endl;
1796     dout << " (__/___/ (%%%%%%%) \\___\\__) | |_) | |__| |/ /__| |_) | " << endl;
1797     dout << " /( )\\ |_.__/ \\____//_____|____/ " << endl;
1798     dout << " / (%%%%%) \\ " << endl;
1799     dout << " (%%%) " << endl;
1800     dout << " ! " << endl;
1801     }
1802     } else {
1803     //we're in public! don't advertise what we're up to :-)
1804     dout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
1805     dout << " Starting the analysis " << endl;
1806 buchmann 1.11 dout << " i:" << !isonpeak << " , b " << dobtag << endl;
1807 buchmann 1.8 dout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
1808 buchmann 1.1 }
1809 buchmann 1.8 dout << "\033[0m" << endl;
1810    
1811 buchmann 1.1 }
1812    
1813    
1814     vector<string> StringSplit(string str, string delim)
1815     {
1816     vector<string> results;
1817    
1818     int cutAt;
1819 buchmann 1.7 while( (cutAt = str.find_first_of(delim)) != (int)str.npos )
1820 buchmann 1.1 {
1821     if(cutAt > 0)
1822     {
1823     results.push_back(str.substr(0,cutAt));
1824     }
1825     str = str.substr(cutAt+1);
1826     }
1827     if(str.length() > 0)
1828     {
1829     results.push_back(str);
1830     }
1831     return results;
1832     }
1833    
1834     void manually_set_jzb_cuts(vector<float> &jzb_cut,string jzbcut_string) {
1835     vector<string> jzbcutvector = StringSplit(jzbcut_string,",");
1836 buchmann 1.7 for(int i=0;i<(int)jzbcutvector.size();i++) {
1837 buchmann 1.1 jzb_cut.push_back(atoi(jzbcutvector[i].c_str()));
1838     dout << "Added a JZB cut manually at " << atoi(jzbcutvector[i].c_str()) << endl;
1839     }
1840     }
1841    
1842     void process_directory(TString directory, vector<string> &files)
1843     {
1844     DIR *dp;
1845     struct dirent *ep;
1846    
1847     dp = opendir (directory);
1848     if (dp != NULL)
1849     {
1850 buchmann 1.7 while ((ep = readdir (dp)))
1851 buchmann 1.1 {
1852     string filename=(string)ep->d_name;
1853 buchmann 1.7 if((int)filename.find(".root")!=-1)
1854 buchmann 1.1 {
1855     files.push_back(string(directory)+filename);
1856     }
1857     }
1858     (void) closedir (dp);
1859     }
1860     else
1861     perror ("Couldn't open the directory");
1862     }
1863    
1864 buchmann 1.14 void ClearHisto(TH1* histo) {
1865 buchmann 1.12 for(int ix=0;ix<=histo->GetNbinsX()+1;ix++) {//also reset over- and underflow
1866     histo->SetBinContent(ix,0);
1867     histo->SetBinContent(ix,0);
1868     }
1869     }
1870    
1871     void AddSquared(TH1F *histo, TH1F *addthis, float weight) {
1872 buchmann 1.14 for(int ix=1;ix<=addthis->GetNbinsX()+1;ix++) {//also include over- and underflow
1873     float bincenter=addthis->GetBinCenter(ix);
1874     int nBinHisto= histo->FindBin(bincenter);
1875     float old_content=histo->GetBinContent(nBinHisto);
1876     histo->SetBinContent(nBinHisto,old_content+((addthis->GetBinContent(ix))*(addthis->GetBinContent(ix))*weight));
1877 buchmann 1.12 }
1878     }
1879    
1880 buchmann 1.14 void SQRT(TH1* histo) {
1881 buchmann 1.12 for(int ix=0;ix<=histo->GetNbinsX()+1;ix++) {//also include over- and underflow
1882     histo->SetBinContent(ix,TMath::Sqrt(histo->GetBinContent(ix)));
1883     }
1884     }
1885    
1886 buchmann 1.1 /*string GetCompleteHostname() {
1887     struct addrinfo hints, *info, *p;
1888     int gai_result;
1889     char hostname[1024];
1890     hostname[1023] = '\0';
1891     gethostname(hostname, 1023);
1892    
1893     string answer="GetCompleteHostname_ERROR";
1894    
1895     memset(&hints, 0, sizeof hints);
1896     hints.ai_family = AF_UNSPEC;
1897     hints.ai_socktype = SOCK_STREAM;
1898     hints.ai_flags = AI_CANONNAME;
1899    
1900     if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
1901     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
1902     }
1903    
1904     for(p = info; p != NULL; p = p->ai_next) {
1905     answer=p->ai_canonname;
1906     printf("hostname: %s\n", p->ai_canonname);
1907     }
1908     return answer;
1909     }*/
1910    
1911     const char* concatenate (const char* a, const char* b) {
1912     stringstream bla;
1913     bla << a << b;
1914     return bla.str().c_str();
1915     }
1916    
1917 buchmann 1.8
1918     string ReplaceCharacter(string originalstring,string replacethis,string replacewiththis)
1919     {
1920     int pos = originalstring.find(replacethis);
1921     while(pos != -1) {
1922     originalstring.replace(pos, replacewiththis.length(), replacewiththis);
1923     pos = originalstring.find(replacethis);
1924     }
1925     return originalstring;
1926     }
1927    
1928     string removefunnystring(string name) {
1929     name=ReplaceCharacter(name,"[","_");
1930     name=ReplaceCharacter(name,"]","_");
1931     name=ReplaceCharacter(name,"{","_");
1932     name=ReplaceCharacter(name,"}","_");
1933 buchmann 1.28 name=ReplaceCharacter(name,"(","_");
1934     name=ReplaceCharacter(name,")","_");
1935     name=ReplaceCharacter(name," ","_");
1936 buchmann 1.8 name=ReplaceCharacter(name,".","_");
1937     name=ReplaceCharacter(name,",","_");
1938     name=ReplaceCharacter(name,";","_");
1939     name=ReplaceCharacter(name,":","_");
1940     name=ReplaceCharacter(name,"'","_");
1941     name=ReplaceCharacter(name,"$","_");
1942     name=ReplaceCharacter(name,"@","_");
1943     name=ReplaceCharacter(name,"#","_");
1944     name=ReplaceCharacter(name,"+","_");
1945     name=ReplaceCharacter(name,"-","_");
1946     name=ReplaceCharacter(name,"/","_");
1947     return name;
1948     }
1949    
1950 buchmann 1.24 TPolyLine* GetFitUncertaintyShape(TF1 *fit, float low, float high,float x0,float x1) {
1951 buchmann 1.23 int nPoints=1000;
1952     double x[nPoints+1];
1953     double y[nPoints];
1954    
1955     float par1=fit->GetParameter(0);
1956     float dpar1=fit->GetParError(0);
1957     float par2=fit->GetParameter(1);
1958     float dpar2=fit->GetParError(1);
1959    
1960     float step=(x1-x0)/(nPoints/2.0 -1);
1961     for(int i=0;i<nPoints/2.0;i++) {
1962     x[i]=x0+i*step;
1963     y[i]=(par1+x[i]*par2) - sqrt(dpar1*dpar1+dpar2*dpar2*x[i]*x[i]);
1964     x[nPoints-1-i]=x[i];
1965     y[nPoints-1-i]=(par1+x[i]*par2) + sqrt(dpar1*dpar1+dpar2*dpar2*x[i]*x[i]);
1966     if(y[i]<low) y[i]=low;
1967     if(y[i]>high) y[i]=high;
1968     if(y[nPoints-1-i]<low) y[nPoints-1-i]=low;
1969     if(y[nPoints-1-i]>high) y[nPoints-1-i]=high;
1970     }
1971    
1972     x[nPoints]=x[0];
1973     y[nPoints]=y[0];
1974    
1975     TPolyLine *l = new TPolyLine(nPoints+1,x,y);
1976 buchmann 1.36 l->SetFillColor(TColor::GetColor("#A2A2FA"));
1977     l->SetLineColor(TColor::GetColor("#A2A2FA"));
1978 buchmann 1.24 l->SetLineWidth(1);
1979 buchmann 1.23 return l;
1980 buchmann 1.24 }
1981    
1982 buchmann 1.27 //code for ReplaceAll copied from
1983     //http://stackoverflow.com/questions/5343190/c-how-do-i-replace-all-instances-of-of-a-string-with-another-string
1984     string ReplaceAll(string str, string from, string to) {
1985     size_t start_pos = 0;
1986     while((start_pos = str.find(from, start_pos)) != std::string::npos) {
1987     str.replace(start_pos, from.length(), to);
1988     start_pos += to.length(); // ...
1989     }
1990     return str;
1991     }
1992 buchmann 1.24
1993     TPolyLine* GetFitUncertaintyShape(TH1 *histo, string fitname, float low, float high) {
1994     TF1 *fit = (TF1*)histo->GetFunction(fitname.c_str());
1995     if(!fit) {
1996     cout << "CANNOT PRODUCE FIT UNCERTAINTY AS THERE IS NO FIT CALLED " << fitname << " IN " << histo->GetName() << endl;
1997     return NULL;
1998     }
1999     float x0=histo->GetBinLowEdge(1);
2000     float x1=histo->GetBinLowEdge(histo->GetNbinsX())+histo->GetBinWidth(histo->GetNbinsX());
2001     return GetFitUncertaintyShape(fit, low, high,x0,x1);
2002     }
2003    
2004     TPolyLine* GetFitUncertaintyShape(TGraphErrors *gr, string fitname, float low, float high, float minx=-999, float maxx=-999) {
2005     TF1 *fit = (TF1*)gr->GetFunction(fitname.c_str());
2006     if(!fit) {
2007     cout << "CANNOT PRODUCE FIT UNCERTAINTY AS THERE IS NO FIT CALLED " << fitname << " IN " << gr->GetName() << endl;
2008     return NULL;
2009     }
2010     double x,y;
2011     gr->GetPoint(0,x,y);
2012     float min=x;
2013     gr->GetPoint(gr->GetN()-1,x,y);
2014     float max=x;
2015     if(minx>-999 && maxx>-999 && minx<maxx) {
2016     max=maxx;
2017     min=minx;
2018     }
2019     return GetFitUncertaintyShape(fit, low, high,min,max);
2020 buchmann 1.23 }
2021    
2022 buchmann 1.1 stringstream all_bugs;
2023    
2024     void bug_tracker(string function, int line, string description) {
2025     cout << "\033[1;31m .-. " << endl;
2026     cout << " o \\ .-. " << endl;
2027     cout << " .----.' \\ " << endl;
2028     cout << " .'o) / `. o " << endl;
2029     cout << " / | " << endl;
2030     cout << " \\_) /-. " << endl;
2031     cout << " '_.` \\ \\ " << endl;
2032     cout << " `. | \\ " << endl;
2033     cout << " | \\ | " << endl;
2034     cout << " .--/`-. / / " << endl;
2035     cout << " .'.-/`-. `. .\\| " << endl;
2036     cout << " /.' /`._ `- '-. " << endl;
2037     cout << " ____(|__/`-..`- '-._ \\ " << endl;
2038     cout << " |`------.'-._ ` ||\\ \\ " << endl;
2039     cout << " || # /-. ` / || \\| " << endl;
2040     cout << " || #/ `--' / /_::_|)__ " << endl;
2041     cout << " `|____|-._.-` / ||`--------` " << endl;
2042     cout << " \\-.___.` | / || # | " << endl;
2043     cout << " \\ | | || # # | " << endl;
2044     cout << " /`.___.'\\ |.`|________| " << endl;
2045     cout << " | /`.__.'|'.` " << endl;
2046     cout << " __/ \\ __/ \\ " << endl;
2047     cout << " /__.-.) /__.-.) LGB " << endl;
2048     cout << "" << endl;
2049     // bug ascii from : http://www.chris.com/ASCII/index.php?art=animals/insects/other
2050     cout << "There is a bug in " << function << " on line " << line << endl;
2051     cout << "The bug description is : " << description << endl;
2052     all_bugs << "There is a bug in " << function << " on line " << line << endl;
2053     all_bugs << "The bug description is : " << description << " \033[0m" << endl;
2054     }
2055    
2056     //TODO: Write a bug summary at the end.
2057    
2058 buchmann 1.2 float pSTAR(float mglu, float mlsp, float mchi2) {
2059 buchmann 1.20 float mz=91.0;
2060 buchmann 1.2 float res=((mchi2*mchi2)-(mlsp+mz)*(mlsp+mz));
2061     res*=((mchi2*mchi2)-(mlsp-mz)*(mlsp-mz));
2062     res=TMath::Sqrt(res)/(2*mchi2);
2063     return res;
2064     }
2065 buchmann 1.3
2066     float generalizedpSTAR(float massmother, float massdaughter1, float massdaughter2) {
2067     float res=((massmother*massmother)-(massdaughter1+massdaughter2)*(massdaughter1+massdaughter2));
2068     res*=((massmother*massmother)-(massdaughter1-massdaughter2)*(massdaughter1-massdaughter2));
2069     res=TMath::Sqrt(res)/(2*massmother);
2070     return res;
2071     }
2072 buchmann 1.24
2073     void FindMinMax(TGraphErrors *gr, float &min, float &max) {
2074     double x,y;
2075     gr->GetPoint(0,x,y);
2076     min=500*y;
2077     max=0.0002*y;
2078     for(int i=0;i<gr->GetN();i++) {
2079     gr->GetPoint(i,x,y);
2080     cout << "Point at " << x << "/" << y << " with error " << gr->GetErrorY(i) << endl;
2081     float potmin=y-1.5*gr->GetErrorY(i); // taking 1.5 times the error to allow for enough space to present the plot
2082     float potmax=y+1.5*gr->GetErrorY(i); // taking 1.5 times the error to allow for enough space to present the plot
2083     if(potmin<min) min=potmin;
2084     if(potmax>max) max=potmax;
2085     }
2086     }
2087 buchmann 1.28
2088    
2089     void CleanLegends() {
2090     for(int ihist=(int)PlottingSetup::FakeHistoHeap.size()-1;ihist>=0;ihist--) {
2091     PlottingSetup::FakeHistoHeap[ihist]->Delete();
2092     PlottingSetup::FakeHistoHeap.pop_back();
2093     }
2094     }
2095 buchmann 1.34
2096     string DigitsAfterComma(float number, int digits) {
2097     float temp=number*pow(10.0,digits);
2098     temp=int(temp)/pow(10.0,digits);
2099     return any2string(temp);
2100     }
2101 buchmann 1.42
2102    
2103     float GetYield(TH1F *histo, float min, float max) {
2104     float res=0.0;
2105     for(int i=1;i<=histo->GetNbinsX();i++) {
2106     if(histo->GetBinLowEdge(i)+histo->GetBinWidth(i)<=min) continue;// considered in the next bin
2107     if(histo->GetBinLowEdge(i)>=max) continue;//above the threshold, out!
2108     // cout << " added yield for bin [" << histo->GetBinLowEdge(i) << "," << histo->GetBinLowEdge(i)+histo->GetBinWidth(i) << "] which is " << histo->GetBinContent(i) << " in GetYield" << endl;
2109     res+=histo->GetBinContent(i);
2110     }
2111     return res;
2112     }
2113    
2114     void ProduceYields(float min, float max, TH1F *data, THStack *stack) {
2115     dout << " *************** <MC YIELDS> ********* " << endl;
2116     dout << " Considering " << min << " < mll < " << max << " " << endl;
2117     dout << " Data : " << GetYield(data,min,max) << endl;
2118     TIter nextSF(stack->GetHists());
2119     TH1F* h;
2120     while ( h = (TH1F*)nextSF() ) {
2121     dout << " " << h->GetName() << " : " << GetYield(h,min,max) << endl;
2122     }
2123     dout << " *************** </MC YIELDS> ********* " << endl;
2124     }
2125    
2126    
2127     void WriteYield(THStack *mc, float low, float high) {
2128     TH1F *h;
2129     TIter NextHisto(mc->GetHists());
2130     while ( h = (TH1F*)NextHisto() ) {
2131     float CurrBKG=0;
2132     float CurrBKGErr=0;
2133     for(int i=1;i<=h->GetNbinsX()+1;i++) {
2134     if(h->GetBinLowEdge(i)+h->GetBinWidth(i)<=low) continue;// considered in the next bin
2135     if(h->GetBinLowEdge(i)>=high) continue;//above the threshold, out!
2136     CurrBKG+=h->GetBinContent(i);
2137     CurrBKGErr=sqrt(CurrBKGErr*CurrBKGErr+h->GetBinError(i)*h->GetBinError(i));
2138     }
2139     dout << " " << h->GetName() << " : " << CurrBKG << " +/- " << CurrBKGErr << endl;
2140     }
2141     }