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