ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/cbrown/AnalysisFramework/Plotting/Modules/GeneralToolBox.C
Revision: 1.36
Committed: Thu Sep 29 14:16:17 2011 UTC (13 years, 7 months ago) by buchmann
Content type: text/plain
Branch: MAIN
Changes since 1.35: +7 -0 lines
Log Message:
Added a function to allow us to flag modified code segments and to verify that they have been double checked

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.1
12     #include <TFile.h>
13     #include <TTree.h>
14     #include <TCut.h>
15     #include <TLegend.h>
16     #include <TLatex.h>
17     #include <TText.h>
18     #include <TGraph.h>
19     #include <TH1.h>
20 buchmann 1.2 #include <TF1.h>
21 buchmann 1.1 #include <TMath.h>
22     #include <TStyle.h>
23     #include <TCanvas.h>
24     #include <TError.h>
25 buchmann 1.3 #include <TVirtualPad.h>
26 buchmann 1.1 #include <TGraphAsymmErrors.h>
27 buchmann 1.7 #include <TPaveText.h>
28 buchmann 1.1 #include <TRandom.h>
29     #ifndef Verbosity
30     #define Verbosity 0
31     #endif
32    
33     /*
34     #ifndef SampleClassLoaded
35     #include "SampleClass.C"
36     #endif
37     */
38     #define GeneralToolBoxLoaded
39    
40     using namespace std;
41    
42 buchmann 1.32 namespace PlottingSetup {
43     string cbafbasedir="";
44 buchmann 1.34 string basedirectory="";
45 buchmann 1.32 }
46    
47 buchmann 1.1 bool dopng=false;
48     bool doC=false;
49     bool doeps=false;
50 buchmann 1.5 bool dopdf=false;
51 buchmann 1.33 bool doroot=false;
52 buchmann 1.26 float generaltoolboxlumi;
53 buchmann 1.1
54 buchmann 1.26 TLegend* make_legend(string title,float posx,float posy, bool drawleg);
55     TText* write_title(bool, string);
56 buchmann 1.1 TText* write_title_low(string title);
57    
58     TText* write_text(float xpos,float ypos,string title);
59     float computeRatioError(float a, float da, float b, float db);
60     float computeProductError(float a, float da, float b, float db);
61     TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning);
62     void setlumi(float l);
63 buchmann 1.26 void DrawPrelim(float writelumi);
64 buchmann 1.1 void CompleteSave(TCanvas *can, string filename, bool feedback);
65 buchmann 1.3 void CompleteSave(TVirtualPad *can, string filename, bool feedback);
66 buchmann 1.1 void write_warning(string funcname, string text);
67     void write_error(string funcname, string text);
68     void write_info(string funcname, string text);
69 buchmann 1.13 string get_directory();
70 buchmann 1.1 //-------------------------------------------------------------------------------------
71 buchmann 1.13
72 buchmann 1.15 template<typename U>
73     inline bool isanyinf(U value)
74     {
75     return !(value >= std::numeric_limits<U>::min() && value <=
76     std::numeric_limits<U>::max());
77     }
78 buchmann 1.13
79 buchmann 1.32 stringstream warningsummary;
80     stringstream infosummary;
81     stringstream errorsummary;
82    
83 buchmann 1.1 template<class A>
84     string any2string(const A& a){
85     ostringstream out;
86     out << a;
87     return out.str();
88     }
89    
90     void do_png(bool s) { dopng=s;}
91     void do_eps(bool s) { doeps=s;}
92     void do_C(bool s) { doC=s;}
93 buchmann 1.33 void do_pdf(bool s) { dopdf=s;}
94     void do_root(bool s){ doroot=s;}
95 buchmann 1.1
96     string topdir(string child) {
97     string tempdirectory=child;
98     if(tempdirectory.substr(tempdirectory.length()-1,1)=="/") tempdirectory=tempdirectory.substr(0,tempdirectory.length());
99     //we now have a directory without the trailing slash so we can just look for the last non-slash character :-)
100     for(int ichar=tempdirectory.length()-1;ichar>=0;ichar--) {
101     if(tempdirectory.substr(ichar,1)=="/") {
102     return tempdirectory.substr(0,ichar);
103     }
104     }
105     }
106    
107 buchmann 1.12 template < typename CHAR_TYPE,
108     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
109    
110     struct basic_teebuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
111     {
112     typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
113     typedef typename TRAITS_TYPE::int_type int_type ;
114    
115     basic_teebuf( streambuf_type* buff_a, streambuf_type* buff_b )
116     : first(buff_a), second(buff_b) {}
117    
118     protected:
119     virtual int_type overflow( int_type c )
120     {
121     const int_type eof = TRAITS_TYPE::eof() ;
122     if( TRAITS_TYPE::eq_int_type( c, eof ) )
123     return TRAITS_TYPE::not_eof(c) ;
124     else
125     {
126     const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(c) ;
127     if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
128     TRAITS_TYPE::eq_int_type( second->sputc(ch), eof ) )
129     return eof ;
130     else return c ;
131     }
132     }
133    
134     virtual int sync()
135     { return !first->pubsync() && !second->pubsync() ? 0 : -1 ; }
136    
137     private:
138     streambuf_type* first ;
139     streambuf_type* second ;
140     };
141    
142     template < typename CHAR_TYPE,
143     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
144     struct basic_teestream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
145     {
146     typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
147     typedef basic_teebuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;
148    
149     basic_teestream( stream_type& first, stream_type& second )
150     : stream_type( &stmbuf), stmbuf( first.rdbuf(), second.rdbuf() ) {}
151    
152     ~basic_teestream() { stmbuf.pubsync() ; }
153    
154     private: streambuff_type stmbuf ;
155     };
156    
157     typedef basic_teebuf<char> teebuf ;
158     typedef basic_teestream<char> teestream ;
159    
160 buchmann 1.13 std::ofstream file("LOG.txt",ios::app) ;
161 buchmann 1.28 std::ofstream texfile("Tex.txt") ;
162 buchmann 1.14 std::ofstream efile("LOGerr.txt",ios::app) ;
163 buchmann 1.13 teestream dout( file, std::cout ) ; // double out
164     teestream eout( efile, std::cout ) ; // double out (errors)
165 buchmann 1.12
166 buchmann 1.28 template < typename CHAR_TYPE,
167     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
168    
169     struct basic_tripbuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
170     {
171     typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
172     typedef typename TRAITS_TYPE::int_type int_type ;
173    
174     basic_tripbuf( streambuf_type* buff_a, streambuf_type* buff_b, streambuf_type* buff_c )
175     : first(buff_a), second(buff_b), third(buff_c) {}
176    
177     protected:
178     virtual int_type overflow( int_type d )
179     {
180     const int_type eof = TRAITS_TYPE::eof() ;
181     if( TRAITS_TYPE::eq_int_type( d, eof ) )
182     return TRAITS_TYPE::not_eof(d) ;
183     else
184     {
185     const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(d) ;
186     if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
187     TRAITS_TYPE::eq_int_type( second->sputc(ch), eof )||
188     TRAITS_TYPE::eq_int_type( third->sputc(ch), eof ) )
189     return eof ;
190     else return d ;
191     }
192     }
193    
194     virtual int sync()
195     { return !first->pubsync() && !second->pubsync() && !third->pubsync() ? 0 : -1 ; }
196    
197     private:
198     streambuf_type* first ;
199     streambuf_type* second ;
200     streambuf_type* third ;
201     };
202    
203     template < typename CHAR_TYPE,
204     typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
205     struct basic_tripstream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
206     {
207     typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
208     typedef basic_tripbuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;
209    
210     basic_tripstream( stream_type& first, stream_type& second, stream_type& third )
211     : stream_type( &stmbuf), stmbuf( first.rdbuf(), second.rdbuf(), third.rdbuf() ) {}
212    
213     ~basic_tripstream() { stmbuf.pubsync() ; }
214    
215     private: streambuff_type stmbuf ;
216     };
217    
218     //typedef basic_tripbuf<char> teebuf ;
219     typedef basic_tripstream<char> tripplestream ;
220    
221     tripplestream tout( file, texfile , std::cout ) ; // tripple out
222    
223 buchmann 1.1 void ensure_directory_exists(string thisdirectory) {
224     struct stat st;
225     if(stat(thisdirectory.c_str(),&st) == 0) {
226 buchmann 1.13 if(Verbosity>0) dout << "Directory " << thisdirectory << " exists!" << endl;
227 buchmann 1.1 }
228     else {
229 buchmann 1.13 if(Verbosity>0) dout << "Directory " << thisdirectory << " does not exist. Need to create it!" << endl;
230 buchmann 1.1 ensure_directory_exists(topdir(thisdirectory));
231     if (mkdir(thisdirectory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
232 buchmann 1.13 if(Verbosity>0) dout << "Created the directory " << thisdirectory << endl;
233 buchmann 1.1 }
234     }
235    
236 buchmann 1.13 void initialize_log() {
237 buchmann 1.14 dout << "____________________________________________________________" << endl;
238     dout << endl;
239 buchmann 1.13 dout << " " << endl;
240     dout << " JJJJJJJJJJJZZZZZZZZZZZZZZZZZZZBBBBBBBBBBBBBBBBB " << endl;
241     dout << " J:::::::::JZ:::::::::::::::::ZB::::::::::::::::B " << endl;
242     dout << " J:::::::::JZ:::::::::::::::::ZB::::::BBBBBB:::::B " << endl;
243     dout << " JJ:::::::JJZ:::ZZZZZZZZ:::::Z BB:::::B B:::::B" << endl;
244     dout << " J:::::J ZZZZZ Z:::::Z B::::B B:::::B" << endl;
245     dout << " J:::::J Z:::::Z B::::B B:::::B" << endl;
246     dout << " J:::::J Z:::::Z B::::BBBBBB:::::B " << endl;
247     dout << " J:::::j Z:::::Z B:::::::::::::BB " << endl;
248     dout << " J:::::J Z:::::Z B::::BBBBBB:::::B " << endl;
249     dout << "JJJJJJJ J:::::J Z:::::Z B::::B B:::::B" << endl;
250     dout << "J:::::J J:::::J Z:::::Z B::::B B:::::B" << endl;
251     dout << "J::::::J J::::::J ZZZ:::::Z ZZZZZ B::::B B:::::B" << endl;
252     dout << "J:::::::JJJ:::::::J Z::::::ZZZZZZZZ:::ZBB:::::BBBBBB::::::B" << endl;
253     dout << " JJ:::::::::::::JJ Z:::::::::::::::::ZB:::::::::::::::::B " << endl;
254     dout << " JJ:::::::::JJ Z:::::::::::::::::ZB::::::::::::::::B " << endl;
255     dout << " JJJJJJJJJ ZZZZZZZZZZZZZZZZZZZBBBBBBBBBBBBBBBBB " << endl;
256     dout << " " << endl;
257     dout << endl << endl;
258     dout << "____________________________________________________________" << endl;
259     time_t rawtime;
260     struct tm * timeinfo;
261     time ( &rawtime );
262     dout << " Analysis run on " << asctime (localtime ( &rawtime ));
263     dout << "____________________________________________________________" << endl;
264     dout << " Results saved in : " << get_directory() << endl << endl;
265     }
266    
267 buchmann 1.32 void extract_cbaf_dir(string curpath) {
268     int position=curpath.find("/Plotting");
269     if(position<0) position=curpath.find("/DistributedModelCalculations");
270     if(position<0) position=curpath.find("/various_assignments");
271     PlottingSetup::cbafbasedir=curpath.substr(0,position);
272     }
273    
274 buchmann 1.1 void set_directory(string basedir="") {
275     if(basedir.substr(0,1)=="/") basedir=basedir.substr(1,basedir.length()-1);
276     if(basedir.substr(basedir.length()-1,1)!="/") basedir+="/";
277     char currentpath[1024];
278 buchmann 1.32 char *path = getcwd(currentpath,1024);
279 buchmann 1.34 PlottingSetup::basedirectory=(string)currentpath+"/Plots/"+basedir;
280     ensure_directory_exists(PlottingSetup::basedirectory);
281 buchmann 1.13 initialize_log();
282 buchmann 1.32 extract_cbaf_dir(currentpath);
283 buchmann 1.1 }
284    
285 buchmann 1.6 string get_directory() {
286 buchmann 1.34 return PlottingSetup::basedirectory;
287 buchmann 1.6 }
288    
289 buchmann 1.1 string extract_directory(string savethis) {
290     bool foundslash=false;
291     int position=savethis.length();
292     while(!foundslash&&position>0) {
293     position--;
294     if(savethis.substr(position,1)=="/") foundslash=true;
295     }
296     if(position>0) return savethis.substr(0,position+1);
297     else return "";
298     }
299    
300 buchmann 1.33 string extract_root_dir(string name) {
301     int position = -1;
302     if(name.substr(0,1)=="/") name=name.substr(1,name.length()-1);
303     for(int ipos=0;ipos<name.length();ipos++) {
304     if(name.substr(ipos,1)=="/") position=ipos;
305     }
306     if(position==-1) return "";
307     return name.substr(0,position);
308     }
309    
310     string extract_root_filename(string name) {
311     int position = -1;
312     if(name.substr(0,1)=="/") name=name.substr(1,name.length()-1);
313     for(int ipos=0;ipos<name.length();ipos++) {
314     if(name.substr(ipos,1)=="/") position=ipos;
315     }
316     return name.substr(position+1,name.length()-position-1);
317     }
318    
319     void SaveToRoot_REAL(TCanvas *can, string name) {
320 buchmann 1.34 TFile *fout = new TFile((TString(PlottingSetup::basedirectory)+TString("allplots.root")),"UPDATE");
321 buchmann 1.33 fout->cd();
322     string directory=extract_root_dir(name);
323     string filename=extract_root_filename(name);
324     if(directory!="") {
325     if(fout->GetDirectory(directory.c_str())) {
326     fout->cd(directory.c_str());
327     can->Write(filename.c_str());
328     }else {
329     fout->mkdir(directory.c_str());
330     fout->cd(directory.c_str());
331     can->Write(filename.c_str());
332     }
333     } else {
334     can->Write(filename.c_str());
335     }
336     fout->cd();
337     fout->Close();
338     }
339    
340     void SaveToRoot(TCanvas *can, string name) {
341     write_warning(__FUNCTION__,"Saving to root file has been deactivated (it works but when opening ROOT complains a bit about filenames which is unelegant)");
342     //if you want to activate this feature anyway, you can rename this to SaveToRoot_Placeholder and rename SaveToRoot_REAL to SaveToRoot.
343     }
344    
345 fronga 1.18 void CompleteSave(TCanvas *can, string filename, bool feedback=false, bool redraw=true) {
346 buchmann 1.3 //any change you make here should also be done below in the CompleteSave function for virtual pads
347 buchmann 1.1 Int_t currlevel=gErrorIgnoreLevel;
348     if(!feedback) gErrorIgnoreLevel=1001;
349 fronga 1.18 if(redraw) can->RedrawAxis();
350 buchmann 1.34 ensure_directory_exists(extract_directory(PlottingSetup::basedirectory+filename));
351     if(dopng) can->SaveAs((PlottingSetup::basedirectory+filename+".png").c_str());
352     if(doeps) can->SaveAs((PlottingSetup::basedirectory+filename+".eps").c_str());
353     if(dopdf) can->SaveAs((PlottingSetup::basedirectory+filename+".pdf").c_str());
354     if(doC) can->SaveAs((PlottingSetup::basedirectory+filename+".C").c_str());
355 buchmann 1.33 if(doroot) SaveToRoot(can,filename);
356 buchmann 1.1 gErrorIgnoreLevel=currlevel;
357 buchmann 1.13 dout << "Saved " << filename << " in all requested formats" << endl;
358 buchmann 1.1 }
359 buchmann 1.3
360 fronga 1.18 void CompleteSave(TVirtualPad *can, string filename, bool feedback=false, bool redraw=true) {
361 buchmann 1.3 Int_t currlevel=gErrorIgnoreLevel;
362     if(!feedback) gErrorIgnoreLevel=1001;
363 fronga 1.18 if(redraw) can->RedrawAxis();
364 buchmann 1.34 ensure_directory_exists(extract_directory(PlottingSetup::basedirectory+filename));
365     if(dopng) can->SaveAs((PlottingSetup::basedirectory+filename+".png").c_str());
366     if(doeps) can->SaveAs((PlottingSetup::basedirectory+filename+".eps").c_str());
367     if(doC) can->SaveAs((PlottingSetup::basedirectory+filename+".C").c_str());
368 buchmann 1.3 gErrorIgnoreLevel=currlevel;
369 buchmann 1.13 dout << "Saved " << filename << " in all requested formats" << endl;
370 buchmann 1.3 }
371    
372 buchmann 1.1
373     void setlumi(float l) {
374 buchmann 1.24 generaltoolboxlumi=l;
375 buchmann 1.1 }
376    
377     int write_first_line(vector<vector<string> > &entries) {
378     if(entries.size()>0) {
379     vector<string> firstline = entries[0];
380     int ncolumns=firstline.size();
381     int ndividers=ncolumns+1;
382     int cellwidth=(int)(((float)(60-ndividers))/(ncolumns));
383 buchmann 1.13 dout << " |";
384 buchmann 1.1 for(int idiv=0;idiv<ncolumns;idiv++) {
385 buchmann 1.13 for(int isig=0;isig<cellwidth;isig++) dout << "-";
386     dout << "|";
387 buchmann 1.1 }
388 buchmann 1.13 dout << endl;
389 buchmann 1.1 return ncolumns;
390     } else {
391     return 0;
392     }
393     }
394    
395     void write_entry(string entry,int width,int iline=0,int ientry=0) {
396     int currwidth=entry.size();
397     while(currwidth<width) {
398     entry=" "+entry;
399     if(entry.size()<width) entry=entry+" ";
400     currwidth=entry.size();
401     }
402     bool do_special=false;
403 buchmann 1.13 if(iline==1&&ientry==1) { dout << "\033[1;32m" << entry << "\033[0m|";do_special=true;}//observed
404     if(iline==1&&ientry==2) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
405     if(iline==2&&ientry==1) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
406     if(iline==2&&ientry==2) { dout << "\033[1;34m" << entry << "\033[0m|";do_special=true;}//predicted (1)
407     if(!do_special) dout << entry << "|";
408 buchmann 1.1 }
409    
410     void make_nice_table(vector<vector <string> > &entries) {
411     int ncolumns=write_first_line(entries);
412     int cellwidth=(int)(((float)(60-(ncolumns+1)))/(ncolumns));
413     for(int iline=0;iline<entries.size();iline++) {
414     vector<string> currline = entries[iline];
415 buchmann 1.13 dout << " |";
416 buchmann 1.1 for(int ientry=0;ientry<currline.size();ientry++) {
417     write_entry(currline[ientry],cellwidth);
418     }
419 buchmann 1.13 dout << endl;
420 buchmann 1.1 if(iline==0) write_first_line(entries);
421     }
422     write_first_line(entries);
423     }
424    
425     void make_nice_jzb_table(vector<vector <string> > &entries) {
426     int ncolumns=write_first_line(entries);
427     int cellwidth=(int)(((float)(60-(ncolumns+1)))/(ncolumns));
428     for(int iline=0;iline<entries.size();iline++) {
429     vector<string> currline = entries[iline];
430 buchmann 1.13 dout << " |";
431 buchmann 1.1 for(int ientry=0;ientry<currline.size();ientry++) {
432     write_entry(currline[ientry],cellwidth,iline,ientry);
433     }
434 buchmann 1.13 dout << endl;
435 buchmann 1.1 if(iline==0) write_first_line(entries);
436     }
437     write_first_line(entries);
438     }
439    
440    
441     void write_warning(string funcname, string text) {
442 buchmann 1.13 eout << endl << endl;
443     eout << "\033[1;33m" << " _ " << endl;
444     eout << "\033[1;33m" << " (_) " << endl;
445     eout << "\033[1;33m" << "__ ____ _ _ __ _ __ _ _ __ __ _ " << endl;
446     eout << "\033[1;33m" << "\\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` |" << endl;
447     eout << "\033[1;33m" << " \\ V V / (_| | | | | | | | | | | (_| |" << endl;
448     eout << "\033[1;33m" << " \\_/\\_/ \\__,_|_| |_| |_|_|_| |_|\\__, |" << endl;
449     eout << "\033[1;33m" << " __/ |" << endl;
450     eout << "\033[1;33m" << " |___/ " << endl;
451     eout << endl;
452     eout << "\033[1;33m [" << funcname << "] " << text << " \033[0m" << endl;
453     eout << endl << endl;
454 buchmann 1.32 warningsummary << "[" << funcname << "] " << text << endl;
455 buchmann 1.1 }
456     void write_error(string funcname, string text) {
457 buchmann 1.13 eout << endl << endl;
458     eout << "\033[1;31m ___ _ __ _ __ ___ _ __ " << endl;
459     eout << "\033[1;31m / _ \\ __| __/ _ \\| '__|" << endl;
460     eout << "\033[1;31m| __/ | | | | (_) | | " << endl;
461     eout << "\033[1;31m \\___|_| |_| \\___/|_| " << endl;
462     eout << endl;
463     eout << "\033[1;31m [" << funcname << "] " << text << " \033[0m" << endl;
464     eout << endl << endl;
465 buchmann 1.32 errorsummary << "[" << funcname << "] " << text << endl;
466 buchmann 1.1 }
467    
468     void write_info(string funcname, string text) {
469 buchmann 1.13 dout << endl << endl;
470     dout << "\033[1;34m _____ __ " << endl;
471     dout << "\033[1;34m |_ _| / _| " << endl;
472     dout << "\033[1;34m | | _ __ | |_ ___ " << endl;
473     dout << "\033[1;34m | | | '_ \\| _/ _ \\ " << endl;
474     dout << "\033[1;34m _| |_| | | | || (_) | " << endl;
475     dout << "\033[1;34m |_____|_| |_|_| \\___/ " << endl;
476     dout << endl;
477     dout << "\033[1;34m [" << funcname << "] " << text << " \033[0m" << endl;
478     dout << endl << endl;
479 buchmann 1.32 infosummary << "[" << funcname << "] " << text << endl;
480 buchmann 1.1 }
481    
482     TText* write_text(float xpos,float ypos,string title)
483     {
484     TLatex* titlebox = new TLatex (xpos,ypos,title.c_str());
485     titlebox->SetNDC(true);
486     titlebox->SetTextFont(42);
487     titlebox->SetTextSize(0.04);
488     titlebox->SetTextAlign(21);
489     return titlebox;
490     }
491    
492     TText* write_title(string title)
493     {
494 buchmann 1.15 TText* titlebox = write_text(0.5,0.945,title);
495 buchmann 1.1 return titlebox;
496     }
497    
498 buchmann 1.7 TText* write_cut_on_canvas(string cut) {
499     // TLatex *normbox = new TLatex(0.96,0.5,cut.c_str());
500     TLatex *normbox = new TLatex(0.96,0.5,"");//currently deactivated
501     normbox->SetNDC(true);
502     normbox->SetTextFont(42);
503     normbox->SetTextSize(0.01);
504     normbox->SetTextAlign(21);
505     normbox->SetTextAngle(270);
506     return normbox;
507     }
508    
509 buchmann 1.1 TText* write_title_low(string title)
510     {
511     TText* titlebox = write_text(0.5,0.94,title);
512     return titlebox;
513     }
514    
515 buchmann 1.27 void DrawPrelim(float writelumi=generaltoolboxlumi,bool isMC=false) {
516 buchmann 1.26 string barn="pb";
517     if(writelumi>=1000)
518     {
519     writelumi/=1000;
520     barn="fb";
521     }
522    
523     stringstream prelimtext;
524     //prelimtext << "CMS Preliminary 2011 , #sqrt{s}= 7 TeV, L= O(1) fb^{-1}"; //temporary replacement
525 fronga 1.31 if(isMC) prelimtext << "CMS MC Simulation , #sqrt{s} = 7 TeV, L_{int} = " << std::setprecision(2) <<writelumi<<" "<<barn<<"^{-1}";
526     else prelimtext << "CMS Preliminary, #sqrt{s} = 7 TeV, L_{int} = " << std::setprecision(2) <<writelumi<<" "<<barn<<"^{-1}";
527 buchmann 1.26 TPaveText *eventSelectionPaveText = new TPaveText(0.27, 0.93,0.77, 1.0,"blNDC");
528     eventSelectionPaveText->SetFillStyle(4000);
529     eventSelectionPaveText->SetBorderSize(0.1);
530     eventSelectionPaveText->SetFillColor(kWhite);
531     eventSelectionPaveText->SetTextFont(42);
532     eventSelectionPaveText->SetTextSize(0.042);
533     eventSelectionPaveText->AddText(prelimtext.str().c_str());
534     eventSelectionPaveText->Draw();
535     }
536    
537 buchmann 1.27 void DrawMCPrelim(float writelumi=generaltoolboxlumi) {
538     DrawPrelim(writelumi,true);
539     }
540    
541 buchmann 1.26 TLegend* make_legend(string title="", float posx=0.6, float posy=0.55, bool drawleg=true)
542 buchmann 1.1 {
543     gStyle->SetTextFont(42);
544 buchmann 1.7 TLegend *leg = new TLegend(posx,posy,0.89,0.89);
545 buchmann 1.1 if(title!="") leg->SetHeader(title.c_str());
546     leg->SetTextFont(42);
547 fronga 1.17 leg->SetTextSize(0.04);
548 buchmann 1.1 leg->SetFillColor(kWhite);
549     leg->SetBorderSize(0);
550     leg->SetLineColor(kWhite);
551 buchmann 1.26 if(drawleg) DrawPrelim();
552 buchmann 1.1 return leg;
553     }
554    
555 buchmann 1.26 TLegend* make_legend(bool drawleg, string title) {
556     return make_legend(title,0.6,0.55,drawleg);
557     }
558    
559 buchmann 1.1 TGraph* make_nice_ratio(int nbins,float binning[],TH1F* histo)
560     {
561     float errorsquared[nbins];
562     float errors[nbins];
563     float bincontent[nbins];
564     for (int i=0;i<nbins;i++) {
565     errorsquared[i]=0;
566     bincontent[i]=0;
567     errors[i]=0;
568     }
569     float currlimit=binning[0];
570     int currtoplim=1;
571     for(int ibin=1;ibin<=histo->GetNbinsX();ibin++)
572     {
573     if(binning[currtoplim]<histo->GetBinCenter(ibin)) currtoplim++;
574 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;
575 buchmann 1.1
576     }
577    
578     return 0;
579     }
580    
581     float statErrorN(float x){return x - 0.5*TMath::ChisquareQuantile(0.3173/2,2*x);}
582     float statErrorP(float x){return 0.5*TMath::ChisquareQuantile(1-0.3173/2,2*(x+1))-x;}
583     float lowLimit(float a, float x){return 0.5*TMath::ChisquareQuantile(a,2*x);}
584     float highLimit(float a,float x){return 0.5*TMath::ChisquareQuantile(1-a,2*(x+1));}
585    
586     float computeRatioError(float a, float da, float b, float db)
587     {
588     float val=0.;
589     float errorSquare = (a/b)*(a/b)*( (da/a)*(da/a) + (db/b)*(db/b));
590     val = TMath::Sqrt(errorSquare);
591     return val;
592    
593     }
594     float computeProductError(float a, float da, float b, float db)
595     {
596     float val=0.;
597     float errorSquare = (a*b)*(a*b)*( (da/a)*(da/a) + (db/b)*(db/b));
598     val = TMath::Sqrt(errorSquare);
599     return val;
600     }
601    
602 buchmann 1.23 TGraphAsymmErrors *histRatio(TH1F *h1,TH1F *h2, int id, vector<float>binning, bool precise=false)
603 buchmann 1.1 {
604     int absJZBbinsNumber = binning.size()-1;
605     TGraphAsymmErrors* graph = new TGraphAsymmErrors(absJZBbinsNumber);
606    
607     for(unsigned int i=0;i<absJZBbinsNumber;i++)
608     {
609     float xCenter=h1->GetBinCenter(i+1);
610     float xWidth=(h1->GetBinWidth(i+1))*0.5;
611     float nominatorError = h1->GetBinError(i+1);
612     float nominator=h1->GetBinContent(i+1);
613     float denominatorError=h2->GetBinError(i+1);
614     float denominator=h2->GetBinContent(i+1);
615     float errorN = 0;
616     float errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
617     if(id==1) // (is data)
618     {
619 buchmann 1.23 if(!precise) errorP = computeRatioError(nominator,statErrorP(nominator),denominator,statErrorP(denominator));
620     else errorP = computeRatioError(nominator,nominatorError,denominator,denominatorError);
621 buchmann 1.1 errorN = errorP; // symmetrize using statErrorP
622     } else {
623     errorN = computeRatioError(nominator,nominatorError,denominator,denominatorError);
624 buchmann 1.23 errorP = errorN;
625 buchmann 1.1 }
626     if(denominator!=0) {
627     graph->SetPoint(i, xCenter, nominator/denominator);
628     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
629     }
630     else {
631     graph->SetPoint(i, xCenter, -999);
632     graph->SetPointError(i,xWidth,xWidth,errorN,errorP);
633     }
634     }
635     return graph;
636     }
637    
638     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!
639     float uperr=0,downerr=0;
640     if(down>up&&down>cent) uperr=down-cent;
641     if(up>down&&up>cent) uperr=up-cent;
642     if(down<cent&&down<up) downerr=cent-down;
643     if(up<cent&&up<down) downerr=cent-up;
644     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!");
645     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!");
646     stringstream result;
647     result << cent << " + " << uperr << " - " << downerr;
648     return result.str();
649     }
650    
651     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")
652     {
653     int last = size - 2;
654     int isChanged = 1;
655    
656     while ( last >= 0 && isChanged )
657     {
658     isChanged = 0;
659     for ( int k = 0; k <= last; k++ )
660     if ( arr[k] > arr[k+1] )
661     {
662     swap ( arr[k], arr[k+1] );
663     isChanged = 1;
664     int bkp=order[k];
665     order[k]=order[k+1];
666     order[k+1]=bkp;
667     }
668     last--;
669     }
670     }
671    
672     void swapvec(vector<float> &vec,int j, int k) {
673     float bkp=vec[j];
674     vec[j]=vec[k];
675     vec[k]=bkp;
676     }
677    
678     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")
679     {
680     int last = arr.size() - 2;
681     int isChanged = 1;
682    
683     while ( last >= 0 && isChanged )
684     {
685     isChanged = 0;
686     for ( int k = 0; k <= last; k++ )
687     if ( arr[k] > arr[k+1] )
688     {
689     swapvec (arr,k,k+1);
690     isChanged = 1;
691     int bkp=order[k];
692     order[k]=order[k+1];
693     order[k+1]=bkp;
694     }
695     last--;
696     }
697     }
698    
699     int numerichistoname=0;
700 buchmann 1.16 bool givingnumber=false;
701 buchmann 1.1 string GetNumericHistoName() {
702 buchmann 1.16 while(givingnumber) sleep(1);
703     givingnumber=true;
704 buchmann 1.1 stringstream b;
705     b << "h_" << numerichistoname;
706     numerichistoname++;
707 buchmann 1.16 givingnumber=false;
708 buchmann 1.1 return b.str();
709     }
710    
711     //********************** BELOW : CUT INTERPRETATION **************************//
712     void splitupcut(string incut, vector<string> &partvector)
713     {
714     //idea: go thru the string called incut; if a parantheses is opened, then the cut cannot be split up until the parantheses is closed.
715     //ok anyway screw the parantheses.
716     int paranthesis_open=0;
717     int substr_start=0;
718     string currchar="";
719     for (int ichar=0;ichar<incut.length();ichar++)
720     {
721     currchar=incut.substr(ichar,1);
722     // if(currchar=="(") paranthesis_open++;
723     // if(currchar==")") paranthesis_open--;
724     if(currchar=="&"&&incut.substr(ichar+1,1)=="&"&&paranthesis_open==0) {
725     partvector.push_back(incut.substr(substr_start,ichar-substr_start));
726     substr_start=ichar+2;
727     }
728     }
729     partvector.push_back(incut.substr(substr_start,incut.length()-substr_start));
730     if(Verbosity>1) {
731 buchmann 1.13 dout << "[ splitupcut() ] : The cut vector now contains the following elements: "<< endl;
732 buchmann 1.1 for (int ipart=0;ipart<partvector.size();ipart++)
733     {
734 buchmann 1.13 dout << " - " << partvector[ipart] << endl;
735 buchmann 1.1 }
736     }
737     }
738    
739     int atleastvalue(string expression, int &morethanlessthan) // takes in an expression such as ">2" or ">=3" and returns e.g. 3 (in both examples)
740     {
741     int retval=0;
742     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
743 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(2,1).c_str()) << " jets" << endl;
744 buchmann 1.1 morethanlessthan=1;
745     return atoi(expression.substr(2,1).c_str());
746     }
747     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
748 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
749 buchmann 1.1 morethanlessthan=0;
750     return atoi(expression.substr(1,1).c_str());
751     }
752     if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
753 buchmann 1.13 // dout << "The expression " << expression << " is saying that we have at least " << atoi(expression.substr(1,1).c_str())+1 << " jets" << endl;
754 buchmann 1.1 morethanlessthan=-1;
755     return 1+atoi(expression.substr(1,1).c_str());
756     }
757     if(expression.substr(0,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 1+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(2,1).c_str()) << " jets" << endl;
764 buchmann 1.1 morethanlessthan=-1;
765     return 1+atoi(expression.substr(2,1).c_str());
766     }
767     }
768    
769     int do_jet_cut(string incut, int *nJets) {
770     string expression=(incut.substr(12,incut.size()-12));
771 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;
772 buchmann 1.1 if(expression.substr(0,1)=="<"&&expression.substr(1,1)=="=") {
773     int nJet=atoi(expression.substr(2,1).c_str());
774     for(int i=nJet+1;i<20;i++) nJets[i]=0;
775 buchmann 1.13 dout << "Is of type <=" << endl;
776 buchmann 1.1 return 0;
777     }
778     if(expression.substr(0,1)=="="&&expression.substr(1,1)=="=") {
779     int nJet=atoi(expression.substr(2,1).c_str());
780     for(int i=0;i<20&&i!=nJet;i++) nJets[i]=0;
781 buchmann 1.13 dout << "Is of type ==" << endl;
782 buchmann 1.1 return 0;
783     }
784     if(expression.substr(0,1)==">"&&expression.substr(1,1)=="=") {
785     int nJet=atoi(expression.substr(2,1).c_str());
786     for(int i=0;i<nJet&&i!=nJet;i++) nJets[i]=0;
787 buchmann 1.13 dout << "Is of type >=" << endl;
788 buchmann 1.1 return 0;
789     }
790     if(expression.substr(0,1)=="<") {
791     int nJet=atoi(expression.substr(1,1).c_str());
792     for(int i=nJet;i<20;i++) nJets[i]=0;
793 buchmann 1.13 dout << "Is of type <" << endl;
794 buchmann 1.1 return 0;
795     }
796     if(expression.substr(0,1)==">") {
797     int nJet=atoi(expression.substr(1,1).c_str());
798     for(int i=0;i<nJet+1&&i!=nJet;i++) nJets[i]=0;
799 buchmann 1.13 dout << "Is of type >" << endl;
800 buchmann 1.1 return 0;
801     }
802     }
803    
804     string interpret_cut(string incut, bool &isJetCut, int *permittednJets)
805     {
806     // isJetCut=false;nJets=-1;
807     if(incut=="()") return "";
808     while(incut.substr(0,1)=="(") incut=incut.substr(1,incut.length()-1);
809     while(incut.length()>0&&incut.substr(incut.length()-1,1)==")") incut=incut.substr(0,incut.length()-1);
810     // 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.
811    
812     if(Verbosity>0) {
813 buchmann 1.13 dout << "Now interpreting cut " << incut << endl;
814 buchmann 1.1 }
815     /*
816     if(incut=="ch1*ch2<0") return "OS";
817     if(incut=="id1==id2") return "SF";
818     if(incut=="id1!=id2") return "OF";
819     */
820     if(incut=="ch1*ch2<0") return "";
821 buchmann 1.5 if(incut=="(mll>55&&mll<70)||(mll>112&&mll<160)") return "SB";
822     if(incut=="(mll>61&&mll<70)||(mll>112&&mll<190)") return "SB'";
823 buchmann 1.1 if(incut=="id1==id2") return "";
824     if(incut=="id1!=id2") return "";
825     if(incut=="mll>2") return "";
826    
827     if(incut=="mll>0") return ""; // my typical "fake cut"
828    
829     if(incut=="passed_triggers||!is_data") return "Triggers";
830     if(incut=="pfjzb[0]>-998") return "";
831    
832    
833     if(incut=="id1==0") return "ee";
834     if(incut=="id1==1") return "#mu#mu";
835     if(incut=="abs(mll-91.2)<20") return "|m_{l^{+}l^{-}}-m_{Z}|<20";
836     if(incut=="pfJetGoodID[0]") return "";
837     if(incut=="pfJetGoodID[1]") return "";
838     if((int)incut.find("pfJetGoodNum")>-1) {
839     //do_jet_cut(incut,permittednJets);
840     stringstream result;
841     result << "nJets" << incut.substr(12,incut.size()-12);
842 buchmann 1.13 /* dout << "Dealing with a jet cut: " << incut << endl;
843 buchmann 1.1 stringstream result;
844     result << "nJets" << incut.substr(12,incut.size()-12);
845     isJetCut=true;
846     if(exactjetcut(incut,nJets))
847     // nJets=atleastvalue((incut.substr(12,incut.size()-12)),morethanlessthan);
848     return result.str();*/
849     return result.str();
850     }
851     return incut;
852     }
853    
854     string interpret_nJet_range(int *nJets) {
855 buchmann 1.13 for (int i=0;i<20;i++) dout << i << " : " << nJets[i] << endl;
856 buchmann 1.1 return "hello";
857     }
858    
859     string interpret_cuts(vector<string> &cutparts)
860     {
861     stringstream nicecut;
862     int nJets;
863     bool isJetCut;
864     int finalJetCut=-1;
865     int permittednJets[20];
866     for(int ijet=0;ijet<20;ijet++) permittednJets[ijet]=1;
867     int morethanlessthan=0;//-1: less than, 0: exactly, 1: more than
868     for(int icut=0;icut<cutparts.size();icut++)
869     {
870     if(icut==0) nicecut<<interpret_cut(cutparts[icut],isJetCut,permittednJets);
871     else {
872     string nice_this_cut = interpret_cut(cutparts[icut],isJetCut,permittednJets);//blublu
873     if(nice_this_cut.length()>0&&nicecut.str().length()>0) {
874     if(!isJetCut) nicecut<<"&&"<<nice_this_cut;
875     else {
876     if(nJets>finalJetCut) finalJetCut=nJets;
877     }
878     }
879     if(nice_this_cut.length()>0&&nicecut.str().length()==0) {
880     if(!isJetCut) {
881     nicecut<<nice_this_cut;
882     }
883     else {
884     if(nJets>finalJetCut) finalJetCut=nJets;
885     }
886     }
887     }
888     }
889     if(finalJetCut>-1) {
890     if(nicecut.str().length()==0) {
891     nicecut << "nJets#geq" << finalJetCut;
892     }
893     else
894     {
895     nicecut << "&&nJets#geq " << finalJetCut;
896     }
897     }
898    
899 buchmann 1.13 // dout << "The nJet allowed range is given by: " << interpret_nJet_range(permittednJets) << endl;
900 buchmann 1.1
901     return nicecut.str();
902     }
903    
904     string decipher_cut(TCut originalcut,TCut ignorethispart)
905     {
906     string incut=(const char*)originalcut;
907     string ignore=(const char*)ignorethispart;
908    
909     if(ignore.length()>0 && incut.find(ignore)!=string::npos) incut=incut.replace(incut.find(ignore),ignore.length(),"");
910    
911     vector<string>cutparts;
912     splitupcut(incut,cutparts);
913     string write_cut=interpret_cuts(cutparts);
914     return write_cut;
915     }
916    
917     //********************** ABOVE : CUT INTERPRETATION **************************//
918 buchmann 1.2
919     Double_t GausRandom(Double_t mu, Double_t sigma) {
920     return gRandom->Gaus(mu,sigma);// real deal
921     //return mu;//debugging : no smearing.
922     }
923    
924 buchmann 1.3 int functionalhistocounter=0;
925 buchmann 1.2 TH1F * makehistofromfunction(TF1 *f1,TH1F *model) {
926     TH1F *histo = (TH1F*)model->Clone();
927 buchmann 1.3 functionalhistocounter++;
928     stringstream histoname;
929     histoname << "histo_based_on_function_" << f1->GetName() << "__"<<functionalhistocounter;
930     histo->SetTitle(histoname.str().c_str());
931     histo->SetName(histoname.str().c_str());
932 buchmann 1.2 int nbins=histo->GetNbinsX();
933     float low=histo->GetBinLowEdge(1);
934     float hi=histo->GetBinLowEdge(histo->GetNbinsX())+histo->GetBinWidth(histo->GetNbinsX());
935    
936     for(int i=0;i<=nbins;i++) {
937 buchmann 1.4 histo->SetBinContent(i,(f1->Integral(histo->GetBinLowEdge(i),histo->GetBinLowEdge(i)+histo->GetBinWidth(i)))/histo->GetBinWidth(i));
938     histo->SetBinError(i,TMath::Sqrt(histo->GetBinContent(i)));
939 buchmann 1.2 }
940    
941     return histo;
942 buchmann 1.4 }
943    
944     float hintegral(TH1 *histo, float low, float high) {
945     float sum=0;
946     for(int i=1;i<histo->GetNbinsX();i++) {
947     if((histo->GetBinLowEdge(i)>=low)&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))<=high) sum+=histo->GetBinContent(i);
948     //now on to the less clear cases!
949     if(histo->GetBinLowEdge(i)<low&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>low) {
950     //need to consider this case still ... the bin is kind of in range but not sooooo much.
951     }
952     if(histo->GetBinLowEdge(i)<high&&(histo->GetBinLowEdge(i)+histo->GetBinWidth(i))>high) {
953     //need to consider this case still ... the bin is kind of in range but not sooooo much.
954     }
955    
956     }
957     return sum;
958 buchmann 1.5 }
959    
960 buchmann 1.6 string newjzbexpression(string oldexpression,float shift) {
961     stringstream ss;
962     if(shift>0) ss<<"("<<oldexpression<<"+"<<shift<<")";
963     if(shift<0) ss<<"("<<oldexpression<<shift<<")";
964     if(shift==0) ss<<oldexpression;
965     return ss.str();
966     }
967    
968 buchmann 1.29 float Round(float num, unsigned int dig)
969 buchmann 1.11 {
970     num *= pow(10, dig);
971     if (num >= 0)
972     num = floor(num + 0.5);
973     else
974     num = ceil(num - 0.5);
975     num/= pow(10, dig);
976     return num;
977 buchmann 1.16 }
978    
979 buchmann 1.29 float SigDig(float num, int digits) {
980     //produces a number with only the given number of significant digits
981    
982     }
983    
984 buchmann 1.16 // The two functions below are for distributed processing
985    
986     int get_job_number(float ipoint, float Npoints,float Njobs) {
987     float pointposition=(ipoint/Npoints);
988     int njob=floor(pointposition*Njobs);
989     if(njob>=Njobs) njob--;
990     // cout << "Looking at point " << ipoint << " out of " << Npoints << " which is at position " << pointposition << " corresponding to " << pointposition*Njobs << " --> JOB " << njob << endl;
991     return njob;
992     }
993    
994    
995     bool do_this_point(int ipoint, int Npoints, int jobnumber, int Njobs) {
996     if(get_job_number(ipoint,Npoints,Njobs)==jobnumber) return true;
997     return false;
998     }
999 buchmann 1.19
1000     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 ,
1001     Option_t *option, Bool_t doError)
1002     {
1003     // internal function compute integral and optionally the error between the limits
1004     // specified by the bin number values working for all histograms (1D, 2D and 3D)
1005    
1006     Int_t nbinsx = histo->GetNbinsX();
1007     if (binx1 < 0) binx1 = 0;
1008     if (binx2 > nbinsx+1 || binx2 < binx1) binx2 = nbinsx+1;
1009     if (histo->GetDimension() > 1) {
1010     Int_t nbinsy = histo->GetNbinsY();
1011     if (biny1 < 0) biny1 = 0;
1012     if (biny2 > nbinsy+1 || biny2 < biny1) biny2 = nbinsy+1;
1013     } else {
1014     biny1 = 0; biny2 = 0;
1015     }
1016     if (histo->GetDimension() > 2) {
1017     Int_t nbinsz = histo->GetNbinsZ();
1018     if (binz1 < 0) binz1 = 0;
1019     if (binz2 > nbinsz+1 || binz2 < binz1) binz2 = nbinsz+1;
1020     } else {
1021     binz1 = 0; binz2 = 0;
1022     }
1023    
1024     // - Loop on bins in specified range
1025     TString opt = option;
1026     opt.ToLower();
1027     Bool_t width = kFALSE;
1028     if (opt.Contains("width")) width = kTRUE;
1029    
1030    
1031     Double_t dx = 1.;
1032     Double_t dy = 1.;
1033     Double_t dz = 1.;
1034     Double_t integral = 0;
1035     Double_t igerr2 = 0;
1036     for (Int_t binx = binx1; binx <= binx2; ++binx) {
1037     if (width) dx = histo->GetXaxis()->GetBinWidth(binx);
1038     for (Int_t biny = biny1; biny <= biny2; ++biny) {
1039     if (width) dy = histo->GetYaxis()->GetBinWidth(biny);
1040     for (Int_t binz = binz1; binz <= binz2; ++binz) {
1041     if (width) dz = histo->GetZaxis()->GetBinWidth(binz);
1042     Int_t bin = histo->GetBin(binx, biny, binz);
1043     if (width) integral += histo->GetBinContent(bin)*dx*dy*dz;
1044     else integral += histo->GetBinContent(bin);
1045     if (doError) {
1046     if (width) igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin)*dx*dx*dy*dy*dz*dz;
1047     else igerr2 += histo->GetBinError(bin)*histo->GetBinError(bin);
1048     }
1049     }
1050     }
1051     }
1052    
1053     if (doError) error = TMath::Sqrt(igerr2);
1054     return integral;
1055     }
1056    
1057     Double_t IntegralAndError(TH1F *histo, Int_t binx1, Int_t binx2, Double_t & error, Option_t *option)
1058     {
1059     //Return integral of bin contents in range [binx1,binx2] and its error
1060     // By default the integral is computed as the sum of bin contents in the range.
1061     // if option "width" is specified, the integral is the sum of
1062     // the bin contents multiplied by the bin width in x.
1063     // the error is computed using error propagation from the bin errors assumming that
1064     // all the bins are uncorrelated
1065     return DoIntegral(histo,binx1,binx2,0,-1,0,-1,error,option,kTRUE);
1066 buchmann 1.21 }
1067    
1068     void print_usage() {
1069     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;
1070 buchmann 1.22 }
1071    
1072    
1073     string format_number( int value )
1074     {
1075     if( value == 0 ) return "00";
1076     if( value < 10 ) return "0"+any2string(value);
1077     return any2string(value);
1078     }
1079    
1080     string seconds_to_time(int seconds) {
1081     const static unsigned int SECONDS_IN_AN_HOUR = 3600;
1082     const static unsigned int SECONDS_IN_A_MINUTE = 60;
1083     stringstream answer;
1084     if( seconds > 0 )
1085     {
1086     answer << format_number( (unsigned int)(seconds / SECONDS_IN_AN_HOUR) ) << ":";
1087     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE) ) << ":";
1088     answer << format_number( (unsigned int)((seconds % SECONDS_IN_AN_HOUR) % (SECONDS_IN_A_MINUTE)) );
1089     }
1090     else
1091     {
1092     answer << "00:00:00";
1093     }
1094     return answer.str();
1095     }
1096 buchmann 1.29
1097     bool Contains(string wholestring, string findme) {
1098 buchmann 1.30 if((int)wholestring.find(findme)>-1) return true;
1099 buchmann 1.29 else return false;
1100 fronga 1.31 }
1101 buchmann 1.35
1102     //////////////////////////////////////////////////////////////////////////////
1103     //
1104     // http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
1105     // process_mem_usage(double &, double &) - takes two doubles by reference,
1106     // attempts to read the system-dependent data for a process' virtual memory
1107     // size and resident set size, and return the results in KB.
1108     //
1109     // On failure, returns 0.0, 0.0
1110    
1111     /* usage:
1112     double vm2, rss2;
1113     process_mem_usage(vm2, rss2);
1114     cout << "Memory usage: VM: " << vm << "; RSS: " << rss << endl;
1115     */
1116    
1117     void process_mem_usage(double& vm_usage, double& resident_set)
1118     {
1119     using std::ios_base;
1120     using std::ifstream;
1121     using std::string;
1122    
1123     vm_usage = 0.0;
1124     resident_set = 0.0;
1125    
1126     // 'file' stat seems to give the most reliable results
1127     //
1128     ifstream stat_stream("/proc/self/stat",ios_base::in);
1129    
1130     // dummy vars for leading entries in stat that we don't care about
1131     //
1132     string pid, comm, state, ppid, pgrp, session, tty_nr;
1133     string tpgid, flags, minflt, cminflt, majflt, cmajflt;
1134     string utime, stime, cutime, cstime, priority, nice;
1135     string O, itrealvalue, starttime;
1136    
1137     // the two fields we want
1138     //
1139     unsigned long vsize;
1140     long rss;
1141    
1142     stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
1143     >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
1144     >> utime >> stime >> cutime >> cstime >> priority >> nice
1145     >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
1146    
1147     stat_stream.close();
1148    
1149     long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
1150     vm_usage = vsize / 1024.0;
1151     resident_set = rss * page_size_kb;
1152     }
1153 buchmann 1.36
1154     void flag_this_change(string function, string line, bool checked=false) {
1155     stringstream peakmodificationwarning;
1156     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 :-) ";
1157     if(!checked) write_warning(function,peakmodificationwarning.str());
1158     else write_info(function,peakmodificationwarning.str());
1159     }