ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/tschum/FWlite_Analysis/PlotTool.cc
(Generate patch)

Comparing UserCode/tschum/FWlite_Analysis/PlotTool.cc (file contents):
Revision 1.13 by tschum, Wed Dec 9 13:02:16 2009 UTC vs.
Revision 1.21 by tschum, Fri Feb 19 10:33:39 2010 UTC

# Line 14 | Line 14 | PlotTool::PlotTool() {
14  
15          showLegend = false;
16          logY = true;
17        addTrackJets = false;
18        addEventInfo = false;
17          verbose = true;
18  
19          globalCuts="";
20  
21 +        varBlockNames = "";   //Set to "ALL" or add Names, i.e. varBlockNames += "CaloTower"
22 +        recreateTree = false; //force recreation of friend tree
23 +
24 +        normHists = false; //scale all histos intergrals to 1
25 +
26   }
27  
28   //------------------------------------------------------------------
# Line 88 | Line 91 | int PlotTool::init(string fileName, stri
91        fileNames.push_back(filePath.c_str());
92  
93        if (((TChain*) this->At(currChain))->AddFile(filePath.c_str(), -1,
94 <                                                   treeName.c_str()) )
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;
96 >      } else {
97 >        return -1;
98 >      }
99  
100      }
101    } else
# Line 134 | Line 138 | int PlotTool::init(string fileName, stri
138  
139    }
140  
137  if( addEventInfo || addTrackJets) {
141  
139    if(verbose)   cout<<"calculating additional variables..."<<endl;
142  
141    //make file for tree friends (adding additional, computed branches)
142    string friendFileName("/scratch/hh/current/cms/user/");
143    friendFileName += gSystem->GetUserInfo()->fUser;
144    friendFileName += "/temp/",
145      friendFileName += fileName;
146    friendFileName += ".root";
147    TFile *f = new TFile(friendFileName.c_str(),"recreate");
148
149    if( f->IsZombie() ) return -1;
150
151    string friendTreeName("friendTree");
152    //char number = currChain;
153    //friendTreeName += number;
154    //TTree *friendTree = new TTree("friendTree","friendTree");
155    TTree *friendTree = new TTree(friendTreeName.c_str(),friendTreeName.c_str());
156    fwlite::ChainEvent ev(fileNames);
157     int _event, _run, _lumi;
158     int nJetsKT;
159     TrackJetKT = new float [100];
160
161    if( addEventInfo ) {
143  
144 +    
145 +  string friendTreeName("friendTree");
146  
147 <      friendTree->Branch("event", &_event, "event/I");
148 <      friendTree->Branch("run", &_run, "run/I");
149 <      friendTree->Branch("lumi", &_lumi, "lumi/I");
150 <
151 <    }
152 <
153 <    if( addTrackJets ) {
154 <
155 <
156 <      friendTree->Branch("nJetsKT", &nJetsKT, "nJetsKT/I");
157 <      friendTree->Branch("TrackJetKT", TrackJetKT, "TrackJetKT[nJetsKT]/F");
158 <    }
159 <
177 <
178 <    int tenth = ev.size() / 10;
179 <    int eventNum =0;
180 <    for (ev.toBegin(); !ev.atEnd(); ++ev, ++eventNum) {
181 <
182 <
183 <      if( addEventInfo ) {
184 <
185 <        _event = ev.id().event();
186 <        _run   = ev.id().run();
187 <        _lumi = ev.luminosityBlock();
188 <
189 <      }
190 <
191 <      if( addTrackJets ) {
192 <
193 <        fwlite::Handle<reco::CaloJetCollection> jets;
194 <        jets.getByLabel(ev, "antikt5CaloJets");
195 <
196 <        fwlite::Handle<reco::TrackCollection> tracks;
197 <        tracks.getByLabel(ev, "generalTracks");
198 <
199 <        if (!jets.isValid())
200 <          continue;
201 <        if (!tracks.isValid())
202 <          continue;
203 <        double trackSum;
204 <        nJetsKT = 0;
205 <        for (reco::CaloJetCollection::const_iterator jet = jets->begin(); jet
206 <               !=jets->end(); jet++) {
207 <          trackSum = 0;
208 <          for (reco::TrackCollection::const_iterator track = tracks->begin(); track
209 <                 !=tracks->end(); track++) {
210 <            if (deltaR(jet->eta(), jet->phi(), track->eta(), track->phi())
211 <                < 0.5)
212 <              trackSum += track->pt();
213 <          }
214 <          TrackJetKT[nJetsKT] = trackSum;
215 <          nJetsKT++;
216 <        }
217 <      }
218 <      friendTree->Fill();
219 <
220 <      if( eventNum != 0 && eventNum%tenth == 0) cout<<"Processed "<<eventNum <<" of "<<ev.size()<<" events. "<<endl;
221 <
222 <    }
223 <    f->cd();
224 <    friendTree->Write();
225 <    f->Close();
147 >  string friendFileName("/scratch/hh/current/cms/user/");
148 >  friendFileName += gSystem->GetUserInfo()->fUser;
149 >  friendFileName += "/temp/";
150 >  friendFileName += fileLabel;
151 >  friendFileName += ".root";
152 >  string fileOpt = "update";
153 >  if( recreateTree )    fileOpt = "recreate";
154 >
155 >  FWliteVariables fwVars(friendTreeName, friendFileName, fileOpt);
156 >
157 >  if(varBlockNames.length() > 1 ) {
158 >    fwVars.loop(fileNames, varBlockNames);
159 >    if(verbose)   cout<<"add friend tree with additional variables: "<<varBlockNames<<endl;
160      ((TChain*) this->At(currChain))->AddFriend(friendTreeName.c_str(),
161                                                 friendFileName.c_str());
162 <
163 <
230 <
162 >  } else {
163 >    if(verbose)   cout<<"No additional variables added."<<endl;
164    }
165  
166 +  
167 +    
168 +
169  
170    timer.Stop();
171    if(verbose) timer.Print();
# Line 239 | Line 175 | int PlotTool::init(string fileName, stri
175   }
176   //------------------------------------------------------------------
177   //Draw given Chain with given variable and given cuts
178 < int PlotTool::plot(int chainIndex, string histName, string cutName,
179 <                int nEntries, string drwOpt) {
178 > TH1* PlotTool::plot(int chainIndex, string histName, string cutName,
179 >                int nEntries, string bins, string drwOpt) {
180 >
181 >        TH1* thisHist = 0;
182  
183          if (chainIndex >= this->GetEntries() )
184 <                return -1;
184 >                return thisHist;
185  
186          TStopwatch timer;
187          if(verbose) {
# Line 310 | Line 248 | int PlotTool::plot(int chainIndex, strin
248  
249  
250          //Draw histogram:
251 <        string cutNameWithGlobal = cutName;
251 >        string cutNameWithGlobal = "";
252 >        if(cutName!="" && globalCuts!="")    cutNameWithGlobal += "(";
253 >        if(cutName!="")                      cutNameWithGlobal += cutName;
254 >        if(cutName!="" && globalCuts!="")    cutNameWithGlobal += ")";
255          if(cutName!="" && globalCuts!="")    cutNameWithGlobal += "&&";
256 +        if(cutName!="" && globalCuts!="")    cutNameWithGlobal += "(";
257          if(globalCuts!="")                   cutNameWithGlobal += globalCuts;
258 +        if(cutName!="" && globalCuts!="")    cutNameWithGlobal += ")";
259 +
260 +        histName += ">>htemp";
261 +        if(bins != "") histName += bins;
262 +
263 +
264 +
265  
266          int draw_err = ((TChain*) this->At(chainIndex))->Draw(histName.c_str(), cutNameWithGlobal.c_str(),
267                          currOpt.c_str(), currN);
268          if (draw_err < 0)
269 <                return draw_err;
269 >                return thisHist;
270  
271          //++++ Fix for histos with no entries +++++++++++++
272          if (draw_err == 0) {
# Line 327 | Line 276 | int PlotTool::plot(int chainIndex, strin
276                          if (useSubPads)
277                                  canvases_[currCanvName.str()]->SetNumber(canvases_[currCanvName.str()]->GetNumber()-1);
278                  }
279 <                cout<< "Warning: "<<currHistName.str().c_str()<<" in "<<currPadName.str()
279 >                if(verbose) cout<< "Warning: "<<currHistName.str().c_str()<<" in "<<currPadName.str()
280                                  <<" has no entries and is not drawn!"<<endl;
281 <                return draw_err;
281 >                return thisHist;
282          }
283          //++++++++++++++++++++++++++++++++++++++++++++++++++
284  
285 <        ((TH1F*) pads_[currPadName.str()]->GetPrimitive("htemp"))->SetName(currHistName.str().c_str()); // Set Name of histogram
285 >        thisHist = (TH1*) pads_[currPadName.str()]->GetPrimitive("htemp");
286 >
287 >        thisHist->SetName(currHistName.str().c_str());
288  
289          // Update for 2D histograms
290 <        if( pads_[currPadName.str()]->GetPrimitive(currHistName.str().c_str())->InheritsFrom("TH2") ) {
290 >        if( thisHist->InheritsFrom("TH2") ) {
291                          pads_[currPadName.str()]->Draw();
292                          setCanvas( pads_[currPadName.str()] );
293          }
# Line 347 | Line 298 | int PlotTool::plot(int chainIndex, strin
298            cout<<"Done: Selected "<<draw_err<<" objects in "<< currN <<" processed events."<<endl;
299            timer.Print();
300          }
301 <        return draw_err;
301 >        return thisHist;
302  
303   }
304   //------------------------------------------------------------------
305   //Standard loop to draw all chains and multiple variables and cuts
306   int PlotTool::loop(vector<string> _histName, vector<string> _cutName,
307 <                int nEntries, string drwOpt, bool correspond) {
307 >                int nEntries, string bins, string drwOpt, bool correspond) {
308  
309          int numProcessed = 0;
310  
311 +        TH1* currHist = 0;
312 +
313 +
314          if (correspond == false) {
315  
316                  for (int i=0; i<this->GetEntries(); ++i) {
# Line 365 | Line 319 | int PlotTool::loop(vector<string> _histN
319                                  for (vector<string>::iterator it2 =_cutName.begin(); it2
320                                                  != _cutName.end(); ++it2) {
321  
322 <                                        numProcessed += plot(i, *it1, *it2, nEntries, drwOpt);
322 >                                  currHist = plot(i, *it1, *it2, nEntries, bins, drwOpt);
323 >                                  if(currHist) numProcessed += int(currHist->GetEntries());
324                                  
325  
326                                  }
# Line 381 | Line 336 | int PlotTool::loop(vector<string> _histN
336                                          _cutName.begin(); it1 != _cutName.end()&&it2
337                                          != _cutName.end(); ++it1, ++it2) {
338  
339 <                                numProcessed += plot(i, *it1, *it2, nEntries, drwOpt);
339 >                          currHist = plot(i, *it1, *it2, nEntries, bins, drwOpt);
340 >                          if(currHist) numProcessed += int(currHist->GetEntries());
341  
342                          }
343                  }
# Line 394 | Line 350 | int PlotTool::loop(vector<string> _histN
350   }
351  
352   //Helper methods to allow for using simple strings as input
353 < int PlotTool::loop(string histName, string cutName, int nEntries, string drwOpt) {
353 > int PlotTool::loop(string histName, string cutName, int nEntries, string bins, string drwOpt) {
354  
355          vector<string> _histName;
356          _histName.push_back(histName);
357          vector<string> _cutName;
358          _cutName.push_back(cutName);
359  
360 <        return loop(_histName, _cutName, nEntries, drwOpt);
360 >        return loop(_histName, _cutName, nEntries, bins, drwOpt);
361  
362   }
363  
364 < int PlotTool::loop(vector<string> _histName, string cutName, int nEntries,
364 > int PlotTool::loop(vector<string> _histName, string cutName, int nEntries, string bins,
365                  string drwOpt) {
366  
367          vector<string> _cutName;
368          _cutName.push_back(cutName);
369  
370 <        return loop(_histName, _cutName, nEntries, drwOpt);
370 >        return loop(_histName, _cutName, nEntries, bins, drwOpt);
371  
372   }
373  
374 < int PlotTool::loop(string histName, vector<string> _cutName, int nEntries,
374 > int PlotTool::loop(string histName, vector<string> _cutName, int nEntries, string bins,
375                  string drwOpt) {
376  
377          vector<string> _histName;
378          _histName.push_back(histName);
379  
380 <        return loop(_histName, _cutName, nEntries, drwOpt);
380 >        return loop(_histName, _cutName, nEntries, bins, drwOpt);
381   }
382   //------------------------------------------------------------------
383   //redraw the canvas to make changes in style visible
384   int PlotTool::updatePads() {
385  
386          for (map< string, TCanvas* >::iterator it=pads_.begin() ; it != pads_.end(); ++it) {
387 <                if (gROOT->GetListOfCanvases()->FindObject((*it).first.c_str() ) ) {
388 <                        (*it).second->Draw();
389 <                        setCanvas((*it).second);
390 <                } else
391 <                        pads_.erase(it);
387 >                if ( ! gROOT->GetListOfCanvases()->FindObject((*it).first.c_str() ) ) {
388 >                  pads_.erase(it);
389 >                  continue;
390 >                }
391 >                if( (*it).second->GetListOfPrimitives()->GetEntries() == 0 ) {
392 >                  (*it).second->Close();
393 >                  pads_.erase(it);
394 >                  continue;
395 >                }
396 >                (*it).second->Draw();
397 >                setCanvas((*it).second);
398 >
399          }
400  
401          return pads_.size();
# Line 495 | Line 458 | int PlotTool::fillCanvases() {
458   //------------------------------------------------------------------
459   void PlotTool::setCanvas(TCanvas* thisCanvas) {
460  
461 +
462          TH1* thisHist = 0;
463          TPaveStats* thisStatsBox = 0;
464          TPaletteAxis* palette =0;
# Line 520 | Line 484 | void PlotTool::setCanvas(TCanvas* thisCa
484  
485          for (int i = 0; i != thisCanvas->GetListOfPrimitives()->GetSize(); ++i) {
486  
487 +
488 +
489                  if ( !thisCanvas->GetListOfPrimitives()->At(i)->InheritsFrom("TH1"))
490                          continue;
491  
492 +
493                  thisHist = ((TH1*) thisCanvas->GetListOfPrimitives()->At(i));
494 +
495 +                TString testString( thisHist->GetName() );
496 +                if( testString.BeginsWith("frame_") ) continue;
497 +
498                  setColor(thisHist, counter);
499                  setMathLabels(thisHist);
500  
501 +                if(normHists) thisHist->Scale(1/thisHist->GetSumOfWeights());
502 +
503                  if (thisHist->GetMaximum() > maxEntry)
504                          maxEntry = thisHist->GetMaximum();
505  
# Line 614 | Line 587 | void PlotTool::setMathLabels(TH1* thisHi
587  
588          //splitlines for many cuts
589          string test1= "{" + globalCuts + "}";
590 <        string test2= "&&" + globalCuts;
590 >        string test2= "&&(" + globalCuts + ")";
591  
592          if(t.find(test1) != string::npos) t.replace(t.find(test1),test1.length(),"");
593          if(t.find(test2) != string::npos) t.replace(t.find(test2),test2.length(),"");
# Line 634 | Line 607 | void PlotTool::setMathLabels(TH1* thisHi
607  
608   void PlotTool::setColor(TH1* thisHist, int counter) {
609  
610 +  thisHist->SetLineWidth(gStyle->GetLineWidth());
611 +
612          if (counter == 0) {
613  
614                  thisHist->SetLineColor(kRed+1);
# Line 678 | Line 653 | void PlotTool::setColor(TH1* thisHist, i
653  
654          }
655  
656 +
657   }
658  
659   void PlotTool::setPalette(TCanvas* thisCanvas, TPaletteAxis* palette) {
# Line 871 | Line 847 | int PlotTool::setVariables(string label)
847          return autoVars.size();
848  
849   }
874 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
875 //Draw efficiencies
876 int  PlotTool::plotEff(int chainIndex, string histName, string cutName, int nEntries, double fitXmin, double fitXmax, string fitFormula)
877 {
878
879  if( chainIndex >= this->GetEntries() ) return -1;
880
881  int currN = nEntries;
882  if(nEntries < 0) currN = ((TChain*) this->At(chainIndex))->GetEntries(); //nEntries<0 : all entries are plotted!
883
884  //++++ Create and name Canvases according to global variables +++++++++++++
885  ostringstream currHistName;
886  if( samePad_trees) currHistName<<((TChain*) this->At(chainIndex))->GetName()<<":";
887  if( samePad_vars)  currHistName<<histName;
888  if( samePad_cuts)  currHistName<<"{"<<cutName<<"}";
889
890  ostringstream currPadName;
891  if(! samePad_trees) currPadName<<((TChain*) this->At(chainIndex))->GetName()<<":";
892  if(! samePad_vars)  currPadName<<histName;
893  if(! samePad_cuts)  currPadName<<"{"<<cutName<<"}";
894
895
896  //Draw total histogram:
897  if( ! pads_["total"] || ! gROOT->FindObject("total") ) {
898    pads_["total"] = new TCanvas("total", "total");
899  } else {
900    pads_["total"]->cd();
901  }
902  ostringstream bins_total;
903  bins_total<<histName;
904  bins_total<<">>total(100,0,1000)";
905
906
907  int draw_err = ((TChain*) this->At(chainIndex))->Draw(bins_total.str().c_str(), "", "", currN);
908  if( draw_err <= 0 ) return draw_err;
909
910
911  TH1* total = ((TH1*) pads_["total"]->GetPrimitive("total"));
912
913  ostringstream bins_bkg;
914  bins_bkg<<histName;
915  bins_bkg<<">>bkg(";
916  bins_bkg<<total->GetNbinsX();
917  bins_bkg<<",";
918  bins_bkg<<total->GetXaxis()->GetXmin();
919  bins_bkg<<",";
920  bins_bkg<<total->GetXaxis()->GetXmax();
921  bins_bkg<<")";
922
923  //Draw bkg histogram:
924  if( ! pads_["bkg"] || ! gROOT->FindObject("bkg") ) {
925    pads_["bkg"] = new TCanvas("bkg", currPadName.str().c_str());
926  } else {
927    pads_["bkg"]->cd();
928  }
929
930  draw_err = ((TChain*) this->At(chainIndex))->Draw(bins_bkg.str().c_str(), cutName.c_str(),"" , currN);
931  if( draw_err <= 0 ) return draw_err;
932
933
934  TH1* bkg = ((TH1*) pads_["bkg"]->GetPrimitive("bkg"));
935
936  //Draw pass histogram:
937  ostringstream bins_pass;
938  bins_pass<<histName;
939  bins_pass<<">>pass(";
940  bins_pass<<total->GetNbinsX();
941  bins_pass<<",";
942  bins_pass<<total->GetXaxis()->GetXmin();
943  bins_pass<<",";
944  bins_pass<<total->GetXaxis()->GetXmax();
945  bins_pass<<")";
946
947  ostringstream cut_pass;
948  cut_pass<<"!(";
949  cut_pass<<cutName;
950  cut_pass<<")";
951  
952
953  if( ! pads_["pass"] || ! gROOT->FindObject("pass") ) {
954    pads_["pass"] = new TCanvas("pass", currPadName.str().c_str());
955  } else {
956    pads_["pass"]->cd();
957  }
958
959  draw_err = ((TChain*) this->At(chainIndex))->Draw(bins_pass.str().c_str(),cut_pass.str().c_str() ,"" , currN);
960  if( draw_err <= 0 ) return draw_err;
961
850  
963  TH1* pass = ((TH1*) pads_["pass"]->GetPrimitive("pass"));
964
965
966  currPadName<<"Eff";
967  //Draw Efficiency Graph:
968  if( ! pads_["EffGraph"] || ! gROOT->FindObject("EffGraph") ) {
969    pads_["EffGraph"] = new TCanvas("EffGraph", currPadName.str().c_str());
970  } else {
971    pads_["EffGraph"]->cd();
972  }
973
974  TGraphAsymmErrors* EffGraph = new TGraphAsymmErrors(bkg, total);
975  EffGraph->SetName(currHistName.str().c_str());
976
977  TF1* reverse = new TF2("reverse","1/y-1",total->GetXaxis()->GetXmin(),total->GetXaxis()->GetXmax());
978  EffGraph->Apply(reverse);
979  EffGraph->Draw("A*");
980
981  TF1* fitfunc = new TF1("fitfunc",fitFormula.c_str(),fitXmin,fitXmax);
982  EffGraph->Fit("fitfunc","R+");
983
984
985  //Save fit function
986
987  ostringstream savefuncName;
988  savefuncName<<histName;
989  savefuncName<<"_";
990
991  if(cutName.find("<") != std::string::npos ) cutName.replace(cutName.find("<"),1,"_");
992  if(cutName.find(">") != std::string::npos ) cutName.replace(cutName.find(">"),1,"_");
993  savefuncName<<cutName;
994
995
996  TFile file("ABCDFunctions.root","UPDATE");
997  TF1* savefunc = new TF1(savefuncName.str().c_str(), fitfunc->GetExpFormula().Data(),0,10000);
998  savefunc->SetParameters( fitfunc->GetParameters() );
999  savefunc->SetParErrors ( fitfunc->GetParErrors() );
1000
1001  //Show results
1002  if( ! pads_["abcd"] || ! gROOT->FindObject("abcd") ) {
1003    pads_["abcd"] = new TCanvas("abcd", "abcd");
1004  } else {
1005    pads_["abcd"]->cd();
1006  }
1007
1008  bkg->Multiply(savefunc);
1009  bkg->Draw();
1010
1011  //  total->Add(bkg,-1);
1012  pass->SetLineColor(kRed);
1013  pass->Draw("sames,e");
1014  pads_["abcd"]->SetLogy();
1015
1016
1017  savefunc->Write();
1018  //  file.Close();
1019
1020
1021  return draw_err;
1022
1023 }
851   //------------------------------------------------------------------

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines