ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/AnalysisFramework/Plotting/Modules/GeneralToolBox.C
Revision: 1.48
Committed: Wed Nov 9 12:13:46 2011 UTC (13 years, 6 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.47: +2 -3 lines
Log Message:
Reduced verbose compiling output (e.g. double instead of float and such)

File Contents

# User Rev Content
1 buchmann 1.1 #include <iostream>
2 fronga 1.17 #include <iomanip>
3 buchmann 1.1 #include <sstream>
4 buchmann 1.13 #include <fstream>
5 buchmann 1.1 #include <vector>
6     #include <stdio.h>
7     #include <stdlib.h>
8     #include <sys/types.h>
9     #include <sys/stat.h>
10 buchmann 1.15 #include <limits>
11 buchmann 1.43 #include <time.h>
12 buchmann 1.44 #include <sys/types.h>
13     #include <dirent.h>
14 buchmann 1.47 #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.1
21     #include <TFile.h>
22     #include <TTree.h>
23     #include <TCut.h>
24     #include <TLegend.h>
25     #include <TLatex.h>
26     #include <TText.h>
27     #include <TGraph.h>
28     #include <TH1.h>
29 buchmann 1.2 #include <TF1.h>
30 buchmann 1.1 #include <TMath.h>
31 buchmann 1.38 #include <THStack.h>
32     #include <TColor.h>
33 buchmann 1.1 #include <TStyle.h>
34     #include <TCanvas.h>
35     #include <TError.h>
36 buchmann 1.3 #include <TVirtualPad.h>
37 buchmann 1.1 #include <TGraphAsymmErrors.h>
38 buchmann 1.7 #include <TPaveText.h>
39 buchmann 1.1 #include <TRandom.h>
40 buchmann 1.38 #include <TGraphErrors.h>
41 buchmann 1.1 #ifndef Verbosity
42     #define Verbosity 0
43     #endif
44    
45 buchmann 1.38
46 buchmann 1.1 /*
47     #ifndef SampleClassLoaded
48     #include "SampleClass.C"
49     #endif
50     */
51     #define GeneralToolBoxLoaded
52    
53     using namespace std;
54    
55 buchmann 1.32 namespace PlottingSetup {
56     string cbafbasedir="";
57 buchmann 1.34 string basedirectory="";
58 buchmann 1.45 vector<float> global_ratio_binning;
59 buchmann 1.32 }
60    
61 buchmann 1.1 bool dopng=false;
62     bool doC=false;
63     bool doeps=false;
64 buchmann 1.5 bool dopdf=false;
65 buchmann 1.33 bool doroot=false;
66 buchmann 1.26 float generaltoolboxlumi;
67 buchmann 1.1
68 buchmann 1.26 TLegend* make_legend(string title,float posx,float posy, bool drawleg);
69     TText* write_title(bool, string);
70 buchmann 1.1 TText* write_title_low(string title);
71    
72     TText* write_text(float xpos,float ypos,string title);
73     float computeRatioError(float a, float da, float b, float db);
74     float computeProductError(float a, float da, float b, float db);
75     TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning);
76     void setlumi(float l);
77 buchmann 1.26 void DrawPrelim(float writelumi);
78 buchmann 1.1 void CompleteSave(TCanvas *can, string filename, bool feedback);
79 buchmann 1.3 void CompleteSave(TVirtualPad *can, string filename, bool feedback);
80 buchmann 1.1 void write_warning(string funcname, string text);
81     void write_error(string funcname, string text);
82     void write_info(string funcname, string text);
83 buchmann 1.13 string get_directory();
84 buchmann 1.40 bool Contains(string wholestring, string findme);
85 buchmann 1.1 //-------------------------------------------------------------------------------------
86 buchmann 1.13
87 buchmann 1.15 template<typename U>
88     inline bool isanyinf(U value)
89     {
90     return !(value >= std::numeric_limits<U>::min() && value <=
91     std::numeric_limits<U>::max());
92     }
93 buchmann 1.13
94 buchmann 1.32 stringstream warningsummary;
95     stringstream infosummary;
96     stringstream errorsummary;
97    
98 buchmann 1.1 template<class A>
99     string any2string(const A& a){
100     ostringstream out;
101     out << a;
102     return out.str();
103     }
104    
105     void do_png(bool s) { dopng=s;}
106     void do_eps(bool s) { doeps=s;}
107     void do_C(bool s) { doC=s;}
108 buchmann 1.33 void do_pdf(bool s) { dopdf=s;}
109     void do_root(bool s){ doroot=s;}
110 buchmann 1.1
111     string topdir(string child) {
112     string tempdirectory=child;
113     if(tempdirectory.substr(tempdirectory.length()-1,1)=="/") tempdirectory=tempdirectory.substr(0,tempdirectory.length());
114     //we now have a directory without the trailing slash so we can just look for the last non-slash character :-)
115     for(int ichar=tempdirectory.length()-1;ichar>=0;ichar--) {
116     if(tempdirectory.substr(ichar,1)=="/") {
117     return tempdirectory.substr(0,ichar);
118     }
119     }
120     }
121    
122 buchmann 1.12 template < typename CHAR_TYPE,
123     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
124    
125     struct basic_teebuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
126     {
127     typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
128     typedef typename TRAITS_TYPE::int_type int_type ;
129    
130     basic_teebuf( streambuf_type* buff_a, streambuf_type* buff_b )
131     : first(buff_a), second(buff_b) {}
132    
133     protected:
134     virtual int_type overflow( int_type c )
135     {
136     const int_type eof = TRAITS_TYPE::eof() ;
137     if( TRAITS_TYPE::eq_int_type( c, eof ) )
138     return TRAITS_TYPE::not_eof(c) ;
139     else
140     {
141     const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(c) ;
142     if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
143     TRAITS_TYPE::eq_int_type( second->sputc(ch), eof ) )
144     return eof ;
145     else return c ;
146     }
147     }
148    
149     virtual int sync()
150     { return !first->pubsync() && !second->pubsync() ? 0 : -1 ; }
151    
152     private:
153     streambuf_type* first ;
154     streambuf_type* second ;
155     };
156    
157     template < typename CHAR_TYPE,
158     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
159     struct basic_teestream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
160     {
161     typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
162     typedef basic_teebuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;
163    
164     basic_teestream( stream_type& first, stream_type& second )
165     : stream_type( &stmbuf), stmbuf( first.rdbuf(), second.rdbuf() ) {}
166    
167     ~basic_teestream() { stmbuf.pubsync() ; }
168    
169     private: streambuff_type stmbuf ;
170     };
171    
172     typedef basic_teebuf<char> teebuf ;
173     typedef basic_teestream<char> teestream ;
174    
175 buchmann 1.13 std::ofstream file("LOG.txt",ios::app) ;
176 buchmann 1.28 std::ofstream texfile("Tex.txt") ;
177 buchmann 1.14 std::ofstream efile("LOGerr.txt",ios::app) ;
178 buchmann 1.13 teestream dout( file, std::cout ) ; // double out
179     teestream eout( efile, std::cout ) ; // double out (errors)
180 buchmann 1.12
181 buchmann 1.28 template < typename CHAR_TYPE,
182     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
183    
184     struct basic_tripbuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
185     {
186     typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
187     typedef typename TRAITS_TYPE::int_type int_type ;
188    
189     basic_tripbuf( streambuf_type* buff_a, streambuf_type* buff_b, streambuf_type* buff_c )
190     : first(buff_a), second(buff_b), third(buff_c) {}
191    
192     protected:
193     virtual int_type overflow( int_type d )
194     {
195     const int_type eof = TRAITS_TYPE::eof() ;
196     if( TRAITS_TYPE::eq_int_type( d, eof ) )
197     return TRAITS_TYPE::not_eof(d) ;
198     else
199     {
200     const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(d) ;
201     if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
202     TRAITS_TYPE::eq_int_type( second->sputc(ch), eof )||
203     TRAITS_TYPE::eq_int_type( third->sputc(ch), eof ) )
204     return eof ;
205     else return d ;
206     }
207     }
208    
209     virtual int sync()
210     { return !first->pubsync() && !second->pubsync() && !third->pubsync() ? 0 : -1 ; }
211    
212     private:
213     streambuf_type* first ;
214     streambuf_type* second ;
215     streambuf_type* third ;
216     };
217    
218     template < typename CHAR_TYPE,
219     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
220     struct basic_tripstream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
221     {
222     typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
223     typedef basic_tripbuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;
224    
225     basic_tripstream( stream_type& first, stream_type& second, stream_type& third )
226     : stream_type( &stmbuf), stmbuf( first.rdbuf(), second.rdbuf(), third.rdbuf() ) {}
227    
228     ~basic_tripstream() { stmbuf.pubsync() ; }
229    
230     private: streambuff_type stmbuf ;
231     };
232    
233     //typedef basic_tripbuf<char> teebuf ;
234     typedef basic_tripstream<char> tripplestream ;
235    
236     tripplestream tout( file, texfile , std::cout ) ; // tripple out
237    
238 buchmann 1.1 void ensure_directory_exists(string thisdirectory) {
239     struct stat st;
240     if(stat(thisdirectory.c_str(),&st) == 0) {
241 buchmann 1.13 if(Verbosity>0) dout << "Directory " << thisdirectory << " exists!" << endl;
242 buchmann 1.1 }
243     else {
244 buchmann 1.13 if(Verbosity>0) dout << "Directory " << thisdirectory << " does not exist. Need to create it!" << endl;
245 buchmann 1.1 ensure_directory_exists(topdir(thisdirectory));
246     if (mkdir(thisdirectory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
247 buchmann 1.13 if(Verbosity>0) dout << "Created the directory " << thisdirectory << endl;
248 buchmann 1.1 }
249     }
250    
251 buchmann 1.13 void initialize_log() {
252 buchmann 1.14 dout << "____________________________________________________________" << endl;
253     dout << endl;
254 buchmann 1.13 dout << " " << endl;
255     dout << " JJJJJJJJJJJZZZZZZZZZZZZZZZZZZZBBBBBBBBBBBBBBBBB " << endl;
256     dout << " J:::::::::JZ:::::::::::::::::ZB::::::::::::::::B " << endl;
257     dout << " J:::::::::JZ:::::::::::::::::ZB::::::BBBBBB:::::B " << endl;
258     dout << " JJ:::::::JJZ:::ZZZZZZZZ:::::Z BB:::::B B:::::B" << endl;
259     dout << " J:::::J ZZZZZ Z:::::Z B::::B B:::::B" << endl;
260     dout << " J:::::J Z:::::Z B::::B B:::::B" << endl;
261     dout << " J:::::J Z:::::Z B::::BBBBBB:::::B " << endl;
262     dout << " J:::::j Z:::::Z B:::::::::::::BB " << endl;
263     dout << " J:::::J Z:::::Z B::::BBBBBB:::::B " << endl;
264     dout << "JJJJJJJ J:::::J Z:::::Z B::::B B:::::B" << endl;
265     dout << "J:::::J J:::::J Z:::::Z B::::B B:::::B" << endl;
266     dout << "J::::::J J::::::J ZZZ:::::Z ZZZZZ B::::B B:::::B" << endl;
267     dout << "J:::::::JJJ:::::::J Z::::::ZZZZZZZZ:::ZBB:::::BBBBBB::::::B" << endl;
268     dout << " JJ:::::::::::::JJ Z:::::::::::::::::ZB:::::::::::::::::B " << endl;
269     dout << " JJ:::::::::JJ Z:::::::::::::::::ZB::::::::::::::::B " << endl;
270     dout << " JJJJJJJJJ ZZZZZZZZZZZZZZZZZZZBBBBBBBBBBBBBBBBB " << endl;
271     dout << " " << endl;
272     dout << endl << endl;
273     dout << "____________________________________________________________" << endl;
274     time_t rawtime;
275     struct tm * timeinfo;
276     time ( &rawtime );
277     dout << " Analysis run on " << asctime (localtime ( &rawtime ));
278     dout << "____________________________________________________________" << endl;
279     dout << " Results saved in : " << get_directory() << endl << endl;
280     }
281    
282 buchmann 1.32 void extract_cbaf_dir(string curpath) {
283     int position=curpath.find("/Plotting");
284     if(position<0) position=curpath.find("/DistributedModelCalculations");
285     if(position<0) position=curpath.find("/various_assignments");
286     PlottingSetup::cbafbasedir=curpath.substr(0,position);
287     }
288    
289 buchmann 1.1 void set_directory(string basedir="") {
290     if(basedir.substr(0,1)=="/") basedir=basedir.substr(1,basedir.length()-1);
291     if(basedir.substr(basedir.length()-1,1)!="/") basedir+="/";
292     char currentpath[1024];
293 buchmann 1.32 char *path = getcwd(currentpath,1024);
294 buchmann 1.34 PlottingSetup::basedirectory=(string)currentpath+"/Plots/"+basedir;
295     ensure_directory_exists(PlottingSetup::basedirectory);
296 buchmann 1.13 initialize_log();
297 buchmann 1.32 extract_cbaf_dir(currentpath);
298 buchmann 1.1 }
299    
300 buchmann 1.6 string get_directory() {
301 buchmann 1.34 return PlottingSetup::basedirectory;
302 buchmann 1.6 }
303    
304 buchmann 1.1 string extract_directory(string savethis) {
305     bool foundslash=false;
306     int position=savethis.length();
307     while(!foundslash&&position>0) {
308     position--;
309     if(savethis.substr(position,1)=="/") foundslash=true;
310     }
311     if(position>0) return savethis.substr(0,position+1);
312     else return "";
313     }
314    
315 buchmann 1.33 string extract_root_dir(string name) {
316     int position = -1;
317     if(name.substr(0,1)=="/") name=name.substr(1,name.length()-1);
318     for(int ipos=0;ipos<name.length();ipos++) {
319     if(name.substr(ipos,1)=="/") position=ipos;
320     }
321     if(position==-1) return "";
322     return name.substr(0,position);
323     }
324    
325     string extract_root_filename(string name) {
326     int position = -1;
327     if(name.substr(0,1)=="/") name=name.substr(1,name.length()-1);
328     for(int ipos=0;ipos<name.length();ipos++) {
329     if(name.substr(ipos,1)=="/") position=ipos;
330     }
331     return name.substr(position+1,name.length()-position-1);
332     }
333    
334 buchmann 1.40 void SaveToRoot(TCanvas *can, string name) {
335 buchmann 1.34 TFile *fout = new TFile((TString(PlottingSetup::basedirectory)+TString("allplots.root")),"UPDATE");
336 buchmann 1.33 fout->cd();
337     string directory=extract_root_dir(name);
338     string filename=extract_root_filename(name);
339     if(directory!="") {
340     if(fout->GetDirectory(directory.c_str())) {
341     fout->cd(directory.c_str());
342     can->Write(filename.c_str());
343     }else {
344     fout->mkdir(directory.c_str());
345     fout->cd(directory.c_str());
346     can->Write(filename.c_str());
347     }
348     } else {
349     can->Write(filename.c_str());
350     }
351     fout->cd();
352     fout->Close();
353     }
354    
355 fronga 1.18 void CompleteSave(TCanvas *can, string filename, bool feedback=false, bool redraw=true) {
356 buchmann 1.3 //any change you make here should also be done below in the CompleteSave function for virtual pads
357 buchmann 1.1 Int_t currlevel=gErrorIgnoreLevel;
358     if(!feedback) gErrorIgnoreLevel=1001;
359 fronga 1.18 if(redraw) can->RedrawAxis();
360 buchmann 1.34 ensure_directory_exists(extract_directory(PlottingSetup::basedirectory+filename));
361     if(dopng) can->SaveAs((PlottingSetup::basedirectory+filename+".png").c_str());
362     if(doeps) can->SaveAs((PlottingSetup::basedirectory+filename+".eps").c_str());
363     if(dopdf) can->SaveAs((PlottingSetup::basedirectory+filename+".pdf").c_str());
364     if(doC) can->SaveAs((PlottingSetup::basedirectory+filename+".C").c_str());
365 buchmann 1.33 if(doroot) SaveToRoot(can,filename);
366 buchmann 1.1 gErrorIgnoreLevel=currlevel;
367 buchmann 1.13 dout << "Saved " << filename << " in all requested formats" << endl;
368 buchmann 1.1 }
369 buchmann 1.3
370 fronga 1.18 void CompleteSave(TVirtualPad *can, string filename, bool feedback=false, bool redraw=true) {
371 buchmann 1.3 Int_t currlevel=gErrorIgnoreLevel;
372     if(!feedback) gErrorIgnoreLevel=1001;
373 fronga 1.18 if(redraw) can->RedrawAxis();
374 buchmann 1.34 ensure_directory_exists(extract_directory(PlottingSetup::basedirectory+filename));
375     if(dopng) can->SaveAs((PlottingSetup::basedirectory+filename+".png").c_str());
376     if(doeps) can->SaveAs((PlottingSetup::basedirectory+filename+".eps").c_str());
377     if(doC) can->SaveAs((PlottingSetup::basedirectory+filename+".C").c_str());
378 buchmann 1.3 gErrorIgnoreLevel=currlevel;
379 buchmann 1.13 dout << "Saved " << filename << " in all requested formats" << endl;
380 buchmann 1.3 }
381    
382 buchmann 1.1
383     void setlumi(float l) {
384 buchmann 1.24 generaltoolboxlumi=l;
385 buchmann 1.1 }
386    
387     int write_first_line(vector<vector<string> > &entries) {
388     if(entries.size()>0) {
389     vector<string> firstline = entries[0];
390     int ncolumns=firstline.size();
391     int ndividers=ncolumns+1;
392     int cellwidth=(int)(((float)(60-ndividers))/(ncolumns));
393 buchmann 1.13 dout << " |";
394 buchmann 1.1 for(int idiv=0;idiv<ncolumns;idiv++) {
395 buchmann 1.13 for(int isig=0;isig<cellwidth;isig++) dout << "-";
396     dout << "|";
397 buchmann 1.1 }
398 buchmann 1.13 dout << endl;
399 buchmann 1.1 return ncolumns;
400     } else {
401     return 0;
402     }
403     }
404    
405     void write_entry(string entry,int width,int iline=0,int ientry=0) {
406     int currwidth=entry.size();
407     while(currwidth<width) {
408     entry=" "+entry;
409     if(entry.size()<width) entry=entry+" ";
410     currwidth=entry.size();
411     }
412     bool do_special=false;
413 buchmann 1.13 if(iline==1&&ientry==1) { dout << "\033[1;32m" << entry << "\033[0m|";do_special=true;}//observed
414     if(iline==1&&ientry==2) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
415     if(iline==2&&ientry==1) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
416     if(iline==2&&ientry==2) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
417     if(!do_special) dout << entry << "|";
418 buchmann 1.1 }
419    
420     void make_nice_table(vector<vector <string> > &entries) {
421     int ncolumns=write_first_line(entries);
422     int cellwidth=(int)(((float)(60-(ncolumns+1)))/(ncolumns));
423     for(int iline=0;iline<entries.size();iline++) {
424     vector<string> currline = entries[iline];
425 buchmann 1.13 dout << " |";
426 buchmann 1.1 for(int ientry=0;ientry<currline.size();ientry++) {
427     write_entry(currline[ientry],cellwidth);
428     }
429 buchmann 1.13 dout << endl;
430 buchmann 1.1 if(iline==0) write_first_line(entries);
431     }
432     write_first_line(entries);
433     }
434    
435     void make_nice_jzb_table(vector<vector <string> > &entries) {
436     int ncolumns=write_first_line(entries);
437     int cellwidth=(int)(((float)(60-(ncolumns+1)))/(ncolumns));
438     for(int iline=0;iline<entries.size();iline++) {
439     vector<string> currline = entries[iline];
440 buchmann 1.13 dout << " |";
441 buchmann 1.1 for(int ientry=0;ientry<currline.size();ientry++) {
442     write_entry(currline[ientry],cellwidth,iline,ientry);
443     }
444 buchmann 1.13 dout << endl;
445 buchmann 1.1 if(iline==0) write_first_line(entries);
446     }
447     write_first_line(entries);
448     }
449    
450    
451     void write_warning(string funcname, string text) {
452 buchmann 1.40 string colid="[1;35m";
453     char hostname[1023];
454     gethostname(hostname,1023);
455     if(!Contains((string)hostname,"t3")) colid="[1;33m";
456     eout << endl << endl;
457     eout << "\033"<<colid<<"" << " _ " << endl;
458     eout << "\033"<<colid<<"" << " (_) " << endl;
459     eout << "\033"<<colid<<"" << "__ ____ _ _ __ _ __ _ _ __ __ _ " << endl;
460     eout << "\033"<<colid<<"" << "\\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` |" << endl;
461     eout << "\033"<<colid<<"" << " \\ V V / (_| | | | | | | | | | | (_| |" << endl;
462     eout << "\033"<<colid<<"" << " \\_/\\_/ \\__,_|_| |_| |_|_|_| |_|\\__, |" << endl;
463     eout << "\033"<<colid<<"" << " __/ |" << endl;
464     eout << "\033"<<colid<<"" << " |___/ " << endl;
465 buchmann 1.13 eout << endl;
466 buchmann 1.40 eout << "\033"<<colid<<" [" << funcname << "] " << text << " \033[0m" << endl;
467 buchmann 1.13 eout << endl << endl;
468 buchmann 1.32 warningsummary << "[" << funcname << "] " << text << endl;
469 buchmann 1.1 }
470 buchmann 1.40
471 buchmann 1.1 void write_error(string funcname, string text) {
472 buchmann 1.13 eout << endl << endl;
473     eout << "\033[1;31m ___ _ __ _ __ ___ _ __ " << endl;
474     eout << "\033[1;31m / _ \\ __| __/ _ \\| '__|" << endl;
475     eout << "\033[1;31m| __/ | | | | (_) | | " << endl;
476     eout << "\033[1;31m \\___|_| |_| \\___/|_| " << endl;
477     eout << endl;
478     eout << "\033[1;31m [" << funcname << "] " << text << " \033[0m" << endl;
479     eout << endl << endl;
480 buchmann 1.32 errorsummary << "[" << funcname << "] " << text << endl;
481 buchmann 1.1 }
482    
483     void write_info(string funcname, string text) {
484 buchmann 1.13 dout << endl << endl;
485     dout << "\033[1;34m _____ __ " << endl;
486     dout << "\033[1;34m |_ _| / _| " << endl;
487     dout << "\033[1;34m | | _ __ | |_ ___ " << endl;
488     dout << "\033[1;34m | | | '_ \\| _/ _ \\ " << endl;
489     dout << "\033[1;34m _| |_| | | | || (_) | " << endl;
490     dout << "\033[1;34m |_____|_| |_|_| \\___/ " << endl;
491     dout << endl;
492     dout << "\033[1;34m [" << funcname << "] " << text << " \033[0m" << endl;
493     dout << endl << endl;
494 buchmann 1.32 infosummary << "[" << funcname << "] " << text << endl;
495 buchmann 1.1 }
496    
497     TText* write_text(float xpos,float ypos,string title)
498     {
499     TLatex* titlebox = new TLatex (xpos,ypos,title.c_str());
500     titlebox->SetNDC(true);
501     titlebox->SetTextFont(42);
502     titlebox->SetTextSize(0.04);
503     titlebox->SetTextAlign(21);
504     return titlebox;
505     }
506    
507     TText* write_title(string title)
508     {
509 buchmann 1.15 TText* titlebox = write_text(0.5,0.945,title);
510 buchmann 1.1 return titlebox;
511     }
512    
513 buchmann 1.7 TText* write_cut_on_canvas(string cut) {
514     // TLatex *normbox = new TLatex(0.96,0.5,cut.c_str());
515     TLatex *normbox = new TLatex(0.96,0.5,"");//currently deactivated
516     normbox->SetNDC(true);
517     normbox->SetTextFont(42);
518     normbox->SetTextSize(0.01);
519     normbox->SetTextAlign(21);
520     normbox->SetTextAngle(270);
521     return normbox;
522     }
523    
524 buchmann 1.1 TText* write_title_low(string title)
525     {
526     TText* titlebox = write_text(0.5,0.94,title);
527     return titlebox;
528     }
529    
530 buchmann 1.27 void DrawPrelim(float writelumi=generaltoolboxlumi,bool isMC=false) {
531 buchmann 1.26 string barn="pb";
532     if(writelumi>=1000)
533     {
534     writelumi/=1000;
535     barn="fb";
536     }
537    
538     stringstream prelimtext;
539     //prelimtext << "CMS Preliminary 2011 , #sqrt{s}= 7 TeV, L= O(1) fb^{-1}"; //temporary replacement
540 fronga 1.31 if(isMC) prelimtext << "CMS MC Simulation , #sqrt{s} = 7 TeV, L_{int} = " << std::setprecision(2) <<writelumi<<" "<<barn<<"^{-1}";
541     else prelimtext << "CMS Preliminary, #sqrt{s} = 7 TeV, L_{int} = " << std::setprecision(2) <<writelumi<<" "<<barn<<"^{-1}";
542 buchmann 1.26 TPaveText *eventSelectionPaveText = new TPaveText(0.27, 0.93,0.77, 1.0,"blNDC");
543     eventSelectionPaveText->SetFillStyle(4000);
544     eventSelectionPaveText->SetFillColor(kWhite);
545     eventSelectionPaveText->SetTextFont(42);
546     eventSelectionPaveText->SetTextSize(0.042);
547     eventSelectionPaveText->AddText(prelimtext.str().c_str());
548     eventSelectionPaveText->Draw();
549     }
550    
551 buchmann 1.27 void DrawMCPrelim(float writelumi=generaltoolboxlumi) {
552     DrawPrelim(writelumi,true);
553     }
554    
555 buchmann 1.26 TLegend* make_legend(string title="", float posx=0.6, float posy=0.55, bool drawleg=true)
556 buchmann 1.1 {
557     gStyle->SetTextFont(42);
558 buchmann 1.7 TLegend *leg = new TLegend(posx,posy,0.89,0.89);
559 buchmann 1.1 if(title!="") leg->SetHeader(title.c_str());
560     leg->SetTextFont(42);
561 fronga 1.17 leg->SetTextSize(0.04);
562 buchmann 1.1 leg->SetFillColor(kWhite);
563     leg->SetBorderSize(0);
564     leg->SetLineColor(kWhite);
565 buchmann 1.26 if(drawleg) DrawPrelim();
566 buchmann 1.1 return leg;
567     }
568    
569 buchmann 1.26 TLegend* make_legend(bool drawleg, string title) {
570     return make_legend(title,0.6,0.55,drawleg);
571     }
572    
573 buchmann 1.1 TGraph* make_nice_ratio(int nbins,float binning[],TH1F* histo)
574     {
575     float errorsquared[nbins];
576     float errors[nbins];
577     float bincontent[nbins];
578     for (int i=0;i<nbins;i++) {
579     errorsquared[i]=0;
580     bincontent[i]=0;
581     errors[i]=0;
582     }
583     float currlimit=binning[0];
584     int currtoplim=1;
585     for(int ibin=1;ibin<=histo->GetNbinsX();ibin++)
586     {
587     if(binning[currtoplim]<histo->GetBinCenter(ibin)) currtoplim++;
588 buchmann 1.13 dout << "Bin i=" << ibin << " with bin center " << histo->GetBinCenter(ibin) << " contains " << histo->GetBinContent(ibin) << " is within " << binning[currtoplim-1] << " and " << binning[currtoplim] << endl;
589 buchmann 1.1
590     }
591    
592     return 0;
593     }
594    
595     float statErrorN(float x){return x - 0.5*TMath::ChisquareQuantile(0.3173/2,2*x);}
596     float statErrorP(float x){return 0.5*TMath::ChisquareQuantile(1-0.3173/2,2*(x+1))-x;}
597     float lowLimit(float a, float x){return 0.5*TMath::ChisquareQuantile(a,2*x);}
598     float highLimit(float a,float x){return 0.5*TMath::ChisquareQuantile(1-a,2*(x+1));}
599    
600     float computeRatioError(float a, float da, float b, float db)
601     {
602     float val=0.;
603     float errorSquare = (a/b)*(a/b)*( (da/a)*(da/a) + (db/b)*(db/b));
604     val = TMath::Sqrt(errorSquare);
605     return val;
606    
607     }
608     float computeProductError(float a, float da, float b, float db)
609     {
610     float val=0.;
611     float errorSquare = (a*b)*(a*b)*( (da/a)*(da/a) + (db/b)*(db/b));
612     val = TMath::Sqrt(errorSquare);
613     return val;
614     }
615    
616 buchmann 1.23 TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning, bool precise=false)
617 buchmann 1.1 {
618     int absJZBbinsNumber = binning.size()-1;
619     TGraphAsymmErrors* graph = new TGraphAsymmErrors(absJZBbinsNumber);
620    
621     for(unsigned int i=0;i<absJZBbinsNumber;i++)
622     {
623     float xCenter=h1->GetBinCenter(i+1);
624     float xWidth=(h1->GetBinWidth(i+1))*0.5;
625     float nominatorError = h1->GetBinError(i+1);
626     float nominator=h1->GetBinContent(i+1);
627     float denominatorError=h2->GetBinError(i+1);
628     float denominator=h2->GetBinContent(i+1);
629     float errorN = 0;
630     float errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
631     if(id==1) // (is data)
632     {
633 buchmann 1.23 if(!precise) errorP = computeRatioError(nominator,statErrorP(nominator),denominator,statErrorP(denominator));
634     else errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
635 buchmann 1.1 errorN = errorP; // symmetrize using statErrorP
636     } else {
637     errorN = computeRatioError(nominator,nominatorError,denominator,denominatorError);
638 buchmann 1.23 errorP = errorN;
639 buchmann 1.1 }
640     if(denominator!=0) {
641     graph->SetPoint(i, xCenter, nominator/denominator);
642     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
643     }
644     else {
645     graph->SetPoint(i, xCenter, -999);
646     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
647     }
648     }
649     return graph;
650     }
651    
652     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!
653     float uperr=0,downerr=0;
654     if(down>up&&down>cent) uperr=down-cent;
655     if(up>down&&up>cent) uperr=up-cent;
656     if(down<cent&&down<up) downerr=cent-down;
657     if(up<cent&&up<down) downerr=cent-up;
658     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!");
659     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!");
660     stringstream result;
661     result << cent << " + " << uperr << " - " << downerr;
662     return result.str();
663     }
664    
665     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")
666     {
667     int last = size - 2;
668     int isChanged = 1;
669    
670     while ( last >= 0 && isChanged )
671     {
672     isChanged = 0;
673     for ( int k = 0; k <= last; k++ )
674     if ( arr[k] > arr[k+1] )
675     {
676     swap ( arr[k], arr[k+1] );
677     isChanged = 1;
678     int bkp=order[k];
679     order[k]=order[k+1];
680     order[k+1]=bkp;
681     }
682     last--;
683     }
684     }
685    
686     void swapvec(vector<float> &vec,int j, int k) {
687     float bkp=vec[j];
688     vec[j]=vec[k];
689     vec[k]=bkp;
690     }
691    
692     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")
693     {
694     int last = arr.size() - 2;
695     int isChanged = 1;
696    
697     while ( last >= 0 && isChanged )
698     {
699     isChanged = 0;
700     for ( int k = 0; k <= last; k++ )
701     if ( arr[k] > arr[k+1] )
702     {
703     swapvec (arr,k,k+1);
704     isChanged = 1;
705     int bkp=order[k];
706     order[k]=order[k+1];
707     order[k+1]=bkp;
708     }
709     last--;
710     }
711     }
712    
713     int numerichistoname=0;
714 buchmann 1.16 bool givingnumber=false;
715 buchmann 1.1 string GetNumericHistoName() {
716 buchmann 1.16 while(givingnumber) sleep(1);
717     givingnumber=true;
718 buchmann 1.1 stringstream b;
719     b << "h_" << numerichistoname;
720     numerichistoname++;
721 buchmann 1.16 givingnumber=false;
722 buchmann 1.1 return b.str();
723     }
724    
725     //********************** BELOW : CUT INTERPRETATION **************************//
726     void splitupcut(string incut, vector<string> &partvector)
727     {
728     //idea: go thru the string called incut; if a parantheses is opened, then the cut cannot be split up until the parantheses is closed.
729     //ok anyway screw the parantheses.
730     int paranthesis_open=0;
731     int substr_start=0;
732     string currchar="";
733     for (int ichar=0;ichar<incut.length();ichar++)
734     {
735     currchar=incut.substr(ichar,1);
736     // if(currchar=="(") paranthesis_open++;
737     // if(currchar==")") paranthesis_open--;
738     if(currchar=="&"&&incut.substr(ichar+1,1)=="&"&&paranthesis_open==0) {
739     partvector.push_back(incut.substr(substr_start,ichar-substr_start));
740     substr_start=ichar+2;
741     }
742     }
743     partvector.push_back(incut.substr(substr_start,incut.length()-substr_start));
744     if(Verbosity>1) {
745 buchmann 1.13 dout << "[ splitupcut() ] : The cut vector now contains the following elements: "<< endl;
746 buchmann 1.1 for (int ipart=0;ipart<partvector.size();ipart++)
747     {
748 buchmann 1.13 dout << " - " << partvector[ipart] << endl;
749 buchmann 1.1 }
750     }
751     }
752    
753     int atleastvalue(string expression, int &morethanlessthan) // takes in an expression such as ">2" or ">=3" and returns e.g. 3 (in both examples)
754     {
755     int retval=0;
756     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
757 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
758 buchmann 1.1 morethanlessthan=1;
759     return atoi(expression.substr(2,1).c_str());
760     }
761     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
762 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
763 buchmann 1.1 morethanlessthan=0;
764     return atoi(expression.substr(1,1).c_str());
765     }
766     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
767 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
768 buchmann 1.1 morethanlessthan=-1;
769     return 1+atoi(expression.substr(1,1).c_str());
770     }
771     if(expression.substr(0,1)==">") {
772 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
773 buchmann 1.1 morethanlessthan=1;
774     return 1+atoi(expression.substr(2,1).c_str());
775     }
776     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
777 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
778 buchmann 1.1 morethanlessthan=-1;
779     return 1+atoi(expression.substr(2,1).c_str());
780     }
781     }
782    
783     int do_jet_cut(string incut, int *nJets) {
784     string expression=(incut.substr(12,incut.size()-12));
785 buchmann 1.13 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;
786 buchmann 1.1 if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
787     int nJet=atoi(expression.substr(2,1).c_str());
788     for(int i=nJet+1;i<20;i++) nJets[i]=0;
789 buchmann 1.13 dout << "Is of type <=" << endl;
790 buchmann 1.1 return 0;
791     }
792     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
793     int nJet=atoi(expression.substr(2,1).c_str());
794     for(int i=0;i<20&&i!=nJet;i++) nJets[i]=0;
795 buchmann 1.13 dout << "Is of type ==" << endl;
796 buchmann 1.1 return 0;
797     }
798     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
799     int nJet=atoi(expression.substr(2,1).c_str());
800     for(int i=0;i<nJet&&i!=nJet;i++) nJets[i]=0;
801 buchmann 1.13 dout << "Is of type >=" << endl;
802 buchmann 1.1 return 0;
803     }
804     if(expression.substr(0,1)=="<") {
805     int nJet=atoi(expression.substr(1,1).c_str());
806     for(int i=nJet;i<20;i++) nJets[i]=0;
807 buchmann 1.13 dout << "Is of type <" << endl;
808 buchmann 1.1 return 0;
809     }
810     if(expression.substr(0,1)==">") {
811     int nJet=atoi(expression.substr(1,1).c_str());
812     for(int i=0;i<nJet+1&&i!=nJet;i++) nJets[i]=0;
813 buchmann 1.13 dout << "Is of type >" << endl;
814 buchmann 1.1 return 0;
815     }
816     }
817    
818     string interpret_cut(string incut, bool &isJetCut, int *permittednJets)
819     {
820     // isJetCut=false;nJets=-1;
821     if(incut=="()") return "";
822     while(incut.substr(0,1)=="(") incut=incut.substr(1,incut.length()-1);
823     while(incut.length()>0&&incut.substr(incut.length()-1,1)==")") incut=incut.substr(0,incut.length()-1);
824     // 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.
825    
826     if(Verbosity>0) {
827 buchmann 1.13 dout << "Now interpreting cut " << incut << endl;
828 buchmann 1.1 }
829     /*
830     if(incut=="ch1*ch2<0") return "OS";
831     if(incut=="id1==id2") return "SF";
832     if(incut=="id1!=id2") return "OF";
833     */
834     if(incut=="ch1*ch2<0") return "";
835 buchmann 1.5 if(incut=="(mll>55&&mll<70)||(mll>112&&mll<160)") return "SB";
836     if(incut=="(mll>61&&mll<70)||(mll>112&&mll<190)") return "SB'";
837 buchmann 1.1 if(incut=="id1==id2") return "";
838     if(incut=="id1!=id2") return "";
839     if(incut=="mll>2") return "";
840    
841     if(incut=="mll>0") return ""; // my typical "fake cut"
842    
843     if(incut=="passed_triggers||!is_data") return "Triggers";
844     if(incut=="pfjzb[0]>-998") return "";
845    
846    
847     if(incut=="id1==0") return "ee";
848     if(incut=="id1==1") return "#mu#mu";
849     if(incut=="abs(mll-91.2)<20") return "|m_{l^{+}l^{-}}-m_{Z}|<20";
850     if(incut=="pfJetGoodID[0]") return "";
851     if(incut=="pfJetGoodID[1]") return "";
852     if((int)incut.find("pfJetGoodNum")>-1) {
853     //do_jet_cut(incut,permittednJets);
854     stringstream result;
855     result << "nJets" << incut.substr(12,incut.size()-12);
856 buchmann 1.13 /* dout << "Dealing with a jet cut: " << incut << endl;
857 buchmann 1.1 stringstream result;
858     result << "nJets" << incut.substr(12,incut.size()-12);
859     isJetCut=true;
860     if(exactjetcut(incut,nJets))
861     // nJets=atleastvalue((incut.substr(12,incut.size()-12)),morethanlessthan);
862     return result.str();*/
863     return result.str();
864     }
865     return incut;
866     }
867    
868     string interpret_nJet_range(int *nJets) {
869 buchmann 1.13 for (int i=0;i<20;i++) dout << i << " : " << nJets[i] << endl;
870 buchmann 1.1 return "hello";
871     }
872    
873     string interpret_cuts(vector<string> &cutparts)
874     {
875     stringstream nicecut;
876     int nJets;
877     bool isJetCut;
878     int finalJetCut=-1;
879     int permittednJets[20];
880     for(int ijet=0;ijet<20;ijet++) permittednJets[ijet]=1;
881     int morethanlessthan=0;//-1: less than, 0: exactly, 1: more than
882     for(int icut=0;icut<cutparts.size();icut++)
883     {
884     if(icut==0) nicecut<<interpret_cut(cutparts[icut],isJetCut,permittednJets);
885     else {
886     string nice_this_cut = interpret_cut(cutparts[icut],isJetCut,permittednJets);//blublu
887     if(nice_this_cut.length()>0&&nicecut.str().length()>0) {
888     if(!isJetCut) nicecut<<"&&"<<nice_this_cut;
889     else {
890     if(nJets>finalJetCut) finalJetCut=nJets;
891     }
892     }
893     if(nice_this_cut.length()>0&&nicecut.str().length()==0) {
894     if(!isJetCut) {
895     nicecut<<nice_this_cut;
896     }
897     else {
898     if(nJets>finalJetCut) finalJetCut=nJets;
899     }
900     }
901     }
902     }
903     if(finalJetCut>-1) {
904     if(nicecut.str().length()==0) {
905     nicecut << "nJets#geq" << finalJetCut;
906     }
907     else
908     {
909     nicecut << "&&nJets#geq " << finalJetCut;
910     }
911     }
912    
913 buchmann 1.13 // dout << "The nJet allowed range is given by: " << interpret_nJet_range(permittednJets) << endl;
914 buchmann 1.1
915     return nicecut.str();
916     }
917    
918     string decipher_cut(TCut originalcut,TCut ignorethispart)
919     {
920     string incut=(const char*)originalcut;
921     string ignore=(const char*)ignorethispart;
922    
923     if(ignore.length()>0 && incut.find(ignore)!=string::npos) incut=incut.replace(incut.find(ignore),ignore.length(),"");
924    
925     vector<string>cutparts;
926     splitupcut(incut,cutparts);
927     string write_cut=interpret_cuts(cutparts);
928     return write_cut;
929     }
930    
931     //********************** ABOVE : CUT INTERPRETATION **************************//
932 buchmann 1.2
933     Double_t GausRandom(Double_t mu, Double_t sigma) {
934     return gRandom->Gaus(mu,sigma);// real deal
935     //return mu;//debugging : no smearing.
936     }
937    
938 buchmann 1.3 int functionalhistocounter=0;
939 buchmann 1.2 TH1F * makehistofromfunction(TF1 *f1,TH1F *model) {
940     TH1F *histo = (TH1F*)model->Clone();
941 buchmann 1.3 functionalhistocounter++;
942     stringstream histoname;
943     histoname << "histo_based_on_function_" << f1->GetName() << "__"<<functionalhistocounter;
944     histo->SetTitle(histoname.str().c_str());
945     histo->SetName(histoname.str().c_str());
946 buchmann 1.2 int nbins=histo->GetNbinsX();
947     float low=histo->GetBinLowEdge(1);
948     float hi=histo->GetBinLowEdge(histo->GetNbinsX())+histo->GetBinWidth(histo->GetNbinsX());
949    
950     for(int i=0;i<=nbins;i++) {
951 buchmann 1.4 histo->SetBinContent(i,(f1->Integral(histo->GetBinLowEdge(i),histo->GetBinLowEdge(i)+histo->GetBinWidth(i)))/histo->GetBinWidth(i));
952     histo->SetBinError(i,TMath::Sqrt(histo->GetBinContent(i)));
953 buchmann 1.2 }
954    
955     return histo;
956 buchmann 1.4 }
957    
958     float hintegral(TH1 *histo, float low, float high) {
959     float sum=0;
960     for(int i=1;i<histo->GetNbinsX();i++) {
961     if((histo->GetBinLowEdge(i)>=low)&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))<=high) sum+=histo->GetBinContent(i);
962     //now on to the less clear cases!
963     if(histo->GetBinLowEdge(i)<low&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>low) {
964     //need to consider this case still ... the bin is kind of in range but not sooooo much.
965     }
966     if(histo->GetBinLowEdge(i)<high&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>high) {
967     //need to consider this case still ... the bin is kind of in range but not sooooo much.
968     }
969    
970     }
971     return sum;
972 buchmann 1.5 }
973    
974 buchmann 1.6 string newjzbexpression(string oldexpression,float shift) {
975     stringstream ss;
976     if(shift>0) ss<<"("<<oldexpression<<"+"<<shift<<")";
977     if(shift<0) ss<<"("<<oldexpression<<shift<<")";
978     if(shift==0) ss<<oldexpression;
979     return ss.str();
980     }
981    
982 buchmann 1.29 float Round(float num, unsigned int dig)
983 buchmann 1.11 {
984     num *= pow(10, dig);
985     if (num >= 0)
986     num = floor(num + 0.5);
987     else
988     num = ceil(num - 0.5);
989     num/= pow(10, dig);
990     return num;
991 buchmann 1.16 }
992    
993 buchmann 1.29 float SigDig(float num, int digits) {
994     //produces a number with only the given number of significant digits
995    
996     }
997    
998 buchmann 1.16 // The two functions below are for distributed processing
999    
1000     int get_job_number(float ipoint, float Npoints,float Njobs) {
1001     float pointposition=(ipoint/Npoints);
1002 buchmann 1.48 int njob=(int)floor(pointposition*Njobs);
1003 buchmann 1.16 if(njob>=Njobs) njob--;
1004     // cout << "Looking at point " << ipoint << " out of " << Npoints << " which is at position " << pointposition << " corresponding to " << pointposition*Njobs << " --> JOB " << njob << endl;
1005     return njob;
1006     }
1007    
1008    
1009     bool do_this_point(int ipoint, int Npoints, int jobnumber, int Njobs) {
1010     if(get_job_number(ipoint,Npoints,Njobs)==jobnumber) return true;
1011     return false;
1012     }
1013 buchmann 1.19
1014     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 ,
1015     Option_t *option, Bool_t doError)
1016     {
1017     // internal function compute integral and optionally the error between the limits
1018     // specified by the bin number values working for all histograms (1D, 2D and 3D)
1019    
1020     Int_t nbinsx = histo->GetNbinsX();
1021     if (binx1 < 0) binx1 = 0;
1022     if (binx2 > nbinsx+1 || binx2 < binx1) binx2 = nbinsx+1;
1023     if (histo->GetDimension() > 1) {
1024     Int_t nbinsy = histo->GetNbinsY();
1025     if (biny1 < 0) biny1 = 0;
1026     if (biny2 > nbinsy+1 || biny2 < biny1) biny2 = nbinsy+1;
1027     } else {
1028     biny1 = 0; biny2 = 0;
1029     }
1030     if (histo->GetDimension() > 2) {
1031     Int_t nbinsz = histo->GetNbinsZ();
1032     if (binz1 < 0) binz1 = 0;
1033     if (binz2 > nbinsz+1 || binz2 < binz1) binz2 = nbinsz+1;
1034     } else {
1035     binz1 = 0; binz2 = 0;
1036     }
1037    
1038     // - Loop on bins in specified range
1039     TString opt = option;
1040     opt.ToLower();
1041     Bool_t width = kFALSE;
1042     if (opt.Contains("width")) width = kTRUE;
1043    
1044    
1045     Double_t dx = 1.;
1046     Double_t dy = 1.;
1047     Double_t dz = 1.;
1048     Double_t integral = 0;
1049     Double_t igerr2 = 0;
1050     for (Int_t binx = binx1; binx <= binx2; ++binx) {
1051     if (width) dx = histo->GetXaxis()->GetBinWidth(binx);
1052     for (Int_t biny = biny1; biny <= biny2; ++biny) {
1053     if (width) dy = histo->GetYaxis()->GetBinWidth(biny);
1054     for (Int_t binz = binz1; binz <= binz2; ++binz) {
1055     if (width) dz = histo->GetZaxis()->GetBinWidth(binz);
1056     Int_t bin = histo->GetBin(binx, biny, binz);
1057     if (width) integral += histo->GetBinContent(bin)*dx*dy*dz;
1058     else integral += histo->GetBinContent(bin);
1059     if (doError) {
1060     if (width) igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin)*dx*dx*dy*dy*dz*dz;
1061     else igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin);
1062     }
1063     }
1064     }
1065     }
1066    
1067     if (doError) error = TMath::Sqrt(igerr2);
1068     return integral;
1069     }
1070    
1071     Double_t IntegralAndError(TH1F *histo, Int_t binx1, Int_t binx2, Double_t & error, Option_t *option)
1072     {
1073     //Return integral of bin contents in range [binx1,binx2] and its error
1074     // By default the integral is computed as the sum of bin contents in the range.
1075     // if option "width" is specified, the integral is the sum of
1076     // the bin contents multiplied by the bin width in x.
1077     // the error is computed using error propagation from the bin errors assumming that
1078     // all the bins are uncorrelated
1079     return DoIntegral(histo,binx1,binx2,0,-1,0,-1,error,option,kTRUE);
1080 buchmann 1.21 }
1081    
1082     void print_usage() {
1083     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;
1084 buchmann 1.22 }
1085    
1086    
1087     string format_number( int value )
1088     {
1089     if( value == 0 ) return "00";
1090     if( value < 10 ) return "0"+any2string(value);
1091     return any2string(value);
1092     }
1093    
1094     string seconds_to_time(int seconds) {
1095     const static unsigned int SECONDS_IN_AN_HOUR = 3600;
1096     const static unsigned int SECONDS_IN_A_MINUTE = 60;
1097     stringstream answer;
1098     if( seconds > 0 )
1099     {
1100     answer << format_number( (unsigned int)(seconds / SECONDS_IN_AN_HOUR) ) << ":";
1101     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE) ) << ":";
1102     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) % (SECONDS_IN_A_MINUTE)) );
1103     }
1104     else
1105     {
1106     answer << "00:00:00";
1107     }
1108     return answer.str();
1109     }
1110 buchmann 1.29
1111     bool Contains(string wholestring, string findme) {
1112 buchmann 1.30 if((int)wholestring.find(findme)>-1) return true;
1113 buchmann 1.29 else return false;
1114 fronga 1.31 }
1115 buchmann 1.35
1116     //////////////////////////////////////////////////////////////////////////////
1117     //
1118     // http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
1119     // process_mem_usage(double &, double &) - takes two doubles by reference,
1120     // attempts to read the system-dependent data for a process' virtual memory
1121     // size and resident set size, and return the results in KB.
1122     //
1123     // On failure, returns 0.0, 0.0
1124    
1125     /* usage:
1126     double vm2, rss2;
1127     process_mem_usage(vm2, rss2);
1128     cout << "Memory usage: VM: " << vm << "; RSS: " << rss << endl;
1129     */
1130    
1131     void process_mem_usage(double& vm_usage, double& resident_set)
1132     {
1133     using std::ios_base;
1134     using std::ifstream;
1135     using std::string;
1136    
1137     vm_usage = 0.0;
1138     resident_set = 0.0;
1139    
1140     // 'file' stat seems to give the most reliable results
1141     //
1142     ifstream stat_stream("/proc/self/stat",ios_base::in);
1143    
1144     // dummy vars for leading entries in stat that we don't care about
1145     //
1146     string pid, comm, state, ppid, pgrp, session, tty_nr;
1147     string tpgid, flags, minflt, cminflt, majflt, cmajflt;
1148     string utime, stime, cutime, cstime, priority, nice;
1149     string O, itrealvalue, starttime;
1150    
1151     // the two fields we want
1152     //
1153     unsigned long vsize;
1154     long rss;
1155    
1156     stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
1157     >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
1158     >> utime >> stime >> cutime >> cstime >> priority >> nice
1159     >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
1160    
1161     stat_stream.close();
1162    
1163     long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
1164     vm_usage = vsize / 1024.0;
1165     resident_set = rss * page_size_kb;
1166     }
1167 buchmann 1.38
1168 buchmann 1.45 TGraphAsymmErrors* produce_ratio_graph(TH1F *baseratio) {
1169 buchmann 1.38 int nbins=baseratio->GetNbinsX();
1170     double x[nbins];
1171     double y[nbins];
1172     double ex[nbins];
1173     double ey[nbins];
1174    
1175     for(int ibin=1;ibin<=nbins;ibin++) {
1176     x[ibin-1]=baseratio->GetBinCenter(ibin);
1177     y[ibin-1]=baseratio->GetBinContent(ibin);
1178     ex[ibin-1]=0.5*baseratio->GetBinWidth(ibin);
1179     ey[ibin-1]=baseratio->GetBinError(ibin);
1180     }
1181    
1182 buchmann 1.45 TGraphAsymmErrors *result = new TGraphAsymmErrors(nbins, x,y,ex,ex,ey,ey);
1183 buchmann 1.38 return result;
1184     }
1185    
1186 buchmann 1.45 void save_with_ratio(TH1F *nominator, TH1F *denominator, TVirtualPad *canvas, string savemeas, bool do_bpred_ratio=false, bool extendrange=false) {
1187     //this function saves the pad being passed as well as a new one including the ratio.
1188     CompleteSave(canvas,savemeas);
1189    
1190 buchmann 1.38 float bottommargin=gStyle->GetPadBottomMargin();
1191     float canvas_height=gStyle->GetCanvasDefH();
1192     float canvas_width=gStyle->GetCanvasDefW();
1193     float ratiospace=0.25;// space the ratio should take up (relative to original pad)
1194    
1195     float ratiobottommargin=0.3;
1196     float ratiotopmargin=0.1;
1197    
1198     float xstretchfactor=((1-ratiospace)*(1-gStyle->GetPadTopMargin()))/((1)*ratiospace);
1199    
1200 buchmann 1.48 TCanvas *main_canvas = new TCanvas("main_canvas","main_canvas",(Int_t)canvas_width,(Int_t)(canvas_height*(1+ratiospace)));
1201 buchmann 1.38 TPad *mainpad = new TPad("mainpad","mainpad",0,1-(1.0/(1+ratiospace)),1,1);//top (main) pad
1202 buchmann 1.46 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
1203     TPad *bottompad = new TPad("bottompad", "Ratio Pad",0,0,1,(1-(1-bottommargin)/(1+ratiospace))-0.015); //bottom pad
1204 buchmann 1.38
1205     main_canvas->Range(0,0,1,1);
1206     main_canvas->SetBorderSize(0);
1207     main_canvas->SetFrameFillColor(0);
1208    
1209     mainpad->Draw();
1210     mainpad->cd();
1211     mainpad->Range(0,0,1,1);
1212     mainpad->SetFillColor(kWhite);
1213     mainpad->SetBorderSize(0);
1214     mainpad->SetFrameFillColor(0);
1215     canvas->Range(0,0,1,1);
1216     canvas->Draw("same");
1217     mainpad->Modified();
1218     main_canvas->cd();
1219 buchmann 1.46 coverpad->Draw();
1220     coverpad->cd();
1221     coverpad->Range(0,0,1,1);
1222     coverpad->SetFillColor(kWhite);
1223     coverpad->SetBorderSize(0);
1224     coverpad->SetFrameFillColor(0);
1225     coverpad->Modified();
1226     main_canvas->cd();
1227 buchmann 1.38 bottompad->SetTopMargin(ratiotopmargin);
1228     bottompad->SetBottomMargin(ratiobottommargin);
1229     bottompad->Draw();
1230     bottompad->cd();
1231     bottompad->Range(0,0,1,1);
1232     bottompad->SetFillColor(kWhite);
1233     TH1F *ratio = (TH1F*)nominator->Clone(GetNumericHistoName().c_str());
1234     ratio->Divide(denominator);
1235 buchmann 1.45
1236    
1237     TGraphAsymmErrors *eratio;
1238     if(!do_bpred_ratio) eratio = produce_ratio_graph(ratio);
1239     else {
1240     bool using_data=false;
1241     if((int)savemeas.find("Data")>0) using_data=true;
1242     eratio = histRatio(nominator,denominator,using_data,PlottingSetup::global_ratio_binning,false);
1243     for(int i=1;i<=ratio->GetNbinsX();i++) {
1244     ratio->SetBinContent(i,0);
1245     ratio->SetBinError(i,0);
1246     }
1247     }
1248 buchmann 1.38 eratio->SetFillColor(TColor::GetColor("#00ADE1"));
1249    
1250     ratio->SetTitle("");
1251     ratio->GetYaxis()->SetRangeUser(0.5,1.5);
1252 buchmann 1.45 if(do_bpred_ratio) ratio->GetYaxis()->SetRangeUser(0.0,2.0);
1253     if(extendrange) ratio->GetYaxis()->SetRangeUser(0.0,4.0);
1254 buchmann 1.38 ratio->GetXaxis()->SetTitle(nominator->GetXaxis()->GetTitle());
1255     ratio->GetXaxis()->CenterTitle();
1256     ratio->GetYaxis()->SetTitle("ratio");
1257     ratio->GetYaxis()->SetTitleOffset(0.4);
1258     ratio->GetYaxis()->CenterTitle();
1259     ratio->SetStats(0);
1260     ratio->GetXaxis()->SetLabelSize(xstretchfactor*ratio->GetXaxis()->GetLabelSize());
1261     ratio->GetYaxis()->SetLabelSize(xstretchfactor*ratio->GetYaxis()->GetLabelSize());
1262     ratio->GetXaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1263     ratio->GetYaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1264     ratio->GetYaxis()->SetNdivisions(502,false);
1265     ratio->SetFillColor(TColor::GetColor("#58D3F7"));
1266     ratio->SetMarkerSize(0);
1267     ratio->Draw("e2");
1268     eratio->Draw("2");
1269     ratio->Draw("same,axis");
1270     TLine *oneline = new TLine(ratio->GetXaxis()->GetBinLowEdge(1),1,ratio->GetXaxis()->GetBinLowEdge(ratio->GetNbinsX())+ratio->GetXaxis()->GetBinWidth(ratio->GetNbinsX()),1);
1271     oneline->SetLineStyle(2);
1272     oneline->SetLineColor(kBlue);
1273     oneline->Draw("same");
1274    
1275     main_canvas->cd();
1276     main_canvas->Modified();
1277     main_canvas->cd();
1278     main_canvas->SetSelected(main_canvas);
1279    
1280 buchmann 1.45 CompleteSave(main_canvas,savemeas+"_withratio");
1281     delete main_canvas;
1282 buchmann 1.38 }
1283    
1284    
1285     TH1F* CollapseStack(THStack stack) {
1286     TH1F *bhist = ((TH1F*)((stack.GetHists())->At(0)));
1287     TH1F *basehisto = (TH1F*)bhist->Clone("base");
1288     TIter next(stack.GetHists());
1289     TH1F *h;
1290     int counter=0;
1291     while ((h=(TH1F*)next())) {
1292     counter++;
1293     if(counter==1) continue;
1294     basehisto->Add(h);
1295     }
1296     return basehisto;
1297     }
1298    
1299 buchmann 1.45 void save_with_ratio(TH1F *nominator, THStack denominator, TVirtualPad *canvas, string savemeas, bool do_bpred_ratio=false) {
1300     save_with_ratio(nominator, CollapseStack(denominator), canvas, savemeas, do_bpred_ratio);
1301 buchmann 1.38 }
1302    
1303 buchmann 1.40 void flag_this_change(string function, int line, int checked=0) {
1304 buchmann 1.38 stringstream peakmodificationwarning;
1305 buchmann 1.40 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 :-) ";
1306     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)";
1307     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.";
1308    
1309    
1310     if(checked==0) write_warning(function,peakmodificationwarning.str());
1311     // if(checked==1) write_info(function,peakmodificationwarning.str());
1312     peakmodificationwarning << " This modification has been checked and the changes have been reproduced. Checks completed.";
1313     if(checked==2) write_info(function,peakmodificationwarning.str());
1314     }
1315    
1316 buchmann 1.41 void write_analysis_type(bool isonpeak) {
1317     //http://www.network-science.de/ascii/, ogre
1318 buchmann 1.42
1319 buchmann 1.41 if(isonpeak) {
1320 buchmann 1.42 dout << "\033[1;34m" << endl;
1321 buchmann 1.41 dout << " //\\\\ _ _ _ " << endl;
1322     dout << " // \\\\ ___ _ __ _ __ ___ __ _| | __ __ _ _ __ __ _| |_ _ ___(_)___" << endl;
1323     dout << " // \\\\ / _ \\| '_ \\| '_ \\ / _ \\/ _` | |/ / / _` | '_ \\ / _` | | | | / __| / __|" << endl;
1324     dout << " // \\\\ | (_) | | | | |_) | __/ (_| | < | (_| | | | | (_| | | |_| \\__ \\ \\__ \\" << endl;
1325     dout << "// \\\\ \\___/|_| |_| .__/ \\___|\\__,_|_|\\_\\ \\__,_|_| |_|\\__,_|_|\\__, |___/_|___/" << endl;
1326     dout << " |_| |___/" << endl;
1327     } else {
1328 buchmann 1.42 dout << "\033[1;33m" << endl;
1329 buchmann 1.41 dout << " __ __ _ _ _ " << endl;
1330     dout << " ___ / _|/ _|_ __ ___ __ _| | __ __ _ _ __ __ _| |_ _ ___(_)___ " << endl;
1331     dout << " /\\ / _ \\| |_| |_| '_ \\ / _ \\/ _` | |/ / / _` | '_ \\ / _` | | | | / __| / __|" << endl;
1332     dout << " __/ \\__ | (_) | _| _| |_) | __/ (_| | < | (_| | | | | (_| | | |_| \\__ \\ \\__ \\" << endl;
1333     dout << " \\___/|_| |_| | .__/ \\___|\\__,_|_|\\_\\ \\__,_|_| |_|\\__,_|_|\\__, |___/_|___/" << endl;
1334     dout << " |_| |___/ " << endl;
1335     }
1336     dout << "\033[0m" << endl;
1337     }
1338    
1339    
1340 buchmann 1.43 vector<string> StringSplit(string str, string delim)
1341     {
1342     vector<string> results;
1343    
1344     int cutAt;
1345     while( (cutAt = str.find_first_of(delim)) != str.npos )
1346     {
1347     if(cutAt > 0)
1348     {
1349     results.push_back(str.substr(0,cutAt));
1350     }
1351     str = str.substr(cutAt+1);
1352     }
1353     if(str.length() > 0)
1354     {
1355     results.push_back(str);
1356     }
1357     return results;
1358     }
1359 buchmann 1.41
1360 buchmann 1.43 void manually_set_jzb_cuts(vector<float> &jzb_cut,string jzbcut_string) {
1361     vector<string> jzbcutvector = StringSplit(jzbcut_string,",");
1362     for(int i=0;i<jzbcutvector.size();i++) {
1363     jzb_cut.push_back(atoi(jzbcutvector[i].c_str()));
1364     dout << "Added a JZB cut manually at " << atoi(jzbcutvector[i].c_str()) << endl;
1365     }
1366     }
1367 buchmann 1.41
1368 buchmann 1.44 void process_directory(TString directory, vector<string> &files)
1369     {
1370     DIR *dp;
1371     struct dirent *ep;
1372    
1373     dp = opendir (directory);
1374     if (dp != NULL)
1375     {
1376     while (ep = readdir (dp))
1377     {
1378     string filename=(string)ep->d_name;
1379     if(filename.find(".root")!=-1)
1380     {
1381     files.push_back(string(directory)+filename);
1382     }
1383     }
1384     (void) closedir (dp);
1385     }
1386     else
1387     perror ("Couldn't open the directory");
1388     }
1389 buchmann 1.41
1390 buchmann 1.47 string GetCompleteHostname() {
1391     struct addrinfo hints, *info, *p;
1392     int gai_result;
1393     char hostname[1024];
1394     hostname[1023] = '\0';
1395     gethostname(hostname, 1023);
1396    
1397     string answer="GetCompleteHostname_ERROR";
1398    
1399     memset(&hints, 0, sizeof hints);
1400     hints.ai_family = AF_UNSPEC;
1401     hints.ai_socktype = SOCK_STREAM;
1402     hints.ai_flags = AI_CANONNAME;
1403    
1404     if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
1405     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
1406     }
1407    
1408     for(p = info; p != NULL; p = p->ai_next) {
1409     answer=p->ai_canonname;
1410     printf("hostname: %s\n", p->ai_canonname);
1411     }
1412     return answer;
1413     }
1414    
1415 buchmann 1.40 stringstream all_bugs;
1416    
1417     void bug_tracker(string function, int line, string description) {
1418     cout << "\033[1;31m .-. " << endl;
1419     cout << " o \\ .-. " << endl;
1420     cout << " .----.' \\ " << endl;
1421     cout << " .'o) / `. o " << endl;
1422     cout << " / | " << endl;
1423     cout << " \\_) /-. " << endl;
1424     cout << " '_.` \\ \\ " << endl;
1425     cout << " `. | \\ " << endl;
1426     cout << " | \\ | " << endl;
1427     cout << " .--/`-. / / " << endl;
1428     cout << " .'.-/`-. `. .\\| " << endl;
1429     cout << " /.' /`._ `- '-. " << endl;
1430     cout << " ____(|__/`-..`- '-._ \\ " << endl;
1431     cout << " |`------.'-._ ` ||\\ \\ " << endl;
1432     cout << " || # /-. ` / || \\| " << endl;
1433     cout << " || #/ `--' / /_::_|)__ " << endl;
1434     cout << " `|____|-._.-` / ||`--------` " << endl;
1435     cout << " \\-.___.` | / || # | " << endl;
1436     cout << " \\ | | || # # | " << endl;
1437     cout << " /`.___.'\\ |.`|________| " << endl;
1438     cout << " | /`.__.'|'.` " << endl;
1439     cout << " __/ \\ __/ \\ " << endl;
1440     cout << " /__.-.) /__.-.) LGB " << endl;
1441     cout << "" << endl;
1442     // bug ascii from : http://www.chris.com/ASCII/index.php?art=animals/insects/other
1443     cout << "There is a bug in " << function << " on line " << line << endl;
1444     cout << "The bug description is : " << description << endl;
1445     all_bugs << "There is a bug in " << function << " on line " << line << endl;
1446     all_bugs << "The bug description is : " << description << " \033[0m" << endl;
1447 buchmann 1.38 }
1448 buchmann 1.40
1449     //TODO: Write a bug summary at the end.
1450