Logo ROOT   6.08/07
Reference Guide
TTreePlayer.cxx
Go to the documentation of this file.
1 // @(#)root/treeplayer:$Id$
2 // Author: Rene Brun 12/01/96
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 /** \class TTreePlayer
13 
14 Implement some of the functionality of the class TTree requiring access to
15 extra libraries (Histogram, display, etc).
16 */
17 
18 #include <string.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 
22 #include "Riostream.h"
23 #include "TTreePlayer.h"
24 #include "TROOT.h"
25 #include "TSystem.h"
26 #include "TFile.h"
27 #include "TEventList.h"
28 #include "TEntryList.h"
29 #include "TBranchObject.h"
30 #include "TBranchElement.h"
31 #include "TStreamerInfo.h"
32 #include "TStreamerElement.h"
33 #include "TLeafObject.h"
34 #include "TLeafF.h"
35 #include "TLeafD.h"
36 #include "TLeafC.h"
37 #include "TLeafB.h"
38 #include "TLeafI.h"
39 #include "TLeafS.h"
40 #include "TMath.h"
41 #include "TH2.h"
42 #include "TH3.h"
43 #include "TPolyMarker.h"
44 #include "TPolyMarker3D.h"
45 #include "TText.h"
46 #include "TDirectory.h"
47 #include "TClonesArray.h"
48 #include "TClass.h"
49 #include "TVirtualPad.h"
50 #include "TProfile.h"
51 #include "TProfile2D.h"
52 #include "TTreeFormula.h"
53 #include "TTreeFormulaManager.h"
54 #include "TStyle.h"
55 #include "Foption.h"
56 #include "TTreeResult.h"
57 #include "TTreeRow.h"
58 #include "TPrincipal.h"
59 #include "TChain.h"
60 #include "TChainElement.h"
61 #include "TF1.h"
62 #include "TH1.h"
63 #include "TVirtualFitter.h"
64 #include "TEnv.h"
65 #include "THLimitsFinder.h"
66 #include "TSelectorDraw.h"
67 #include "TSelectorEntries.h"
68 #include "TPluginManager.h"
69 #include "TObjString.h"
70 #include "TTreeProxyGenerator.h"
71 #include "TTreeReaderGenerator.h"
72 #include "TTreeIndex.h"
73 #include "TChainIndex.h"
74 #include "TRefProxy.h"
75 #include "TRefArrayProxy.h"
76 #include "TVirtualMonitoring.h"
77 #include "TTreeCache.h"
78 #include "TStyle.h"
79 
80 #include "HFitInterface.h"
81 #include "Foption.h"
82 #include "Fit/DataVector.h"
83 #include "Fit/UnBinData.h"
84 #include "Math/MinimizerOptions.h"
85 
86 
87 
89 
91 
93 
94 ////////////////////////////////////////////////////////////////////////////////
95 /// Default Tree constructor.
96 
98 {
99  fTree = 0;
100  fScanFileName = 0;
101  fScanRedirect = kFALSE;
102  fSelectedRows = 0;
103  fDimension = 0;
104  fHistogram = 0;
105  fFormulaList = new TList();
106  fFormulaList->SetOwner(kTRUE);
107  fSelector = new TSelectorDraw();
108  fSelectorFromFile = 0;
109  fSelectorClass = 0;
110  fSelectorUpdate = 0;
111  fInput = new TList();
112  fInput->Add(new TNamed("varexp",""));
113  fInput->Add(new TNamed("selection",""));
114  fSelector->SetInputList(fInput);
115  gROOT->GetListOfCleanups()->Add(this);
118 }
119 
120 ////////////////////////////////////////////////////////////////////////////////
121 /// Tree destructor.
122 
124 {
125  delete fFormulaList;
126  delete fSelector;
128  fInput->Delete();
129  delete fInput;
130  gROOT->GetListOfCleanups()->Remove(this);
131 }
132 
133 ////////////////////////////////////////////////////////////////////////////////
134 /// Build the index for the tree (see TTree::BuildIndex)
135 
136 TVirtualIndex *TTreePlayer::BuildIndex(const TTree *T, const char *majorname, const char *minorname)
137 {
138  TVirtualIndex *index;
139  if (dynamic_cast<const TChain*>(T)) {
140  index = new TChainIndex(T, majorname, minorname);
141  if (index->IsZombie()) {
142  delete index;
143  Error("BuildIndex", "Creating a TChainIndex unsuccessful - switching to TTreeIndex");
144  }
145  else
146  return index;
147  }
148  return new TTreeIndex(T,majorname,minorname);
149 }
150 
151 ////////////////////////////////////////////////////////////////////////////////
152 /// Copy a Tree with selection, make a clone of this Tree header, then copy the
153 /// selected entries.
154 ///
155 /// - selection is a standard selection expression (see TTreePlayer::Draw)
156 /// - option is reserved for possible future use
157 /// - nentries is the number of entries to process (default is all)
158 /// - first is the first entry to process (default is 0)
159 ///
160 /// IMPORTANT: The copied tree stays connected with this tree until this tree
161 /// is deleted. In particular, any changes in branch addresses
162 /// in this tree are forwarded to the clone trees. Any changes
163 /// made to the branch addresses of the copied trees are over-ridden
164 /// anytime this tree changes its branch addresses.
165 /// Once this tree is deleted, all the addresses of the copied tree
166 /// are reset to their default values.
167 ///
168 /// The following example illustrates how to copy some events from the Tree
169 /// generated in $ROOTSYS/test/Event
170 /// ~~~{.cpp}
171 /// gSystem->Load("libEvent");
172 /// TFile f("Event.root");
173 /// TTree *T = (TTree*)f.Get("T");
174 /// Event *event = new Event();
175 /// T->SetBranchAddress("event",&event);
176 /// TFile f2("Event2.root","recreate");
177 /// TTree *T2 = T->CopyTree("fNtrack<595");
178 /// T2->Write();
179 /// ~~~
180 
182  Long64_t firstentry)
183 {
184 
185  // we make a copy of the tree header
186  TTree *tree = fTree->CloneTree(0);
187  if (tree == 0) return 0;
188 
189  // The clone should not delete any shared i/o buffers.
191  Int_t nb = branches->GetEntriesFast();
192  for (Int_t i = 0; i < nb; ++i) {
193  TBranch* br = (TBranch*) branches->UncheckedAt(i);
194  if (br->InheritsFrom(TBranchElement::Class())) {
195  ((TBranchElement*) br)->ResetDeleteObject();
196  }
197  }
198 
199  Long64_t entry,entryNumber;
200  nentries = GetEntriesToProcess(firstentry, nentries);
201 
202  // Compile selection expression if there is one
203  TTreeFormula *select = 0; // no need to interfere with fSelect since we
204  // handle the loop explicitly below and can call
205  // UpdateFormulaLeaves ourselves.
206  if (strlen(selection)) {
207  select = new TTreeFormula("Selection",selection,fTree);
208  if (!select || !select->GetNdim()) {
209  delete select;
210  delete tree;
211  return 0;
212  }
213  fFormulaList->Add(select);
214  }
215 
216  //loop on the specified entries
217  Int_t tnumber = -1;
218  for (entry=firstentry;entry<firstentry+nentries;entry++) {
219  entryNumber = fTree->GetEntryNumber(entry);
220  if (entryNumber < 0) break;
221  Long64_t localEntry = fTree->LoadTree(entryNumber);
222  if (localEntry < 0) break;
223  if (tnumber != fTree->GetTreeNumber()) {
224  tnumber = fTree->GetTreeNumber();
225  if (select) select->UpdateFormulaLeaves();
226  }
227  if (select) {
228  Int_t ndata = select->GetNdata();
229  Bool_t keep = kFALSE;
230  for(Int_t current = 0; current<ndata && !keep; current++) {
231  keep |= (select->EvalInstance(current) != 0);
232  }
233  if (!keep) continue;
234  }
235  fTree->GetEntry(entryNumber);
236  tree->Fill();
237  }
238  fFormulaList->Clear();
239  return tree;
240 }
241 
242 ////////////////////////////////////////////////////////////////////////////////
243 /// Delete any selector created by this object.
244 /// The selector has been created using TSelector::GetSelector(file)
245 
247 {
249  if (fSelectorClass->IsLoaded()) {
250  delete fSelectorFromFile;
251  }
252  }
253  fSelectorFromFile = 0;
254  fSelectorClass = 0;
255 }
256 
257 ////////////////////////////////////////////////////////////////////////////////
258 /// Draw the result of a C++ script.
259 ///
260 /// The macrofilename and optionally cutfilename are assumed to contain
261 /// at least a method with the same name as the file. The method
262 /// should return a value that can be automatically cast to
263 /// respectively a double and a boolean.
264 ///
265 /// Both methods will be executed in a context such that the
266 /// branch names can be used as C++ variables. This is
267 /// accomplished by generating a TTreeProxy (see MakeProxy)
268 /// and including the files in the proper location.
269 ///
270 /// If the branch name can not be used a proper C++ symbol name,
271 /// it will be modified as follow:
272 /// - white spaces are removed
273 /// - if the leading character is not a letter, an underscore is inserted
274 /// - < and > are replace by underscores
275 /// - * is replaced by st
276 /// - & is replaced by rf
277 ///
278 /// If a cutfilename is specified, for each entry, we execute
279 /// ~~~{.cpp}
280 /// if (cutfilename()) htemp->Fill(macrofilename());
281 /// ~~~
282 /// If no cutfilename is specified, for each entry we execute
283 /// ~~~{.cpp}
284 /// htemp(macrofilename());
285 /// ~~~
286 /// The default for the histogram are the same as for
287 /// TTreePlayer::DrawSelect
288 
289 Long64_t TTreePlayer::DrawScript(const char* wrapperPrefix,
290  const char *macrofilename, const char *cutfilename,
291  Option_t *option, Long64_t nentries, Long64_t firstentry)
292 {
293  if (!macrofilename || strlen(macrofilename)==0) return 0;
294 
295  TString aclicMode;
296  TString arguments;
297  TString io;
298  TString realcutname;
299  if (cutfilename && strlen(cutfilename))
300  realcutname = gSystem->SplitAclicMode(cutfilename, aclicMode, arguments, io);
301 
302  // we ignore the aclicMode for the cutfilename!
303  TString realname = gSystem->SplitAclicMode(macrofilename, aclicMode, arguments, io);
304 
305  TString selname = wrapperPrefix;
306 
307  ROOT::Internal::TTreeProxyGenerator gp(fTree,realname,realcutname,selname,option,3);
308 
309  selname = gp.GetFileName();
310  if (aclicMode.Length()==0) {
311  Warning("DrawScript","TTreeProxy does not work in interpreted mode yet. The script will be compiled.");
312  aclicMode = "+";
313  }
314  selname.Append(aclicMode);
315 
316  Info("DrawScript","%s",Form("Will process tree/chain using %s",selname.Data()));
317  Long64_t result = fTree->Process(selname,option,nentries,firstentry);
318  fTree->SetNotify(0);
319 
320  // could delete the file selname+".h"
321  // However this would remove the optimization of avoiding a useless
322  // recompilation if the user ask for the same thing twice!
323 
324  return result;
325 }
326 
327 ////////////////////////////////////////////////////////////////////////////////
328 /// Draw expression varexp for specified entries that matches the selection.
329 /// Returns -1 in case of error or number of selected events in case of success.
330 ///
331 /// See the documentation of TTree::Draw for the complete details.
332 
333 Long64_t TTreePlayer::DrawSelect(const char *varexp0, const char *selection, Option_t *option,Long64_t nentries, Long64_t firstentry)
334 {
335  if (fTree->GetEntriesFriend() == 0) return 0;
336 
337  // Let's see if we have a filename as arguments instead of
338  // a TTreeFormula expression.
339 
340  TString possibleFilename = varexp0;
341  Ssiz_t dot_pos = possibleFilename.Last('.');
342  if ( dot_pos != kNPOS
343  && possibleFilename.Index("Alt$")<0 && possibleFilename.Index("Entries$")<0
344  && possibleFilename.Index("LocalEntries$")<0
345  && possibleFilename.Index("Length$")<0 && possibleFilename.Index("Entry$")<0
346  && possibleFilename.Index("LocalEntry$")<0
347  && possibleFilename.Index("Min$")<0 && possibleFilename.Index("Max$")<0
348  && possibleFilename.Index("MinIf$")<0 && possibleFilename.Index("MaxIf$")<0
349  && possibleFilename.Index("Iteration$")<0 && possibleFilename.Index("Sum$")<0
350  && possibleFilename.Index(">")<0 && possibleFilename.Index("<")<0
351  && gSystem->IsFileInIncludePath(possibleFilename.Data())) {
352 
353  if (selection && strlen(selection) && !gSystem->IsFileInIncludePath(selection)) {
354  Error("DrawSelect",
355  "Drawing using a C++ file currently requires that both the expression and the selection are files\n\t\"%s\" is not a file",
356  selection);
357  return 0;
358  }
359  return DrawScript("generatedSel",varexp0,selection,option,nentries,firstentry);
360 
361  } else {
362  possibleFilename = selection;
363  if (possibleFilename.Index("Alt$")<0 && possibleFilename.Index("Entries$")<0
364  && possibleFilename.Index("LocalEntries$")<0
365  && possibleFilename.Index("Length$")<0 && possibleFilename.Index("Entry$")<0
366  && possibleFilename.Index("LocalEntry$")<0
367  && possibleFilename.Index("Min$")<0 && possibleFilename.Index("Max$")<0
368  && possibleFilename.Index("MinIf$")<0 && possibleFilename.Index("MaxIf$")<0
369  && possibleFilename.Index("Iteration$")<0 && possibleFilename.Index("Sum$")<0
370  && possibleFilename.Index(">")<0 && possibleFilename.Index("<")<0
371  && gSystem->IsFileInIncludePath(possibleFilename.Data())) {
372 
373  Error("DrawSelect",
374  "Drawing using a C++ file currently requires that both the expression and the selection are files\n\t\"%s\" is not a file",
375  varexp0);
376  return 0;
377  }
378  }
379 
380  Long64_t oldEstimate = fTree->GetEstimate();
381  TEventList *evlist = fTree->GetEventList();
382  TEntryList *elist = fTree->GetEntryList();
383  if (evlist && elist){
384  elist->SetBit(kCanDelete, kTRUE);
385  }
386  TNamed *cvarexp = (TNamed*)fInput->FindObject("varexp");
387  TNamed *cselection = (TNamed*)fInput->FindObject("selection");
388  if (cvarexp) cvarexp->SetTitle(varexp0);
389  if (cselection) cselection->SetTitle(selection);
390 
391  TString opt = option;
392  opt.ToLower();
393  Bool_t optpara = kFALSE;
394  Bool_t optcandle = kFALSE;
395  Bool_t optgl5d = kFALSE;
396  Bool_t optnorm = kFALSE;
397  if (opt.Contains("norm")) {optnorm = kTRUE; opt.ReplaceAll("norm",""); opt.ReplaceAll(" ","");}
398  if (opt.Contains("para")) optpara = kTRUE;
399  if (opt.Contains("candle")) optcandle = kTRUE;
400  if (opt.Contains("gl5d")) optgl5d = kTRUE;
402  if (optgl5d) {
404  if (!gPad) {
405  if (pgl == kFALSE) gStyle->SetCanvasPreferGL(kTRUE);
406  gROOT->ProcessLineFast("new TCanvas();");
407  }
408  }
409 
410  // Do not process more than fMaxEntryLoop entries
411  if (nentries > fTree->GetMaxEntryLoop()) nentries = fTree->GetMaxEntryLoop();
412 
413  // invoke the selector
414  Long64_t nrows = Process(fSelector,option,nentries,firstentry);
415  fSelectedRows = nrows;
417 
418  //*-* an Event List
419  if (fDimension <= 0) {
420  fTree->SetEstimate(oldEstimate);
421  if (fSelector->GetCleanElist()) {
422  // We are in the case where the input list was reset!
423  fTree->SetEntryList(elist);
424  delete fSelector->GetObject();
425  }
426  return nrows;
427  }
428 
429  // Draw generated histogram
430  Long64_t drawflag = fSelector->GetDrawFlag();
431  Int_t action = fSelector->GetAction();
432  Bool_t draw = kFALSE;
433  if (!drawflag && !opt.Contains("goff")) draw = kTRUE;
434  if (!optcandle && !optpara) fHistogram = (TH1*)fSelector->GetObject();
435  if (optnorm) {
437  if (sumh != 0) fHistogram->Scale(1./sumh);
438  }
439 
440  //if (!nrows && draw && drawflag && !opt.Contains("same")) {
441  // if (gPad) gPad->Clear();
442  // return 0;
443  //}
444  if (drawflag) {
445  if (gPad) {
446  if (!opt.Contains("same")) {
447  gPad->DrawFrame(-1.,-1.,1.,1.);
448  TText *text_empty = new TText(0.,0.,"Empty");
449  text_empty->SetTextAlign(22);
450  text_empty->SetTextFont(42);
451  text_empty->SetTextSize(0.1);
452  text_empty->SetTextColor(1);
453  text_empty->Draw();
454  }
455  } else {
456  Warning("DrawSelect", "The selected TTree subset is empty.");
457  }
458  }
459 
460  //*-*- 1-D distribution
461  if (fDimension == 1 && !(optpara||optcandle)) {
463  if (draw) fHistogram->Draw(opt.Data());
464 
465  //*-*- 2-D distribution
466  } else if (fDimension == 2 && !(optpara||optcandle)) {
469  if (action == 4) {
470  if (draw) fHistogram->Draw(opt.Data());
471  } else {
472  Bool_t graph = kFALSE;
473  Int_t l = opt.Length();
474  if (l == 0 || opt == "same") graph = kTRUE;
475  if (opt.Contains("p") || opt.Contains("*") || opt.Contains("l")) graph = kTRUE;
476  if (opt.Contains("surf") || opt.Contains("lego") || opt.Contains("cont")) graph = kFALSE;
477  if (opt.Contains("col") || opt.Contains("hist") || opt.Contains("scat")) graph = kFALSE;
478  if (!graph) {
479  if (draw) fHistogram->Draw(opt.Data());
480  } else {
481  if (fSelector->GetOldHistogram() && draw) fHistogram->Draw(opt.Data());
482  }
483  }
484  //*-*- 3-D distribution
485  } else if (fDimension == 3 && !(optpara||optcandle)) {
489  if (action == 23) {
490  if (draw) fHistogram->Draw(opt.Data());
491  } else if (action == 33) {
492  if (draw) {
493  if (opt.Contains("z")) fHistogram->Draw("func z");
494  else fHistogram->Draw("func");
495  }
496  } else {
497  Int_t noscat = opt.Length();
498  if (opt.Contains("same")) noscat -= 4;
499  if (noscat) {
500  if (draw) fHistogram->Draw(opt.Data());
501  } else {
502  if (fSelector->GetOldHistogram() && draw) fHistogram->Draw(opt.Data());
503  }
504  }
505  //*-*- 4-D distribution
506  } else if (fDimension == 4 && !(optpara||optcandle)) {
510  if (draw) fHistogram->Draw(opt.Data());
511  Int_t ncolors = gStyle->GetNumberOfColors();
512  TObjArray *pms = (TObjArray*)fHistogram->GetListOfFunctions()->FindObject("polymarkers");
513  for (Int_t col=0;col<ncolors;col++) {
514  if (!pms) continue;
515  TPolyMarker3D *pm3d = (TPolyMarker3D*)pms->UncheckedAt(col);
516  if (draw) pm3d->Draw();
517  }
518  //*-*- Parallel Coordinates or Candle chart.
519  } else if (fDimension > 1 && (optpara || optcandle)) {
520  if (draw) {
521  TObject* para = fSelector->GetObject();
522  fTree->Draw(">>enlist",selection,"entrylist",nentries,firstentry);
523  TObject *enlist = gDirectory->FindObject("enlist");
524  gROOT->ProcessLine(Form("TParallelCoord::SetEntryList((TParallelCoord*)0x%lx,(TEntryList*)0x%lx)",
525  (ULong_t)para, (ULong_t)enlist));
526  }
527  //*-*- 5d with gl
528  } else if (fDimension == 5 && optgl5d) {
529  gROOT->ProcessLineFast(Form("(new TGL5DDataSet((TTree *)0x%lx))->Draw(\"%s\");", (ULong_t)fTree, opt.Data()));
531  }
532 
534  return fSelectedRows;
535 }
536 
537 ////////////////////////////////////////////////////////////////////////////////
538 /// Fit a projected item(s) from a Tree.
539 /// Returns -1 in case of error or number of selected events in case of success.
540 ///
541 /// The formula is a TF1 expression.
542 ///
543 /// See TTree::Draw for explanations of the other parameters.
544 ///
545 /// By default the temporary histogram created is called htemp.
546 /// If varexp contains >>hnew , the new histogram created is called hnew
547 /// and it is kept in the current directory.
548 /// Example:
549 /// ~~~{.cpp}
550 /// tree.Fit("pol4","sqrt(x)>>hsqrt","y>0")
551 /// will fit sqrt(x) and save the histogram as "hsqrt" in the current
552 /// directory.
553 /// ~~~
554 ///
555 /// The function returns the status of the histogram fit (see TH1::Fit)
556 /// If no entries were selected, the function returns -1;
557 /// (i.e. fitResult is null if the fit is OK)
558 
559 Int_t TTreePlayer::Fit(const char *formula ,const char *varexp, const char *selection,Option_t *option ,Option_t *goption,Long64_t nentries, Long64_t firstentry)
560 {
561  Int_t nch = option ? strlen(option) + 10 : 10;
562  char *opt = new char[nch];
563  if (option) strlcpy(opt,option,nch-1);
564  else strlcpy(opt,"goff",5);
565 
566  Long64_t nsel = DrawSelect(varexp,selection,opt,nentries,firstentry);
567 
568  delete [] opt;
569  Int_t fitResult = -1;
570 
571  if (fHistogram && nsel > 0) {
572  fitResult = fHistogram->Fit(formula,option,goption);
573  }
574  return fitResult;
575 }
576 
577 ////////////////////////////////////////////////////////////////////////////////
578 /// Return the number of entries matching the selection.
579 /// Return -1 in case of errors.
580 ///
581 /// If the selection uses any arrays or containers, we return the number
582 /// of entries where at least one element match the selection.
583 /// GetEntries is implemented using the selector class TSelectorEntries,
584 /// which can be used directly (see code in TTreePlayer::GetEntries) for
585 /// additional option.
586 /// If SetEventList was used on the TTree or TChain, only that subset
587 /// of entries will be considered.
588 
589 Long64_t TTreePlayer::GetEntries(const char *selection)
590 {
591  TSelectorEntries s(selection);
592  fTree->Process(&s);
593  fTree->SetNotify(0);
594  return s.GetSelectedRows();
595 }
596 
597 ////////////////////////////////////////////////////////////////////////////////
598 /// return the number of entries to be processed
599 /// this function checks that nentries is not bigger than the number
600 /// of entries in the Tree or in the associated TEventlist
601 
603 {
604  Long64_t lastentry = firstentry + nentries - 1;
605  if (lastentry > fTree->GetEntriesFriend()-1) {
606  lastentry = fTree->GetEntriesFriend() - 1;
607  nentries = lastentry - firstentry + 1;
608  }
609  //TEventList *elist = fTree->GetEventList();
610  //if (elist && elist->GetN() < nentries) nentries = elist->GetN();
611  TEntryList *elist = fTree->GetEntryList();
612  if (elist && elist->GetN() < nentries) nentries = elist->GetN();
613  return nentries;
614 }
615 
616 ////////////////////////////////////////////////////////////////////////////////
617 /// Return name corresponding to colindex in varexp.
618 ///
619 /// - varexp is a string of names separated by :
620 /// - index is an array with pointers to the start of name[i] in varexp
621 
622 const char *TTreePlayer::GetNameByIndex(TString &varexp, Int_t *index,Int_t colindex)
623 {
624  TTHREAD_TLS_DECL(std::string,column);
625  if (colindex<0 ) return "";
626  Int_t i1,n;
627  i1 = index[colindex] + 1;
628  n = index[colindex+1] - i1;
629  column = varexp(i1,n).Data();
630  // return (const char*)Form((const char*)column);
631  return column.c_str();
632 }
633 
634 ////////////////////////////////////////////////////////////////////////////////
635 /// Return the name of the branch pointer needed by MakeClass/MakeSelector
636 
638 {
639  TLeaf *leafcount = leaf->GetLeafCount();
640  TBranch *branch = leaf->GetBranch();
641 
642  TString branchname( branch->GetName() );
643 
644  if ( branch->GetNleaves() <= 1 ) {
645  if (branch->IsA() != TBranchObject::Class()) {
646  if (!leafcount) {
647  TBranch *mother = branch->GetMother();
648  const char* ltitle = leaf->GetTitle();
649  if (mother && mother!=branch) {
650  branchname = mother->GetName();
651  if (branchname[branchname.Length()-1]!='.') {
652  branchname += ".";
653  }
654  if (strncmp(branchname.Data(),ltitle,branchname.Length())==0) {
655  branchname = "";
656  }
657  } else {
658  branchname = "";
659  }
660  branchname += ltitle;
661  }
662  }
663  }
664  if (replace) {
665  char *bname = (char*)branchname.Data();
666  char *twodim = (char*)strstr(bname,"[");
667  if (twodim) *twodim = 0;
668  while (*bname) {
669  if (*bname == '.') *bname='_';
670  if (*bname == ',') *bname='_';
671  if (*bname == ':') *bname='_';
672  if (*bname == '<') *bname='_';
673  if (*bname == '>') *bname='_';
674  bname++;
675  }
676  }
677  return branchname;
678 }
679 
680 ////////////////////////////////////////////////////////////////////////////////
681 /// Generate skeleton analysis class for this Tree.
682 ///
683 /// The following files are produced: classname.h and classname.C
684 /// If classname is 0, classname will be called "nameoftree.
685 ///
686 /// The generated code in classname.h includes the following:
687 /// - Identification of the original Tree and Input file name
688 /// - Definition of analysis class (data and functions)
689 /// - the following class functions:
690 /// - constructor (connecting by default the Tree file)
691 /// - GetEntry(Long64_t entry)
692 /// - Init(TTree *tree) to initialize a new TTree
693 /// - Show(Long64_t entry) to read and Dump entry
694 ///
695 /// The generated code in classname.C includes only the main
696 /// analysis function Loop.
697 ///
698 /// To use this function:
699 /// - connect your Tree file (eg: TFile f("myfile.root");)
700 /// - T->MakeClass("MyClass");
701 ///
702 /// where T is the name of the Tree in file myfile.root
703 /// and MyClass.h, MyClass.C the name of the files created by this function.
704 /// In a ROOT session, you can do:
705 /// ~~~{.cpp}
706 /// root> .L MyClass.C
707 /// root> MyClass t
708 /// root> t.GetEntry(12); // Fill t data members with entry number 12
709 /// root> t.Show(); // Show values of entry 12
710 /// root> t.Show(16); // Read and show values of entry 16
711 /// root> t.Loop(); // Loop on all entries
712 /// ~~~
713 /// NOTE: Do not use the code generated for one Tree in case of a TChain.
714 /// Maximum dimensions calculated on the basis of one TTree only
715 /// might be too small when processing all the TTrees in one TChain.
716 /// Instead of myTree.MakeClass(.., use myChain.MakeClass(..
717 
718 Int_t TTreePlayer::MakeClass(const char *classname, const char *option)
719 {
720  TString opt = option;
721  opt.ToLower();
722 
723  // Connect output files
724  if (!classname) classname = fTree->GetName();
725 
726  TString thead;
727  thead.Form("%s.h", classname);
728  FILE *fp = fopen(thead, "w");
729  if (!fp) {
730  Error("MakeClass","cannot open output file %s", thead.Data());
731  return 3;
732  }
733  TString tcimp;
734  tcimp.Form("%s.C", classname);
735  FILE *fpc = fopen(tcimp, "w");
736  if (!fpc) {
737  Error("MakeClass","cannot open output file %s", tcimp.Data());
738  fclose(fp);
739  return 3;
740  }
741  TString treefile;
742  if (fTree->GetDirectory() && fTree->GetDirectory()->GetFile()) {
743  treefile = fTree->GetDirectory()->GetFile()->GetName();
744  } else {
745  treefile = "Memory Directory";
746  }
747  // In the case of a chain, the GetDirectory information usually does
748  // pertain to the Chain itself but to the currently loaded tree.
749  // So we can not rely on it.
750  Bool_t ischain = fTree->InheritsFrom(TChain::Class());
751  Bool_t isHbook = fTree->InheritsFrom("THbookTree");
752  if (isHbook)
753  treefile = fTree->GetTitle();
754 
755 //======================Generate classname.h=====================
756  // Print header
757  TObjArray *leaves = fTree->GetListOfLeaves();
758  Int_t nleaves = leaves ? leaves->GetEntriesFast() : 0;
759  TDatime td;
760  fprintf(fp,"//////////////////////////////////////////////////////////\n");
761  fprintf(fp,"// This class has been automatically generated on\n");
762  fprintf(fp,"// %s by ROOT version %s\n",td.AsString(),gROOT->GetVersion());
763  if (!ischain) {
764  fprintf(fp,"// from TTree %s/%s\n",fTree->GetName(),fTree->GetTitle());
765  fprintf(fp,"// found on file: %s\n",treefile.Data());
766  } else {
767  fprintf(fp,"// from TChain %s/%s\n",fTree->GetName(),fTree->GetTitle());
768  }
769  fprintf(fp,"//////////////////////////////////////////////////////////\n");
770  fprintf(fp,"\n");
771  fprintf(fp,"#ifndef %s_h\n",classname);
772  fprintf(fp,"#define %s_h\n",classname);
773  fprintf(fp,"\n");
774  fprintf(fp,"#include <TROOT.h>\n");
775  fprintf(fp,"#include <TChain.h>\n");
776  fprintf(fp,"#include <TFile.h>\n");
777  if (isHbook) fprintf(fp,"#include <THbookFile.h>\n");
778  if (opt.Contains("selector")) fprintf(fp,"#include <TSelector.h>\n");
779 
780  // See if we can add any #include about the user data.
781  Int_t l;
782  fprintf(fp,"\n// Header file for the classes stored in the TTree if any.\n");
783  TList listOfHeaders;
784  listOfHeaders.SetOwner();
785  for (l=0;l<nleaves;l++) {
786  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
787  TBranch *branch = leaf->GetBranch();
788  TClass *cl = TClass::GetClass(branch->GetClassName());
789  if (cl && cl->IsLoaded() && !listOfHeaders.FindObject(cl->GetName())) {
790  const char *declfile = cl->GetDeclFileName();
791  if (declfile && declfile[0]) {
792  static const char *precstl = "prec_stl/";
793  static const unsigned int precstl_len = strlen(precstl);
794  static const char *rootinclude = "include/";
795  static const unsigned int rootinclude_len = strlen(rootinclude);
796  if (strncmp(declfile,precstl,precstl_len) == 0) {
797  fprintf(fp,"#include <%s>\n",declfile+precstl_len);
798  listOfHeaders.Add(new TNamed(cl->GetName(),declfile+precstl_len));
799  } else if (strncmp(declfile,"/usr/include/",13) == 0) {
800  fprintf(fp,"#include <%s>\n",declfile+strlen("/include/c++/"));
801  listOfHeaders.Add(new TNamed(cl->GetName(),declfile+strlen("/include/c++/")));
802  } else if (strstr(declfile,"/include/c++/") != 0) {
803  fprintf(fp,"#include <%s>\n",declfile+strlen("/include/c++/"));
804  listOfHeaders.Add(new TNamed(cl->GetName(),declfile+strlen("/include/c++/")));
805  } else if (strncmp(declfile,rootinclude,rootinclude_len) == 0) {
806  fprintf(fp,"#include <%s>\n",declfile+rootinclude_len);
807  listOfHeaders.Add(new TNamed(cl->GetName(),declfile+rootinclude_len));
808  } else {
809  fprintf(fp,"#include \"%s\"\n",declfile);
810  listOfHeaders.Add(new TNamed(cl->GetName(),declfile));
811  }
812  }
813  }
814  }
815 
816  // First loop on all leaves to generate dimension declarations
817  Int_t len, lenb;
818  char blen[1024];
819  char *bname;
820  Int_t *leaflen = new Int_t[nleaves];
821  TObjArray *leafs = new TObjArray(nleaves);
822  for (l=0;l<nleaves;l++) {
823  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
824  leafs->AddAt(new TObjString(leaf->GetName()),l);
825  leaflen[l] = leaf->GetMaximum();
826  }
827  if (ischain) {
828  // In case of a chain, one must find the maximum dimension of each leaf
829  // One must be careful and not assume that all Trees in the chain
830  // have the same leaves and in the same order!
831  TChain *chain = (TChain*)fTree;
832  Int_t ntrees = chain->GetNtrees();
833  for (Int_t file=0;file<ntrees;file++) {
834  Long64_t first = chain->GetTreeOffset()[file];
835  chain->LoadTree(first);
836  for (l=0;l<nleaves;l++) {
837  TObjString *obj = (TObjString*)leafs->At(l);
838  TLeaf *leaf = chain->GetLeaf(obj->GetName());
839  if (leaf) {
840  leaflen[l] = TMath::Max(leaflen[l],leaf->GetMaximum());
841  }
842  }
843  }
844  chain->LoadTree(0);
845  }
846 
847  fprintf(fp,"\n");
848  if (opt.Contains("selector")) {
849  fprintf(fp,"class %s : public TSelector {\n",classname);
850  fprintf(fp,"public :\n");
851  fprintf(fp," TTree *fChain; //!pointer to the analyzed TTree or TChain\n");
852  } else {
853  fprintf(fp,"class %s {\n",classname);
854  fprintf(fp,"public :\n");
855  fprintf(fp," TTree *fChain; //!pointer to the analyzed TTree or TChain\n");
856  fprintf(fp," Int_t fCurrent; //!current Tree number in a TChain\n");
857  }
858 
859  fprintf(fp,"\n// Fixed size dimensions of array or collections stored in the TTree if any.\n");
860  leaves = fTree->GetListOfLeaves();
861  for (l=0;l<nleaves;l++) {
862  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
863  strlcpy(blen,leaf->GetName(),sizeof(blen));
864  bname = &blen[0];
865  while (*bname) {
866  if (*bname == '.') *bname='_';
867  if (*bname == ',') *bname='_';
868  if (*bname == ':') *bname='_';
869  if (*bname == '<') *bname='_';
870  if (*bname == '>') *bname='_';
871  bname++;
872  }
873  lenb = strlen(blen);
874  if (blen[lenb-1] == '_') {
875  blen[lenb-1] = 0;
876  len = leaflen[l];
877  if (len <= 0) len = 1;
878  fprintf(fp," const Int_t kMax%s = %d;\n",blen,len);
879  }
880  }
881  delete [] leaflen;
882  leafs->Delete();
883  delete leafs;
884 
885 // second loop on all leaves to generate type declarations
886  fprintf(fp,"\n // Declaration of leaf types\n");
887  TLeaf *leafcount;
888  TLeafObject *leafobj;
889  TBranchElement *bre=0;
890  const char *headOK = " ";
891  const char *headcom = " //";
892  const char *head;
893  char branchname[1024];
894  char aprefix[1024];
895  TObjArray branches(100);
896  TObjArray mustInit(100);
897  TObjArray mustInitArr(100);
898  mustInitArr.SetOwner(kFALSE);
899  Int_t *leafStatus = new Int_t[nleaves];
900  for (l=0;l<nleaves;l++) {
901  Int_t kmax = 0;
902  head = headOK;
903  leafStatus[l] = 0;
904  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
905  len = leaf->GetLen(); if (len<=0) len = 1;
906  leafcount =leaf->GetLeafCount();
907  TBranch *branch = leaf->GetBranch();
908  branchname[0] = 0;
909  strlcpy(branchname,branch->GetName(),sizeof(branchname));
910  strlcpy(aprefix,branch->GetName(),sizeof(aprefix));
911  if (!branches.FindObject(branch)) branches.Add(branch);
912  else leafStatus[l] = 1;
913  if ( branch->GetNleaves() > 1) {
914  // More than one leaf for the branch we need to distinguish them
915  strlcat(branchname,".",sizeof(branchname));
916  strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
917  if (leafcount) {
918  // remove any dimension in title
919  char *dim = (char*)strstr(branchname,"["); if (dim) dim[0] = 0;
920  }
921  } else {
922  strlcpy(branchname,branch->GetName(),sizeof(branchname));
923  }
924  char *twodim = (char*)strstr(leaf->GetTitle(),"][");
925  bname = branchname;
926  while (*bname) {
927  if (*bname == '.') *bname='_';
928  if (*bname == ',') *bname='_';
929  if (*bname == ':') *bname='_';
930  if (*bname == '<') *bname='_';
931  if (*bname == '>') *bname='_';
932  bname++;
933  }
934  if (branch->IsA() == TBranchObject::Class()) {
935  if (branch->GetListOfBranches()->GetEntriesFast()) {leafStatus[l] = 1; continue;}
936  leafobj = (TLeafObject*)leaf;
937  if (!leafobj->GetClass()) {leafStatus[l] = 1; head = headcom;}
938  fprintf(fp,"%s%-15s *%s;\n",head,leafobj->GetTypeName(), leafobj->GetName());
939  if (leafStatus[l] == 0) mustInit.Add(leafobj);
940  continue;
941  }
942  if (leafcount) {
943  len = leafcount->GetMaximum();
944  if (len<=0) len = 1;
945  strlcpy(blen,leafcount->GetName(),sizeof(blen));
946  bname = &blen[0];
947  while (*bname) {
948  if (*bname == '.') *bname='_';
949  if (*bname == ',') *bname='_';
950  if (*bname == ':') *bname='_';
951  if (*bname == '<') *bname='_';
952  if (*bname == '>') *bname='_';
953  bname++;
954  }
955  lenb = strlen(blen);
956  if (blen[lenb-1] == '_') {blen[lenb-1] = 0; kmax = 1;}
957  else snprintf(blen,sizeof(blen),"%d",len);
958  }
959  if (branch->IsA() == TBranchElement::Class()) {
960  bre = (TBranchElement*)branch;
961  if (bre->GetType() != 3 && bre->GetType() != 4
962  && bre->GetStreamerType() <= 0 && bre->GetListOfBranches()->GetEntriesFast()) {
963  leafStatus[l] = 0;
964  }
965  if (bre->GetType() == 3 || bre->GetType() == 4) {
966  fprintf(fp," %-15s %s_;\n","Int_t", branchname);
967  continue;
968  }
969  if (bre->IsBranchFolder()) {
970  fprintf(fp," %-15s *%s;\n",bre->GetClassName(), branchname);
971  mustInit.Add(bre);
972  continue;
973  } else {
974  if (branch->GetListOfBranches()->GetEntriesFast()) {leafStatus[l] = 1;}
975  }
976  if (bre->GetStreamerType() < 0) {
977  if (branch->GetListOfBranches()->GetEntriesFast()) {
978  fprintf(fp,"%s%-15s *%s;\n",headcom,bre->GetClassName(), branchname);
979  } else {
980  fprintf(fp,"%s%-15s *%s;\n",head,bre->GetClassName(), branchname);
981  mustInit.Add(bre);
982  }
983  continue;
984  }
985  if (bre->GetStreamerType() == 0) {
986  if (!TClass::GetClass(bre->GetClassName())->HasInterpreterInfo()) {leafStatus[l] = 1; head = headcom;}
987  fprintf(fp,"%s%-15s *%s;\n",head,bre->GetClassName(), branchname);
988  if (leafStatus[l] == 0) mustInit.Add(bre);
989  continue;
990  }
991  if (bre->GetStreamerType() > 60) {
992  TClass *cle = TClass::GetClass(bre->GetClassName());
993  if (!cle) {leafStatus[l] = 1; continue;}
994  if (bre->GetStreamerType() == 66) leafStatus[l] = 0;
995  char brename[256];
996  strlcpy(brename,bre->GetName(),255);
997  char *bren = brename;
998  char *adot = strrchr(bren,'.');
999  if (adot) bren = adot+1;
1000  char *brack = strchr(bren,'[');
1001  if (brack) *brack = 0;
1003  if (elem) {
1004  if (elem->IsA() == TStreamerBase::Class()) {leafStatus[l] = 1; continue;}
1005  if (!TClass::GetClass(elem->GetTypeName())) {leafStatus[l] = 1; continue;}
1006  if (!TClass::GetClass(elem->GetTypeName())->HasInterpreterInfo()) {leafStatus[l] = 1; head = headcom;}
1007  if (leafcount) fprintf(fp,"%s%-15s %s[kMax%s];\n",head,elem->GetTypeName(), branchname,blen);
1008  else fprintf(fp,"%s%-15s %s;\n",head,elem->GetTypeName(), branchname);
1009  } else {
1010  if (!TClass::GetClass(bre->GetClassName())->HasInterpreterInfo()) {leafStatus[l] = 1; head = headcom;}
1011  fprintf(fp,"%s%-15s %s;\n",head,bre->GetClassName(), branchname);
1012  }
1013  continue;
1014  }
1015  }
1016  if (strlen(leaf->GetTypeName()) == 0) {leafStatus[l] = 1; continue;}
1017  if (leafcount) {
1018  //len = leafcount->GetMaximum();
1019  //strlcpy(blen,leafcount->GetName(),sizeof(blen));
1020  //bname = &blen[0];
1021  //while (*bname) {if (*bname == '.') *bname='_'; bname++;}
1022  //lenb = strlen(blen);
1023  //Int_t kmax = 0;
1024  //if (blen[lenb-1] == '_') {blen[lenb-1] = 0; kmax = 1;}
1025  //else sprintf(blen,"%d",len);
1026 
1027  const char *stars = " ";
1028  if (bre && bre->GetBranchCount2()) {
1029  stars = "*";
1030  }
1031  // Dimensions can be in the branchname for a split Object with a fix length C array.
1032  // Theses dimensions HAVE TO be placed after the dimension explicited by leafcount
1033  TString dimensions;
1034  char *dimInName = (char*) strstr(branchname,"[");
1035  if ( twodim || dimInName ) {
1036  if (dimInName) {
1037  dimensions = dimInName;
1038  dimInName[0] = 0; // terminate branchname before the array dimensions.
1039  }
1040  if (twodim) dimensions += (char*)(twodim+1);
1041  }
1042  const char* leafcountName = leafcount->GetName();
1043  char b2len[1024];
1044  if (bre && bre->GetBranchCount2()) {
1045  TLeaf * l2 = (TLeaf*)bre->GetBranchCount2()->GetListOfLeaves()->At(0);
1046  strlcpy(b2len,l2->GetName(),sizeof(b2len));
1047  bname = &b2len[0];
1048  while (*bname) {
1049  if (*bname == '.') *bname='_';
1050  if (*bname == ',') *bname='_';
1051  if (*bname == ':') *bname='_';
1052  if (*bname == '<') *bname='_';
1053  if (*bname == '>') *bname='_';
1054  bname++;
1055  }
1056  leafcountName = b2len;
1057  }
1058  if (dimensions.Length()) {
1059  if (kmax) fprintf(fp," %-14s %s%s[kMax%s]%s; //[%s]\n",leaf->GetTypeName(), stars,
1060  branchname,blen,dimensions.Data(),leafcountName);
1061  else fprintf(fp," %-14s %s%s[%d]%s; //[%s]\n",leaf->GetTypeName(), stars,
1062  branchname,len,dimensions.Data(),leafcountName);
1063  } else {
1064  if (kmax) fprintf(fp," %-14s %s%s[kMax%s]; //[%s]\n",leaf->GetTypeName(), stars, branchname,blen,leafcountName);
1065  else fprintf(fp," %-14s %s%s[%d]; //[%s]\n",leaf->GetTypeName(), stars, branchname,len,leafcountName);
1066  }
1067  if (stars[0]=='*') {
1068  TNamed *n;
1069  if (kmax) n = new TNamed(branchname, Form("kMax%s",blen));
1070  else n = new TNamed(branchname, Form("%d",len));
1071  mustInitArr.Add(n);
1072  }
1073  } else {
1074  if (strstr(branchname,"[")) len = 1;
1075  if (len < 2) fprintf(fp," %-15s %s;\n",leaf->GetTypeName(), branchname);
1076  else {
1077  if (twodim) fprintf(fp," %-15s %s%s;\n",leaf->GetTypeName(), branchname,(char*)strstr(leaf->GetTitle(),"["));
1078  else fprintf(fp," %-15s %s[%d];\n",leaf->GetTypeName(), branchname,len);
1079  }
1080  }
1081  }
1082 
1083 // generate list of branches
1084  fprintf(fp,"\n");
1085  fprintf(fp," // List of branches\n");
1086  for (l=0;l<nleaves;l++) {
1087  if (leafStatus[l]) continue;
1088  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1089  fprintf(fp," TBranch *b_%s; //!\n",R__GetBranchPointerName(leaf).Data());
1090  }
1091 
1092 // generate class member functions prototypes
1093  if (opt.Contains("selector")) {
1094  fprintf(fp,"\n");
1095  fprintf(fp," %s(TTree * /*tree*/ =0) : fChain(0) { }\n",classname) ;
1096  fprintf(fp," virtual ~%s() { }\n",classname);
1097  fprintf(fp," virtual Int_t Version() const { return 2; }\n");
1098  fprintf(fp," virtual void Begin(TTree *tree);\n");
1099  fprintf(fp," virtual void SlaveBegin(TTree *tree);\n");
1100  fprintf(fp," virtual void Init(TTree *tree);\n");
1101  fprintf(fp," virtual Bool_t Notify();\n");
1102  fprintf(fp," virtual Bool_t Process(Long64_t entry);\n");
1103  fprintf(fp," virtual Int_t GetEntry(Long64_t entry, Int_t getall = 0) { return fChain ? fChain->GetTree()->GetEntry(entry, getall) : 0; }\n");
1104  fprintf(fp," virtual void SetOption(const char *option) { fOption = option; }\n");
1105  fprintf(fp," virtual void SetObject(TObject *obj) { fObject = obj; }\n");
1106  fprintf(fp," virtual void SetInputList(TList *input) { fInput = input; }\n");
1107  fprintf(fp," virtual TList *GetOutputList() const { return fOutput; }\n");
1108  fprintf(fp," virtual void SlaveTerminate();\n");
1109  fprintf(fp," virtual void Terminate();\n\n");
1110  fprintf(fp," ClassDef(%s,0);\n",classname);
1111  fprintf(fp,"};\n");
1112  fprintf(fp,"\n");
1113  fprintf(fp,"#endif\n");
1114  fprintf(fp,"\n");
1115  } else {
1116  fprintf(fp,"\n");
1117  fprintf(fp," %s(TTree *tree=0);\n",classname);
1118  fprintf(fp," virtual ~%s();\n",classname);
1119  fprintf(fp," virtual Int_t Cut(Long64_t entry);\n");
1120  fprintf(fp," virtual Int_t GetEntry(Long64_t entry);\n");
1121  fprintf(fp," virtual Long64_t LoadTree(Long64_t entry);\n");
1122  fprintf(fp," virtual void Init(TTree *tree);\n");
1123  fprintf(fp," virtual void Loop();\n");
1124  fprintf(fp," virtual Bool_t Notify();\n");
1125  fprintf(fp," virtual void Show(Long64_t entry = -1);\n");
1126  fprintf(fp,"};\n");
1127  fprintf(fp,"\n");
1128  fprintf(fp,"#endif\n");
1129  fprintf(fp,"\n");
1130  }
1131 // generate code for class constructor
1132  fprintf(fp,"#ifdef %s_cxx\n",classname);
1133  if (!opt.Contains("selector")) {
1134  fprintf(fp,"%s::%s(TTree *tree) : fChain(0) \n",classname,classname);
1135  fprintf(fp,"{\n");
1136  fprintf(fp,"// if parameter tree is not specified (or zero), connect the file\n");
1137  fprintf(fp,"// used to generate this class and read the Tree.\n");
1138  fprintf(fp," if (tree == 0) {\n");
1139  if (ischain) {
1140  fprintf(fp,"\n#ifdef SINGLE_TREE\n");
1141  fprintf(fp," // The following code should be used if you want this class to access\n");
1142  fprintf(fp," // a single tree instead of a chain\n");
1143  }
1144  if (isHbook) {
1145  fprintf(fp," THbookFile *f = (THbookFile*)gROOT->GetListOfBrowsables()->FindObject(\"%s\");\n",
1146  treefile.Data());
1147  fprintf(fp," if (!f) {\n");
1148  fprintf(fp," f = new THbookFile(\"%s\");\n",treefile.Data());
1149  fprintf(fp," }\n");
1150  Int_t hid;
1151  sscanf(fTree->GetName(),"h%d",&hid);
1152  fprintf(fp," tree = (TTree*)f->Get(%d);\n\n",hid);
1153  } else {
1154  fprintf(fp," TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(\"%s\");\n",treefile.Data());
1155  fprintf(fp," if (!f || !f->IsOpen()) {\n");
1156  fprintf(fp," f = new TFile(\"%s\");\n",treefile.Data());
1157  fprintf(fp," }\n");
1158  if (fTree->GetDirectory() != fTree->GetCurrentFile()) {
1159  fprintf(fp," TDirectory * dir = (TDirectory*)f->Get(\"%s\");\n",fTree->GetDirectory()->GetPath());
1160  fprintf(fp," dir->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1161  } else {
1162  fprintf(fp," f->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1163  }
1164  }
1165  if (ischain) {
1166  fprintf(fp,"#else // SINGLE_TREE\n\n");
1167  fprintf(fp," // The following code should be used if you want this class to access a chain\n");
1168  fprintf(fp," // of trees.\n");
1169  fprintf(fp," TChain * chain = new TChain(\"%s\",\"%s\");\n",
1170  fTree->GetName(),fTree->GetTitle());
1171  {
1173  TIter next(((TChain*)fTree)->GetListOfFiles());
1174  TChainElement *element;
1175  while ((element = (TChainElement*)next())) {
1176  fprintf(fp," chain->Add(\"%s/%s\");\n",element->GetTitle(),element->GetName());
1177  }
1178  }
1179  fprintf(fp," tree = chain;\n");
1180  fprintf(fp,"#endif // SINGLE_TREE\n\n");
1181  }
1182  fprintf(fp," }\n");
1183  fprintf(fp," Init(tree);\n");
1184  fprintf(fp,"}\n");
1185  fprintf(fp,"\n");
1186  }
1187 
1188 // generate code for class destructor()
1189  if (!opt.Contains("selector")) {
1190  fprintf(fp,"%s::~%s()\n",classname,classname);
1191  fprintf(fp,"{\n");
1192  fprintf(fp," if (!fChain) return;\n");
1193  if (isHbook) {
1194  //fprintf(fp," delete fChain->GetCurrentFile();\n");
1195  } else {
1196  fprintf(fp," delete fChain->GetCurrentFile();\n");
1197  }
1198  fprintf(fp,"}\n");
1199  fprintf(fp,"\n");
1200  }
1201 // generate code for class member function GetEntry()
1202  if (!opt.Contains("selector")) {
1203  fprintf(fp,"Int_t %s::GetEntry(Long64_t entry)\n",classname);
1204  fprintf(fp,"{\n");
1205  fprintf(fp,"// Read contents of entry.\n");
1206 
1207  fprintf(fp," if (!fChain) return 0;\n");
1208  fprintf(fp," return fChain->GetEntry(entry);\n");
1209  fprintf(fp,"}\n");
1210  }
1211 // generate code for class member function LoadTree()
1212  if (!opt.Contains("selector")) {
1213  fprintf(fp,"Long64_t %s::LoadTree(Long64_t entry)\n",classname);
1214  fprintf(fp,"{\n");
1215  fprintf(fp,"// Set the environment to read one entry\n");
1216  fprintf(fp," if (!fChain) return -5;\n");
1217  fprintf(fp," Long64_t centry = fChain->LoadTree(entry);\n");
1218  fprintf(fp," if (centry < 0) return centry;\n");
1219  fprintf(fp," if (fChain->GetTreeNumber() != fCurrent) {\n");
1220  fprintf(fp," fCurrent = fChain->GetTreeNumber();\n");
1221  fprintf(fp," Notify();\n");
1222  fprintf(fp," }\n");
1223  fprintf(fp," return centry;\n");
1224  fprintf(fp,"}\n");
1225  fprintf(fp,"\n");
1226  }
1227 
1228 // generate code for class member function Init(), first pass = get branch pointer
1229  fprintf(fp,"void %s::Init(TTree *tree)\n",classname);
1230  fprintf(fp,"{\n");
1231  fprintf(fp," // The Init() function is called when the selector needs to initialize\n"
1232  " // a new tree or chain. Typically here the branch addresses and branch\n"
1233  " // pointers of the tree will be set.\n"
1234  " // It is normally not necessary to make changes to the generated\n"
1235  " // code, but the routine can be extended by the user if needed.\n"
1236  " // Init() will be called many times when running on PROOF\n"
1237  " // (once per file to be processed).\n\n");
1238  if (mustInit.Last()) {
1239  TIter next(&mustInit);
1240  TObject *obj;
1241  fprintf(fp," // Set object pointer\n");
1242  while( (obj = next()) ) {
1243  if (obj->InheritsFrom(TBranch::Class())) {
1244  strlcpy(branchname,((TBranch*)obj)->GetName(),sizeof(branchname));
1245  } else if (obj->InheritsFrom(TLeaf::Class())) {
1246  strlcpy(branchname,((TLeaf*)obj)->GetName(),sizeof(branchname));
1247  }
1248  branchname[1023]=0;
1249  bname = branchname;
1250  while (*bname) {
1251  if (*bname == '.') *bname='_';
1252  if (*bname == ',') *bname='_';
1253  if (*bname == ':') *bname='_';
1254  if (*bname == '<') *bname='_';
1255  if (*bname == '>') *bname='_';
1256  bname++;
1257  }
1258  fprintf(fp," %s = 0;\n",branchname );
1259  }
1260  }
1261  if (mustInitArr.Last()) {
1262  TIter next(&mustInitArr);
1263  TNamed *info;
1264  fprintf(fp," // Set array pointer\n");
1265  while( (info = (TNamed*)next()) ) {
1266  fprintf(fp," for(int i=0; i<%s; ++i) %s[i] = 0;\n",info->GetTitle(),info->GetName());
1267  }
1268  fprintf(fp,"\n");
1269  }
1270  fprintf(fp," // Set branch addresses and branch pointers\n");
1271  fprintf(fp," if (!tree) return;\n");
1272  fprintf(fp," fChain = tree;\n");
1273  if (!opt.Contains("selector")) fprintf(fp," fCurrent = -1;\n");
1274  fprintf(fp," fChain->SetMakeClass(1);\n");
1275  fprintf(fp,"\n");
1276  for (l=0;l<nleaves;l++) {
1277  if (leafStatus[l]) continue;
1278  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1279  len = leaf->GetLen();
1280  leafcount =leaf->GetLeafCount();
1281  TBranch *branch = leaf->GetBranch();
1282  strlcpy(aprefix,branch->GetName(),sizeof(aprefix));
1283 
1284  if ( branch->GetNleaves() > 1) {
1285  // More than one leaf for the branch we need to distinguish them
1286  strlcpy(branchname,branch->GetName(),sizeof(branchname));
1287  strlcat(branchname,".",sizeof(branchname));
1288  strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
1289  if (leafcount) {
1290  // remove any dimension in title
1291  char *dim = (char*)strstr(branchname,"["); if (dim) dim[0] = 0;
1292  }
1293  } else {
1294  strlcpy(branchname,branch->GetName(),sizeof(branchname));
1295  if (branch->IsA() == TBranchElement::Class()) {
1296  bre = (TBranchElement*)branch;
1297  if (bre->GetType() == 3 || bre->GetType()==4) strlcat(branchname,"_",sizeof(branchname));
1298  }
1299  }
1300  bname = branchname;
1301  char *brak = strstr(branchname,"["); if (brak) *brak = 0;
1302  char *twodim = (char*)strstr(bname,"["); if (twodim) *twodim = 0;
1303  while (*bname) {
1304  if (*bname == '.') *bname='_';
1305  if (*bname == ',') *bname='_';
1306  if (*bname == ':') *bname='_';
1307  if (*bname == '<') *bname='_';
1308  if (*bname == '>') *bname='_';
1309  bname++;
1310  }
1311  const char *maybedisable = "";
1312  if (branch != fTree->GetBranch(branch->GetName())) {
1313  Error("MakeClass","The branch named %s (full path name: %s) is hidden by another branch of the same name and its data will not be loaded.",branch->GetName(),R__GetBranchPointerName(leaf,kFALSE).Data());
1314  maybedisable = "// ";
1315  }
1316  if (branch->IsA() == TBranchObject::Class()) {
1317  if (branch->GetListOfBranches()->GetEntriesFast()) {
1318  fprintf(fp,"%s fChain->SetBranchAddress(\"%s\",(void*)-1,&b_%s);\n",maybedisable,branch->GetName(),R__GetBranchPointerName(leaf).Data());
1319  continue;
1320  }
1321  strlcpy(branchname,branch->GetName(),sizeof(branchname));
1322  }
1323  if (branch->IsA() == TBranchElement::Class()) {
1324  if (((TBranchElement*)branch)->GetType() == 3) len =1;
1325  if (((TBranchElement*)branch)->GetType() == 4) len =1;
1326  }
1327  if (leafcount) len = leafcount->GetMaximum()+1;
1328  if (len > 1) fprintf(fp,"%s fChain->SetBranchAddress(\"%s\", %s, &b_%s);\n",
1329  maybedisable,branch->GetName(), branchname, R__GetBranchPointerName(leaf).Data());
1330  else fprintf(fp,"%s fChain->SetBranchAddress(\"%s\", &%s, &b_%s);\n",
1331  maybedisable,branch->GetName(), branchname, R__GetBranchPointerName(leaf).Data());
1332  }
1333  //must call Notify in case of MakeClass
1334  if (!opt.Contains("selector")) {
1335  fprintf(fp," Notify();\n");
1336  }
1337 
1338  fprintf(fp,"}\n");
1339  fprintf(fp,"\n");
1340 
1341 // generate code for class member function Notify()
1342  fprintf(fp,"Bool_t %s::Notify()\n",classname);
1343  fprintf(fp,"{\n");
1344  fprintf(fp," // The Notify() function is called when a new file is opened. This\n"
1345  " // can be either for a new TTree in a TChain or when when a new TTree\n"
1346  " // is started when using PROOF. It is normally not necessary to make changes\n"
1347  " // to the generated code, but the routine can be extended by the\n"
1348  " // user if needed. The return value is currently not used.\n\n");
1349  fprintf(fp," return kTRUE;\n");
1350  fprintf(fp,"}\n");
1351  fprintf(fp,"\n");
1352 
1353 // generate code for class member function Show()
1354  if (!opt.Contains("selector")) {
1355  fprintf(fp,"void %s::Show(Long64_t entry)\n",classname);
1356  fprintf(fp,"{\n");
1357  fprintf(fp,"// Print contents of entry.\n");
1358  fprintf(fp,"// If entry is not specified, print current entry\n");
1359 
1360  fprintf(fp," if (!fChain) return;\n");
1361  fprintf(fp," fChain->Show(entry);\n");
1362  fprintf(fp,"}\n");
1363  }
1364 // generate code for class member function Cut()
1365  if (!opt.Contains("selector")) {
1366  fprintf(fp,"Int_t %s::Cut(Long64_t entry)\n",classname);
1367  fprintf(fp,"{\n");
1368  fprintf(fp,"// This function may be called from Loop.\n");
1369  fprintf(fp,"// returns 1 if entry is accepted.\n");
1370  fprintf(fp,"// returns -1 otherwise.\n");
1371 
1372  fprintf(fp," return 1;\n");
1373  fprintf(fp,"}\n");
1374  }
1375  fprintf(fp,"#endif // #ifdef %s_cxx\n",classname);
1376 
1377 //======================Generate classname.C=====================
1378  if (!opt.Contains("selector")) {
1379  // generate code for class member function Loop()
1380  fprintf(fpc,"#define %s_cxx\n",classname);
1381  fprintf(fpc,"#include \"%s\"\n",thead.Data());
1382  fprintf(fpc,"#include <TH2.h>\n");
1383  fprintf(fpc,"#include <TStyle.h>\n");
1384  fprintf(fpc,"#include <TCanvas.h>\n");
1385  fprintf(fpc,"\n");
1386  fprintf(fpc,"void %s::Loop()\n",classname);
1387  fprintf(fpc,"{\n");
1388  fprintf(fpc,"// In a ROOT session, you can do:\n");
1389  fprintf(fpc,"// root> .L %s.C\n",classname);
1390  fprintf(fpc,"// root> %s t\n",classname);
1391  fprintf(fpc,"// root> t.GetEntry(12); // Fill t data members with entry number 12\n");
1392  fprintf(fpc,"// root> t.Show(); // Show values of entry 12\n");
1393  fprintf(fpc,"// root> t.Show(16); // Read and show values of entry 16\n");
1394  fprintf(fpc,"// root> t.Loop(); // Loop on all entries\n");
1395  fprintf(fpc,"//\n");
1396  fprintf(fpc,"\n// This is the loop skeleton where:\n");
1397  fprintf(fpc,"// jentry is the global entry number in the chain\n");
1398  fprintf(fpc,"// ientry is the entry number in the current Tree\n");
1399  fprintf(fpc,"// Note that the argument to GetEntry must be:\n");
1400  fprintf(fpc,"// jentry for TChain::GetEntry\n");
1401  fprintf(fpc,"// ientry for TTree::GetEntry and TBranch::GetEntry\n");
1402  fprintf(fpc,"//\n");
1403  fprintf(fpc,"// To read only selected branches, Insert statements like:\n");
1404  fprintf(fpc,"// METHOD1:\n");
1405  fprintf(fpc,"// fChain->SetBranchStatus(\"*\",0); // disable all branches\n");
1406  fprintf(fpc,"// fChain->SetBranchStatus(\"branchname\",1); // activate branchname\n");
1407  fprintf(fpc,"// METHOD2: replace line\n");
1408  fprintf(fpc,"// fChain->GetEntry(jentry); //read all branches\n");
1409  fprintf(fpc,"//by b_branchname->GetEntry(ientry); //read only this branch\n");
1410  fprintf(fpc," if (fChain == 0) return;\n");
1411  fprintf(fpc,"\n Long64_t nentries = fChain->GetEntriesFast();\n");
1412  fprintf(fpc,"\n Long64_t nbytes = 0, nb = 0;\n");
1413  fprintf(fpc," for (Long64_t jentry=0; jentry<nentries;jentry++) {\n");
1414  fprintf(fpc," Long64_t ientry = LoadTree(jentry);\n");
1415  fprintf(fpc," if (ientry < 0) break;\n");
1416  fprintf(fpc," nb = fChain->GetEntry(jentry); nbytes += nb;\n");
1417  fprintf(fpc," // if (Cut(ientry) < 0) continue;\n");
1418  fprintf(fpc," }\n");
1419  fprintf(fpc,"}\n");
1420  }
1421  if (opt.Contains("selector")) {
1422  // generate usage comments and list of includes
1423  fprintf(fpc,"#define %s_cxx\n",classname);
1424  fprintf(fpc,"// The class definition in %s.h has been generated automatically\n",classname);
1425  fprintf(fpc,"// by the ROOT utility TTree::MakeSelector(). This class is derived\n");
1426  fprintf(fpc,"// from the ROOT class TSelector. For more information on the TSelector\n"
1427  "// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.\n\n");
1428  fprintf(fpc,"// The following methods are defined in this file:\n");
1429  fprintf(fpc,"// Begin(): called every time a loop on the tree starts,\n");
1430  fprintf(fpc,"// a convenient place to create your histograms.\n");
1431  fprintf(fpc,"// SlaveBegin(): called after Begin(), when on PROOF called only on the\n"
1432  "// slave servers.\n");
1433  fprintf(fpc,"// Process(): called for each event, in this function you decide what\n");
1434  fprintf(fpc,"// to read and fill your histograms.\n");
1435  fprintf(fpc,"// SlaveTerminate: called at the end of the loop on the tree, when on PROOF\n"
1436  "// called only on the slave servers.\n");
1437  fprintf(fpc,"// Terminate(): called at the end of the loop on the tree,\n");
1438  fprintf(fpc,"// a convenient place to draw/fit your histograms.\n");
1439  fprintf(fpc,"//\n");
1440  fprintf(fpc,"// To use this file, try the following session on your Tree T:\n");
1441  fprintf(fpc,"//\n");
1442  fprintf(fpc,"// root> T->Process(\"%s.C\")\n",classname);
1443  fprintf(fpc,"// root> T->Process(\"%s.C\",\"some options\")\n",classname);
1444  fprintf(fpc,"// root> T->Process(\"%s.C+\")\n",classname);
1445  fprintf(fpc,"//\n\n");
1446  fprintf(fpc,"#include \"%s\"\n",thead.Data());
1447  fprintf(fpc,"#include <TH2.h>\n");
1448  fprintf(fpc,"#include <TStyle.h>\n");
1449  fprintf(fpc,"\n");
1450  // generate code for class member function Begin
1451  fprintf(fpc,"\n");
1452  fprintf(fpc,"void %s::Begin(TTree * /*tree*/)\n",classname);
1453  fprintf(fpc,"{\n");
1454  fprintf(fpc," // The Begin() function is called at the start of the query.\n");
1455  fprintf(fpc," // When running with PROOF Begin() is only called on the client.\n");
1456  fprintf(fpc," // The tree argument is deprecated (on PROOF 0 is passed).\n");
1457  fprintf(fpc,"\n");
1458  fprintf(fpc," TString option = GetOption();\n");
1459  fprintf(fpc,"\n");
1460  fprintf(fpc,"}\n");
1461  // generate code for class member function SlaveBegin
1462  fprintf(fpc,"\n");
1463  fprintf(fpc,"void %s::SlaveBegin(TTree * /*tree*/)\n",classname);
1464  fprintf(fpc,"{\n");
1465  fprintf(fpc," // The SlaveBegin() function is called after the Begin() function.\n");
1466  fprintf(fpc," // When running with PROOF SlaveBegin() is called on each slave server.\n");
1467  fprintf(fpc," // The tree argument is deprecated (on PROOF 0 is passed).\n");
1468  fprintf(fpc,"\n");
1469  fprintf(fpc," TString option = GetOption();\n");
1470  fprintf(fpc,"\n");
1471  fprintf(fpc,"}\n");
1472  // generate code for class member function Process
1473  fprintf(fpc,"\n");
1474  fprintf(fpc,"Bool_t %s::Process(Long64_t entry)\n",classname);
1475  fprintf(fpc,"{\n");
1476  fprintf(fpc," // The Process() function is called for each entry in the tree (or possibly\n"
1477  " // keyed object in the case of PROOF) to be processed. The entry argument\n"
1478  " // specifies which entry in the currently loaded tree is to be processed.\n"
1479  " // It can be passed to either %s::GetEntry() or TBranch::GetEntry()\n"
1480  " // to read either all or the required parts of the data. When processing\n"
1481  " // keyed objects with PROOF, the object is already loaded and is available\n"
1482  " // via the fObject pointer.\n"
1483  " //\n"
1484  " // This function should contain the \"body\" of the analysis. It can contain\n"
1485  " // simple or elaborate selection criteria, run algorithms on the data\n"
1486  " // of the event and typically fill histograms.\n"
1487  " //\n"
1488  " // The processing can be stopped by calling Abort().\n"
1489  " //\n"
1490  " // Use fStatus to set the return value of TTree::Process().\n"
1491  " //\n"
1492  " // The return value is currently not used.\n\n", classname);
1493  fprintf(fpc,"\n");
1494  fprintf(fpc," return kTRUE;\n");
1495  fprintf(fpc,"}\n");
1496  // generate code for class member function SlaveTerminate
1497  fprintf(fpc,"\n");
1498  fprintf(fpc,"void %s::SlaveTerminate()\n",classname);
1499  fprintf(fpc,"{\n");
1500  fprintf(fpc," // The SlaveTerminate() function is called after all entries or objects\n"
1501  " // have been processed. When running with PROOF SlaveTerminate() is called\n"
1502  " // on each slave server.");
1503  fprintf(fpc,"\n");
1504  fprintf(fpc,"\n");
1505  fprintf(fpc,"}\n");
1506  // generate code for class member function Terminate
1507  fprintf(fpc,"\n");
1508  fprintf(fpc,"void %s::Terminate()\n",classname);
1509  fprintf(fpc,"{\n");
1510  fprintf(fpc," // The Terminate() function is the last function to be called during\n"
1511  " // a query. It always runs on the client, it can be used to present\n"
1512  " // the results graphically or save the results to file.");
1513  fprintf(fpc,"\n");
1514  fprintf(fpc,"\n");
1515  fprintf(fpc,"}\n");
1516  }
1517  Info("MakeClass","Files: %s and %s generated from TTree: %s",thead.Data(),tcimp.Data(),fTree->GetName());
1518  delete [] leafStatus;
1519  fclose(fp);
1520  fclose(fpc);
1521 
1522  return 0;
1523 }
1524 
1525 
1526 ////////////////////////////////////////////////////////////////////////////////
1527 /// Generate skeleton function for this Tree
1528 ///
1529 /// The function code is written on filename.
1530 /// If filename is 0, filename will be called nameoftree.C
1531 ///
1532 /// The generated code includes the following:
1533 /// - Identification of the original Tree and Input file name
1534 /// - Connection of the Tree file
1535 /// - Declaration of Tree variables
1536 /// - Setting of branches addresses
1537 /// - A skeleton for the entry loop
1538 ///
1539 /// To use this function:
1540 /// - connect your Tree file (eg: TFile f("myfile.root");)
1541 /// - T->MakeCode("anal.C");
1542 /// where T is the name of the Tree in file myfile.root
1543 /// and anal.C the name of the file created by this function.
1544 ///
1545 /// NOTE: Since the implementation of this function, a new and better
1546 /// function TTree::MakeClass() has been developed.
1547 
1548 Int_t TTreePlayer::MakeCode(const char *filename)
1549 {
1550 // Connect output file
1551  TString tfile;
1552  if (filename)
1553  tfile = filename;
1554  else
1555  tfile.Form("%s.C", fTree->GetName());
1556  FILE *fp = fopen(tfile, "w");
1557  if (!fp) {
1558  Error("MakeCode","cannot open output file %s", tfile.Data());
1559  return 3;
1560  }
1561  TString treefile;
1562  if (fTree->GetDirectory() && fTree->GetDirectory()->GetFile()) {
1563  treefile = fTree->GetDirectory()->GetFile()->GetName();
1564  } else {
1565  treefile = "Memory Directory";
1566  }
1567  // In the case of a chain, the GetDirectory information usually does
1568  // pertain to the Chain itself but to the currently loaded tree.
1569  // So we can not rely on it.
1570  Bool_t ischain = fTree->InheritsFrom(TChain::Class());
1571 
1572 // Print header
1573  TObjArray *leaves = fTree->GetListOfLeaves();
1574  Int_t nleaves = leaves ? leaves->GetEntriesFast() : 0;
1575  TDatime td;
1576  fprintf(fp,"{\n");
1577  fprintf(fp,"//////////////////////////////////////////////////////////\n");
1578  fprintf(fp,"// This file has been automatically generated \n");
1579  fprintf(fp,"// (%s by ROOT version%s)\n",td.AsString(),gROOT->GetVersion());
1580  if (!ischain) {
1581  fprintf(fp,"// from TTree %s/%s\n",fTree->GetName(),fTree->GetTitle());
1582  fprintf(fp,"// found on file: %s\n",treefile.Data());
1583  } else {
1584  fprintf(fp,"// from TChain %s/%s\n",fTree->GetName(),fTree->GetTitle());
1585  }
1586  fprintf(fp,"//////////////////////////////////////////////////////////\n");
1587  fprintf(fp,"\n");
1588  fprintf(fp,"\n");
1589 
1590 
1591 // Reset and file connect
1592  fprintf(fp,"//Reset ROOT and connect tree file\n");
1593  fprintf(fp," gROOT->Reset();\n");
1594  if (ischain) {
1595  fprintf(fp,"\n#ifdef SINGLE_TREE\n");
1596  fprintf(fp," // The following code should be used if you want this code to access\n");
1597  fprintf(fp," // a single tree instead of a chain\n");
1598  }
1599  fprintf(fp," TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(\"%s\");\n",treefile.Data());
1600  fprintf(fp," if (!f) {\n");
1601  fprintf(fp," f = new TFile(\"%s\");\n",treefile.Data());
1602  fprintf(fp," }\n");
1603  if (fTree->GetDirectory() != fTree->GetCurrentFile()) {
1604  fprintf(fp," TDirectory * dir = (TDirectory*)f->Get(\"%s\");\n",fTree->GetDirectory()->GetPath());
1605  fprintf(fp," dir->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1606  } else {
1607  fprintf(fp," f->GetObject(\"%s\",tree);\n\n",fTree->GetName());
1608  }
1609  if (ischain) {
1610  fprintf(fp,"#else // SINGLE_TREE\n\n");
1611  fprintf(fp," // The following code should be used if you want this code to access a chain\n");
1612  fprintf(fp," // of trees.\n");
1613  fprintf(fp," TChain *%s = new TChain(\"%s\",\"%s\");\n",
1615  {
1617  TIter next(((TChain*)fTree)->GetListOfFiles());
1618  TChainElement *element;
1619  while ((element = (TChainElement*)next())) {
1620  fprintf(fp," %s->Add(\"%s/%s\");\n",fTree->GetName(),element->GetTitle(),element->GetName());
1621  }
1622  }
1623  fprintf(fp,"#endif // SINGLE_TREE\n\n");
1624  }
1625 
1626 // First loop on all leaves to generate type declarations
1627  fprintf(fp,"//Declaration of leaves types\n");
1628  Int_t len, l;
1629  TLeaf *leafcount;
1630  TLeafObject *leafobj;
1631  char *bname;
1632  const char *headOK = " ";
1633  const char *headcom = " //";
1634  const char *head;
1635  char branchname[1024];
1636  for (l=0;l<nleaves;l++) {
1637  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1638  len = leaf->GetLen();
1639  leafcount =leaf->GetLeafCount();
1640  TBranch *branch = leaf->GetBranch();
1641  if (branch->GetListOfBranches()->GetEntriesFast() > 0) continue;
1642 
1643  if ( branch->GetNleaves() > 1) {
1644  // More than one leaf for the branch we need to distinguish them
1645  strlcpy(branchname,branch->GetName(),sizeof(branchname));
1646  strlcat(branchname,".",sizeof(branchname));
1647  strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
1648  if (leafcount) {
1649  // remove any dimension in title
1650  char *dim = (char*)strstr(branchname,"[");
1651  if (dim) dim[0] = 0;
1652  }
1653  } else {
1654  if (leafcount) strlcpy(branchname,branch->GetName(),sizeof(branchname));
1655  else strlcpy(branchname,leaf->GetTitle(),sizeof(branchname));
1656  }
1657  char *twodim = (char*)strstr(leaf->GetTitle(),"][");
1658  bname = branchname;
1659  while (*bname) {
1660  if (*bname == '.') *bname='_';
1661  if (*bname == ',') *bname='_';
1662  if (*bname == ':') *bname='_';
1663  if (*bname == '<') *bname='_';
1664  if (*bname == '>') *bname='_';
1665  bname++;
1666  }
1667  if (branch->IsA() == TBranchObject::Class()) {
1668  leafobj = (TLeafObject*)leaf;
1669  if (leafobj->GetClass()) head = headOK;
1670  else head = headcom;
1671  fprintf(fp,"%s%-15s *%s = 0;\n",head,leafobj->GetTypeName(), leafobj->GetName());
1672  continue;
1673  }
1674  if (leafcount) {
1675  len = leafcount->GetMaximum();
1676  // Dimensions can be in the branchname for a split Object with a fix length C array.
1677  // Theses dimensions HAVE TO be placed after the dimension explicited by leafcount
1678  char *dimInName = (char*) strstr(branchname,"[");
1679  TString dimensions;
1680  if ( twodim || dimInName ) {
1681  if (dimInName) {
1682  dimensions = dimInName;
1683  dimInName[0] = 0; // terminate branchname before the array dimensions.
1684  }
1685  if (twodim) dimensions += (char*)(twodim+1);
1686  }
1687  if (dimensions.Length()) {
1688  fprintf(fp," %-15s %s[%d]%s;\n",leaf->GetTypeName(), branchname,len,dimensions.Data());
1689  } else {
1690  fprintf(fp," %-15s %s[%d];\n",leaf->GetTypeName(), branchname,len);
1691  }
1692  } else {
1693  if (strstr(branchname,"[")) len = 1;
1694  if (len < 2) fprintf(fp," %-15s %s;\n",leaf->GetTypeName(), branchname);
1695  else fprintf(fp," %-15s %s[%d];\n",leaf->GetTypeName(), branchname,len);
1696  }
1697  }
1698 
1699 // Second loop on all leaves to set the corresponding branch address
1700  fprintf(fp,"\n // Set branch addresses.\n");
1701  for (l=0;l<nleaves;l++) {
1702  TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
1703  len = leaf->GetLen();
1704  leafcount =leaf->GetLeafCount();
1705  TBranch *branch = leaf->GetBranch();
1706 
1707  if ( branch->GetNleaves() > 1) {
1708  // More than one leaf for the branch we need to distinguish them
1709  strlcpy(branchname,branch->GetName(),sizeof(branchname));
1710  strlcat(branchname,".",sizeof(branchname));
1711  strlcat(branchname,leaf->GetTitle(),sizeof(branchname));
1712  if (leafcount) {
1713  // remove any dimension in title
1714  char *dim = (char*)strstr(branchname,"[");
1715  if (dim) dim[0] = 0;
1716  }
1717  } else {
1718  if (leafcount) strlcpy(branchname,branch->GetName(),sizeof(branchname));
1719  else strlcpy(branchname,leaf->GetTitle(),sizeof(branchname));
1720  }
1721  bname = branchname;
1722  while (*bname) {
1723  if (*bname == '.') *bname='_';
1724  if (*bname == ',') *bname='_';
1725  if (*bname == ':') *bname='_';
1726  if (*bname == '<') *bname='_';
1727  if (*bname == '>') *bname='_';
1728  bname++;
1729  }
1730  char *brak = strstr(branchname,"[");
1731  if (brak) *brak = 0;
1732  head = headOK;
1733  if (branch->IsA() == TBranchObject::Class()) {
1734  strlcpy(branchname,branch->GetName(),sizeof(branchname));
1735  leafobj = (TLeafObject*)leaf;
1736  if (!leafobj->GetClass()) head = headcom;
1737  }
1738  if (leafcount) len = leafcount->GetMaximum()+1;
1739  if (len > 1 || brak) fprintf(fp,"%s%s->SetBranchAddress(\"%s\",%s);\n",head,fTree->GetName(),branch->GetName(),branchname);
1740  else fprintf(fp,"%s%s->SetBranchAddress(\"%s\",&%s);\n",head,fTree->GetName(),branch->GetName(),branchname);
1741  }
1742 
1743 //Generate instructions to make the loop on entries
1744  fprintf(fp,"\n// This is the loop skeleton\n");
1745  fprintf(fp,"// To read only selected branches, Insert statements like:\n");
1746  fprintf(fp,"// %s->SetBranchStatus(\"*\",0); // disable all branches\n",fTree->GetName());
1747  fprintf(fp,"// %s->SetBranchStatus(\"branchname\",1); // activate branchname\n",GetName());
1748  fprintf(fp,"\n Long64_t nentries = %s->GetEntries();\n",fTree->GetName());
1749  fprintf(fp,"\n Long64_t nbytes = 0;\n");
1750  fprintf(fp,"// for (Long64_t i=0; i<nentries;i++) {\n");
1751  fprintf(fp,"// nbytes += %s->GetEntry(i);\n",fTree->GetName());
1752  fprintf(fp,"// }\n");
1753  fprintf(fp,"}\n");
1754 
1755  printf("Macro: %s generated from Tree: %s\n",tfile.Data(), fTree->GetName());
1756  fclose(fp);
1757 
1758  return 0;
1759 }
1760 
1761 ////////////////////////////////////////////////////////////////////////////////
1762 /// Generate a skeleton analysis class for this Tree using TBranchProxy.
1763 /// TBranchProxy is the base of a class hierarchy implementing an
1764 /// indirect access to the content of the branches of a TTree.
1765 ///
1766 /// "proxyClassname" is expected to be of the form:
1767 /// ~~~{.cpp}
1768 /// [path/]fileprefix
1769 /// ~~~
1770 /// The skeleton will then be generated in the file:
1771 /// ~~~{.cpp}
1772 /// fileprefix.h
1773 /// ~~~
1774 /// located in the current directory or in 'path/' if it is specified.
1775 /// The class generated will be named 'fileprefix'.
1776 /// If the fileprefix contains a period, the right side of the period
1777 /// will be used as the extension (instead of 'h') and the left side
1778 /// will be used as the classname.
1779 ///
1780 /// "macrofilename" and optionally "cutfilename" are expected to point
1781 /// to source file which will be included in by the generated skeletong.
1782 /// Method of the same name as the file(minus the extension and path)
1783 /// will be called by the generated skeleton's Process method as follow:
1784 /// ~~~{.cpp}
1785 /// [if (cutfilename())] htemp->Fill(macrofilename());
1786 /// ~~~
1787 /// "option" can be used select some of the optional features during
1788 /// the code generation. The possible options are:
1789 /// - nohist : indicates that the generated ProcessFill should not
1790 /// fill the histogram.
1791 ///
1792 /// 'maxUnrolling' controls how deep in the class hierarchy does the
1793 /// system 'unroll' class that are not split. 'unrolling' a class
1794 /// will allow direct access to its data members a class (this
1795 /// emulates the behavior of TTreeFormula).
1796 ///
1797 /// The main features of this skeleton are:
1798 ///
1799 /// * on-demand loading of branches
1800 /// * ability to use the 'branchname' as if it was a data member
1801 /// * protection against array out-of-bound
1802 /// * ability to use the branch data as object (when the user code is available)
1803 ///
1804 /// For example with Event.root, if
1805 /// ~~~{.cpp}
1806 /// Double_t somepx = fTracks.fPx[2];
1807 /// ~~~
1808 /// is executed by one of the method of the skeleton,
1809 /// somepx will be updated with the current value of fPx of the 3rd track.
1810 ///
1811 /// Both macrofilename and the optional cutfilename are expected to be
1812 /// the name of source files which contain at least a free standing
1813 /// function with the signature:
1814 /// ~~~{.cpp}
1815 /// x_t macrofilename(); // i.e function with the same name as the file
1816 /// ~~~
1817 /// and
1818 /// ~~~{.cpp}
1819 /// y_t cutfilename(); // i.e function with the same name as the file
1820 /// ~~~
1821 /// x_t and y_t needs to be types that can convert respectively to a double
1822 /// and a bool (because the skeleton uses:
1823 /// ~~~{.cpp}
1824 /// if (cutfilename()) htemp->Fill(macrofilename());
1825 /// ~~~
1826 /// This 2 functions are run in a context such that the branch names are
1827 /// available as local variables of the correct (read-only) type.
1828 ///
1829 /// Note that if you use the same 'variable' twice, it is more efficient
1830 /// to 'cache' the value. For example
1831 /// ~~~{.cpp}
1832 /// Int_t n = fEventNumber; // Read fEventNumber
1833 /// if (n<10 || n>10) { ... }
1834 /// ~~~
1835 /// is more efficient than
1836 /// ~~~{.cpp}
1837 /// if (fEventNumber<10 || fEventNumber>10)
1838 /// ~~~
1839 /// Access to TClonesArray.
1840 ///
1841 /// If a branch (or member) is a TClonesArray (let's say fTracks), you
1842 /// can access the TClonesArray itself by using ->:
1843 /// ~~~{.cpp}
1844 /// fTracks->GetLast();
1845 /// ~~~
1846 /// However this will load the full TClonesArray object and its content.
1847 /// To quickly read the size of the TClonesArray use (note the dot):
1848 /// ~~~{.cpp}
1849 /// fTracks.GetEntries();
1850 /// ~~~
1851 /// This will read only the size from disk if the TClonesArray has been
1852 /// split.
1853 /// To access the content of the TClonesArray, use the [] operator:
1854 /// ~~~
1855 /// float px = fTracks[i].fPx; // fPx of the i-th track
1856 /// ~~~
1857 /// Warning:
1858 ///
1859 /// The variable actually use for access are 'wrapper' around the
1860 /// real data type (to add autoload for example) and hence getting to
1861 /// the data involves the implicit call to a C++ conversion operator.
1862 /// This conversion is automatic in most case. However it is not invoked
1863 /// in a few cases, in particular in variadic function (like printf).
1864 /// So when using printf you should either explicitly cast the value or
1865 /// use any intermediary variable:
1866 /// ~~~{.cpp}
1867 /// fprintf(stdout,"trs[%d].a = %d\n",i,(int)trs.a[i]);
1868 /// ~~~
1869 /// Also, optionally, the generated selector will also call methods named
1870 /// macrofilename_methodname in each of 6 main selector methods if the method
1871 /// macrofilename_methodname exist (Where macrofilename is stripped of its
1872 /// extension).
1873 ///
1874 /// Concretely, with the script named h1analysisProxy.C,
1875 ///
1876 /// - The method calls the method (if it exist)
1877 /// - Begin -> void h1analysisProxy_Begin(TTree*);
1878 /// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
1879 /// - Notify -> Bool_t h1analysisProxy_Notify();
1880 /// - Process -> Bool_t h1analysisProxy_Process(Long64_t);
1881 /// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
1882 /// - Terminate -> void h1analysisProxy_Terminate();
1883 ///
1884 /// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
1885 /// it is included before the declaration of the proxy class. This can
1886 /// be used in particular to insure that the include files needed by
1887 /// the macro file are properly loaded.
1888 ///
1889 /// The default histogram is accessible via the variable named 'htemp'.
1890 ///
1891 /// If the library of the classes describing the data in the branch is
1892 /// loaded, the skeleton will add the needed #include statements and
1893 /// give the ability to access the object stored in the branches.
1894 ///
1895 /// To draw px using the file hsimple.root (generated by the
1896 /// hsimple.C tutorial), we need a file named hsimple.cxx:
1897 /// ~~~{.cpp}
1898 /// double hsimple() {
1899 /// return px;
1900 /// }
1901 /// ~~~
1902 /// MakeProxy can then be used indirectly via the TTree::Draw interface
1903 /// as follow:
1904 /// ~~~{.cpp}
1905 /// new TFile("hsimple.root")
1906 /// ntuple->Draw("hsimple.cxx");
1907 /// ~~~
1908 /// A more complete example is available in the tutorials directory:
1909 /// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
1910 /// which reimplement the selector found in h1analysis.C
1911 
1912 Int_t TTreePlayer::MakeProxy(const char *proxyClassname,
1913  const char *macrofilename, const char *cutfilename,
1914  const char *option, Int_t maxUnrolling)
1915 {
1916  if (macrofilename==0 || strlen(macrofilename)==0 ) {
1917  // We currently require a file name for the script
1918  Error("MakeProxy","A file name for the user script is required");
1919  return 0;
1920  }
1921 
1922  ROOT::Internal::TTreeProxyGenerator gp(fTree,macrofilename,cutfilename,proxyClassname,option,maxUnrolling);
1923 
1924  return 0;
1925 }
1926 
1927 
1928 ////////////////////////////////////////////////////////////////////////////////
1929 /// Generate skeleton selector class for this tree.
1930 ///
1931 /// The following files are produced: classname.h and classname.C.
1932 /// If classname is 0, the selector will be called "nameoftree".
1933 /// The option can be used to specify the branches that will have a data member.
1934 /// - If option is empty, readers will be generated for each leaf.
1935 /// - If option is "@", readers will be generated for the topmost branches.
1936 /// - Individual branches can also be picked by their name:
1937 /// - "X" generates readers for leaves of X.
1938 /// - "@X" generates a reader for X as a whole.
1939 /// - "@X;Y" generates a reader for X as a whole and also readers for the
1940 /// leaves of Y.
1941 /// - For further examples see the figure below.
1942 ///
1943 /// \image html ttree_makeselector_option_examples.png
1944 ///
1945 /// The generated code in classname.h includes the following:
1946 /// - Identification of the original Tree and Input file name
1947 /// - Definition of selector class (data and functions)
1948 /// - The following class functions:
1949 /// - constructor and destructor
1950 /// - void Begin(TTree *tree)
1951 /// - void SlaveBegin(TTree *tree)
1952 /// - void Init(TTree *tree)
1953 /// - Bool_t Notify()
1954 /// - Bool_t Process(Long64_t entry)
1955 /// - void Terminate()
1956 /// - void SlaveTerminate()
1957 ///
1958 /// The selector derives from TSelector.
1959 /// The generated code in classname.C includes empty functions defined above.
1960 ///
1961 /// To use this function:
1962 /// - connect your Tree file (eg: TFile f("myfile.root");)
1963 /// - T->MakeSelector("myselect");
1964 /// where T is the name of the Tree in file myfile.root
1965 /// and myselect.h, myselect.C the name of the files created by this function.
1966 /// In a ROOT session, you can do:
1967 /// root > T->Process("myselect.C")
1968 
1969 Int_t TTreePlayer::MakeReader(const char *classname, Option_t *option)
1970 {
1971  if (!classname) classname = fTree->GetName();
1972 
1973  ROOT::Internal::TTreeReaderGenerator gsr(fTree, classname, option);
1974 
1975  return 0;
1976 }
1977 
1978 
1979 ////////////////////////////////////////////////////////////////////////////////
1980 /// Interface to the Principal Components Analysis class.
1981 ///
1982 /// Create an instance of TPrincipal
1983 /// Fill it with the selected variables
1984 ///
1985 /// - if option "n" is specified, the TPrincipal object is filled with
1986 /// normalized variables.
1987 /// - If option "p" is specified, compute the principal components
1988 /// - If option "p" and "d" print results of analysis
1989 /// - If option "p" and "h" generate standard histograms
1990 /// - If option "p" and "c" generate code of conversion functions
1991 ///
1992 /// return a pointer to the TPrincipal object. It is the user responsibility
1993 /// to delete this object.
1994 ///
1995 /// The option default value is "np"
1996 ///
1997 /// See TTreePlayer::DrawSelect for explanation of the other parameters.
1998 
1999 TPrincipal *TTreePlayer::Principal(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
2000 {
2001  TTreeFormula **var;
2002  std::vector<TString> cnames;
2003  TString opt = option;
2004  opt.ToLower();
2005  TPrincipal *principal = 0;
2006  Long64_t entry,entryNumber;
2007  Int_t i,nch;
2008  Int_t ncols = 8; // by default first 8 columns are printed only
2009  TObjArray *leaves = fTree->GetListOfLeaves();
2010  Int_t nleaves = leaves->GetEntriesFast();
2011  if (nleaves < ncols) ncols = nleaves;
2012  nch = varexp ? strlen(varexp) : 0;
2013 
2014  nentries = GetEntriesToProcess(firstentry, nentries);
2015 
2016 //*-*- Compile selection expression if there is one
2017  TTreeFormula *select = 0;
2018  if (strlen(selection)) {
2019  select = new TTreeFormula("Selection",selection,fTree);
2020  if (!select) return principal;
2021  if (!select->GetNdim()) { delete select; return principal; }
2022  fFormulaList->Add(select);
2023  }
2024 //*-*- if varexp is empty, take first 8 columns by default
2025  int allvar = 0;
2026  if (varexp && !strcmp(varexp, "*")) { ncols = nleaves; allvar = 1; }
2027  if (nch == 0 || allvar) {
2028  for (i=0;i<ncols;i++) {
2029  cnames.push_back( ((TLeaf*)leaves->At(i))->GetName() );
2030  }
2031 //*-*- otherwise select only the specified columns
2032  } else {
2033  ncols = fSelector->SplitNames(varexp,cnames);
2034  }
2035  var = new TTreeFormula* [ncols];
2036  Double_t *xvars = new Double_t[ncols];
2037 
2038 //*-*- Create the TreeFormula objects corresponding to each column
2039  for (i=0;i<ncols;i++) {
2040  var[i] = new TTreeFormula("Var1",cnames[i].Data(),fTree);
2041  fFormulaList->Add(var[i]);
2042  }
2043 
2044 //*-*- Create a TreeFormulaManager to coordinate the formulas
2045  TTreeFormulaManager *manager=0;
2046  if (fFormulaList->LastIndex()>=0) {
2047  manager = new TTreeFormulaManager;
2048  for(i=0;i<=fFormulaList->LastIndex();i++) {
2049  manager->Add((TTreeFormula*)fFormulaList->At(i));
2050  }
2051  manager->Sync();
2052  }
2053 
2054 //*-* Build the TPrincipal object
2055  if (opt.Contains("n")) principal = new TPrincipal(ncols, "n");
2056  else principal = new TPrincipal(ncols);
2057 
2058 //*-*- loop on all selected entries
2059  fSelectedRows = 0;
2060  Int_t tnumber = -1;
2061  for (entry=firstentry;entry<firstentry+nentries;entry++) {
2062  entryNumber = fTree->GetEntryNumber(entry);
2063  if (entryNumber < 0) break;
2064  Long64_t localEntry = fTree->LoadTree(entryNumber);
2065  if (localEntry < 0) break;
2066  if (tnumber != fTree->GetTreeNumber()) {
2067  tnumber = fTree->GetTreeNumber();
2068  if (manager) manager->UpdateFormulaLeaves();
2069  }
2070  int ndata = 1;
2071  if (manager && manager->GetMultiplicity()) {
2072  ndata = manager->GetNdata();
2073  }
2074 
2075  for(int inst=0;inst<ndata;inst++) {
2076  Bool_t loaded = kFALSE;
2077  if (select) {
2078  if (select->EvalInstance(inst) == 0) {
2079  continue;
2080  }
2081  }
2082 
2083  if (inst==0) loaded = kTRUE;
2084  else if (!loaded) {
2085  // EvalInstance(0) always needs to be called so that
2086  // the proper branches are loaded.
2087  for (i=0;i<ncols;i++) {
2088  var[i]->EvalInstance(0);
2089  }
2090  loaded = kTRUE;
2091  }
2092 
2093  for (i=0;i<ncols;i++) {
2094  xvars[i] = var[i]->EvalInstance(inst);
2095  }
2096  principal->AddRow(xvars);
2097  }
2098  }
2099 
2100  //*-* some actions with principal ?
2101  if (opt.Contains("p")) {
2102  principal->MakePrincipals(); // Do the actual analysis
2103  if (opt.Contains("d")) principal->Print();
2104  if (opt.Contains("h")) principal->MakeHistograms();
2105  if (opt.Contains("c")) principal->MakeCode();
2106  }
2107 
2108 //*-*- delete temporary objects
2109  fFormulaList->Clear();
2110  delete [] var;
2111  delete [] xvars;
2112 
2113  return principal;
2114 }
2115 
2116 ////////////////////////////////////////////////////////////////////////////////
2117 /// Process this tree executing the TSelector code in the specified filename.
2118 /// The return value is -1 in case of error and TSelector::GetStatus() in
2119 /// in case of success.
2120 ///
2121 /// The code in filename is loaded (interpreted or compiled, see below),
2122 /// filename must contain a valid class implementation derived from TSelector,
2123 /// where TSelector has the following member functions:
2124 ///
2125 /// - Begin(): called every time a loop on the tree starts,
2126 /// a convenient place to create your histograms.
2127 /// - SlaveBegin(): called after Begin(), when on PROOF called only on the
2128 /// slave servers.
2129 /// - Process(): called for each event, in this function you decide what
2130 /// to read and fill your histograms.
2131 /// - SlaveTerminate: called at the end of the loop on the tree, when on PROOF
2132 /// called only on the slave servers.
2133 /// - Terminate(): called at the end of the loop on the tree,
2134 /// a convenient place to draw/fit your histograms.
2135 ///
2136 /// If filename is of the form file.C, the file will be interpreted.
2137 /// If filename is of the form file.C++, the file file.C will be compiled
2138 /// and dynamically loaded.
2139 ///
2140 /// If filename is of the form file.C+, the file file.C will be compiled
2141 /// and dynamically loaded. At next call, if file.C is older than file.o
2142 /// and file.so, the file.C is not compiled, only file.so is loaded.
2143 ///
2144 /// ### NOTE 1
2145 /// It may be more interesting to invoke directly the other Process function
2146 /// accepting a TSelector* as argument.eg
2147 /// ~~~{.cpp}
2148 /// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
2149 /// selector->CallSomeFunction(..);
2150 /// mytree.Process(selector,..);
2151 /// ~~~
2152 /// ### NOTE 2
2153 /// One should not call this function twice with the same selector file
2154 /// in the same script. If this is required, proceed as indicated in NOTE1,
2155 /// by getting a pointer to the corresponding TSelector,eg
2156 ///#### workaround 1
2157 /// ~~~{.cpp}
2158 ///void stubs1() {
2159 /// TSelector *selector = TSelector::GetSelector("h1test.C");
2160 /// TFile *f1 = new TFile("stubs_nood_le1.root");
2161 /// TTree *h1 = (TTree*)f1->Get("h1");
2162 /// h1->Process(selector);
2163 /// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
2164 /// TTree *h2 = (TTree*)f2->Get("h1");
2165 /// h2->Process(selector);
2166 ///}
2167 /// ~~~
2168 /// or use ACLIC to compile the selector
2169 ///#### workaround 2
2170 /// ~~~{.cpp}
2171 ///void stubs2() {
2172 /// TFile *f1 = new TFile("stubs_nood_le1.root");
2173 /// TTree *h1 = (TTree*)f1->Get("h1");
2174 /// h1->Process("h1test.C+");
2175 /// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
2176 /// TTree *h2 = (TTree*)f2->Get("h1");
2177 /// h2->Process("h1test.C+");
2178 ///}
2179 /// ~~~
2180 
2181 Long64_t TTreePlayer::Process(const char *filename,Option_t *option, Long64_t nentries, Long64_t firstentry)
2182 {
2183  DeleteSelectorFromFile(); //delete previous selector if any
2184 
2185  // This might reloads the script and delete your option
2186  // string! so let copy it first:
2187  TString opt(option);
2188  TString file(filename);
2189  TSelector *selector = TSelector::GetSelector(file);
2190  if (!selector) return -1;
2191 
2192  fSelectorFromFile = selector;
2193  fSelectorClass = selector->IsA();
2194 
2195  Long64_t nsel = Process(selector,opt,nentries,firstentry);
2196  return nsel;
2197 }
2198 
2199 ////////////////////////////////////////////////////////////////////////////////
2200 /// Process this tree executing the code in the specified selector.
2201 /// The return value is -1 in case of error and TSelector::GetStatus() in
2202 /// in case of success.
2203 ///
2204 /// The TSelector class has the following member functions:
2205 ///
2206 /// - Begin(): called every time a loop on the tree starts,
2207 /// a convenient place to create your histograms.
2208 /// - SlaveBegin(): called after Begin(), when on PROOF called only on the
2209 /// slave servers.
2210 /// - Process(): called for each event, in this function you decide what
2211 /// to read and fill your histograms.
2212 /// - SlaveTerminate: called at the end of the loop on the tree, when on PROOF
2213 /// called only on the slave servers.
2214 /// - Terminate(): called at the end of the loop on the tree,
2215 /// a convenient place to draw/fit your histograms.
2216 ///
2217 /// If the Tree (Chain) has an associated EventList, the loop is on the nentries
2218 /// of the EventList, starting at firstentry, otherwise the loop is on the
2219 /// specified Tree entries.
2220 
2222 {
2223  nentries = GetEntriesToProcess(firstentry, nentries);
2224 
2225  TDirectory::TContext ctxt;
2226 
2227  fTree->SetNotify(selector);
2228 
2229  selector->SetOption(option);
2230 
2231  selector->Begin(fTree); //<===call user initialization function
2232  selector->SlaveBegin(fTree); //<===call user initialization function
2233  if (selector->Version() >= 2)
2234  selector->Init(fTree);
2235  selector->Notify();
2236 
2237  if (gMonitoringWriter)
2239 
2240  Bool_t process = (selector->GetAbort() != TSelector::kAbortProcess &&
2241  (selector->Version() != 0 || selector->GetStatus() != -1)) ? kTRUE : kFALSE;
2242  if (process) {
2243 
2244  Long64_t readbytesatstart = 0;
2245  readbytesatstart = TFile::GetFileBytesRead();
2246 
2247  //set the file cache
2248  TTreeCache *tpf = 0;
2249  TFile *curfile = fTree->GetCurrentFile();
2250  if (curfile && fTree->GetCacheSize() > 0) {
2251  tpf = (TTreeCache*)curfile->GetCacheRead(fTree);
2252  if (tpf)
2253  tpf->SetEntryRange(firstentry,firstentry+nentries);
2254  else {
2256  tpf = (TTreeCache*)curfile->GetCacheRead(fTree);
2257  if (tpf) tpf->SetEntryRange(firstentry,firstentry+nentries);
2258  }
2259  }
2260 
2261  //Create a timer to get control in the entry loop(s)
2263  Int_t interval = fTree->GetTimerInterval();
2264  if (!gROOT->IsBatch() && interval)
2265  timer = new TProcessEventTimer(interval);
2266 
2267  //loop on entries (elist or all entries)
2268  Long64_t entry, entryNumber, localEntry;
2269 
2270  Bool_t useCutFill = selector->Version() == 0;
2271 
2272  // force the first monitoring info
2273  if (gMonitoringWriter)
2275 
2276  //trying to set the first tree, because in the Draw function
2277  //the tree corresponding to firstentry has already been loaded,
2278  //so it is not set in the entry list
2279  fSelectorUpdate = selector;
2281 
2282  for (entry=firstentry;entry<firstentry+nentries;entry++) {
2283  entryNumber = fTree->GetEntryNumber(entry);
2284  if (entryNumber < 0) break;
2285  if (timer && timer->ProcessEvents()) break;
2286  if (gROOT->IsInterrupted()) break;
2287  localEntry = fTree->LoadTree(entryNumber);
2288  if (localEntry < 0) break;
2289  if(useCutFill) {
2290  if (selector->ProcessCut(localEntry))
2291  selector->ProcessFill(localEntry); //<==call user analysis function
2292  } else {
2293  selector->Process(localEntry); //<==call user analysis function
2294  }
2295  if (gMonitoringWriter)
2296  gMonitoringWriter->SendProcessingProgress((entry-firstentry),TFile::GetFileBytesRead()-readbytesatstart,kTRUE);
2297  if (selector->GetAbort() == TSelector::kAbortProcess) break;
2298  if (selector->GetAbort() == TSelector::kAbortFile) {
2299  // Skip to the next file.
2300  entry += fTree->GetTree()->GetEntries() - localEntry;
2301  // Reset the abort status.
2302  selector->ResetAbort();
2303  }
2304  }
2305  delete timer;
2306  //we must reset the cache
2307  {
2308  TFile *curfile2 = fTree->GetCurrentFile();
2309  if (curfile2 && fTree->GetCacheSize() > 0) {
2310  tpf = (TTreeCache*)curfile2->GetCacheRead(fTree);
2311  if (tpf) tpf->SetEntryRange(0,0);
2312  }
2313  }
2314  }
2315 
2316  process = (selector->GetAbort() != TSelector::kAbortProcess &&
2317  (selector->Version() != 0 || selector->GetStatus() != -1)) ? kTRUE : kFALSE;
2318  Long64_t res = (process) ? 0 : -1;
2319  if (process) {
2320  selector->SlaveTerminate(); //<==call user termination function
2321  selector->Terminate(); //<==call user termination function
2322  res = selector->GetStatus();
2323  }
2324  fTree->SetNotify(0); // Detach the selector from the tree.
2325  fSelectorUpdate = 0;
2326  if (gMonitoringWriter)
2328 
2329  return res;
2330 }
2331 
2332 ////////////////////////////////////////////////////////////////////////////////
2333 /// cleanup pointers in the player pointing to obj
2334 
2336 {
2337  if (fHistogram == obj) fHistogram = 0;
2338 }
2339 
2340 ////////////////////////////////////////////////////////////////////////////////
2341 /// Loop on Tree and print entries passing selection. If varexp is 0 (or "")
2342 /// then print only first 8 columns. If varexp = "*" print all columns.
2343 /// Otherwise a columns selection can be made using "var1:var2:var3".
2344 /// The function returns the number of entries passing the selection.
2345 ///
2346 /// By default 50 rows are shown and you are asked for <CR>
2347 /// to see the next 50 rows.
2348 ///
2349 /// You can change the default number of rows to be shown before <CR>
2350 /// via mytree->SetScanField(maxrows) where maxrows is 50 by default.
2351 /// if maxrows is set to 0 all rows of the Tree are shown.
2352 ///
2353 /// This option is interesting when dumping the contents of a Tree to
2354 /// an ascii file, eg from the command line
2355 /// ~~~{.cpp}
2356 /// tree->SetScanField(0);
2357 /// tree->Scan("*"); >tree.log
2358 /// ~~~
2359 /// will create a file tree.log
2360 ///
2361 /// Arrays (within an entry) are printed in their linear forms.
2362 /// If several arrays with multiple dimensions are printed together,
2363 /// they will NOT be synchronized. For example print
2364 /// arr1[4][2] and arr2[2][3] will results in a printing similar to:
2365 /// ~~~{.cpp}
2366 /// ***********************************************
2367 /// * Row * Instance * arr1 * arr2 *
2368 /// ***********************************************
2369 /// * x * 0 * arr1[0][0]* arr2[0][0]*
2370 /// * x * 1 * arr1[0][1]* arr2[0][1]*
2371 /// * x * 2 * arr1[1][0]* arr2[0][2]*
2372 /// * x * 3 * arr1[1][1]* arr2[1][0]*
2373 /// * x * 4 * arr1[2][0]* arr2[1][1]*
2374 /// * x * 5 * arr1[2][1]* arr2[1][2]*
2375 /// * x * 6 * arr1[3][0]* *
2376 /// * x * 7 * arr1[3][1]* *
2377 /// ~~~
2378 /// However, if there is a selection criterion which is an array, then
2379 /// all the formulas will be synchronized with the selection criterion
2380 /// (see TTreePlayer::DrawSelect for more information).
2381 ///
2382 /// The options string can contains the following parameters:
2383 ///
2384 /// - lenmax=dd
2385 /// Where 'dd' is the maximum number of elements per array that should
2386 /// be printed. If 'dd' is 0, all elements are printed (this is the
2387 /// default)
2388 /// - colsize=ss
2389 /// Where 'ss' will be used as the default size for all the column
2390 /// If this options is not specified, the default column size is 9
2391 /// - precision=pp
2392 /// Where 'pp' will be used as the default 'precision' for the
2393 /// printing format.
2394 /// - col=xxx
2395 /// Where 'xxx' is colon (:) delimited list of printing format for
2396 /// each column. The format string should follow the printf format
2397 /// specification. The value given will be prefixed by % and, if no
2398 /// conversion specifier is given, will be suffixed by the letter g.
2399 /// before being passed to fprintf. If no format is specified for a
2400 /// column, the default is used (aka ${colsize}.${precision}g )
2401 ///
2402 /// For example:
2403 /// ~~~{.cpp}
2404 /// tree->Scan("a:b:c","","colsize=30 precision=3 col=::20.10:#x:5ld");
2405 /// ~~~
2406 /// Will print 3 columns, the first 2 columns will be 30 characters long,
2407 /// the third columns will be 20 characters long. The printing format used
2408 /// for the columns (assuming they are numbers) will be respectively:
2409 /// `%30.3g %30.3g %20.10g %#x %5ld`
2410 
2411 Long64_t TTreePlayer::Scan(const char *varexp, const char *selection,
2412  Option_t * option,
2413  Long64_t nentries, Long64_t firstentry)
2414 {
2415 
2416  TString opt = option;
2417  opt.ToLower();
2418  UInt_t ui;
2419  UInt_t lenmax = 0;
2420  UInt_t colDefaultSize = 9;
2421  UInt_t colPrecision = 9;
2422  std::vector<TString> colFormats;
2423  std::vector<Int_t> colSizes;
2424 
2425  if (opt.Contains("lenmax=")) {
2426  int start = opt.Index("lenmax=");
2427  int numpos = start + strlen("lenmax=");
2428  int numlen = 0;
2429  int len = opt.Length();
2430  while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) ) numlen++;
2431  TString num = opt(numpos,numlen);
2432  opt.Remove(start,strlen("lenmax")+numlen);
2433 
2434  lenmax = atoi(num.Data());
2435  }
2436  if (opt.Contains("colsize=")) {
2437  int start = opt.Index("colsize=");
2438  int numpos = start + strlen("colsize=");
2439  int numlen = 0;
2440  int len = opt.Length();
2441  while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) ) numlen++;
2442  TString num = opt(numpos,numlen);
2443  opt.Remove(start,strlen("size")+numlen);
2444 
2445  colDefaultSize = atoi(num.Data());
2446  colPrecision = colDefaultSize;
2447  if (colPrecision>18) colPrecision = 18;
2448  }
2449  if (opt.Contains("precision=")) {
2450  int start = opt.Index("precision=");
2451  int numpos = start + strlen("precision=");
2452  int numlen = 0;
2453  int len = opt.Length();
2454  while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) ) numlen++;
2455  TString num = opt(numpos,numlen);
2456  opt.Remove(start,strlen("precision")+numlen);
2457 
2458  colPrecision = atoi(num.Data());
2459  }
2460  TString defFormat = Form("%d.%d",colDefaultSize,colPrecision);
2461  if (opt.Contains("col=")) {
2462  int start = opt.Index("col=");
2463  int numpos = start + strlen("col=");
2464  int numlen = 0;
2465  int len = opt.Length();
2466  while( (numpos+numlen<len) &&
2467  (isdigit(opt[numpos+numlen])
2468  || opt[numpos+numlen] == 'c'
2469  || opt[numpos+numlen] == 'd'
2470  || opt[numpos+numlen] == 'i'
2471  || opt[numpos+numlen] == 'o'
2472  || opt[numpos+numlen] == 'x'
2473  || opt[numpos+numlen] == 'X'
2474  || opt[numpos+numlen] == 'u'
2475  || opt[numpos+numlen] == 'f'
2476  || opt[numpos+numlen] == 'e'
2477  || opt[numpos+numlen] == 'E'
2478  || opt[numpos+numlen] == 'g'
2479  || opt[numpos+numlen] == 'G'
2480  || opt[numpos+numlen] == 'l'
2481  || opt[numpos+numlen] == 'L'
2482  || opt[numpos+numlen] == 'h'
2483  || opt[numpos+numlen] == 's'
2484  || opt[numpos+numlen] == '#'
2485  || opt[numpos+numlen]=='.'
2486  || opt[numpos+numlen]==':')) numlen++;
2487  TString flist = opt(numpos,numlen);
2488  opt.Remove(start,strlen("col")+numlen);
2489 
2490  int i = 0;
2491  while(i<flist.Length() && flist[i]==':') {
2492  colFormats.push_back(defFormat);
2493  colSizes.push_back(colDefaultSize);
2494  ++i;
2495  }
2496  for(; i<flist.Length(); ++i) {
2497  int next = flist.Index(":",i);
2498  if (next==i) {
2499  colFormats.push_back(defFormat);
2500  } else if (next==kNPOS) {
2501  colFormats.push_back(flist(i,flist.Length()-i));
2502  i = flist.Length();
2503  } else {
2504  colFormats.push_back(flist(i,next-i));
2505  i = next;
2506  }
2507  UInt_t siz = atoi(colFormats[colFormats.size()-1].Data());
2508  colSizes.push_back( siz ? siz : colDefaultSize );
2509  }
2510  }
2511 
2512  TTreeFormula **var;
2513  std::vector<TString> cnames;
2514  TString onerow;
2515  Long64_t entry,entryNumber;
2516  Int_t i,nch;
2517  UInt_t ncols = 8; // by default first 8 columns are printed only
2518  std::ofstream out;
2519  Int_t lenfile = 0;
2520  char * fname = 0;
2521  if (fScanRedirect) {
2522  fTree->SetScanField(0); // no page break if Scan is redirected
2523  fname = (char *) fScanFileName;
2524  if (!fname) fname = (char*)"";
2525  lenfile = strlen(fname);
2526  if (!lenfile) {
2527  Int_t nch2 = strlen(fTree->GetName());
2528  fname = new char[nch2+10];
2529  strlcpy(fname, fTree->GetName(),nch2+10);
2530  strlcat(fname, "-scan.dat",nch2+10);
2531  }
2532  out.open(fname, std::ios::out);
2533  if (!out.good ()) {
2534  if (!lenfile) delete [] fname;
2535  Error("Scan","Can not open file for redirection");
2536  return 0;
2537  }
2538  }
2539  TObjArray *leaves = fTree->GetListOfLeaves();
2540  if (leaves==0) return 0;
2541  UInt_t nleaves = leaves->GetEntriesFast();
2542  if (nleaves < ncols) ncols = nleaves;
2543  nch = varexp ? strlen(varexp) : 0;
2544 
2545  nentries = GetEntriesToProcess(firstentry, nentries);
2546 
2547 //*-*- Compile selection expression if there is one
2548  TTreeFormula *select = 0;
2549  if (selection && strlen(selection)) {
2550  select = new TTreeFormula("Selection",selection,fTree);
2551  if (!select) return -1;
2552  if (!select->GetNdim()) { delete select; return -1; }
2553  fFormulaList->Add(select);
2554  }
2555 //*-*- if varexp is empty, take first 8 columns by default
2556  int allvar = 0;
2557  if (varexp && !strcmp(varexp, "*")) { ncols = nleaves; allvar = 1; }
2558  if (nch == 0 || allvar) {
2559  UInt_t ncs = ncols;
2560  ncols = 0;
2561  for (ui=0;ui<ncs;++ui) {
2562  TLeaf *lf = (TLeaf*)leaves->At(ui);
2563  if (lf->GetBranch()->GetListOfBranches()->GetEntries() > 0) continue;
2564  cnames.push_back( lf->GetBranch()->GetMother()->GetName() );
2565  if (cnames[ncols] == lf->GetName() ) {
2566  // Already complete, let move on.
2567  } else if (cnames[ncols][cnames[ncols].Length()-1]=='.') {
2568  cnames[ncols] = lf->GetBranch()->GetName(); // name of branch already include mother's name
2569  } else {
2570  if (lf->GetBranch()->GetMother()->IsA()->InheritsFrom(TBranchElement::Class())) {
2571  TBranchElement *mother = (TBranchElement*)lf->GetBranch()->GetMother();
2572  if (mother->GetType() == 3 || mother->GetType() == 4) {
2573  // The name of the mother branch is embedded in the sub-branch names.
2574  cnames[ncols] = lf->GetBranch()->GetName();
2575  ++ncols;
2576  continue;
2577  }
2578  }
2579  if (!strchr(lf->GetBranch()->GetName() ,'[') ) {
2580  cnames[ncols].Append('.');
2581  cnames[ncols].Append( lf->GetBranch()->GetName() );
2582  }
2583  }
2584  if (strcmp( lf->GetBranch()->GetName(), lf->GetName() ) != 0 ) {
2585  cnames[ncols].Append('.');
2586  cnames[ncols].Append( lf->GetName() );
2587  }
2588  ++ncols;
2589  }
2590 //*-*- otherwise select only the specified columns
2591  } else {
2592 
2593  ncols = fSelector->SplitNames(varexp, cnames);
2594 
2595  }
2596  var = new TTreeFormula* [ncols];
2597 
2598  for(ui=colFormats.size();ui<ncols;++ui) {
2599  colFormats.push_back(defFormat);
2600  colSizes.push_back(colDefaultSize);
2601  }
2602 
2603 //*-*- Create the TreeFormula objects corresponding to each column
2604  for (ui=0;ui<ncols;ui++) {
2605  var[ui] = new TTreeFormula("Var1",cnames[ui].Data(),fTree);
2606  fFormulaList->Add(var[ui]);
2607  }
2608 
2609 //*-*- Create a TreeFormulaManager to coordinate the formulas
2610  TTreeFormulaManager *manager=0;
2611  Bool_t hasArray = kFALSE;
2612  Bool_t forceDim = kFALSE;
2613  if (fFormulaList->LastIndex()>=0) {
2614  if (select) {
2615  if (select->GetManager()->GetMultiplicity() > 0 ) {
2616  manager = new TTreeFormulaManager;
2617  for(i=0;i<=fFormulaList->LastIndex();i++) {
2618  manager->Add((TTreeFormula*)fFormulaList->At(i));
2619  }
2620  manager->Sync();
2621  }
2622  }
2623  for(i=0;i<=fFormulaList->LastIndex();i++) {
2624  TTreeFormula *form = ((TTreeFormula*)fFormulaList->At(i));
2625  switch( form->GetManager()->GetMultiplicity() ) {
2626  case 1:
2627  case 2:
2628  hasArray = kTRUE;
2629  forceDim = kTRUE;
2630  break;
2631  case -1:
2632  forceDim = kTRUE;
2633  break;
2634  case 0:
2635  break;
2636  }
2637 
2638  }
2639  }
2640 
2641 //*-*- Print header
2642  onerow = "***********";
2643  if (hasArray) onerow += "***********";
2644 
2645  for (ui=0;ui<ncols;ui++) {
2646  TString starFormat = Form("*%%%d.%ds",colSizes[ui]+2,colSizes[ui]+2);
2647  onerow += Form(starFormat.Data(),var[ui]->PrintValue(-2));
2648  }
2649  if (fScanRedirect)
2650  out<<onerow.Data()<<"*"<<std::endl;
2651  else
2652  printf("%s*\n",onerow.Data());
2653  onerow = "* Row ";
2654  if (hasArray) onerow += "* Instance ";
2655  for (ui=0;ui<ncols;ui++) {
2656  TString numbFormat = Form("* %%%d.%ds ",colSizes[ui],colSizes[ui]);
2657  onerow += Form(numbFormat.Data(),var[ui]->PrintValue(-1));
2658  }
2659  if (fScanRedirect)
2660  out<<onerow.Data()<<"*"<<std::endl;
2661  else
2662  printf("%s*\n",onerow.Data());
2663  onerow = "***********";
2664  if (hasArray) onerow += "***********";
2665  for (ui=0;ui<ncols;ui++) {
2666  TString starFormat = Form("*%%%d.%ds",colSizes[ui]+2,colSizes[ui]+2);
2667  onerow += Form(starFormat.Data(),var[ui]->PrintValue(-2));
2668  }
2669  if (fScanRedirect)
2670  out<<onerow.Data()<<"*"<<std::endl;
2671  else
2672  printf("%s*\n",onerow.Data());
2673 //*-*- loop on all selected entries
2674  fSelectedRows = 0;
2675  Int_t tnumber = -1;
2676  Bool_t exitloop = kFALSE;
2677  for (entry=firstentry;
2678  entry<(firstentry+nentries) && !exitloop;
2679  entry++) {
2680  entryNumber = fTree->GetEntryNumber(entry);
2681  if (entryNumber < 0) break;
2682  Long64_t localEntry = fTree->LoadTree(entryNumber);
2683  if (localEntry < 0) break;
2684  if (tnumber != fTree->GetTreeNumber()) {
2685  tnumber = fTree->GetTreeNumber();
2686  if (manager) manager->UpdateFormulaLeaves();
2687  else {
2688  for(i=0;i<=fFormulaList->LastIndex();i++) {
2690  }
2691  }
2692  }
2693 
2694  int ndata = 1;
2695  if (forceDim) {
2696 
2697  if (manager) {
2698 
2699  ndata = manager->GetNdata(kTRUE);
2700 
2701  } else {
2702 
2703  // let's print the max number of column
2704  for (ui=0;ui<ncols;ui++) {
2705  if (ndata < var[ui]->GetNdata() ) {
2706  ndata = var[ui]->GetNdata();
2707  }
2708  }
2709  if (select && select->GetNdata()==0) ndata = 0;
2710  }
2711 
2712  }
2713 
2714  if (lenmax && ndata>(int)lenmax) ndata = lenmax;
2715  Bool_t loaded = kFALSE;
2716  for(int inst=0;inst<ndata;inst++) {
2717  if (select) {
2718  if (select->EvalInstance(inst) == 0) {
2719  continue;
2720  }
2721  }
2722  if (inst==0) loaded = kTRUE;
2723  else if (!loaded) {
2724  // EvalInstance(0) always needs to be called so that
2725  // the proper branches are loaded.
2726  for (ui=0;ui<ncols;ui++) {
2727  var[ui]->EvalInstance(0);
2728  }
2729  loaded = kTRUE;
2730  }
2731  onerow = Form("* %8lld ",entryNumber);
2732  if (hasArray) {
2733  onerow += Form("* %8d ",inst);
2734  }
2735  for (ui=0;ui<ncols;++ui) {
2736  TString numbFormat = Form("* %%%d.%ds ",colSizes[ui],colSizes[ui]);
2737  if (var[ui]->GetNdim()) onerow += Form(numbFormat.Data(),var[ui]->PrintValue(0,inst,colFormats[ui].Data()));
2738  else {
2739  TString emptyForm = Form("* %%%dc ",colSizes[ui]);
2740  onerow += Form(emptyForm.Data(),' ');
2741  }
2742  }
2743  fSelectedRows++;
2744  if (fScanRedirect)
2745  out<<onerow.Data()<<"*"<<std::endl;
2746  else
2747  printf("%s*\n",onerow.Data());
2748  if (fTree->GetScanField() > 0 && fSelectedRows > 0) {
2749  if (fSelectedRows%fTree->GetScanField() == 0) {
2750  fprintf(stderr,"Type <CR> to continue or q to quit ==> ");
2751  int answer, readch;
2752  readch = getchar();
2753  answer = readch;
2754  while (readch != '\n' && readch != EOF) readch = getchar();
2755  if (answer == 'q' || answer == 'Q') {
2756  exitloop = kTRUE;
2757  break;
2758  }
2759  }
2760  }
2761  }
2762  }
2763  onerow = "***********";
2764  if (hasArray) onerow += "***********";
2765  for (ui=0;ui<ncols;ui++) {
2766  TString starFormat = Form("*%%%d.%ds",colSizes[ui]+2,colSizes[ui]+2);
2767  onerow += Form(starFormat.Data(),var[ui]->PrintValue(-2));
2768  }
2769  if (fScanRedirect)
2770  out<<onerow.Data()<<"*"<<std::endl;
2771  else
2772  printf("%s*\n",onerow.Data());
2773  if (select) Printf("==> %lld selected %s", fSelectedRows,
2774  fSelectedRows == 1 ? "entry" : "entries");
2775  if (fScanRedirect) printf("File <%s> created\n", fname);
2776 
2777 //*-*- delete temporary objects
2778  fFormulaList->Clear();
2779  // The TTreeFormulaManager is deleted by the last TTreeFormula.
2780  delete [] var;
2781  return fSelectedRows;
2782 }
2783 
2784 ////////////////////////////////////////////////////////////////////////////////
2785 /// Loop on Tree and return TSQLResult object containing entries passing
2786 /// selection. If varexp is 0 (or "") then print only first 8 columns.
2787 /// If varexp = "*" print all columns. Otherwise a columns selection can
2788 /// be made using "var1:var2:var3". In case of error 0 is returned otherwise
2789 /// a TSQLResult object which must be deleted by the user.
2790 
2791 TSQLResult *TTreePlayer::Query(const char *varexp, const char *selection,
2792  Option_t *, Long64_t nentries, Long64_t firstentry)
2793 {
2794  TTreeFormula **var;
2795  std::vector<TString> cnames;
2796  TString onerow;
2797  Long64_t entry,entryNumber;
2798  Int_t i,nch;
2799  Int_t ncols = 8; // by default first 8 columns are printed only
2800  TObjArray *leaves = fTree->GetListOfLeaves();
2801  Int_t nleaves = leaves->GetEntriesFast();
2802  if (nleaves < ncols) ncols = nleaves;
2803  nch = varexp ? strlen(varexp) : 0;
2804 
2805  nentries = GetEntriesToProcess(firstentry, nentries);
2806 
2807  // compile selection expression if there is one
2808  TTreeFormula *select = 0;
2809  if (strlen(selection)) {
2810  select = new TTreeFormula("Selection",selection,fTree);
2811  if (!select) return 0;
2812  if (!select->GetNdim()) { delete select; return 0; }
2813  fFormulaList->Add(select);
2814  }
2815 
2816  // if varexp is empty, take first 8 columns by default
2817  int allvar = 0;
2818  if (varexp && !strcmp(varexp, "*")) { ncols = nleaves; allvar = 1; }
2819  if (nch == 0 || allvar) {
2820  for (i=0;i<ncols;i++) {
2821  cnames.push_back( ((TLeaf*)leaves->At(i))->GetName() );
2822  }
2823  } else {
2824  // otherwise select only the specified columns
2825  ncols = fSelector->SplitNames(varexp,cnames);
2826  }
2827  var = new TTreeFormula* [ncols];
2828 
2829  // create the TreeFormula objects corresponding to each column
2830  for (i=0;i<ncols;i++) {
2831  var[i] = new TTreeFormula("Var1",cnames[i].Data(),fTree);
2832  fFormulaList->Add(var[i]);
2833  }
2834 
2835  // fill header info into result object
2836  TTreeResult *res = new TTreeResult(ncols);
2837  for (i = 0; i < ncols; i++) {
2838  res->AddField(i, var[i]->PrintValue(-1));
2839  }
2840 
2841  //*-*- Create a TreeFormulaManager to coordinate the formulas
2842  TTreeFormulaManager *manager=0;
2843  if (fFormulaList->LastIndex()>=0) {
2844  manager = new TTreeFormulaManager;
2845  for(i=0;i<=fFormulaList->LastIndex();i++) {
2846  manager->Add((TTreeFormula*)fFormulaList->At(i));
2847  }
2848  manager->Sync();
2849  }
2850 
2851  // loop on all selected entries
2852  const char *aresult;
2853  Int_t len;
2854  char *arow = new char[ncols*50];
2855  fSelectedRows = 0;
2856  Int_t tnumber = -1;
2857  Int_t *fields = new Int_t[ncols];
2858  for (entry=firstentry;entry<firstentry+nentries;entry++) {
2859  entryNumber = fTree->GetEntryNumber(entry);
2860  if (entryNumber < 0) break;
2861  Long64_t localEntry = fTree->LoadTree(entryNumber);
2862  if (localEntry < 0) break;
2863  if (tnumber != fTree->GetTreeNumber()) {
2864  tnumber = fTree->GetTreeNumber();
2865  for (i=0;i<ncols;i++) var[i]->UpdateFormulaLeaves();
2866  }
2867 
2868  Int_t ndata = 1;
2869  if (manager && manager->GetMultiplicity()) {
2870  ndata = manager->GetNdata();
2871  }
2872 
2873  if (select) {
2874  select->GetNdata();
2875  if (select->EvalInstance(0) == 0) continue;
2876  }
2877 
2878  Bool_t loaded = kFALSE;
2879  for(int inst=0;inst<ndata;inst++) {
2880  if (select) {
2881  if (select->EvalInstance(inst) == 0) {
2882  continue;
2883  }
2884  }
2885 
2886  if (inst==0) loaded = kTRUE;
2887  else if (!loaded) {
2888  // EvalInstance(0) always needs to be called so that
2889  // the proper branches are loaded.
2890  for (i=0;i<ncols;i++) {
2891  var[i]->EvalInstance(0);
2892  }
2893  loaded = kTRUE;
2894  }
2895  for (i=0;i<ncols;i++) {
2896  aresult = var[i]->PrintValue(0,inst);
2897  len = strlen(aresult)+1;
2898  if (i == 0) {
2899  memcpy(arow,aresult,len);
2900  fields[i] = len;
2901  } else {
2902  memcpy(arow+fields[i-1],aresult,len);
2903  fields[i] = fields[i-1] + len;
2904  }
2905  }
2906  res->AddRow(new TTreeRow(ncols,fields,arow));
2907  fSelectedRows++;
2908  }
2909  }
2910 
2911  // delete temporary objects
2912  fFormulaList->Clear();
2913  // The TTreeFormulaManager is deleted by the last TTreeFormula.
2914  delete [] fields;
2915  delete [] arow;
2916  delete [] var;
2917 
2918  return res;
2919 }
2920 
2921 ////////////////////////////////////////////////////////////////////////////////
2922 /// Set number of entries to estimate variable limits.
2923 
2925 {
2926  fSelector->SetEstimate(n);
2927 }
2928 
2929 ////////////////////////////////////////////////////////////////////////////////
2930 /// Start the TTreeViewer on this TTree.
2931 ///
2932 /// - ww is the width of the canvas in pixels
2933 /// - wh is the height of the canvas in pixels
2934 
2936 {
2937  if (gROOT->IsBatch()) {
2938  Warning("StartViewer", "viewer cannot run in batch mode");
2939  return;
2940  }
2941 
2942  if (ww || wh) { } // use unused variables
2943  TPluginHandler *h;
2944  if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualTreeViewer"))) {
2945  if (h->LoadPlugin() == -1)
2946  return;
2947  h->ExecPlugin(1,fTree);
2948  }
2949 }
2950 
2951 ////////////////////////////////////////////////////////////////////////////////
2952 /// Unbinned fit of one or more variable(s) from a Tree.
2953 ///
2954 /// funcname is a TF1 function.
2955 ///
2956 /// See TTree::Draw for explanations of the other parameters.
2957 ///
2958 /// Fit the variable varexp using the function funcname using the
2959 /// selection cuts given by selection.
2960 ///
2961 /// The list of fit options is given in parameter option.
2962 ///
2963 /// - option = "Q" Quiet mode (minimum printing)
2964 /// - option = "V" Verbose mode (default is between Q and V)
2965 /// - option = "E" Perform better Errors estimation using Minos technique
2966 /// - option = "M" More. Improve fit results
2967 /// - option = "D" Draw the projected histogram with the fitted function
2968 /// normalized to the number of selected rows
2969 /// and multiplied by the bin width
2970 ///
2971 /// You can specify boundary limits for some or all parameters via
2972 /// ~~~{.cpp}
2973 /// func->SetParLimits(p_number, parmin, parmax);
2974 /// ~~~
2975 /// if parmin>=parmax, the parameter is fixed
2976 ///
2977 /// Note that you are not forced to fix the limits for all parameters.
2978 /// For example, if you fit a function with 6 parameters, you can do:
2979 /// ~~~{.cpp}
2980 /// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
2981 /// func->SetParLimits(4,-10,-4);
2982 /// func->SetParLimits(5, 1,1);
2983 /// ~~~
2984 /// With this setup, parameters 0->3 can vary freely
2985 /// - Parameter 4 has boundaries [-10,-4] with initial value -8
2986 /// - Parameter 5 is fixed to 100.
2987 ///
2988 /// For the fit to be meaningful, the function must be self-normalized.
2989 ///
2990 /// i.e. It must have the same integral regardless of the parameter
2991 /// settings. Otherwise the fit will effectively just maximize the
2992 /// area.
2993 ///
2994 /// It is mandatory to have a normalization variable
2995 /// which is fixed for the fit. e.g.
2996 /// ~~~{.cpp}
2997 /// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
2998 /// f1->SetParameters(1, 3.1, 0.01);
2999 /// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
3000 /// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
3001 /// ~~~
3002 ///
3003 /// 1, 2 and 3 Dimensional fits are supported.
3004 /// See also TTree::Fit
3005 ///
3006 /// ### Return status
3007 ///
3008 /// The function return the status of the fit in the following form
3009 /// ~~~{.cpp}
3010 /// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
3011 /// ~~~
3012 /// - The fitResult is 0 is the fit is OK.
3013 /// - The fitResult is negative in case of an error not connected with the fit.
3014 /// - The number of entries used in the fit can be obtained via
3015 /// ~~~{.cpp}
3016 /// mytree.GetSelectedRows();
3017 /// ~~~
3018 /// - If the number of selected entries is null the function returns -1
3019 ///
3020 /// new implementation using new Fitter classes
3021 
3022 Int_t TTreePlayer::UnbinnedFit(const char *funcname ,const char *varexp, const char *selection,Option_t *option ,Long64_t nentries, Long64_t firstentry)
3023 {
3024  // function is given by name, find it in gROOT
3025  TF1* fitfunc = (TF1*)gROOT->GetFunction(funcname);
3026  if (!fitfunc) { Error("UnbinnedFit", "Unknown function: %s",funcname); return 0; }
3027 
3028  Int_t npar = fitfunc->GetNpar();
3029  if (npar <=0) { Error("UnbinnedFit", "Illegal number of parameters = %d",npar); return 0; }
3030 
3031  // Spin through the data to select out the events of interest
3032  // Make sure that the arrays V1,etc are created large enough to accommodate
3033  // all entries
3034  Long64_t oldEstimate = fTree->GetEstimate();
3035  Long64_t nent = fTree->GetEntriesFriend();
3036  fTree->SetEstimate(TMath::Min(nent,nentries));
3037 
3038  // build FitOptions
3039  TString opt = option;
3040  opt.ToUpper();
3041  Foption_t fitOption;
3042  if (opt.Contains("Q")) fitOption.Quiet = 1;
3043  if (opt.Contains("V")){fitOption.Verbose = 1; fitOption.Quiet = 0;}
3044  if (opt.Contains("E")) fitOption.Errors = 1;
3045  if (opt.Contains("M")) fitOption.More = 1;
3046  if (!opt.Contains("D")) fitOption.Nograph = 1; // what about 0
3047  // could add range and automatic normalization of functions and gradient
3048 
3049  TString drawOpt = "goff";
3050  if (!fitOption.Nograph) drawOpt = "";
3051  Long64_t nsel = DrawSelect(varexp, selection,drawOpt, nentries, firstentry);
3052 
3053  if (!fitOption.Nograph && GetSelectedRows() <= 0 && GetDimension() > 4) {
3054  Info("UnbinnedFit","Ignore option D with more than 4 variables");
3055  nsel = DrawSelect(varexp, selection,"goff", nentries, firstentry);
3056  }
3057 
3058  //if no selected entries return
3059  Long64_t nrows = GetSelectedRows();
3060 
3061  if (nrows <= 0) {
3062  Error("UnbinnedFit", "Cannot fit: no entries selected");
3063  return -1;
3064  }
3065 
3066  // Check that function has same dimension as number of variables
3067  Int_t ndim = GetDimension();
3068  // do not check with TF1::GetNdim() since it returns 1 for TF1 classes created with
3069  // a C function with larger dimension
3070 
3071 
3072  // use pointer stored in the tree (not copy the data in)
3073  std::vector<double *> vlist(ndim);
3074  for (int i = 0; i < ndim; ++i)
3075  vlist[i] = fSelector->GetVal(i);
3076 
3077  // fill the fit data object
3078  // the object will be then managed by the fitted classes - however it will be invalid when the
3079  // data pointers (given by fSelector->GetVal() ) wil be invalidated
3080  ROOT::Fit::UnBinData * fitdata = new ROOT::Fit::UnBinData(nrows, ndim, vlist.begin());
3081 
3082 
3083 
3084  ROOT::Math::MinimizerOptions minOption;
3085  TFitResultPtr ret = ROOT::Fit::UnBinFit(fitdata,fitfunc, fitOption, minOption);
3086 
3087  //reset estimate
3088  fTree->SetEstimate(oldEstimate);
3089 
3090  //if option "D" is specified, draw the projected histogram
3091  //with the fitted function normalized to the number of selected rows
3092  //and multiplied by the bin width
3093  if (!fitOption.Nograph && fHistogram) {
3094  if (fHistogram->GetDimension() < 2) {
3095  TH1 *hf = (TH1*)fHistogram->Clone("unbinnedFit");
3096  hf->SetLineWidth(3);
3097  hf->Reset();
3100  for (Int_t bin=1;bin<=nbins;bin++) {
3101  Double_t func = norm*fitfunc->Eval(hf->GetBinCenter(bin));
3102  hf->SetBinContent(bin,func);
3103  }
3104  fHistogram->GetListOfFunctions()->Add(hf,"lsame");
3105  }
3106  fHistogram->Draw();
3107  }
3108 
3109 
3110  return int(ret);
3111 
3112 }
3113 
3114 ////////////////////////////////////////////////////////////////////////////////
3115 /// this function is called by TChain::LoadTree when a new Tree is loaded.
3116 /// Because Trees in a TChain may have a different list of leaves, one
3117 /// must update the leaves numbers in the TTreeFormula used by the TreePlayer.
3118 
3120 {
3121  if (fSelector) fSelector->Notify();
3122  if (fSelectorUpdate){
3123  //If the selector is writing into a TEntryList, the entry list's
3124  //sublists need to be changed according to the loaded tree
3125  if (fSelector==fSelectorUpdate) {
3126  //FIXME: should be more consistent with selector from file
3127  TObject *obj = fSelector->GetObject();
3128  if (obj){
3131  }
3132  }
3133  }
3136  TEntryList *elist=0;
3137  while ((elist=(TEntryList*)next())){
3138  if (elist->InheritsFrom(TEntryList::Class())){
3139  elist->SetTree(fTree->GetTree());
3140  }
3141  }
3142  }
3143  }
3144 
3145  if (fFormulaList->GetSize()) {
3146  TObjLink *lnk = fFormulaList->FirstLink();
3147  while (lnk) {
3148  lnk->GetObject()->Notify();
3149  lnk = lnk->Next();
3150  }
3151  }
3152 }
const int ndata
TClass * GetClass() const
Definition: TLeafObject.h:50
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
void DeleteSelectorFromFile()
Delete any selector created by this object.
virtual const char * GetClassName() const
Return the name of the user class whose content is stored in this branch, if any. ...
Definition: TBranch.cxx:1182
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition: TAttLine.h:49
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition: TLeaf.h:37
static TString R__GetBranchPointerName(TLeaf *leaf, Bool_t replace=kTRUE)
Return the name of the branch pointer needed by MakeClass/MakeSelector.
TBranchElement * GetBranchCount2() const
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:5936
int Errors
Definition: Foption.h:37
An array of TObjects.
Definition: TObjArray.h:39
Principal Components Analysis (PCA)
Definition: TPrincipal.h:28
virtual void Delete(Option_t *option="")
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:405
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition: TH1.cxx:8251
virtual Int_t GetAction() const
Definition: TSelectorDraw.h:80
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:899
void AddRow(TSQLRow *row)
Adopt a row to result set.
virtual Long64_t GetEntriesToProcess(Long64_t firstentry, Long64_t nentries) const
return the number of entries to be processed this function checks that nentries is not bigger than th...
Bool_t ProcessEvents()
Process events if timer did time out.
Definition: TSystem.cxx:82
long long Long64_t
Definition: RtypesCore.h:69
virtual Long64_t GetN() const
Definition: TEntryList.h:77
TTree * fTree
Definition: TTreePlayer.h:50
Abstract interface for Tree Index.
Definition: TVirtualIndex.h:31
const char * GetDeclFileName() const
Definition: TClass.h:386
virtual Int_t GetScanField() const
Definition: TTree.h:438
virtual Double_t * GetVal(Int_t i) const
Return the last values corresponding to the i-th component of the formula being processed (where the ...
Int_t GetType() const
TVirtualFitter * tFitter
Definition: TTreePlayer.cxx:90
virtual Bool_t Notify()
This method must be overridden to handle object notification.
Definition: TSelector.h:64
virtual TLeaf * GetLeaf(const char *branchname, const char *leafname)
Return a pointer to the leaf name in the current tree.
Definition: TChain.cxx:1017
virtual void Print(Option_t *opt="MSE") const
Print the statistics Options are.
virtual Bool_t SendProcessingProgress(Double_t, Double_t, Bool_t=kFALSE)
void AdoptReferenceProxy(TVirtualRefProxy *proxy)
Adopt the Reference proxy pointer to indicate that this class represents a reference.
Definition: TClass.cxx:6249
Collectable string class.
Definition: TObjString.h:32
TSelectorDraw * fSelector
Pointer to histogram used for the projection.
Definition: TTreePlayer.h:56
const char * GetNameByIndex(TString &varexp, Int_t *index, Int_t colindex)
Set to the selector address when it&#39;s entry list needs to be updated by the UpdateFormulaLeaves funct...
const char Option_t
Definition: RtypesCore.h:62
virtual Bool_t Sync()
Synchronize all the formulae.
virtual void SetEstimate(Long64_t n)
Set number of entries to estimate variable limits.
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form: ~~~ {.cpp} [path/]macro.C[+|++[k|f|g|O|c|s|d|v|-]][(args)]...
Definition: TSystem.cxx:4109
virtual void Delete(Option_t *option="")
Remove all objects from the array AND delete all heap based objects.
Definition: TObjArray.cxx:329
double T(double x)
Definition: ChebyshevPol.h:34
virtual Bool_t ProcessCut(Long64_t)
Definition: TSelector.cxx:262
A TLeaf for a general object derived from TObject.
Definition: TLeafObject.h:35
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
R__EXTERN TStyle * gStyle
Definition: TStyle.h:418
R__EXTERN Foption_t Foption
Definition: TTreePlayer.cxx:88
int Verbose
Definition: Foption.h:30
virtual Int_t Fill()
Fill all branches.
Definition: TTree.cxx:4375
virtual TEntryList * GetEntryList()
Returns the entry list, set to this tree.
Definition: TTree.cxx:5419
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
TH1 * h
Definition: legend2.C:5
A specialized TFileCacheRead object for a TTree.
Definition: TTreeCache.h:34
virtual const char * GetTypeName() const
Definition: TLeaf.h:81
TVirtualStreamerInfo * GetStreamerInfo(Int_t version=0) const
returns a pointer to the TVirtualStreamerInfo object for version If the object does not exist...
Definition: TClass.cxx:4368
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7100
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format...
Definition: TFile.h:50
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1102
#define gROOT
Definition: TROOT.h:364
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
virtual Int_t GetEntry(Long64_t entry=0, Int_t getall=0)
Read all branches of entry and return total number of bytes read.
Definition: TTree.cxx:5211
Int_t LoadPlugin()
Load the plugin library for this handler.
Basic string class.
Definition: TString.h:137
Class describing the unbinned data sets (just x coordinates values) of any dimensions.
Definition: UnBinData.h:47
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:170
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1089
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
virtual Long64_t GetMaxEntryLoop() const
Definition: TTree.h:426
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:63
const Bool_t kFALSE
Definition: Rtypes.h:92
virtual void Draw(Option_t *option="")
Default Draw method for all objects.
Definition: TObject.cxx:255
int nbins[3]
virtual Long64_t Scan(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
Loop on Tree and print entries passing selection.
virtual void UpdateFormulaLeaves()
This function could be called TTreePlayer::UpdateFormulaLeaves, itself called by TChain::LoadTree whe...
virtual TTree * CloneTree(Long64_t nentries=-1, Option_t *option="")
Create a clone of this tree and copy nentries.
Definition: TTree.cxx:3004
TObject * At(Int_t idx) const
Definition: TObjArray.h:167
const char * Class
Definition: TXMLSetup.cxx:64
A TChainElement describes a component of a TChain.
Definition: TChainElement.h:30
int Nograph
Definition: Foption.h:42
virtual void Add(TTreeFormula *)
Add a new formula to the list of formulas managed The manager of the formula will be changed and the ...
virtual Int_t GetDimension() const
Definition: TSelectorDraw.h:82
A Tree Index with majorname and minorname.
Definition: TTreeIndex.h:32
Long64_t * GetTreeOffset() const
Definition: TChain.h:119
virtual void SetTree(const TTree *tree)
If a list for a tree with such name and filename exists, sets it as the current sublist If not...
virtual void SetTree(TTree *t)
Definition: TTreePlayer.h:132
virtual Int_t GetNdim() const
Definition: TFormula.h:243
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:739
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6418
virtual TObject * FindObject(const char *name) const
Find an object in this list using its name.
Definition: TList.cxx:497
if object in a list can be deleted
Definition: TObject.h:56
virtual Int_t GetDimension() const
Definition: TTreePlayer.h:82
TPrincipal * Principal(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
Interface to the Principal Components Analysis class.
TFitResultPtr UnBinFit(ROOT::Fit::UnBinData *data, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption)
fit an unbin data set (from tree or from histogram buffer) using a TF1 pointer and fit options...
Definition: HFitImpl.cxx:788
virtual Long64_t DrawSelect(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
Draw expression varexp for specified entries that matches the selection.
virtual void SetTextFont(Font_t tfont=62)
Set the text font.
Definition: TAttText.h:51
virtual Int_t GetDimension() const
Definition: TH1.h:287
virtual void ProcessFill(Long64_t)
Definition: TSelector.cxx:279
TObject * Last() const
Return the object in the last filled slot. Returns 0 if no entries.
Definition: TObjArray.cxx:479
virtual Long64_t GetCacheSize() const
Definition: TTree.h:384
virtual TObjArray * GetListOfBranches()
Definition: TTree.h:417
TStopwatch timer
Definition: pirndm.C:37
virtual Long64_t DrawScript(const char *wrapperPrefix, const char *macrofilename, const char *cutfilename, Option_t *option, Long64_t nentries, Long64_t firstentry)
Draw the result of a C++ script.
Used to coordinate one or more TTreeFormula objects.
virtual TTree * CopyTree(const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
Copy a Tree with selection, make a clone of this Tree header, then copy the selected entries...
Class defining interface to a row of a TTree query result.
Definition: TTreeRow.h:31
TTreeFormulaManager * GetManager() const
Definition: TTreeFormula.h:195
virtual Long64_t Process(const char *filename, Option_t *option, Long64_t nentries, Long64_t firstentry)
Process this tree executing the TSelector code in the specified filename.
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:33
virtual TObject * FindObject(const char *name) const
Find an object in this collection using its name.
Definition: TObjArray.cxx:396
TTreeFormula * GetVar2() const
Definition: TSelectorDraw.h:95
virtual Bool_t Notify()
This method must be overridden to handle object notification.
Definition: TObject.cxx:551
virtual Long64_t GetStatus() const
Definition: TSelector.h:66
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition: TTree.cxx:6010
static Long64_t GetFileBytesRead()
Static function returning the total number of bytes read from all files.
Definition: TFile.cxx:4375
Bool_t IsLoaded() const
Return true if the shared library of this class is currently in the a process&#39;s memory.
Definition: TClass.cxx:5557
R__EXTERN TVirtualMonitoringWriter * gMonitoringWriter
TString & Append(const char *cs)
Definition: TString.h:492
std::vector< std::vector< double > > Data
Base class for several text objects.
Definition: TText.h:33
TSelector * fSelectorFromFile
Pointer to current selector.
Definition: TTreePlayer.h:57
virtual void Begin(TTree *)
Definition: TSelector.h:62
TObjArray * GetListOfBranches()
Definition: TBranch.h:178
virtual Long64_t LoadTree(Long64_t entry)
Find the tree which contains entry, and set it as the current tree.
Definition: TChain.cxx:1253
virtual void MakeHistograms(const char *name="pca", Option_t *option="epsdx")
Make histograms of the result of the analysis.
Definition: TPrincipal.cxx:569
virtual TFile * GetFile() const
Definition: TDirectory.h:155
Used to pass a selection expression to the Tree drawing routine.
Definition: TTreeFormula.h:64
virtual void SetTextAlign(Short_t align=11)
Set the text alignment.
Definition: TAttText.h:47
virtual ~TTreePlayer()
Tree destructor.
virtual TTree * GetTree() const
Definition: TTree.h:444
virtual void UpdateFormulaLeaves()
this function is called by TChain::LoadTree when a new Tree is loaded.
virtual Int_t GetTreeNumber() const
Definition: TTree.h:446
A doubly linked list.
Definition: TList.h:47
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition: TTree.cxx:4869
virtual void StartViewer(Int_t ww, Int_t wh)
Start the TTreeViewer on this TTree.
void SetCanvasPreferGL(Bool_t prefer=kTRUE)
Definition: TStyle.h:332
const char * GetName() const
Returns name of object.
Definition: TObjString.h:42
virtual Int_t UnbinnedFit(const char *formula, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
Unbinned fit of one or more variable(s) from a Tree.
virtual void SetEstimate(Long64_t n)
Set number of entries to estimate variable limits.
virtual Long64_t GetEntryNumber(Long64_t entry) const
Return entry number corresponding to entry.
Definition: TTree.cxx:5430
virtual Int_t GetLen() const
Return the number of effective elements of this leaf.
Definition: TLeaf.cxx:279
virtual void SetEntryRange(Long64_t emin, Long64_t emax)
Set the minimum and maximum entry number to be processed this information helps to optimize the numbe...
virtual int Version() const
Definition: TSelector.h:60
virtual Int_t MakeReader(const char *classname, Option_t *option)
Generate skeleton selector class for this tree.
virtual Bool_t Notify()
This function is called at the first entry of a new tree in a chain.
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition: TTree.cxx:8467
virtual Long64_t GetSelectedRows() const
Definition: TTreePlayer.h:89
R__EXTERN TSystem * gSystem
Definition: TSystem.h:549
virtual void AddRow(const Double_t *x)
Add a data point and update the covariance matrix.
Definition: TPrincipal.cxx:410
TClass * fSelectorClass
Pointer to a user defined selector created by this TTreePlayer object.
Definition: TTreePlayer.h:58
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2851
const char * fScanFileName
Definition: TTreePlayer.h:52
Class defining interface to a TTree query result with the same interface as for SQL databases...
Definition: TTreeResult.h:36
TObject * GetObject() const
Definition: TSelectorDraw.h:84
virtual Long64_t GetSelectedRows() const
A container proxy, which allows to access references stored in a TRefArray from TTree::Draw.
virtual Int_t MakeProxy(const char *classname, const char *macrofilename=0, const char *cutfilename=0, const char *option=0, Int_t maxUnrolling=3)
Generate a skeleton analysis class for this Tree using TBranchProxy.
Long_t ExecPlugin(int nargs, const T &... params)
Int_t fDimension
Definition: TTreePlayer.h:53
virtual void SlaveBegin(TTree *)
Definition: TSelector.h:63
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
Definition: TFitResultPtr.h:33
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:488
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition: TH1.cxx:8323
TList * fInput
Pointer to the actual class of the TSelectorFromFile.
Definition: TTreePlayer.h:59
virtual char * PrintValue(Int_t mode=0) const
Return value of variable as a string.
virtual void SetNotify(TObject *obj)
Definition: TTree.h:556
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2322
NOTE: Must always be 0 !!!
Definition: TH1.h:93
unsigned int UInt_t
Definition: RtypesCore.h:42
virtual void LabelsDeflate(Option_t *axis="X")
Reduce the number of bins for the axis passed in the option to the number of bins having a label...
Definition: TH1.cxx:4803
Int_t GetEntriesFast() const
Definition: TObjArray.h:66
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:925
TFile * GetCurrentFile() const
Return pointer to the current file.
Definition: TTree.cxx:5053
char * Form(const char *fmt,...)
Ssiz_t Length() const
Definition: TString.h:390
virtual void UpdateFormulaLeaves()
This function is called TTreePlayer::UpdateFormulaLeaves, itself called by TChain::LoadTree when a ne...
virtual TLeaf * GetLeafCount() const
Definition: TLeaf.h:71
int More
Definition: Foption.h:38
virtual Bool_t SendProcessingStatus(const char *, Bool_t=kFALSE)
A TEventList object is a list of selected events (entries) in a TTree.
Definition: TEventList.h:33
TLine * l
Definition: textangle.C:4
The ROOT global object gROOT contains a list of all defined classes.
Definition: TClass.h:81
virtual Long64_t GetEstimate() const
Definition: TTree.h:397
virtual Int_t MakeCode(const char *filename)
Generate skeleton function for this Tree.
virtual TObject * At(Int_t idx) const
Returns the object at position idx. Returns 0 if idx is out of range.
Definition: TList.cxx:311
virtual void MakePrincipals()
Perform the principal components analysis.
Definition: TPrincipal.cxx:862
virtual const char * GetPath() const
Returns the full path of the directory.
Definition: TDirectory.cxx:911
Definition: graph.py:1
Int_t GetNumberOfColors() const
Return number of colors in the color palette.
Definition: TStyle.cxx:801
virtual void Draw(Option_t *option="")
Draws 3-D polymarker with its current attributes.
virtual void AddAt(TObject *obj, Int_t idx)
Add object at position ids.
Definition: TObjArray.cxx:239
Int_t LastIndex() const
virtual TObjLink * FirstLink() const
Definition: TList.h:101
virtual void Terminate()
Definition: TSelector.h:78
A Branch for the case of an object.
#define Printf
Definition: TGeoToOCC.h:18
A specialized TSelector for TTree::Draw.
Definition: TSelectorDraw.h:33
virtual void SlaveTerminate()
Definition: TSelector.h:77
virtual Long64_t Process(const char *filename, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Process this tree executing the TSelector code in the specified filename.
Definition: TTree.cxx:6922
static TSelector * GetSelector(const char *filename)
The code in filename is loaded (interpreted or compiled, see below), filename must contain a valid cl...
Definition: TSelector.cxx:142
TString & Remove(Ssiz_t pos)
Definition: TString.h:616
int Ssiz_t
Definition: RtypesCore.h:63
virtual Int_t GetNdata()
Return number of available instances in the formula.
virtual Int_t GetTimerInterval() const
Definition: TTree.h:441
virtual Double_t Eval(Double_t x, Double_t y=0, Double_t z=0, Double_t t=0) const
Evaluate this function.
Definition: TF1.cxx:1196
TObject * UncheckedAt(Int_t i) const
Definition: TObjArray.h:91
virtual Int_t GetMaximum() const
Definition: TLeaf.h:76
#define ClassImp(name)
Definition: Rtypes.h:279
Bool_t IsZombie() const
Definition: TObject.h:120
virtual void ResetAbort()
Definition: TSelector.h:81
virtual void SetEntryList(TEntryList *list, Option_t *opt="")
Set an EntryList.
Definition: TTree.cxx:8403
double Double_t
Definition: RtypesCore.h:55
virtual TObjArray * GetElements() const =0
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition: TString.cxx:865
TDirectory * GetDirectory() const
Definition: TTree.h:392
virtual const char * GetClassName() const
Return the name of the user class whose content is stored in this branch, if any. ...
TSelector * fSelectorUpdate
Pointer to a list of coordinated list TTreeFormula (used by Scan and Query)
Definition: TTreePlayer.h:61
Bool_t fScanRedirect
Pointer to current Tree.
Definition: TTreePlayer.h:51
TH1 * fHistogram
Definition: TTreePlayer.h:55
unsigned long ULong_t
Definition: RtypesCore.h:51
virtual void Draw(Option_t *opt)
Default Draw method for all objects.
Definition: TTree.h:367
int nentries
Definition: THbookFile.cxx:89
double func(double *x, double *p)
Definition: stressTF1.cxx:213
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
The TH1 histogram class.
Definition: TH1.h:80
TTreeFormula * GetVar3() const
Definition: TSelectorDraw.h:97
const char * AsString() const
Return the date & time as a string (ctime() format).
Definition: TDatime.cxx:101
#define R__LOCKGUARD(mutex)
virtual Bool_t Process(Long64_t)
Definition: TSelector.cxx:292
TObjArray * GetListOfLeaves()
Definition: TBranch.h:179
T EvalInstance(Int_t i=0, const char *stringStack[]=0)
Evaluate this treeformula.
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition: TClass.cxx:2893
virtual void Clear(Option_t *option="")
Remove all objects from the list.
Definition: TList.cxx:349
virtual Int_t SetCacheSize(Long64_t cachesize=-1)
Set maximum size of the file cache .
Definition: TTree.cxx:8048
virtual void RecursiveRemove(TObject *obj)
cleanup pointers in the player pointing to obj
Bool_t IsBranchFolder() const
The class is derived from the ROOT class TSelector.
virtual Long64_t GetEntries() const
Definition: TTree.h:393
virtual void SetOption(const char *option)
Definition: TSelector.h:71
Int_t GetNtrees() const
Definition: TChain.h:97
Abstract Base Class for Fitting.
const char * GetTypeName() const
Returns name of leaf type.
virtual UInt_t SetCanExtend(UInt_t extendBitMask)
Make the histogram axes extendable / not extendable according to the bit mask returns the previous bi...
Definition: TH1.cxx:5973
Mother of all ROOT objects.
Definition: TObject.h:37
virtual Bool_t IsFileInIncludePath(const char *name, char **fullpath=0)
Return true if &#39;name&#39; is a file that can be found in the ROOT include path or the current directory...
Definition: TSystem.cxx:961
virtual Long64_t GetDrawFlag() const
Definition: TSelectorDraw.h:83
#define R__EXTERN
Definition: DllImport.h:27
virtual Int_t GetNpar() const
Definition: TF1.h:349
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:526
virtual Long64_t GetEntries(const char *selection)
Return the number of entries matching the selection.
A 3D polymarker.
Definition: TPolyMarker3D.h:40
const char * GetTypeName() const
virtual void Add(TObject *obj)
Definition: TList.h:81
const Ssiz_t kNPOS
Definition: Rtypes.h:115
Definition: file.py:1
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:202
1-Dim function class
Definition: TF1.h:149
A chain is a collection of files containg TTree objects.
Definition: TChain.h:35
Long64_t fSelectedRows
Definition: TTreePlayer.h:54
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2544
virtual Bool_t IsInteger(Bool_t fast=kTRUE) const
Return TRUE if the formula corresponds to one single Tree leaf and this leaf is short, int or unsigned short, int When a leaf is of type integer or string, the generated histogram is forced to have an integer bin width.
virtual TVirtualIndex * BuildIndex(const TTree *T, const char *majorname, const char *minorname)
Build the index for the tree (see TTree::BuildIndex)
#define snprintf
Definition: civetweb.c:822
Int_t GetEntries() const
Return the number of objects in array (i.e.
Definition: TObjArray.cxx:494
#define gPad
Definition: TVirtualPad.h:289
virtual void SetTextColor(Color_t tcolor=1)
Set the text color.
Definition: TAttText.h:49
virtual void MakeCode(const char *filename="pca", Option_t *option="")
Generates the file <filename>, with .C appended if it does argument doesn&#39;t end in ...
Definition: TPrincipal.cxx:544
virtual UInt_t SplitNames(const TString &varexp, std::vector< TString > &names)
Build Index array for names in varexp.
Definition: tree.py:1
TFileCacheRead * GetCacheRead(TObject *tree=0) const
Return a pointer to the current read cache.
Definition: TFile.cxx:1202
void Add(TObject *obj)
Definition: TObjArray.h:75
A TTree object has a header with a name and a title.
Definition: TTree.h:98
TH1 * GetOldHistogram() const
Definition: TSelectorDraw.h:87
#define gDirectory
Definition: TDirectory.h:221
double result[121]
TEventList * GetEventList() const
Definition: TTree.h:403
virtual Int_t GetNdata(Bool_t forceLoadDim=kFALSE)
Return number of available instances in the formulas.
Definition: first.py:1
TList * fFormulaList
input list to the selector
Definition: TTreePlayer.h:60
virtual void SetTextSize(Float_t tsize=1)
Set the text size.
Definition: TAttText.h:52
Int_t GetNbins() const
Definition: TAxis.h:127
TBranch * GetBranch() const
Definition: TLeaf.h:70
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:189
Implement some of the functionality of the class TTree requiring access to extra libraries (Histogram...
Definition: TTreePlayer.h:43
int Quiet
Definition: Foption.h:29
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:416
virtual Int_t GetSize() const
Definition: TCollection.h:95
A TTree is a list of TBranches.
Definition: TBranch.h:58
virtual Bool_t GetCleanElist() const
Definition: TSelectorDraw.h:81
A TSelector object is used by the TTree::Draw, TTree::Scan, TTree::Process to navigate in a TTree and...
Definition: TSelector.h:39
const Bool_t kTRUE
Definition: Rtypes.h:91
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:155
TList * GetListOfFunctions() const
Definition: TH1.h:248
virtual Int_t Fit(const char *formula, const char *varexp, const char *selection, Option_t *option, Option_t *goption, Long64_t nentries, Long64_t firstentry)
Fit a projected item(s) from a Tree.
A List of entry numbers in a TTree or TChain.
Definition: TEntryList.h:27
virtual TFitResultPtr Fit(const char *formula, Option_t *option="", Option_t *goption="", Double_t xmin=0, Double_t xmax=0)
Fit histogram with function fname.
Definition: TH1.cxx:3563
double norm(double *x, double *p)
Definition: unuranDistr.cxx:40
virtual Int_t GetMultiplicity() const
const Int_t n
Definition: legend1.C:16
virtual Int_t MakeClass(const char *classname, Option_t *option)
Generate skeleton analysis class for this Tree.
virtual void SetScanField(Int_t n=50)
Definition: TTree.h:560
void AddField(Int_t field, const char *fieldname)
Add field name to result set.
Int_t GetStreamerType() const
TBranch * GetMother() const
Get our top-level parent branch in the tree.
Definition: TBranch.cxx:1551
virtual EAbort GetAbort() const
Definition: TSelector.h:80
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:911
TAxis * GetXaxis()
Definition: TH1.h:324
TTreeFormula * GetVar1() const
Definition: TSelectorDraw.h:93
virtual TList * GetOutputList() const
Definition: TSelector.h:76
virtual Long64_t GetEntriesFriend() const
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition: TTree.cxx:5086
if(line.BeginsWith("/*"))
Definition: HLFactory.cxx:443
A Chain Index.
Definition: TChainIndex.h:41
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:52
This class stores the date and time with a precision of one second in an unsigned 32 bit word (950130...
Definition: TDatime.h:39
virtual TObjArray * GetListOfLeaves()
Definition: TTree.h:418
virtual void Init(TTree *)
Definition: TSelector.h:61
Int_t GetNleaves() const
Definition: TBranch.h:181
const char * Data() const
Definition: TString.h:349
virtual TSQLResult * Query(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)
Loop on Tree and return TSQLResult object containing entries passing selection.