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