ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/AnalysisFramework/Plotting/Modules/GeneralToolBox.C
Revision: 1.47
Committed: Tue Nov 8 08:45:29 2011 UTC (13 years, 6 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.46: +31 -0 lines
Log Message:
Better detection of host for scans (plus safety check before deleting anything)

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->SetBorderSize(0.1);
545     eventSelectionPaveText->SetFillColor(kWhite);
546     eventSelectionPaveText->SetTextFont(42);
547     eventSelectionPaveText->SetTextSize(0.042);
548     eventSelectionPaveText->AddText(prelimtext.str().c_str());
549     eventSelectionPaveText->Draw();
550     }
551    
552 buchmann 1.27 void DrawMCPrelim(float writelumi=generaltoolboxlumi) {
553     DrawPrelim(writelumi,true);
554     }
555    
556 buchmann 1.26 TLegend* make_legend(string title="", float posx=0.6, float posy=0.55, bool drawleg=true)
557 buchmann 1.1 {
558     gStyle->SetTextFont(42);
559 buchmann 1.7 TLegend *leg = new TLegend(posx,posy,0.89,0.89);
560 buchmann 1.1 if(title!="") leg->SetHeader(title.c_str());
561     leg->SetTextFont(42);
562 fronga 1.17 leg->SetTextSize(0.04);
563 buchmann 1.1 leg->SetFillColor(kWhite);
564     leg->SetBorderSize(0);
565     leg->SetLineColor(kWhite);
566 buchmann 1.26 if(drawleg) DrawPrelim();
567 buchmann 1.1 return leg;
568     }
569    
570 buchmann 1.26 TLegend* make_legend(bool drawleg, string title) {
571     return make_legend(title,0.6,0.55,drawleg);
572     }
573    
574 buchmann 1.1 TGraph* make_nice_ratio(int nbins,float binning[],TH1F* histo)
575     {
576     float errorsquared[nbins];
577     float errors[nbins];
578     float bincontent[nbins];
579     for (int i=0;i<nbins;i++) {
580     errorsquared[i]=0;
581     bincontent[i]=0;
582     errors[i]=0;
583     }
584     float currlimit=binning[0];
585     int currtoplim=1;
586     for(int ibin=1;ibin<=histo->GetNbinsX();ibin++)
587     {
588     if(binning[currtoplim]<histo->GetBinCenter(ibin)) currtoplim++;
589 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;
590 buchmann 1.1
591     }
592    
593     return 0;
594     }
595    
596     float statErrorN(float x){return x - 0.5*TMath::ChisquareQuantile(0.3173/2,2*x);}
597     float statErrorP(float x){return 0.5*TMath::ChisquareQuantile(1-0.3173/2,2*(x+1))-x;}
598     float lowLimit(float a, float x){return 0.5*TMath::ChisquareQuantile(a,2*x);}
599     float highLimit(float a,float x){return 0.5*TMath::ChisquareQuantile(1-a,2*(x+1));}
600    
601     float computeRatioError(float a, float da, float b, float db)
602     {
603     float val=0.;
604     float errorSquare = (a/b)*(a/b)*( (da/a)*(da/a) + (db/b)*(db/b));
605     val = TMath::Sqrt(errorSquare);
606     return val;
607    
608     }
609     float computeProductError(float a, float da, float b, float db)
610     {
611     float val=0.;
612     float errorSquare = (a*b)*(a*b)*( (da/a)*(da/a) + (db/b)*(db/b));
613     val = TMath::Sqrt(errorSquare);
614     return val;
615     }
616    
617 buchmann 1.23 TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning, bool precise=false)
618 buchmann 1.1 {
619     int absJZBbinsNumber = binning.size()-1;
620     TGraphAsymmErrors* graph = new TGraphAsymmErrors(absJZBbinsNumber);
621    
622     for(unsigned int i=0;i<absJZBbinsNumber;i++)
623     {
624     float xCenter=h1->GetBinCenter(i+1);
625     float xWidth=(h1->GetBinWidth(i+1))*0.5;
626     float nominatorError = h1->GetBinError(i+1);
627     float nominator=h1->GetBinContent(i+1);
628     float denominatorError=h2->GetBinError(i+1);
629     float denominator=h2->GetBinContent(i+1);
630     float errorN = 0;
631     float errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
632     if(id==1) // (is data)
633     {
634 buchmann 1.23 if(!precise) errorP = computeRatioError(nominator,statErrorP(nominator),denominator,statErrorP(denominator));
635     else errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
636 buchmann 1.1 errorN = errorP; // symmetrize using statErrorP
637     } else {
638     errorN = computeRatioError(nominator,nominatorError,denominator,denominatorError);
639 buchmann 1.23 errorP = errorN;
640 buchmann 1.1 }
641     if(denominator!=0) {
642     graph->SetPoint(i, xCenter, nominator/denominator);
643     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
644     }
645     else {
646     graph->SetPoint(i, xCenter, -999);
647     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
648     }
649     }
650     return graph;
651     }
652    
653     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!
654     float uperr=0,downerr=0;
655     if(down>up&&down>cent) uperr=down-cent;
656     if(up>down&&up>cent) uperr=up-cent;
657     if(down<cent&&down<up) downerr=cent-down;
658     if(up<cent&&up<down) downerr=cent-up;
659     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!");
660     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!");
661     stringstream result;
662     result << cent << " + " << uperr << " - " << downerr;
663     return result.str();
664     }
665    
666     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")
667     {
668     int last = size - 2;
669     int isChanged = 1;
670    
671     while ( last >= 0 && isChanged )
672     {
673     isChanged = 0;
674     for ( int k = 0; k <= last; k++ )
675     if ( arr[k] > arr[k+1] )
676     {
677     swap ( arr[k], arr[k+1] );
678     isChanged = 1;
679     int bkp=order[k];
680     order[k]=order[k+1];
681     order[k+1]=bkp;
682     }
683     last--;
684     }
685     }
686    
687     void swapvec(vector<float> &vec,int j, int k) {
688     float bkp=vec[j];
689     vec[j]=vec[k];
690     vec[k]=bkp;
691     }
692    
693     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")
694     {
695     int last = arr.size() - 2;
696     int isChanged = 1;
697    
698     while ( last >= 0 && isChanged )
699     {
700     isChanged = 0;
701     for ( int k = 0; k <= last; k++ )
702     if ( arr[k] > arr[k+1] )
703     {
704     swapvec (arr,k,k+1);
705     isChanged = 1;
706     int bkp=order[k];
707     order[k]=order[k+1];
708     order[k+1]=bkp;
709     }
710     last--;
711     }
712     }
713    
714     int numerichistoname=0;
715 buchmann 1.16 bool givingnumber=false;
716 buchmann 1.1 string GetNumericHistoName() {
717 buchmann 1.16 while(givingnumber) sleep(1);
718     givingnumber=true;
719 buchmann 1.1 stringstream b;
720     b << "h_" << numerichistoname;
721     numerichistoname++;
722 buchmann 1.16 givingnumber=false;
723 buchmann 1.1 return b.str();
724     }
725    
726     //********************** BELOW : CUT INTERPRETATION **************************//
727     void splitupcut(string incut, vector<string> &partvector)
728     {
729     //idea: go thru the string called incut; if a parantheses is opened, then the cut cannot be split up until the parantheses is closed.
730     //ok anyway screw the parantheses.
731     int paranthesis_open=0;
732     int substr_start=0;
733     string currchar="";
734     for (int ichar=0;ichar<incut.length();ichar++)
735     {
736     currchar=incut.substr(ichar,1);
737     // if(currchar=="(") paranthesis_open++;
738     // if(currchar==")") paranthesis_open--;
739     if(currchar=="&"&&incut.substr(ichar+1,1)=="&"&&paranthesis_open==0) {
740     partvector.push_back(incut.substr(substr_start,ichar-substr_start));
741     substr_start=ichar+2;
742     }
743     }
744     partvector.push_back(incut.substr(substr_start,incut.length()-substr_start));
745     if(Verbosity>1) {
746 buchmann 1.13 dout << "[ splitupcut() ] : The cut vector now contains the following elements: "<< endl;
747 buchmann 1.1 for (int ipart=0;ipart<partvector.size();ipart++)
748     {
749 buchmann 1.13 dout << " - " << partvector[ipart] << endl;
750 buchmann 1.1 }
751     }
752     }
753    
754     int atleastvalue(string expression, int &morethanlessthan) // takes in an expression such as ">2" or ">=3" and returns e.g. 3 (in both examples)
755     {
756     int retval=0;
757     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
758 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
759 buchmann 1.1 morethanlessthan=1;
760     return atoi(expression.substr(2,1).c_str());
761     }
762     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
763 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
764 buchmann 1.1 morethanlessthan=0;
765     return atoi(expression.substr(1,1).c_str());
766     }
767     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
768 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
769 buchmann 1.1 morethanlessthan=-1;
770     return 1+atoi(expression.substr(1,1).c_str());
771     }
772     if(expression.substr(0,1)==">") {
773 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
774 buchmann 1.1 morethanlessthan=1;
775     return 1+atoi(expression.substr(2,1).c_str());
776     }
777     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
778 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
779 buchmann 1.1 morethanlessthan=-1;
780     return 1+atoi(expression.substr(2,1).c_str());
781     }
782     }
783    
784     int do_jet_cut(string incut, int *nJets) {
785     string expression=(incut.substr(12,incut.size()-12));
786 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;
787 buchmann 1.1 if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
788     int nJet=atoi(expression.substr(2,1).c_str());
789     for(int i=nJet+1;i<20;i++) nJets[i]=0;
790 buchmann 1.13 dout << "Is of type <=" << endl;
791 buchmann 1.1 return 0;
792     }
793     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
794     int nJet=atoi(expression.substr(2,1).c_str());
795     for(int i=0;i<20&&i!=nJet;i++) nJets[i]=0;
796 buchmann 1.13 dout << "Is of type ==" << endl;
797 buchmann 1.1 return 0;
798     }
799     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
800     int nJet=atoi(expression.substr(2,1).c_str());
801     for(int i=0;i<nJet&&i!=nJet;i++) nJets[i]=0;
802 buchmann 1.13 dout << "Is of type >=" << endl;
803 buchmann 1.1 return 0;
804     }
805     if(expression.substr(0,1)=="<") {
806     int nJet=atoi(expression.substr(1,1).c_str());
807     for(int i=nJet;i<20;i++) nJets[i]=0;
808 buchmann 1.13 dout << "Is of type <" << endl;
809 buchmann 1.1 return 0;
810     }
811     if(expression.substr(0,1)==">") {
812     int nJet=atoi(expression.substr(1,1).c_str());
813     for(int i=0;i<nJet+1&&i!=nJet;i++) nJets[i]=0;
814 buchmann 1.13 dout << "Is of type >" << endl;
815 buchmann 1.1 return 0;
816     }
817     }
818    
819     string interpret_cut(string incut, bool &isJetCut, int *permittednJets)
820     {
821     // isJetCut=false;nJets=-1;
822     if(incut=="()") return "";
823     while(incut.substr(0,1)=="(") incut=incut.substr(1,incut.length()-1);
824     while(incut.length()>0&&incut.substr(incut.length()-1,1)==")") incut=incut.substr(0,incut.length()-1);
825     // 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.
826    
827     if(Verbosity>0) {
828 buchmann 1.13 dout << "Now interpreting cut " << incut << endl;
829 buchmann 1.1 }
830     /*
831     if(incut=="ch1*ch2<0") return "OS";
832     if(incut=="id1==id2") return "SF";
833     if(incut=="id1!=id2") return "OF";
834     */
835     if(incut=="ch1*ch2<0") return "";
836 buchmann 1.5 if(incut=="(mll>55&&mll<70)||(mll>112&&mll<160)") return "SB";
837     if(incut=="(mll>61&&mll<70)||(mll>112&&mll<190)") return "SB'";
838 buchmann 1.1 if(incut=="id1==id2") return "";
839     if(incut=="id1!=id2") return "";
840     if(incut=="mll>2") return "";
841    
842     if(incut=="mll>0") return ""; // my typical "fake cut"
843    
844     if(incut=="passed_triggers||!is_data") return "Triggers";
845     if(incut=="pfjzb[0]>-998") return "";
846    
847    
848     if(incut=="id1==0") return "ee";
849     if(incut=="id1==1") return "#mu#mu";
850     if(incut=="abs(mll-91.2)<20") return "|m_{l^{+}l^{-}}-m_{Z}|<20";
851     if(incut=="pfJetGoodID[0]") return "";
852     if(incut=="pfJetGoodID[1]") return "";
853     if((int)incut.find("pfJetGoodNum")>-1) {
854     //do_jet_cut(incut,permittednJets);
855     stringstream result;
856     result << "nJets" << incut.substr(12,incut.size()-12);
857 buchmann 1.13 /* dout << "Dealing with a jet cut: " << incut << endl;
858 buchmann 1.1 stringstream result;
859     result << "nJets" << incut.substr(12,incut.size()-12);
860     isJetCut=true;
861     if(exactjetcut(incut,nJets))
862     // nJets=atleastvalue((incut.substr(12,incut.size()-12)),morethanlessthan);
863     return result.str();*/
864     return result.str();
865     }
866     return incut;
867     }
868    
869     string interpret_nJet_range(int *nJets) {
870 buchmann 1.13 for (int i=0;i<20;i++) dout << i << " : " << nJets[i] << endl;
871 buchmann 1.1 return "hello";
872     }
873    
874     string interpret_cuts(vector<string> &cutparts)
875     {
876     stringstream nicecut;
877     int nJets;
878     bool isJetCut;
879     int finalJetCut=-1;
880     int permittednJets[20];
881     for(int ijet=0;ijet<20;ijet++) permittednJets[ijet]=1;
882     int morethanlessthan=0;//-1: less than, 0: exactly, 1: more than
883     for(int icut=0;icut<cutparts.size();icut++)
884     {
885     if(icut==0) nicecut<<interpret_cut(cutparts[icut],isJetCut,permittednJets);
886     else {
887     string nice_this_cut = interpret_cut(cutparts[icut],isJetCut,permittednJets);//blublu
888     if(nice_this_cut.length()>0&&nicecut.str().length()>0) {
889     if(!isJetCut) nicecut<<"&&"<<nice_this_cut;
890     else {
891     if(nJets>finalJetCut) finalJetCut=nJets;
892     }
893     }
894     if(nice_this_cut.length()>0&&nicecut.str().length()==0) {
895     if(!isJetCut) {
896     nicecut<<nice_this_cut;
897     }
898     else {
899     if(nJets>finalJetCut) finalJetCut=nJets;
900     }
901     }
902     }
903     }
904     if(finalJetCut>-1) {
905     if(nicecut.str().length()==0) {
906     nicecut << "nJets#geq" << finalJetCut;
907     }
908     else
909     {
910     nicecut << "&&nJets#geq " << finalJetCut;
911     }
912     }
913    
914 buchmann 1.13 // dout << "The nJet allowed range is given by: " << interpret_nJet_range(permittednJets) << endl;
915 buchmann 1.1
916     return nicecut.str();
917     }
918    
919     string decipher_cut(TCut originalcut,TCut ignorethispart)
920     {
921     string incut=(const char*)originalcut;
922     string ignore=(const char*)ignorethispart;
923    
924     if(ignore.length()>0 && incut.find(ignore)!=string::npos) incut=incut.replace(incut.find(ignore),ignore.length(),"");
925    
926     vector<string>cutparts;
927     splitupcut(incut,cutparts);
928     string write_cut=interpret_cuts(cutparts);
929     return write_cut;
930     }
931    
932     //********************** ABOVE : CUT INTERPRETATION **************************//
933 buchmann 1.2
934     Double_t GausRandom(Double_t mu, Double_t sigma) {
935     return gRandom->Gaus(mu,sigma);// real deal
936     //return mu;//debugging : no smearing.
937     }
938    
939 buchmann 1.3 int functionalhistocounter=0;
940 buchmann 1.2 TH1F * makehistofromfunction(TF1 *f1,TH1F *model) {
941     TH1F *histo = (TH1F*)model->Clone();
942 buchmann 1.3 functionalhistocounter++;
943     stringstream histoname;
944     histoname << "histo_based_on_function_" << f1->GetName() << "__"<<functionalhistocounter;
945     histo->SetTitle(histoname.str().c_str());
946     histo->SetName(histoname.str().c_str());
947 buchmann 1.2 int nbins=histo->GetNbinsX();
948     float low=histo->GetBinLowEdge(1);
949     float hi=histo->GetBinLowEdge(histo->GetNbinsX())+histo->GetBinWidth(histo->GetNbinsX());
950    
951     for(int i=0;i<=nbins;i++) {
952 buchmann 1.4 histo->SetBinContent(i,(f1->Integral(histo->GetBinLowEdge(i),histo->GetBinLowEdge(i)+histo->GetBinWidth(i)))/histo->GetBinWidth(i));
953     histo->SetBinError(i,TMath::Sqrt(histo->GetBinContent(i)));
954 buchmann 1.2 }
955    
956     return histo;
957 buchmann 1.4 }
958    
959     float hintegral(TH1 *histo, float low, float high) {
960     float sum=0;
961     for(int i=1;i<histo->GetNbinsX();i++) {
962     if((histo->GetBinLowEdge(i)>=low)&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))<=high) sum+=histo->GetBinContent(i);
963     //now on to the less clear cases!
964     if(histo->GetBinLowEdge(i)<low&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>low) {
965     //need to consider this case still ... the bin is kind of in range but not sooooo much.
966     }
967     if(histo->GetBinLowEdge(i)<high&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>high) {
968     //need to consider this case still ... the bin is kind of in range but not sooooo much.
969     }
970    
971     }
972     return sum;
973 buchmann 1.5 }
974    
975 buchmann 1.6 string newjzbexpression(string oldexpression,float shift) {
976     stringstream ss;
977     if(shift>0) ss<<"("<<oldexpression<<"+"<<shift<<")";
978     if(shift<0) ss<<"("<<oldexpression<<shift<<")";
979     if(shift==0) ss<<oldexpression;
980     return ss.str();
981     }
982    
983 buchmann 1.29 float Round(float num, unsigned int dig)
984 buchmann 1.11 {
985     num *= pow(10, dig);
986     if (num >= 0)
987     num = floor(num + 0.5);
988     else
989     num = ceil(num - 0.5);
990     num/= pow(10, dig);
991     return num;
992 buchmann 1.16 }
993    
994 buchmann 1.29 float SigDig(float num, int digits) {
995     //produces a number with only the given number of significant digits
996    
997     }
998    
999 buchmann 1.16 // The two functions below are for distributed processing
1000    
1001     int get_job_number(float ipoint, float Npoints,float Njobs) {
1002     float pointposition=(ipoint/Npoints);
1003     int njob=floor(pointposition*Njobs);
1004     if(njob>=Njobs) njob--;
1005     // cout << "Looking at point " << ipoint << " out of " << Npoints << " which is at position " << pointposition << " corresponding to " << pointposition*Njobs << " --> JOB " << njob << endl;
1006     return njob;
1007     }
1008    
1009    
1010     bool do_this_point(int ipoint, int Npoints, int jobnumber, int Njobs) {
1011     if(get_job_number(ipoint,Npoints,Njobs)==jobnumber) return true;
1012     return false;
1013     }
1014 buchmann 1.19
1015     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 ,
1016     Option_t *option, Bool_t doError)
1017     {
1018     // internal function compute integral and optionally the error between the limits
1019     // specified by the bin number values working for all histograms (1D, 2D and 3D)
1020    
1021     Int_t nbinsx = histo->GetNbinsX();
1022     if (binx1 < 0) binx1 = 0;
1023     if (binx2 > nbinsx+1 || binx2 < binx1) binx2 = nbinsx+1;
1024     if (histo->GetDimension() > 1) {
1025     Int_t nbinsy = histo->GetNbinsY();
1026     if (biny1 < 0) biny1 = 0;
1027     if (biny2 > nbinsy+1 || biny2 < biny1) biny2 = nbinsy+1;
1028     } else {
1029     biny1 = 0; biny2 = 0;
1030     }
1031     if (histo->GetDimension() > 2) {
1032     Int_t nbinsz = histo->GetNbinsZ();
1033     if (binz1 < 0) binz1 = 0;
1034     if (binz2 > nbinsz+1 || binz2 < binz1) binz2 = nbinsz+1;
1035     } else {
1036     binz1 = 0; binz2 = 0;
1037     }
1038    
1039     // - Loop on bins in specified range
1040     TString opt = option;
1041     opt.ToLower();
1042     Bool_t width = kFALSE;
1043     if (opt.Contains("width")) width = kTRUE;
1044    
1045    
1046     Double_t dx = 1.;
1047     Double_t dy = 1.;
1048     Double_t dz = 1.;
1049     Double_t integral = 0;
1050     Double_t igerr2 = 0;
1051     for (Int_t binx = binx1; binx <= binx2; ++binx) {
1052     if (width) dx = histo->GetXaxis()->GetBinWidth(binx);
1053     for (Int_t biny = biny1; biny <= biny2; ++biny) {
1054     if (width) dy = histo->GetYaxis()->GetBinWidth(biny);
1055     for (Int_t binz = binz1; binz <= binz2; ++binz) {
1056     if (width) dz = histo->GetZaxis()->GetBinWidth(binz);
1057     Int_t bin = histo->GetBin(binx, biny, binz);
1058     if (width) integral += histo->GetBinContent(bin)*dx*dy*dz;
1059     else integral += histo->GetBinContent(bin);
1060     if (doError) {
1061     if (width) igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin)*dx*dx*dy*dy*dz*dz;
1062     else igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin);
1063     }
1064     }
1065     }
1066     }
1067    
1068     if (doError) error = TMath::Sqrt(igerr2);
1069     return integral;
1070     }
1071    
1072     Double_t IntegralAndError(TH1F *histo, Int_t binx1, Int_t binx2, Double_t & error, Option_t *option)
1073     {
1074     //Return integral of bin contents in range [binx1,binx2] and its error
1075     // By default the integral is computed as the sum of bin contents in the range.
1076     // if option "width" is specified, the integral is the sum of
1077     // the bin contents multiplied by the bin width in x.
1078     // the error is computed using error propagation from the bin errors assumming that
1079     // all the bins are uncorrelated
1080     return DoIntegral(histo,binx1,binx2,0,-1,0,-1,error,option,kTRUE);
1081 buchmann 1.21 }
1082    
1083     void print_usage() {
1084     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;
1085 buchmann 1.22 }
1086    
1087    
1088     string format_number( int value )
1089     {
1090     if( value == 0 ) return "00";
1091     if( value < 10 ) return "0"+any2string(value);
1092     return any2string(value);
1093     }
1094    
1095     string seconds_to_time(int seconds) {
1096     const static unsigned int SECONDS_IN_AN_HOUR = 3600;
1097     const static unsigned int SECONDS_IN_A_MINUTE = 60;
1098     stringstream answer;
1099     if( seconds > 0 )
1100     {
1101     answer << format_number( (unsigned int)(seconds / SECONDS_IN_AN_HOUR) ) << ":";
1102     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE) ) << ":";
1103     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) % (SECONDS_IN_A_MINUTE)) );
1104     }
1105     else
1106     {
1107     answer << "00:00:00";
1108     }
1109     return answer.str();
1110     }
1111 buchmann 1.29
1112     bool Contains(string wholestring, string findme) {
1113 buchmann 1.30 if((int)wholestring.find(findme)>-1) return true;
1114 buchmann 1.29 else return false;
1115 fronga 1.31 }
1116 buchmann 1.35
1117     //////////////////////////////////////////////////////////////////////////////
1118     //
1119     // http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
1120     // process_mem_usage(double &, double &) - takes two doubles by reference,
1121     // attempts to read the system-dependent data for a process' virtual memory
1122     // size and resident set size, and return the results in KB.
1123     //
1124     // On failure, returns 0.0, 0.0
1125    
1126     /* usage:
1127     double vm2, rss2;
1128     process_mem_usage(vm2, rss2);
1129     cout << "Memory usage: VM: " << vm << "; RSS: " << rss << endl;
1130     */
1131    
1132     void process_mem_usage(double& vm_usage, double& resident_set)
1133     {
1134     using std::ios_base;
1135     using std::ifstream;
1136     using std::string;
1137    
1138     vm_usage = 0.0;
1139     resident_set = 0.0;
1140    
1141     // 'file' stat seems to give the most reliable results
1142     //
1143     ifstream stat_stream("/proc/self/stat",ios_base::in);
1144    
1145     // dummy vars for leading entries in stat that we don't care about
1146     //
1147     string pid, comm, state, ppid, pgrp, session, tty_nr;
1148     string tpgid, flags, minflt, cminflt, majflt, cmajflt;
1149     string utime, stime, cutime, cstime, priority, nice;
1150     string O, itrealvalue, starttime;
1151    
1152     // the two fields we want
1153     //
1154     unsigned long vsize;
1155     long rss;
1156    
1157     stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
1158     >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
1159     >> utime >> stime >> cutime >> cstime >> priority >> nice
1160     >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
1161    
1162     stat_stream.close();
1163    
1164     long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
1165     vm_usage = vsize / 1024.0;
1166     resident_set = rss * page_size_kb;
1167     }
1168 buchmann 1.38
1169 buchmann 1.45 TGraphAsymmErrors* produce_ratio_graph(TH1F *baseratio) {
1170 buchmann 1.38 int nbins=baseratio->GetNbinsX();
1171     double x[nbins];
1172     double y[nbins];
1173     double ex[nbins];
1174     double ey[nbins];
1175    
1176     for(int ibin=1;ibin<=nbins;ibin++) {
1177     x[ibin-1]=baseratio->GetBinCenter(ibin);
1178     y[ibin-1]=baseratio->GetBinContent(ibin);
1179     ex[ibin-1]=0.5*baseratio->GetBinWidth(ibin);
1180     ey[ibin-1]=baseratio->GetBinError(ibin);
1181     }
1182    
1183 buchmann 1.45 TGraphAsymmErrors *result = new TGraphAsymmErrors(nbins, x,y,ex,ex,ey,ey);
1184 buchmann 1.38 return result;
1185     }
1186    
1187 buchmann 1.45 void save_with_ratio(TH1F *nominator, TH1F *denominator, TVirtualPad *canvas, string savemeas, bool do_bpred_ratio=false, bool extendrange=false) {
1188     //this function saves the pad being passed as well as a new one including the ratio.
1189     CompleteSave(canvas,savemeas);
1190    
1191 buchmann 1.38 float bottommargin=gStyle->GetPadBottomMargin();
1192     float canvas_height=gStyle->GetCanvasDefH();
1193     float canvas_width=gStyle->GetCanvasDefW();
1194     float ratiospace=0.25;// space the ratio should take up (relative to original pad)
1195    
1196     float ratiobottommargin=0.3;
1197     float ratiotopmargin=0.1;
1198    
1199     float xstretchfactor=((1-ratiospace)*(1-gStyle->GetPadTopMargin()))/((1)*ratiospace);
1200    
1201     TCanvas *main_canvas = new TCanvas("main_canvas","main_canvas",canvas_width,canvas_height*(1+ratiospace));
1202     TPad *mainpad = new TPad("mainpad","mainpad",0,1-(1.0/(1+ratiospace)),1,1);//top (main) pad
1203 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
1204     TPad *bottompad = new TPad("bottompad", "Ratio Pad",0,0,1,(1-(1-bottommargin)/(1+ratiospace))-0.015); //bottom pad
1205 buchmann 1.38
1206     main_canvas->Range(0,0,1,1);
1207     main_canvas->SetBorderSize(0);
1208     main_canvas->SetFrameFillColor(0);
1209    
1210     mainpad->Draw();
1211     mainpad->cd();
1212     mainpad->Range(0,0,1,1);
1213     mainpad->SetFillColor(kWhite);
1214     mainpad->SetBorderSize(0);
1215     mainpad->SetFrameFillColor(0);
1216     canvas->Range(0,0,1,1);
1217     canvas->Draw("same");
1218     mainpad->Modified();
1219     main_canvas->cd();
1220 buchmann 1.46 coverpad->Draw();
1221     coverpad->cd();
1222     coverpad->Range(0,0,1,1);
1223     coverpad->SetFillColor(kWhite);
1224     coverpad->SetBorderSize(0);
1225     coverpad->SetFrameFillColor(0);
1226     coverpad->Modified();
1227     main_canvas->cd();
1228 buchmann 1.38 bottompad->SetTopMargin(ratiotopmargin);
1229     bottompad->SetBottomMargin(ratiobottommargin);
1230     bottompad->Draw();
1231     bottompad->cd();
1232     bottompad->Range(0,0,1,1);
1233     bottompad->SetFillColor(kWhite);
1234     TH1F *ratio = (TH1F*)nominator->Clone(GetNumericHistoName().c_str());
1235     ratio->Divide(denominator);
1236 buchmann 1.45
1237    
1238     TGraphAsymmErrors *eratio;
1239     if(!do_bpred_ratio) eratio = produce_ratio_graph(ratio);
1240     else {
1241     bool using_data=false;
1242     if((int)savemeas.find("Data")>0) using_data=true;
1243     eratio = histRatio(nominator,denominator,using_data,PlottingSetup::global_ratio_binning,false);
1244     for(int i=1;i<=ratio->GetNbinsX();i++) {
1245     ratio->SetBinContent(i,0);
1246     ratio->SetBinError(i,0);
1247     }
1248     }
1249 buchmann 1.38 eratio->SetFillColor(TColor::GetColor("#00ADE1"));
1250    
1251     ratio->SetTitle("");
1252     ratio->GetYaxis()->SetRangeUser(0.5,1.5);
1253 buchmann 1.45 if(do_bpred_ratio) ratio->GetYaxis()->SetRangeUser(0.0,2.0);
1254     if(extendrange) ratio->GetYaxis()->SetRangeUser(0.0,4.0);
1255 buchmann 1.38 ratio->GetXaxis()->SetTitle(nominator->GetXaxis()->GetTitle());
1256     ratio->GetXaxis()->CenterTitle();
1257     ratio->GetYaxis()->SetTitle("ratio");
1258     ratio->GetYaxis()->SetTitleOffset(0.4);
1259     ratio->GetYaxis()->CenterTitle();
1260     ratio->SetStats(0);
1261     ratio->GetXaxis()->SetLabelSize(xstretchfactor*ratio->GetXaxis()->GetLabelSize());
1262     ratio->GetYaxis()->SetLabelSize(xstretchfactor*ratio->GetYaxis()->GetLabelSize());
1263     ratio->GetXaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1264     ratio->GetYaxis()->SetTitleSize(xstretchfactor*gStyle->GetTitleSize());
1265     ratio->GetYaxis()->SetNdivisions(502,false);
1266     ratio->SetFillColor(TColor::GetColor("#58D3F7"));
1267     ratio->SetMarkerSize(0);
1268     ratio->Draw("e2");
1269     eratio->Draw("2");
1270     ratio->Draw("same,axis");
1271     TLine *oneline = new TLine(ratio->GetXaxis()->GetBinLowEdge(1),1,ratio->GetXaxis()->GetBinLowEdge(ratio->GetNbinsX())+ratio->GetXaxis()->GetBinWidth(ratio->GetNbinsX()),1);
1272     oneline->SetLineStyle(2);
1273     oneline->SetLineColor(kBlue);
1274     oneline->Draw("same");
1275    
1276     main_canvas->cd();
1277     main_canvas->Modified();
1278     main_canvas->cd();
1279     main_canvas->SetSelected(main_canvas);
1280    
1281 buchmann 1.45 CompleteSave(main_canvas,savemeas+"_withratio");
1282     delete main_canvas;
1283 buchmann 1.38 }
1284    
1285    
1286     TH1F* CollapseStack(THStack stack) {
1287     TH1F *bhist = ((TH1F*)((stack.GetHists())->At(0)));
1288     TH1F *basehisto = (TH1F*)bhist->Clone("base");
1289     TIter next(stack.GetHists());
1290     TH1F *h;
1291     int counter=0;
1292     while ((h=(TH1F*)next())) {
1293     counter++;
1294     if(counter==1) continue;
1295     basehisto->Add(h);
1296     }
1297     return basehisto;
1298     }
1299    
1300 buchmann 1.45 void save_with_ratio(TH1F *nominator, THStack denominator, TVirtualPad *canvas, string savemeas, bool do_bpred_ratio=false) {
1301     save_with_ratio(nominator, CollapseStack(denominator), canvas, savemeas, do_bpred_ratio);
1302 buchmann 1.38 }
1303    
1304 buchmann 1.40 void flag_this_change(string function, int line, int checked=0) {
1305 buchmann 1.38 stringstream peakmodificationwarning;
1306 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 :-) ";
1307     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)";
1308     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.";
1309    
1310    
1311     if(checked==0) write_warning(function,peakmodificationwarning.str());
1312     // if(checked==1) write_info(function,peakmodificationwarning.str());
1313     peakmodificationwarning << " This modification has been checked and the changes have been reproduced. Checks completed.";
1314     if(checked==2) write_info(function,peakmodificationwarning.str());
1315     }
1316    
1317 buchmann 1.41 void write_analysis_type(bool isonpeak) {
1318     //http://www.network-science.de/ascii/, ogre
1319 buchmann 1.42
1320 buchmann 1.41 if(isonpeak) {
1321 buchmann 1.42 dout << "\033[1;34m" << endl;
1322 buchmann 1.41 dout << " //\\\\ _ _ _ " << endl;
1323     dout << " // \\\\ ___ _ __ _ __ ___ __ _| | __ __ _ _ __ __ _| |_ _ ___(_)___" << endl;
1324     dout << " // \\\\ / _ \\| '_ \\| '_ \\ / _ \\/ _` | |/ / / _` | '_ \\ / _` | | | | / __| / __|" << endl;
1325     dout << " // \\\\ | (_) | | | | |_) | __/ (_| | < | (_| | | | | (_| | | |_| \\__ \\ \\__ \\" << endl;
1326     dout << "// \\\\ \\___/|_| |_| .__/ \\___|\\__,_|_|\\_\\ \\__,_|_| |_|\\__,_|_|\\__, |___/_|___/" << endl;
1327     dout << " |_| |___/" << endl;
1328     } else {
1329 buchmann 1.42 dout << "\033[1;33m" << endl;
1330 buchmann 1.41 dout << " __ __ _ _ _ " << endl;
1331     dout << " ___ / _|/ _|_ __ ___ __ _| | __ __ _ _ __ __ _| |_ _ ___(_)___ " << endl;
1332     dout << " /\\ / _ \\| |_| |_| '_ \\ / _ \\/ _` | |/ / / _` | '_ \\ / _` | | | | / __| / __|" << endl;
1333     dout << " __/ \\__ | (_) | _| _| |_) | __/ (_| | < | (_| | | | | (_| | | |_| \\__ \\ \\__ \\" << endl;
1334     dout << " \\___/|_| |_| | .__/ \\___|\\__,_|_|\\_\\ \\__,_|_| |_|\\__,_|_|\\__, |___/_|___/" << endl;
1335     dout << " |_| |___/ " << endl;
1336     }
1337     dout << "\033[0m" << endl;
1338     }
1339    
1340    
1341 buchmann 1.43 vector<string> StringSplit(string str, string delim)
1342     {
1343     vector<string> results;
1344    
1345     int cutAt;
1346     while( (cutAt = str.find_first_of(delim)) != str.npos )
1347     {
1348     if(cutAt > 0)
1349     {
1350     results.push_back(str.substr(0,cutAt));
1351     }
1352     str = str.substr(cutAt+1);
1353     }
1354     if(str.length() > 0)
1355     {
1356     results.push_back(str);
1357     }
1358     return results;
1359     }
1360 buchmann 1.41
1361 buchmann 1.43 void manually_set_jzb_cuts(vector<float> &jzb_cut,string jzbcut_string) {
1362     vector<string> jzbcutvector = StringSplit(jzbcut_string,",");
1363     for(int i=0;i<jzbcutvector.size();i++) {
1364     jzb_cut.push_back(atoi(jzbcutvector[i].c_str()));
1365     dout << "Added a JZB cut manually at " << atoi(jzbcutvector[i].c_str()) << endl;
1366     }
1367     }
1368 buchmann 1.41
1369 buchmann 1.44 void process_directory(TString directory, vector<string> &files)
1370     {
1371     DIR *dp;
1372     struct dirent *ep;
1373    
1374     dp = opendir (directory);
1375     if (dp != NULL)
1376     {
1377     while (ep = readdir (dp))
1378     {
1379     string filename=(string)ep->d_name;
1380     if(filename.find(".root")!=-1)
1381     {
1382     files.push_back(string(directory)+filename);
1383     }
1384     }
1385     (void) closedir (dp);
1386     }
1387     else
1388     perror ("Couldn't open the directory");
1389     }
1390 buchmann 1.41
1391 buchmann 1.47 string GetCompleteHostname() {
1392     struct addrinfo hints, *info, *p;
1393     int gai_result;
1394     char hostname[1024];
1395     hostname[1023] = '\0';
1396     gethostname(hostname, 1023);
1397    
1398     string answer="GetCompleteHostname_ERROR";
1399    
1400     memset(&hints, 0, sizeof hints);
1401     hints.ai_family = AF_UNSPEC;
1402     hints.ai_socktype = SOCK_STREAM;
1403     hints.ai_flags = AI_CANONNAME;
1404    
1405     if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
1406     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
1407     }
1408    
1409     for(p = info; p != NULL; p = p->ai_next) {
1410     answer=p->ai_canonname;
1411     printf("hostname: %s\n", p->ai_canonname);
1412     }
1413     return answer;
1414     }
1415    
1416 buchmann 1.40 stringstream all_bugs;
1417    
1418     void bug_tracker(string function, int line, string description) {
1419     cout << "\033[1;31m .-. " << endl;
1420     cout << " o \\ .-. " << endl;
1421     cout << " .----.' \\ " << endl;
1422     cout << " .'o) / `. o " << 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 << " __/ \\ __/ \\ " << endl;
1441     cout << " /__.-.) /__.-.) LGB " << endl;
1442     cout << "" << endl;
1443     // bug ascii from : http://www.chris.com/ASCII/index.php?art=animals/insects/other
1444     cout << "There is a bug in " << function << " on line " << line << endl;
1445     cout << "The bug description is : " << description << endl;
1446     all_bugs << "There is a bug in " << function << " on line " << line << endl;
1447     all_bugs << "The bug description is : " << description << " \033[0m" << endl;
1448 buchmann 1.38 }
1449 buchmann 1.40
1450     //TODO: Write a bug summary at the end.
1451