ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/tschum/FWlite_Analysis/PlotTool.cc
Revision: 1.14
Committed: Thu Dec 10 18:29:27 2009 UTC (15 years, 5 months ago) by tschum
Content type: text/plain
Branch: MAIN
Changes since 1.13: +150 -58 lines
Log Message:
friendtree only recreated on demand, add CaloTowers

File Contents

# Content
1 #include "PlotTool.h"
2 //------------------------------------------------------------------
3 //Constructur: Set some global Variables to define canvas output
4 PlotTool::PlotTool() {
5
6 this->SetClass("TChain", 100);
7
8 samePad_trees = true;
9 samePad_vars = false;
10 samePad_cuts = false;
11 sameCanv_trees = false;
12 sameCanv_vars = false;
13 sameCanv_cuts = false;
14
15 showLegend = false;
16 logY = true;
17 addTrackJets = false;
18 addEventInfo = false;
19 addTower = false;
20 verbose = true;
21
22 globalCuts="";
23
24 recreateTree = false; //force recreation of friend tree
25
26 }
27
28 //------------------------------------------------------------------
29 //Fill object PlotTool with Chains constructed from files from given source
30
31 int PlotTool::init(string fileName, string dirPath, string treeName,
32 string fileLabel) {
33 this->New(this->GetEntries() );
34 int currChain = this->GetEntries() - 1;
35
36 if (currChain < 0)
37 return currChain;
38
39 TStopwatch timer;
40 timer.Start();
41
42
43 fileNames.clear();
44
45 //check if alternative label is different from default(searchString)
46 if (fileLabel=="") {
47 fileLabel=fileName;
48 }
49 ((TChain*) this->At(currChain))->SetName(fileLabel.c_str());
50
51 TList *files = new TList();
52 TSystemFile* sysFile = 0;
53 if(fileName.find(".") != string::npos) {
54 ifstream f(fileName.c_str());
55 if( ! f.is_open() ) return -1;
56 string line;
57
58 while (!f.eof()) {
59 getline(f,line);
60 sysFile = new TSystemFile(line.c_str(),dirPath.c_str());
61 files->Add(sysFile);
62 }
63
64
65 } else {
66 TSystemDirectory dir("sourceDir", dirPath.c_str());
67 files = dir.GetListOfFiles();
68 }
69 if (files->GetEntries()>0) {
70 TIter next(files);
71 TSystemFile *file;
72 TString fname;
73 string filePath;
74
75 if(verbose && fileName.find(".") == string::npos ) cout<<"Open"<<dirPath.c_str()<<" Search for .root files that contain: "
76 <<fileName.c_str()<<endl;
77 if(verbose && fileName.find(".") != string::npos ) cout<<"Open"<<dirPath.c_str()<<" Search lines with .root in: "
78 <<fileName.c_str()<<endl;
79
80
81 while ((file=(TSystemFile*)next())) {
82 fname = file->GetName();
83 if (!fname.EndsWith(".root"))
84 continue;
85 if (!fname.Contains(fileName.c_str()) && fileName.find(".") == string::npos )
86 continue;
87
88 filePath = dirPath;
89 filePath += fname.Data();
90 //fwlite::ChainEvent to lop over events, jets, etc
91 fileNames.push_back(filePath.c_str());
92
93 if (((TChain*) this->At(currChain))->AddFile(filePath.c_str(), -1,
94 treeName.c_str()) )
95 if(verbose) cout<<"Chained "<<((TChain*) this->At(currChain))->GetNtrees()<<" file(s) with "<<((TChain*) this->At(currChain))->GetEntries()<<" events."<<endl;
96 else
97 return -1;
98
99 }
100 } else
101 return -1;
102
103 for (int i=0; i<((TChain*) this->At(currChain))->GetListOfBranches()->GetEntries(); ++i) {
104
105 string s(((TChain*) this->At(currChain))->GetListOfBranches()->At(i)->GetName());
106
107 string branch_alias = s;
108 string branch_name = s;
109 if (s.find(".", s.size()-1) != string::npos)
110 branch_name += "obj";
111
112 size_t a = s.find("_");
113 if (a != string::npos) {
114 size_t b = s.find("_", a+1);
115 if (b != string::npos) {
116 size_t c = s.find("_", b+1);
117 if (c != string::npos) {
118 string _prod =s.substr(0,a);
119 string _label =s.substr(a+1, b-a-1);
120 string _instance =s.substr(b+1, c-b-1);
121 branch_alias = _label;
122 if(_instance.length() > 0 ) {
123 branch_alias += "_";
124 branch_alias += _instance;
125 ((TChain*) this->At(currChain))->SetAlias(_instance.c_str(),
126 branch_name.c_str());
127 }
128 string branch_alias_full = _prod + "_" + branch_alias;
129 ((TChain*) this->At(currChain))->SetAlias(branch_alias_full.c_str(),
130 branch_name.c_str());
131 }
132 }
133 }
134
135 ((TChain*) this->At(currChain))->SetAlias(branch_alias.c_str(),
136 branch_name.c_str());
137
138 }
139
140 if( addEventInfo || addTrackJets || addTower ) {
141
142 if(verbose) cout<<"add friend tree with additional variables..."<<endl;
143
144 //make file for tree friends (adding additional, computed branches)
145 string friendFileName("/scratch/hh/current/cms/user/");
146 friendFileName += gSystem->GetUserInfo()->fUser;
147 friendFileName += "/temp/";
148 friendFileName += fileLabel;
149 friendFileName += ".root";
150 string fileOpt = "update";
151 if( recreateTree ) fileOpt = "recreate";
152
153 TFile *f = new TFile(friendFileName.c_str(),fileOpt.c_str());
154
155 if( f->IsZombie() ) return -1;
156
157 string friendTreeName("friendTree");
158 //char number = currChain;
159 //friendTreeName += number;
160 //TTree *friendTree = new TTree("friendTree","friendTree");
161
162 if(! f->FindKey(friendTreeName.c_str())) {
163 if(verbose) cout<<"calculating additional variables..."<<endl;
164
165
166 TTree *friendTree = new TTree(friendTreeName.c_str(),friendTreeName.c_str());
167 fwlite::ChainEvent ev(fileNames);
168 int _event, _run, _lumi;
169 int nJetsKT;
170 TrackJetKT = new float [100];
171
172 //tower data
173 const int kMAX = 10000;
174 int NobjTowCal;
175 towet = new float [ kMAX ];
176 toweta = new float [ kMAX ];
177 towphi = new float [ kMAX ];
178 towen = new float [ kMAX ];
179 towem = new float [ kMAX ];
180 towhd = new float [ kMAX ];
181 towoe = new float [ kMAX ];
182 towid_phi = new int[ kMAX ];
183 towid_eta = new int[ kMAX ];
184 towid = new int[ kMAX ];
185
186
187 if( addEventInfo ) {
188
189
190 friendTree->Branch("event", &_event, "event/I");
191 friendTree->Branch("run", &_run, "run/I");
192 friendTree->Branch("lumi", &_lumi, "lumi/I");
193
194 }
195
196 if( addTrackJets ) {
197
198
199 friendTree->Branch("nJetsKT", &nJetsKT, "nJetsKT/I");
200 friendTree->Branch("TrackJetKT", TrackJetKT, "TrackJetKT[nJetsKT]/F");
201 }
202
203 if( addTower) {
204
205 // CaloTower branches
206 friendTree->Branch( "NobjTowCal",&NobjTowCal,"NobjTowCal/I" );
207 friendTree->Branch( "TowId", towid, "TowId[NobjTowCal]/I" );
208 friendTree->Branch( "TowId_phi", towid_phi, "TowId_phi[NobjTowCal]/I" );
209 friendTree->Branch( "TowId_eta", towid_eta, "TowId_eta[NobjTowCal]/I" );
210 friendTree->Branch( "TowEt", towet, "TowEt[NobjTowCal]/F" );
211 friendTree->Branch( "TowEta", toweta, "TowEta[NobjTowCal]/F" );
212 friendTree->Branch( "TowPhi", towphi, "TowPhi[NobjTowCal]/F" );
213 friendTree->Branch( "TowE", towen, "TowE[NobjTowCal]/F" );
214 friendTree->Branch( "TowEm", towem, "TowEm[NobjTowCal]/F" );
215 friendTree->Branch( "TowHad", towhd, "TowHad[NobjTowCal]/F" );
216 friendTree ->Branch( "TowOE", towoe, "TowOE[NobjTowCal]/F" );
217
218
219 }
220
221
222 int tenth = ev.size() / 10;
223 int eventNum =0;
224 for (ev.toBegin(); !ev.atEnd(); ++ev, ++eventNum) {
225
226
227 if( addEventInfo ) {
228
229
230 if(eventNum==0) {
231 // fwlite::Handle<edm::TriggerResults> hltHandle;
232 // hltHandle.getByLabel(ev, "TriggerResults");
233
234 // fwlite::Handle<edm::TriggerResults> hTriggerResults;
235
236 // hTriggerResults.getByLabel(ev, "TriggerResults","","TEST");
237 // fwlite::TriggerNames const& triggerNames = ev.triggerNames(*hTriggerResults);
238
239
240 // // std::vector<std::string> const& names = triggerNames.triggerNames();
241 // for (unsigned i = 0; i < triggerNames.size(); ++i) {
242 // std::cout << i << " " << triggerNames.triggerName(i) << std::endl;
243 // }
244 }
245
246 _event = ev.id().event();
247 _run = ev.id().run();
248 _lumi = ev.luminosityBlock();
249
250 }
251
252 if( addTrackJets ) {
253
254 fwlite::Handle<reco::CaloJetCollection> jets;
255 jets.getByLabel(ev, "ak5CaloJets");
256
257 fwlite::Handle<reco::TrackCollection> tracks;
258 tracks.getByLabel(ev, "generalTracks");
259
260 if (!jets.isValid())
261 continue;
262 if (!tracks.isValid())
263 continue;
264 double trackSum;
265 nJetsKT = 0;
266 for (reco::CaloJetCollection::const_iterator jet = jets->begin(); jet
267 !=jets->end(); jet++) {
268 trackSum = 0;
269 for (reco::TrackCollection::const_iterator track = tracks->begin(); track
270 !=tracks->end(); track++) {
271 if (deltaR(jet->eta(), jet->phi(), track->eta(), track->phi())
272 < 0.5)
273 trackSum += track->pt();
274 }
275 TrackJetKT[nJetsKT] = trackSum;
276 nJetsKT++;
277 }
278 }
279 if( addTower) {
280
281 fwlite::Handle<CaloTowerCollection> towers;
282 towers.getByLabel(ev, "towerMaker");
283
284 int jtow = 0;
285 NobjTowCal=towers->size();
286 for(CaloTowerCollection::const_iterator tow = towers->begin();
287 tow != towers->end(); ++tow, ++jtow){
288 towet [jtow] = tow->et();
289 toweta[jtow] = tow->eta();
290 towphi[jtow] = tow->phi();
291 towen [jtow] = tow->energy();
292 towem [jtow] = tow->emEnergy();
293 towhd [jtow] = tow->hadEnergy();
294 towoe [jtow] = tow->outerEnergy();
295 towid_phi[jtow] = tow->id().iphi();
296 towid_eta[jtow] = tow->id().ieta();
297 towid [jtow] = tow->id().rawId();
298 }
299
300
301 }
302 friendTree->Fill();
303
304 if( eventNum != 0 && eventNum%tenth == 0) cout<<"Processed "<<eventNum <<" of "<<ev.size()<<" events. "<<endl;
305
306 }
307 f->cd();
308 friendTree->Write();
309 }
310 f->Close();
311 ((TChain*) this->At(currChain))->AddFriend(friendTreeName.c_str(),
312 friendFileName.c_str());
313
314
315
316 }
317
318
319 timer.Stop();
320 if(verbose) timer.Print();
321
322 return this->GetEntries();
323
324 }
325 //------------------------------------------------------------------
326 //Draw given Chain with given variable and given cuts
327 int PlotTool::plot(int chainIndex, string histName, string cutName,
328 int nEntries, string drwOpt) {
329
330 if (chainIndex >= this->GetEntries() )
331 return -1;
332
333 TStopwatch timer;
334 if(verbose) {
335 cout<<"Plot: "<<histName<<" "<<cutName<<" from chain "<<this->At(chainIndex)->GetName()<<endl;
336 timer.Start();
337 }
338
339 int currN = nEntries;
340 if (nEntries < 0)
341 currN = ((TChain*) this->At(chainIndex))->GetEntries(); //nEntries<0 : all entries are plotted!
342
343 //++++ Create and name Canvases according to global variables +++++++++++++
344 ostringstream currHistName;
345 if (samePad_trees)
346 currHistName<<((TChain*) this->At(chainIndex))->GetName()<<":";
347 if (samePad_vars)
348 currHistName<<histName;
349 if (samePad_cuts)
350 currHistName<<"{"<<cutName<<"}";
351
352 ostringstream currPadName;
353 if (!samePad_trees)
354 currPadName<<((TChain*) this->At(chainIndex))->GetName()<<":";
355 if (!samePad_vars)
356 currPadName<<histName;
357 if (!samePad_cuts)
358 currPadName<<"{"<<cutName<<"}";
359
360 ostringstream currCanvName;
361 if (!sameCanv_trees && !samePad_trees)
362 currCanvName<<((TChain*) this->At(chainIndex))->GetName()<<":";
363 if (!sameCanv_vars && !samePad_vars)
364 currCanvName<<histName;
365 if (!sameCanv_cuts && !samePad_cuts)
366 currCanvName<<"{"<<cutName<<"}";
367
368 if ( (sameCanv_trees || samePad_trees) && (sameCanv_vars || samePad_vars)
369 && (sameCanv_cuts || samePad_cuts))
370 currCanvName<<"All";
371
372 string currOpt = drwOpt;
373 bool useSubPads = (sameCanv_trees && !samePad_trees) || (sameCanv_vars
374 && !samePad_vars) || (sameCanv_cuts && !samePad_cuts);
375
376 if (useSubPads) {
377 if ( !canvases_[currCanvName.str()] || !gROOT->GetListOfCanvases()->FindObject(currCanvName.str().c_str()) ) {
378 canvases_[currCanvName.str()] = new TCanvas(currCanvName.str().c_str(), currCanvName.str().c_str());
379 } else if (canvases_[currCanvName.str()]->GetNumber() >= 0) {
380 canvases_[currCanvName.str()]->SetNumber(canvases_[currCanvName.str()]->GetNumber()+1);
381 }
382 }
383
384 if ( !pads_[currPadName.str()] || !gROOT->GetListOfCanvases()->FindObject(currPadName.str().c_str()) ) {
385 pads_[currPadName.str()] = new TCanvas(currPadName.str().c_str(), currPadName.str().c_str());
386 // if (logY)
387 // pads_[currPadName.str()]->SetLogy(1);
388 } else {
389 pads_[currPadName.str()]->cd();
390 currOpt += "SAMES";
391 if (useSubPads)
392 canvases_[currCanvName.str()]->SetNumber(canvases_[currCanvName.str()]->GetNumber()-1);
393 }
394 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
395
396
397 //Draw histogram:
398 string cutNameWithGlobal = cutName;
399 if(cutName!="" && globalCuts!="") cutNameWithGlobal += "&&";
400 if(globalCuts!="") cutNameWithGlobal += globalCuts;
401
402 int draw_err = ((TChain*) this->At(chainIndex))->Draw(histName.c_str(), cutNameWithGlobal.c_str(),
403 currOpt.c_str(), currN);
404 if (draw_err < 0)
405 return draw_err;
406
407 //++++ Fix for histos with no entries +++++++++++++
408 if (draw_err == 0) {
409 if (currOpt.find("SAMES") == string::npos) {
410 pads_[currPadName.str()]->Close();
411 pads_.erase(currPadName.str() );
412 if (useSubPads)
413 canvases_[currCanvName.str()]->SetNumber(canvases_[currCanvName.str()]->GetNumber()-1);
414 }
415 cout<< "Warning: "<<currHistName.str().c_str()<<" in "<<currPadName.str()
416 <<" has no entries and is not drawn!"<<endl;
417 return draw_err;
418 }
419 //++++++++++++++++++++++++++++++++++++++++++++++++++
420
421 ((TH1F*) pads_[currPadName.str()]->GetPrimitive("htemp"))->SetName(currHistName.str().c_str()); // Set Name of histogram
422
423 // Update for 2D histograms
424 if( pads_[currPadName.str()]->GetPrimitive(currHistName.str().c_str())->InheritsFrom("TH2") ) {
425 pads_[currPadName.str()]->Draw();
426 setCanvas( pads_[currPadName.str()] );
427 }
428
429
430 if(verbose && draw_err > 0) {
431 timer.Stop();
432 cout<<"Done: Selected "<<draw_err<<" objects in "<< currN <<" processed events."<<endl;
433 timer.Print();
434 }
435 return draw_err;
436
437 }
438 //------------------------------------------------------------------
439 //Standard loop to draw all chains and multiple variables and cuts
440 int PlotTool::loop(vector<string> _histName, vector<string> _cutName,
441 int nEntries, string drwOpt, bool correspond) {
442
443 int numProcessed = 0;
444
445 if (correspond == false) {
446
447 for (int i=0; i<this->GetEntries(); ++i) {
448 for (vector<string>::iterator it1 =_histName.begin(); it1
449 != _histName.end(); ++it1) {
450 for (vector<string>::iterator it2 =_cutName.begin(); it2
451 != _cutName.end(); ++it2) {
452
453 numProcessed += plot(i, *it1, *it2, nEntries, drwOpt);
454
455
456 }
457 }
458 }
459 } else {
460
461 if (_histName.size() != _cutName.size() )
462 return -1;
463
464 for (int i=0; i<this->GetEntries(); ++i) {
465 for (vector<string>::iterator it1 =_histName.begin(), it2 =
466 _cutName.begin(); it1 != _cutName.end()&&it2
467 != _cutName.end(); ++it1, ++it2) {
468
469 numProcessed += plot(i, *it1, *it2, nEntries, drwOpt);
470
471 }
472 }
473 }
474
475 updatePads();
476 fillCanvases();
477
478 return numProcessed;
479 }
480
481 //Helper methods to allow for using simple strings as input
482 int PlotTool::loop(string histName, string cutName, int nEntries, string drwOpt) {
483
484 vector<string> _histName;
485 _histName.push_back(histName);
486 vector<string> _cutName;
487 _cutName.push_back(cutName);
488
489 return loop(_histName, _cutName, nEntries, drwOpt);
490
491 }
492
493 int PlotTool::loop(vector<string> _histName, string cutName, int nEntries,
494 string drwOpt) {
495
496 vector<string> _cutName;
497 _cutName.push_back(cutName);
498
499 return loop(_histName, _cutName, nEntries, drwOpt);
500
501 }
502
503 int PlotTool::loop(string histName, vector<string> _cutName, int nEntries,
504 string drwOpt) {
505
506 vector<string> _histName;
507 _histName.push_back(histName);
508
509 return loop(_histName, _cutName, nEntries, drwOpt);
510 }
511 //------------------------------------------------------------------
512 //redraw the canvas to make changes in style visible
513 int PlotTool::updatePads() {
514
515 for (map< string, TCanvas* >::iterator it=pads_.begin() ; it != pads_.end(); ++it) {
516 if ( ! gROOT->GetListOfCanvases()->FindObject((*it).first.c_str() ) ) {
517 pads_.erase(it);
518 continue;
519 }
520 if( (*it).second->GetListOfPrimitives()->GetEntries() == 0 ) {
521 (*it).second->Close();
522 pads_.erase(it);
523 continue;
524 }
525 (*it).second->Draw();
526 setCanvas((*it).second);
527
528 }
529
530 return pads_.size();
531
532 }
533
534 int PlotTool::fillCanvases() {
535
536 for (map< string, TCanvas* >::iterator it=canvases_.begin() ; it
537 != canvases_.end(); ++it) {
538 string canvName = (*it).first;
539 if (gROOT->GetListOfCanvases()->FindObject(canvName.c_str()) ) {
540
541 int numP = (*it).second->GetNumber()+1;
542
543 if (numP <= 0)
544 continue;
545
546 int x = int( sqrt(numP) );
547 int y = x;
548 if (x*y < numP)
549 x += 1;
550 if (x*y < numP)
551 x += 1;
552 if (x*y < numP) {
553 x -= 1;
554 y += 1;
555 }
556
557
558 (*it).second->Divide(x, y);
559 int padIndex = 1;
560 for (map< string, TCanvas* >::iterator it2=pads_.begin() ; it2
561 != pads_.end(); ++it2) {
562 string padName = (*it2).first;
563 if (gROOT->GetListOfCanvases()->FindObject(padName.c_str() ) ) {
564 string n1 = canvName.substr(0,canvName.find(":"));
565 string n2("");
566 if(canvName.find("{") != string::npos ) n2 = canvName.substr(canvName.find("{"),canvName.find("}"));
567
568 if ( (padName.find(canvName.c_str()) != string::npos ) || (padName.find(n1) != string::npos && padName.find(n2) != string::npos) || !strcmp( canvName.c_str(), "All") ) {
569 (*it).second->cd(padIndex);
570 (*it2).second->DrawClonePad();
571 (*it2).second->Close();
572 pads_.erase(it2);
573 ++padIndex;
574 }
575 } else
576 pads_.erase(it2);
577 }
578 (*it).second->SetNumber(-1);
579
580 } else
581 canvases_.erase(it);
582 }
583
584 return canvases_.size();
585
586 }
587 //------------------------------------------------------------------
588 void PlotTool::setCanvas(TCanvas* thisCanvas) {
589
590 TH1* thisHist = 0;
591 TPaveStats* thisStatsBox = 0;
592 TPaletteAxis* palette =0;
593 TLegend* thisLeg = 0;
594 int counter =0;
595 double maxEntry=0;
596
597 ((TFrame*) thisCanvas->GetFrame())->Delete();
598 thisCanvas->GetFrame()->SetLineWidth(gStyle->GetLineWidth() );
599
600 thisCanvas->SetLeftMargin(0.2);
601 thisCanvas->SetRightMargin(0.06);
602 thisCanvas->SetBottomMargin(0.2);
603 thisCanvas->SetTopMargin(0.1);
604
605 if (logY)
606 thisCanvas->SetLogy(1);
607 else
608 thisCanvas->SetLogy(0);
609
610 if (showLegend)
611 thisLeg = new TLegend();
612
613 for (int i = 0; i != thisCanvas->GetListOfPrimitives()->GetSize(); ++i) {
614
615 if ( !thisCanvas->GetListOfPrimitives()->At(i)->InheritsFrom("TH1"))
616 continue;
617
618 thisHist = ((TH1*) thisCanvas->GetListOfPrimitives()->At(i));
619 setColor(thisHist, counter);
620 setMathLabels(thisHist);
621
622 if (thisHist->GetMaximum() > maxEntry)
623 maxEntry = thisHist->GetMaximum();
624
625 thisStatsBox = (TPaveStats*) thisHist->GetListOfFunctions()->FindObject("stats");
626 if (thisStatsBox)
627 setStats(thisCanvas, thisStatsBox, thisHist, counter);
628
629 palette = (TPaletteAxis*) thisHist->GetListOfFunctions()->FindObject("palette");
630 if (palette)
631 setPalette(thisCanvas, palette);
632
633 if (thisLeg)
634 thisLeg->AddEntry(thisHist,thisHist->GetName())->SetTextSize(0.04);
635
636 ++counter;
637
638 }
639
640 if (maxEntry != 0)
641 setHistMax(thisCanvas, maxEntry);
642
643 thisCanvas->cd();
644 thisCanvas->Update();
645
646 if (thisLeg)
647 setLegend(thisCanvas, thisLeg, counter);
648
649 }
650 //------------------------------------------------------------------
651 //private helper classes to set the canvas and hist style
652 void PlotTool::setStats(TCanvas* thisCanvas, TPaveStats* thisStatsBox,
653 TH1* thisHist, int counter) {
654
655 if (thisCanvas->GetRightMargin() < .2)
656 thisCanvas->SetRightMargin(.2);
657
658 thisStatsBox->SetLineColor(thisHist->GetLineColor());
659 thisStatsBox->SetX2NDC(1.);
660 thisStatsBox->SetY2NDC(1-thisCanvas->GetTopMargin()-0.16*counter);
661 thisStatsBox->SetX1NDC(1-thisCanvas->GetRightMargin()+0.01);
662 thisStatsBox->SetY1NDC(thisStatsBox->GetY2NDC()-.15);
663
664 }
665
666 void PlotTool::setMathLabels(TH1* thisHist) {
667
668 string t = thisHist ->GetTitle();
669 string x = thisHist->GetXaxis()->GetTitle();
670 string y = thisHist->GetYaxis()->GetTitle();
671
672 // if (x.find("__") != string::npos)
673 // x = x.substr(0,x.find("__"));
674 // if (y.find("__") != string::npos)
675 // y = y.substr(0,y.find("__"));
676
677 if (x.find(".phi()") != string::npos)
678 x.replace(x.find(".phi()"), 6, " #phi");
679 if (y.find(".phi()") != string::npos)
680 y.replace(y.find(".phi()"), 6, " #phi");
681
682 if (x.find(".eta()") != string::npos)
683 x.replace(x.find(".eta()"), 6, " #eta");
684 if (y.find(".eta()") != string::npos)
685 y.replace(y.find(".eta()"), 6, " #eta");
686
687 if (x.find(".theta()") != string::npos)
688 x.replace(x.find(".theta()"), 6, " #theta");
689 if (y.find(".theta()") != string::npos)
690 y.replace(y.find(".theta()"), 6, " #theta");
691
692 if (x.find(".chi2()") != string::npos)
693 x.replace(x.find(".chi2()"), 7, " #chi^{2}");
694 if (y.find(".chi2()") != string::npos)
695 y.replace(y.find(".chi2()"), 7, " #chi^{2}");
696
697 if (x.find(".pt()") != string::npos)
698 x.replace(x.find(".pt()"), 5, " p_{T} [GeV]");
699 if (y.find(".pt()") != string::npos)
700 y.replace(y.find(".pt()"), 5, " p_{T} [GeV]");
701
702 if (x.find(".et()") != string::npos)
703 x.replace(x.find(".et()"), 5, " E_{T} [GeV]");
704 if (y.find(".et()") != string::npos)
705 y.replace(y.find(".et()"), 5, " E_{T} [GeV]");
706
707 //splitlines for many cuts
708 string test1= "{" + globalCuts + "}";
709 string test2= "&&" + globalCuts;
710
711 if(t.find(test1) != string::npos) t.replace(t.find(test1),test1.length(),"");
712 if(t.find(test2) != string::npos) t.replace(t.find(test2),test2.length(),"");
713
714 if (t.find("{") != string::npos && t.find("#splitline") == string::npos) {
715 t.replace(t.find_last_of("{"), 1, "}{");
716 string t_old = t;
717 t = "#splitline{";
718 t += t_old;
719 }
720
721 thisHist ->SetTitle(t.c_str());
722 thisHist->GetXaxis()->SetTitle(x.c_str());
723 thisHist->GetYaxis()->SetTitle(y.c_str());
724
725 }
726
727 void PlotTool::setColor(TH1* thisHist, int counter) {
728
729 if (counter == 0) {
730
731 thisHist->SetLineColor(kRed+1);
732 //if( gStyle->GetHistFillStyle() ) thisHist->SetFillColor (kRed+1);
733 //else
734 thisHist->SetFillStyle(0);
735 thisHist->SetMarkerColor(kRed+1);
736 } else if (counter == 1) {
737 thisHist->SetLineColor(kBlue+1);
738 //if( gStyle->GetHistFillStyle() ) thisHist->SetFillColor (kBlue+1);
739 //else
740 thisHist->SetFillStyle(0);
741 thisHist->SetMarkerColor(kBlue+1);
742
743 } else if (counter == 2) {
744 thisHist->SetLineColor(kGreen+2);
745 //if( gStyle->GetHistFillStyle() ) thisHist->SetFillColor (kGreen+2);
746 //else
747 thisHist->SetFillStyle(0);
748 thisHist->SetMarkerColor(kGreen+2);
749
750 } else if (counter == 3) {
751 thisHist->SetLineColor(kMagenta+2);
752 //if( gStyle->GetHistFillStyle() ) thisHist->SetFillColor (kMagenta+2);
753 //else
754 thisHist->SetFillStyle(0);
755 thisHist->SetMarkerColor(kMagenta+2);
756
757 } else if (counter == 4) {
758 thisHist->SetLineColor(kCyan+2);
759 //if( gStyle->GetHistFillStyle() ) thisHist->SetFillColor (kCyan+2);
760 //else
761 thisHist->SetFillStyle(0);
762 thisHist->SetMarkerColor(kCyan+2);
763
764 } else {
765 thisHist->SetLineColor(kBlack);
766 //if( gStyle->GetHistFillStyle() ) thisHist->SetFillColor (kBlack);
767 //else
768 thisHist->SetFillStyle(0);
769 thisHist->SetMarkerColor(kBlack);
770
771 }
772
773 }
774
775 void PlotTool::setPalette(TCanvas* thisCanvas, TPaletteAxis* palette) {
776
777 palette->SetLabelSize(0.045);
778 if (thisCanvas->GetRightMargin() < .15)
779 thisCanvas->SetRightMargin(.15);
780 palette->SetX1NDC(1-thisCanvas->GetRightMargin()+0.01);
781 palette->SetY1NDC(thisCanvas->GetBottomMargin());
782 palette->SetX2NDC(palette->GetX1NDC()+0.05);
783 palette->SetY2NDC(1-thisCanvas->GetTopMargin());
784
785 }
786
787 void PlotTool::setHistMax(TCanvas* thisCanvas, double maxEntry) {
788
789 TH1* thisHist = 0;
790
791 for (int i = 0; i != thisCanvas->GetListOfPrimitives()->GetSize(); ++i) {
792
793 if ( !thisCanvas->GetListOfPrimitives()->At(i)->InheritsFrom("TH1") )
794 continue;
795 thisHist = ((TH1*) thisCanvas->GetListOfPrimitives()->At(i));
796 if (thisHist->GetMaximum() < maxEntry) {
797 double minEntry=thisHist->GetBinContent(thisHist->GetMinimumBin());
798 if (logY) {
799 int bin = (thisHist->GetMinimumBin()+1);
800 minEntry=thisHist->GetBinContent(bin);
801 }
802 thisHist->GetYaxis()->SetRangeUser(minEntry, maxEntry*1.2);
803 }
804 break;
805
806 }
807
808 }
809
810 void PlotTool::setLegend(TCanvas* thisCanvas, TLegend* thisLeg, int counter) {
811
812 thisLeg->SetFillStyle(0);
813 thisLeg->SetX1NDC(1-thisCanvas->GetRightMargin()-0.5);
814 thisLeg->SetY1NDC(1-thisCanvas->GetTopMargin()-0.05*counter);
815 thisLeg->SetX2NDC(1-thisCanvas->GetRightMargin());
816 thisLeg->SetY2NDC(1-thisCanvas->GetTopMargin());
817 thisLeg->SetEntrySeparation(0.5);
818 thisLeg->Draw("NDC");
819
820 }
821
822 void PlotTool::createColors() {
823 const Int_t NRGBs = 5;
824 const Int_t NCont = 255;
825
826 Double_t stops[NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
827 Double_t red[NRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 };
828 Double_t green[NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
829 Double_t blue[NRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 };
830 TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont);
831 gStyle->SetNumberContours(NCont);
832
833 }
834
835 //------------------------------------------------------------------
836
837 int PlotTool::saveCanvases(string name, string path) {
838
839 TSystemDirectory d("", path.c_str());
840 if (!d.GetListOfFiles())
841 return -1;
842
843 string namePs = path +"/" + name;
844 string nameRt = path +"/" + name;
845
846 if (name.find(".ps") == string::npos)
847 namePs += ".ps";
848
849 if (name.find(".root") == string::npos)
850 nameRt += ".root";
851
852 int savedCanvs =0;
853
854
855 TIter next(gROOT->GetListOfCanvases());
856 TCanvas* canv;
857 while ((canv=(TCanvas*)next())) {
858 string modName = (*canv).GetName();
859 if(modName.find("{") != string::npos) modName = modName.substr(0,modName.find("{"));
860 (*canv).SetTitle( modName.c_str() );
861
862 }
863
864
865 TPostScript ps(namePs.c_str(),112);
866 TFile rt(nameRt.c_str(),"recreate");
867
868 next.Reset();
869 while ((canv=(TCanvas*)next())) {
870 ps.NewPage();
871
872
873 (*canv).Write();
874 (*canv).Draw();
875 (*canv).Update();
876
877
878 ++savedCanvs;
879
880 }
881
882 ps.Close();
883 rt.Close();
884
885
886 if(verbose && savedCanvs) {
887 cout<<"Saved file "<<rt.GetName()<<" with "<<savedCanvs<<" canvases."<<endl;
888 cout<<"Saved file "<<ps.GetName()<<" with "<<savedCanvs<<" pages."<<endl;
889 }
890 return savedCanvs;
891
892 }
893 //------------------------------------------------------------------
894
895 int PlotTool::clearCanvases()
896 {
897
898 while(gROOT->GetListOfCanvases()->GetEntries()) ((TCanvas*) gROOT->GetListOfCanvases()->At(0))->Close();
899 pads_.clear();
900 autoVars.clear();
901 return pads_.size() + gROOT->GetListOfCanvases()->GetEntries();
902
903 }
904 //------------------------------------------------------------------
905 int PlotTool::setVariables(string label)
906 {
907
908 for (int i=0; i< this->GetEntries(); ++i) {
909 cout<<"--------------------------------"<<endl;
910 cout<<((TChain*) this->At(i))->GetName()<<endl;
911 cout<<"------------"<<endl;
912
913 TList* leaves = (TList*) ((TChain*) this->At(i))->GetListOfLeaves();
914 for (int j=0; j< leaves->GetEntries(); ++j) {
915 TString leafName ( leaves->At(j)->GetName() );
916 if(! leafName.EndsWith(".") ) continue;
917 if(! leafName.Contains(label.c_str() ) ) continue;
918
919 TClass cl( ( (TLeafElement*) leaves->At(j) )->GetTypeName() );
920 cout<<"++++++"<<endl;
921 cout<< leafName.Data() <<endl;
922 for(int k=0;k<cl.GetListOfAllPublicMethods()->GetEntries();++k) {
923 string typeName ( ((TMethod*) cl.GetListOfAllPublicMethods()->At(k))->GetReturnTypeName() );
924 string methName ( cl.GetListOfAllPublicMethods()->At(k)->GetName() );
925 if( methName != "product") continue;
926 cout<< typeName <<endl;
927 string _type;
928 TString testString( typeName.c_str() );
929 if( testString.BeginsWith("vector<") ) {
930 _type = typeName.substr(typeName.find("<")+1,typeName.find(">")-typeName.find("<")-1);
931 string _varSize = leafName.Data();
932 _varSize += "obj@.size()";
933 autoVars.push_back( _varSize );
934 }
935 else _type = typeName.substr(0,typeName.find("*"));
936 TClass _cl( _type.c_str() );
937 for(int l=0;l<_cl.GetListOfAllPublicMethods()->GetEntries();++l) {
938 string _typeName ( ((TMethod*) _cl.GetListOfAllPublicMethods()->At(l))->GetReturnTypeName() );
939 string _methName ( _cl.GetListOfAllPublicMethods()->At(l)->GetName() );
940 // if(_typeName.find("void") != string::npos ) continue;
941 // cout<<" "<<_typeName<<" "<<_methName<<endl;
942
943 cout<<" "<<_typeName<<" "<<_methName<<endl;
944 if(_methName.find("operator")==string::npos&&(_typeName=="float"||_typeName=="double"||_typeName=="int"||_typeName=="unsigned int"||_typeName=="bool"||_typeName=="unsigned short"||_typeName=="unsigned long"||_typeName=="unsigned long long")) {
945
946 cout<<"--> "<<_typeName<<" "<<_methName<<endl;
947
948 string _varName = leafName.Data();
949 _varName += "obj.";
950 _varName += _methName;
951 _varName += "()";
952 autoVars.push_back( _varName );
953 }
954 }
955
956
957 }
958
959 }
960
961 }
962
963 return autoVars.size();
964
965 }
966 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
967 //Draw efficiencies
968 int PlotTool::plotEff(int chainIndex, string histName, string cutName, int nEntries, double fitXmin, double fitXmax, string fitFormula)
969 {
970
971 if( chainIndex >= this->GetEntries() ) return -1;
972
973 int currN = nEntries;
974 if(nEntries < 0) currN = ((TChain*) this->At(chainIndex))->GetEntries(); //nEntries<0 : all entries are plotted!
975
976 //++++ Create and name Canvases according to global variables +++++++++++++
977 ostringstream currHistName;
978 if( samePad_trees) currHistName<<((TChain*) this->At(chainIndex))->GetName()<<":";
979 if( samePad_vars) currHistName<<histName;
980 if( samePad_cuts) currHistName<<"{"<<cutName<<"}";
981
982 ostringstream currPadName;
983 if(! samePad_trees) currPadName<<((TChain*) this->At(chainIndex))->GetName()<<":";
984 if(! samePad_vars) currPadName<<histName;
985 if(! samePad_cuts) currPadName<<"{"<<cutName<<"}";
986
987
988 //Draw total histogram:
989 if( ! pads_["total"] || ! gROOT->FindObject("total") ) {
990 pads_["total"] = new TCanvas("total", "total");
991 } else {
992 pads_["total"]->cd();
993 }
994 ostringstream bins_total;
995 bins_total<<histName;
996 bins_total<<">>total(100,0,1000)";
997
998
999 int draw_err = ((TChain*) this->At(chainIndex))->Draw(bins_total.str().c_str(), "", "", currN);
1000 if( draw_err <= 0 ) return draw_err;
1001
1002
1003 TH1* total = ((TH1*) pads_["total"]->GetPrimitive("total"));
1004
1005 ostringstream bins_bkg;
1006 bins_bkg<<histName;
1007 bins_bkg<<">>bkg(";
1008 bins_bkg<<total->GetNbinsX();
1009 bins_bkg<<",";
1010 bins_bkg<<total->GetXaxis()->GetXmin();
1011 bins_bkg<<",";
1012 bins_bkg<<total->GetXaxis()->GetXmax();
1013 bins_bkg<<")";
1014
1015 //Draw bkg histogram:
1016 if( ! pads_["bkg"] || ! gROOT->FindObject("bkg") ) {
1017 pads_["bkg"] = new TCanvas("bkg", currPadName.str().c_str());
1018 } else {
1019 pads_["bkg"]->cd();
1020 }
1021
1022 draw_err = ((TChain*) this->At(chainIndex))->Draw(bins_bkg.str().c_str(), cutName.c_str(),"" , currN);
1023 if( draw_err <= 0 ) return draw_err;
1024
1025
1026 TH1* bkg = ((TH1*) pads_["bkg"]->GetPrimitive("bkg"));
1027
1028 //Draw pass histogram:
1029 ostringstream bins_pass;
1030 bins_pass<<histName;
1031 bins_pass<<">>pass(";
1032 bins_pass<<total->GetNbinsX();
1033 bins_pass<<",";
1034 bins_pass<<total->GetXaxis()->GetXmin();
1035 bins_pass<<",";
1036 bins_pass<<total->GetXaxis()->GetXmax();
1037 bins_pass<<")";
1038
1039 ostringstream cut_pass;
1040 cut_pass<<"!(";
1041 cut_pass<<cutName;
1042 cut_pass<<")";
1043
1044
1045 if( ! pads_["pass"] || ! gROOT->FindObject("pass") ) {
1046 pads_["pass"] = new TCanvas("pass", currPadName.str().c_str());
1047 } else {
1048 pads_["pass"]->cd();
1049 }
1050
1051 draw_err = ((TChain*) this->At(chainIndex))->Draw(bins_pass.str().c_str(),cut_pass.str().c_str() ,"" , currN);
1052 if( draw_err <= 0 ) return draw_err;
1053
1054
1055 TH1* pass = ((TH1*) pads_["pass"]->GetPrimitive("pass"));
1056
1057
1058 currPadName<<"Eff";
1059 //Draw Efficiency Graph:
1060 if( ! pads_["EffGraph"] || ! gROOT->FindObject("EffGraph") ) {
1061 pads_["EffGraph"] = new TCanvas("EffGraph", currPadName.str().c_str());
1062 } else {
1063 pads_["EffGraph"]->cd();
1064 }
1065
1066 TGraphAsymmErrors* EffGraph = new TGraphAsymmErrors(bkg, total);
1067 EffGraph->SetName(currHistName.str().c_str());
1068
1069 TF1* reverse = new TF2("reverse","1/y-1",total->GetXaxis()->GetXmin(),total->GetXaxis()->GetXmax());
1070 EffGraph->Apply(reverse);
1071 EffGraph->Draw("A*");
1072
1073 TF1* fitfunc = new TF1("fitfunc",fitFormula.c_str(),fitXmin,fitXmax);
1074 EffGraph->Fit("fitfunc","R+");
1075
1076
1077 //Save fit function
1078
1079 ostringstream savefuncName;
1080 savefuncName<<histName;
1081 savefuncName<<"_";
1082
1083 if(cutName.find("<") != std::string::npos ) cutName.replace(cutName.find("<"),1,"_");
1084 if(cutName.find(">") != std::string::npos ) cutName.replace(cutName.find(">"),1,"_");
1085 savefuncName<<cutName;
1086
1087
1088 TFile file("ABCDFunctions.root","UPDATE");
1089 TF1* savefunc = new TF1(savefuncName.str().c_str(), fitfunc->GetExpFormula().Data(),0,10000);
1090 savefunc->SetParameters( fitfunc->GetParameters() );
1091 savefunc->SetParErrors ( fitfunc->GetParErrors() );
1092
1093 //Show results
1094 if( ! pads_["abcd"] || ! gROOT->FindObject("abcd") ) {
1095 pads_["abcd"] = new TCanvas("abcd", "abcd");
1096 } else {
1097 pads_["abcd"]->cd();
1098 }
1099
1100 bkg->Multiply(savefunc);
1101 bkg->Draw();
1102
1103 // total->Add(bkg,-1);
1104 pass->SetLineColor(kRed);
1105 pass->Draw("sames,e");
1106 pads_["abcd"]->SetLogy();
1107
1108
1109 savefunc->Write();
1110 // file.Close();
1111
1112
1113 return draw_err;
1114
1115 }
1116 //------------------------------------------------------------------