Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
TTree.cxx
Go to the documentation of this file.
1// @(#)root/tree:$Id$
2// Author: Rene Brun 12/01/96
3
4/*************************************************************************
5 * Copyright (C) 1995-2024, 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 \defgroup tree Tree Library
13
14 RNTuple is the modern way of storing columnar datasets: please consider to use it
15 before starting new projects based on TTree and related classes.
16
17 In order to store columnar datasets, ROOT historically provides the TTree, TChain,
18 TNtuple and TNtupleD classes.
19 The TTree class represents a columnar dataset. Any C++ type can be stored in the
20 columns. The TTree has allowed to store about **1 EB** of data coming from the LHC alone:
21 it is demonstrated to scale and it's battle tested. It has been optimized during the years
22 to reduce dataset sizes on disk and to deliver excellent runtime performance.
23 It allows to access only part of the columns of the datasets, too.
24 The TNtuple and TNtupleD classes are specialisations of the TTree class which can
25 only hold single precision and double precision floating-point numbers respectively;
26 The TChain is a collection of TTrees, which can be located also in different files.
27
28*/
29
30/** \class TTree
31\ingroup tree
32
33A TTree represents a columnar dataset. Any C++ type can be stored in its columns. The modern
34version of TTree is RNTuple: please consider using it before opting for TTree.
35
36A TTree, often called in jargon *tree*, consists of a list of independent columns or *branches*,
37represented by the TBranch class.
38Behind each branch, buffers are allocated automatically by ROOT.
39Such buffers are automatically written to disk or kept in memory until the size stored in the
40attribute fMaxVirtualSize is reached.
41Variables of one branch are written to the same buffer. A branch buffer is
42automatically compressed if the file compression attribute is set (default).
43Branches may be written to different files (see TBranch::SetFile).
44
45The ROOT user can decide to make one single branch and serialize one object into
46one single I/O buffer or to make several branches.
47Making several branches is particularly interesting in the data analysis phase,
48when it is desirable to have a high reading rate and not all columns are equally interesting
49
50\anchor creatingattreetoc
51## Create a TTree to store columnar data
52- [Construct a TTree](\ref creatingattree)
53- [Add a column of Fundamental Types and Arrays thereof](\ref addcolumnoffundamentaltypes)
54- [Add a column of a STL Collection instances](\ref addingacolumnofstl)
55- [Add a column holding an object](\ref addingacolumnofobjs)
56- [Add a column holding a TObjectArray](\ref addingacolumnofobjs)
57- [Fill the tree](\ref fillthetree)
58- [Add a column to an already existing Tree](\ref addcoltoexistingtree)
59- [An Example](\ref fullexample)
60
61\anchor creatingattree
62## Construct a TTree
63
64~~~ {.cpp}
65 TTree tree(name, title)
66~~~
67Creates a Tree with name and title.
68
69Various kinds of branches can be added to a tree:
70- Variables representing fundamental types, simple classes/structures or list of variables: for example for C or Fortran
71structures.
72- Any C++ object or collection, provided by the STL or ROOT.
73
74In the following, the details about the creation of different types of branches are given.
75
76\anchor addcolumnoffundamentaltypes
77## Add a column ("branch") holding fundamental types and arrays thereof
78This strategy works also for lists of variables, e.g. to describe simple structures.
79It is strongly recommended to persistify those as objects rather than lists of leaves.
80
81~~~ {.cpp}
82 auto branch = tree.Branch(branchname, address, leaflist, bufsize)
83~~~
84- `address` is the address of the first item of a structure
85- `leaflist` is the concatenation of all the variable names and types
86 separated by a colon character :
87 The variable name and the variable type are separated by a
88 slash (/). The variable type must be 1 character. (Characters
89 after the first are legal and will be appended to the visible
90 name of the leaf, but have no effect.) If no type is given, the
91 type of the variable is assumed to be the same as the previous
92 variable. If the first variable does not have a type, it is
93 assumed of type F by default. The list of currently supported
94 types is given below:
95 - `C` : a character string terminated by the 0 character
96 - `B` : an 8 bit signed integer (`Char_t`); Treated as a character when in an array.
97 - `b` : an 8 bit unsigned integer (`UChar_t`)
98 - `S` : a 16 bit signed integer (`Short_t`)
99 - `s` : a 16 bit unsigned integer (`UShort_t`)
100 - `I` : a 32 bit signed integer (`Int_t`)
101 - `i` : a 32 bit unsigned integer (`UInt_t`)
102 - `F` : a 32 bit floating point (`Float_t`)
103 - `f` : a 21 bit floating point with truncated mantissa (`Float16_t`): 1 for the sign, 8 for the exponent and 12 for the mantissa.
104 - `D` : a 64 bit floating point (`Double_t`)
105 - `d` : a 32 bit truncated floating point (`Double32_t`): 1 for the sign, 8 for the exponent and 23 for the mantissa.
106 - `L` : a 64 bit signed integer (`Long64_t`)
107 - `l` : a 64 bit unsigned integer (`ULong64_t`)
108 - `G` : a long signed integer, stored as 64 bit (`Long_t`)
109 - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
110 - `O` : [the letter `o`, not a zero] a boolean (`bool`)
111
112 Examples:
113 - A int: "myVar/I"
114 - A float array with fixed size: "myArrfloat[42]/F"
115 - An double array with variable size, held by the `myvar` column: "myArrdouble[myvar]/D"
116 - An Double32_t array with variable size, held by the `myvar` column , with values between 0 and 16: "myArr[myvar]/d[0,10]"
117 - The `myvar` column, which holds the variable size, **MUST** be an `Int_t` (/I).
118
119- If the address points to a single numerical variable, the leaflist is optional:
120~~~ {.cpp}
121 int value;
122 tree->Branch(branchname, &value);
123~~~
124- If the address points to more than one numerical variable, we strongly recommend
125 that the variable be sorted in decreasing order of size. Any other order will
126 result in a non-portable TTree (i.e. you will not be able to read it back on a
127 platform with a different padding strategy).
128 We recommend to persistify objects rather than composite leaflists.
129- In case of the truncated floating point types (`Float16_t` and `Double32_t`) you can
130 also specify the range in the style `[xmin,xmax]` or `[xmin,xmax,nbits]` after
131 the type character. For example, for storing a variable size array `myArr` of
132 `Double32_t` with values within a range of `[0, 2*pi]` and the size of which is stored
133 in an `Int_t` (/I) branch called `myArrSize`, the syntax for the `leaflist` string would
134 be: `myArr[myArrSize]/d[0,twopi]`. Of course the number of bits could be specified,
135 the standard rules of opaque typedefs annotation are valid. For example, if only
136 18 bits were sufficient, the syntax would become: `myArr[myArrSize]/d[0,twopi,18]`
137
138\anchor addingacolumnofstl
139## Adding a column holding STL collection instances (e.g. std::vector or std::list)
140
141~~~ {.cpp}
142 auto branch = tree.Branch( branchname, STLcollection, buffsize, splitlevel);
143~~~
144`STLcollection` is the address of a pointer to a container of the standard
145library such as `std::vector`, `std::list`, containing pointers, fundamental types
146or objects.
147If the splitlevel is a value bigger than 100 (`TTree::kSplitCollectionOfPointers`)
148then the collection will be written in split mode, i.e. transparently storing
149individual data members as arrays, therewith potentially increasing compression ratio.
150
151### Note
152In case of dynamic structures changing with each entry, see e.g.
153~~~ {.cpp}
154 branch->SetAddress(void *address)
155~~~
156one must redefine the branch address before filling the branch
157again. This is done via the `TBranch::SetAddress` member function.
158
159\anchor addingacolumnofobjs
160## Add a column holding objects
161
162~~~ {.cpp}
163 MyClass object;
164 auto branch = tree.Branch(branchname, &object, bufsize, splitlevel)
165~~~
166Note: The 2nd parameter must be the address of a valid object.
167 The object must not be destroyed (i.e. be deleted) until the TTree
168 is deleted or TTree::ResetBranchAddress is called.
169
170- if splitlevel=0, the object is serialized in the branch buffer.
171- if splitlevel=1 (default), this branch will automatically be split
172 into subbranches, with one subbranch for each data member or object
173 of the object itself. In case the object member is a TClonesArray,
174 the mechanism described in case C is applied to this array.
175- if splitlevel=2 ,this branch will automatically be split
176 into subbranches, with one subbranch for each data member or object
177 of the object itself. In case the object member is a TClonesArray,
178 it is processed as a TObject*, only one branch.
179
180Another available syntax is the following:
181
182~~~ {.cpp}
183 auto branch_a = tree.Branch(branchname, &p_object, bufsize, splitlevel)
184 auto branch_b = tree.Branch(branchname, className, &p_object, bufsize, splitlevel)
185~~~
186- `p_object` is a pointer to an object.
187- If `className` is not specified, the `Branch` method uses the type of `p_object`
188 to determine the type of the object.
189- If `className` is used to specify explicitly the object type, the `className`
190 must be of a type related to the one pointed to by the pointer. It should be
191 either a parent or derived class.
192
193Note: The pointer whose address is passed to `TTree::Branch` must not
194 be destroyed (i.e. go out of scope) until the TTree is deleted or
195 TTree::ResetBranchAddress is called.
196
197Note: The pointer `p_object` can be initialized before calling `TTree::Branch`
198~~~ {.cpp}
199 auto p_object = new MyDataClass;
200 tree.Branch(branchname, &p_object);
201~~~
202or not
203~~~ {.cpp}
204 MyDataClass* p_object = nullptr;
205 tree.Branch(branchname, &p_object);
206~~~
207In either case, the ownership of the object is not taken over by the `TTree`.
208Even though in the first case an object is be allocated by `TTree::Branch`,
209the object will <b>not</b> be deleted when the `TTree` is deleted.
210
211\anchor addingacolumnoftclonesarray
212## Add a column holding TClonesArray instances
213
214*The usage of `TClonesArray` should be abandoned in favour of `std::vector`,
215for which `TTree` has been heavily optimised, as well as `RNTuple`.*
216
217~~~ {.cpp}
218 // clonesarray is the address of a pointer to a TClonesArray.
219 auto branch = tree.Branch(branchname,clonesarray, bufsize, splitlevel)
220~~~
221The TClonesArray is a direct access list of objects of the same class.
222For example, if the TClonesArray is an array of TTrack objects,
223this function will create one subbranch for each data member of
224the object TTrack.
225
226\anchor fillthetree
227## Fill the Tree
228
229A TTree instance is filled with the invocation of the TTree::Fill method:
230~~~ {.cpp}
231 tree.Fill()
232~~~
233Upon its invocation, a loop on all defined branches takes place that for each branch invokes
234the TBranch::Fill method.
235
236\anchor addcoltoexistingtree
237## Add a column to an already existing Tree
238
239You may want to add a branch to an existing tree. For example,
240if one variable in the tree was computed with a certain algorithm,
241you may want to try another algorithm and compare the results.
242One solution is to add a new branch, fill it, and save the tree.
243The code below adds a simple branch to an existing tree.
244Note the `kOverwrite` option in the `Write` method: it overwrites the
245existing tree. If it is not specified, two copies of the tree headers
246are saved.
247~~~ {.cpp}
248 void addBranchToTree() {
249 TFile f("tree.root", "update");
250
251 Float_t new_v;
252 auto mytree = f->Get<TTree>("mytree");
253 auto newBranch = mytree->Branch("new_v", &new_v, "new_v/F");
254
255 auto nentries = mytree->GetEntries(); // read the number of entries in the mytree
256
257 for (Long64_t i = 0; i < nentries; i++) {
258 new_v = gRandom->Gaus(0, 1);
259 newBranch->Fill();
260 }
261
262 mytree->Write("", TObject::kOverwrite); // save only the new version of the tree
263 }
264~~~
265It is not always possible to add branches to existing datasets stored in TFiles: for example,
266these files might not be writeable, just readable. In addition, modifying in place a TTree
267causes a new TTree instance to be written and the previous one to be deleted.
268For this reasons, ROOT offers the concept of friends for TTree and TChain.
269
270\anchor fullexample
271## A Complete Example
272
273~~~ {.cpp}
274// A simple example creating a tree
275// Compile it with: `g++ myTreeExample.cpp -o myTreeExample `root-config --cflags --libs`
276
277#include "TFile.h"
278#include "TH1D.h"
279#include "TRandom3.h"
280#include "TTree.h"
281
282int main()
283{
284 // Create a new ROOT binary machine independent file.
285 // Note that this file may contain any kind of ROOT objects, histograms,trees
286 // pictures, graphics objects, detector geometries, tracks, events, etc..
287 TFile hfile("htree.root", "RECREATE", "Demo ROOT file with trees");
288
289 // Define a histogram and some simple structures
290 TH1D hpx("hpx", "This is the px distribution", 100, -4, 4);
291
292 typedef struct {
293 Float_t x, y, z;
294 } Point;
295
296 typedef struct {
297 Int_t ntrack, nseg, nvertex;
298 UInt_t flag;
299 Float_t temperature;
300 } Event;
301 Point point;
302 Event event;
303
304 // Create a ROOT Tree
305 TTree tree("T", "An example of ROOT tree with a few branches");
306 tree.Branch("point", &point, "x:y:z");
307 tree.Branch("event", &event, "ntrack/I:nseg:nvertex:flag/i:temperature/F");
308 tree.Branch("hpx", &hpx);
309
310 float px, py;
311
312 TRandom3 myGenerator;
313
314 // Here we start a loop on 1000 events
315 for (Int_t i = 0; i < 1000; i++) {
316 myGenerator.Rannor(px, py);
317 const auto random = myGenerator.Rndm(1);
318
319 // Fill histogram
320 hpx.Fill(px);
321
322 // Fill structures
323 point.x = 10 * (random - 1);
324 point.y = 5 * random;
325 point.z = 20 * random;
326 event.ntrack = int(100 * random);
327 event.nseg = int(2 * event.ntrack);
328 event.nvertex = 1;
329 event.flag = int(random + 0.5);
330 event.temperature = 20 + random;
331
332 // Fill the tree. For each event, save the 2 structures and object.
333 // In this simple example, the objects hpx, hprof and hpxpy are only slightly
334 // different from event to event. We expect a big compression factor!
335 tree.Fill();
336 }
337
338 // Save all objects in this file
339 hfile.Write();
340
341 // Close the file. Note that this is automatically done when you leave
342 // the application upon file destruction.
343 hfile.Close();
344
345 return 0;
346}
347~~~
348## TTree Diagram
349
350The following diagram shows the organisation of the federation of classes related to TTree.
351
352Begin_Macro
353../../../tutorials/legacy/tree/tree.C
354End_Macro
355*/
356
357#include <ROOT/RConfig.hxx>
358#include "TTree.h"
359
360#include "ROOT/TIOFeatures.hxx"
361#include "TArrayC.h"
362#include "TBufferFile.h"
363#include "TBaseClass.h"
364#include "TBasket.h"
365#include "TBranchClones.h"
366#include "TBranchElement.h"
367#include "TBranchObject.h"
368#include "TBranchRef.h"
369#include "TBrowser.h"
370#include "TClass.h"
371#include "TClassEdit.h"
372#include "TClonesArray.h"
373#include "TCut.h"
374#include "TDataMember.h"
375#include "TDataType.h"
376#include "TDirectory.h"
377#include "TError.h"
378#include "TEntryList.h"
379#include "TEnv.h"
380#include "TEventList.h"
381#include "TFile.h"
382#include "TFolder.h"
383#include "TFriendElement.h"
384#include "TInterpreter.h"
385#include "TLeaf.h"
386#include "TLeafB.h"
387#include "TLeafC.h"
388#include "TLeafD.h"
389#include "TLeafElement.h"
390#include "TLeafF.h"
391#include "TLeafI.h"
392#include "TLeafL.h"
393#include "TLeafObject.h"
394#include "TLeafS.h"
395#include "TList.h"
396#include "TMath.h"
397#include "TMemFile.h"
398#include "TROOT.h"
399#include "TRealData.h"
400#include "TRegexp.h"
401#include "TRefTable.h"
402#include "TStreamerElement.h"
403#include "TStreamerInfo.h"
404#include "TStyle.h"
405#include "TSystem.h"
406#include "TTreeCloner.h"
407#include "TTreeCache.h"
408#include "TTreeCacheUnzip.h"
411#include "TVirtualIndex.h"
412#include "TVirtualPerfStats.h"
413#include "TVirtualPad.h"
414#include "TBranchSTL.h"
415#include "TSchemaRuleSet.h"
416#include "TFileMergeInfo.h"
417#include "ROOT/StringConv.hxx"
418#include "TVirtualMutex.h"
419#include "strlcpy.h"
420#include "snprintf.h"
421
422#include "TBranchIMTHelper.h"
423#include "TNotifyLink.h"
424
425#include <chrono>
426#include <cstddef>
427#include <iostream>
428#include <fstream>
429#include <sstream>
430#include <string>
431#include <cstdio>
432#include <climits>
433#include <algorithm>
434#include <set>
435
436#ifdef R__USE_IMT
438#include <thread>
439#endif
441constexpr Int_t kNEntriesResort = 100;
443
444Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
445Long64_t TTree::fgMaxTreeSize = 100000000000LL;
446
448
449////////////////////////////////////////////////////////////////////////////////
450////////////////////////////////////////////////////////////////////////////////
451////////////////////////////////////////////////////////////////////////////////
454{
455 // Return the leaflist 'char' for a given datatype.
456
457 switch(datatype) {
458 case kChar_t: return 'B';
459 case kUChar_t: return 'b';
460 case kBool_t: return 'O';
461 case kShort_t: return 'S';
462 case kUShort_t: return 's';
463 case kCounter:
464 case kInt_t: return 'I';
465 case kUInt_t: return 'i';
466 case kDouble_t: return 'D';
467 case kDouble32_t: return 'd';
468 case kFloat_t: return 'F';
469 case kFloat16_t: return 'f';
470 case kLong_t: return 'G';
471 case kULong_t: return 'g';
472 case kchar: return 0; // unsupported
473 case kLong64_t: return 'L';
474 case kULong64_t: return 'l';
475
476 case kCharStar: return 'C';
477 case kBits: return 0; //unsupported
478
479 case kOther_t:
480 case kNoType_t:
481 default:
482 return 0;
483 }
484 return 0;
485}
486
487////////////////////////////////////////////////////////////////////////////////
488/// \class TTree::TFriendLock
489/// Helper class to prevent infinite recursion in the usage of TTree Friends.
490
491////////////////////////////////////////////////////////////////////////////////
492/// Record in tree that it has been used while recursively looks through the friends.
495: fTree(tree)
496{
497 // We could also add some code to acquire an actual
498 // lock to prevent multi-thread issues
500 if (fTree) {
503 } else {
504 fPrevious = false;
505 }
506}
507
508////////////////////////////////////////////////////////////////////////////////
509/// Copy constructor.
512 fTree(tfl.fTree),
513 fMethodBit(tfl.fMethodBit),
514 fPrevious(tfl.fPrevious)
515{
516}
517
518////////////////////////////////////////////////////////////////////////////////
519/// Assignment operator.
522{
523 if(this!=&tfl) {
524 fTree=tfl.fTree;
525 fMethodBit=tfl.fMethodBit;
526 fPrevious=tfl.fPrevious;
527 }
528 return *this;
529}
530
531////////////////////////////////////////////////////////////////////////////////
532/// Restore the state of tree the same as before we set the lock.
535{
536 if (fTree) {
537 if (!fPrevious) {
538 fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
539 }
540 }
541}
542
543////////////////////////////////////////////////////////////////////////////////
544/// \class TTree::TClusterIterator
545/// Helper class to iterate over cluster of baskets.
546/// \note In contrast to class TListIter, looping here must NOT be done using
547/// `while (iter())` or `while (iter.Next())` that would lead to an infinite loop, but rather using
548/// `while( (auto clusterStart = iter()) < tree->GetEntries() )`.
549/// \see TTree::GetClusterIterator
550
551////////////////////////////////////////////////////////////////////////////////
552/// Regular constructor.
553/// TTree is not set as const, since we might modify if it is a TChain.
555TTree::TClusterIterator::TClusterIterator(TTree *tree, Long64_t firstEntry) : fTree(tree), fClusterRange(0), fStartEntry(0), fNextEntry(0), fEstimatedSize(-1)
556{
557 if (fTree->fNClusterRange) {
558 // Find the correct cluster range.
559 //
560 // Since fClusterRangeEnd contains the inclusive upper end of the range, we need to search for the
561 // range that was containing the previous entry and add 1 (because BinarySearch consider the values
562 // to be the inclusive start of the bucket).
564
567 if (fClusterRange == 0) {
568 pedestal = 0;
570 } else {
573 }
577 } else {
579 }
580 if (autoflush <= 0) {
582 }
584 } else if ( fTree->GetAutoFlush() <= 0 ) {
585 // Case of old files before November 9 2009 *or* small tree where AutoFlush was never set.
587 } else {
589 }
590 fNextEntry = fStartEntry; // Position correctly for the first call to Next()
591}
592
593////////////////////////////////////////////////////////////////////////////////
594/// Estimate the cluster size.
595///
596/// In almost all cases, this quickly returns the size of the auto-flush
597/// in the TTree.
598///
599/// However, in the case where the cluster size was not fixed (old files and
600/// case where autoflush was explicitly set to zero), we need estimate
601/// a cluster size in relation to the size of the cache.
602///
603/// After this value is calculated once for the TClusterIterator, it is
604/// cached and reused in future calls.
607{
608 auto autoFlush = fTree->GetAutoFlush();
609 if (autoFlush > 0) return autoFlush;
610 if (fEstimatedSize > 0) return fEstimatedSize;
611
612 Long64_t zipBytes = fTree->GetZipBytes();
613 if (zipBytes == 0) {
614 fEstimatedSize = fTree->GetEntries() - 1;
615 if (fEstimatedSize <= 0)
616 fEstimatedSize = 1;
617 } else {
619 Long64_t cacheSize = fTree->GetCacheSize();
620 if (cacheSize == 0) {
621 // Humm ... let's double check on the file.
622 TFile *file = fTree->GetCurrentFile();
623 if (file) {
624 TFileCacheRead *cache = fTree->GetReadCache(file);
625 if (cache) {
626 cacheSize = cache->GetBufferSize();
627 }
628 }
629 }
630 // If neither file nor tree has a cache, use the current default.
631 if (cacheSize <= 0) {
632 cacheSize = 30000000;
633 }
634 clusterEstimate = fTree->GetEntries() * cacheSize / zipBytes;
635 // If there are no entries, then just default to 1.
636 fEstimatedSize = clusterEstimate ? clusterEstimate : 1;
637 }
638 return fEstimatedSize;
639}
640
641////////////////////////////////////////////////////////////////////////////////
642/// Move on to the next cluster and return the starting entry
643/// of this next cluster
646{
647 fStartEntry = fNextEntry;
648 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
649 if (fClusterRange == fTree->fNClusterRange) {
650 // We are looking at a range which size
651 // is defined by AutoFlush itself and goes to the GetEntries.
652 fNextEntry += GetEstimatedClusterSize();
653 } else {
654 if (fStartEntry > fTree->fClusterRangeEnd[fClusterRange]) {
655 ++fClusterRange;
656 }
657 if (fClusterRange == fTree->fNClusterRange) {
658 // We are looking at the last range which size
659 // is defined by AutoFlush itself and goes to the GetEntries.
660 fNextEntry += GetEstimatedClusterSize();
661 } else {
662 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
663 if (clusterSize == 0) {
664 clusterSize = GetEstimatedClusterSize();
665 }
666 fNextEntry += clusterSize;
667 if (fNextEntry > fTree->fClusterRangeEnd[fClusterRange]) {
668 // The last cluster of the range was a partial cluster,
669 // so the next cluster starts at the beginning of the
670 // next range.
671 fNextEntry = fTree->fClusterRangeEnd[fClusterRange] + 1;
672 }
673 }
674 }
675 } else {
676 // Case of old files before November 9 2009
677 fNextEntry = fStartEntry + GetEstimatedClusterSize();
678 }
679 if (fNextEntry > fTree->GetEntries()) {
680 fNextEntry = fTree->GetEntries();
681 }
682 return fStartEntry;
683}
684
685////////////////////////////////////////////////////////////////////////////////
686/// Move on to the previous cluster and return the starting entry
687/// of this previous cluster
690{
691 fNextEntry = fStartEntry;
692 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
693 if (fClusterRange == 0 || fTree->fNClusterRange == 0) {
694 // We are looking at a range which size
695 // is defined by AutoFlush itself.
696 fStartEntry -= GetEstimatedClusterSize();
697 } else {
698 if (fNextEntry <= fTree->fClusterRangeEnd[fClusterRange]) {
699 --fClusterRange;
700 }
701 if (fClusterRange == 0) {
702 // We are looking at the first range.
703 fStartEntry = 0;
704 } else {
705 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
706 if (clusterSize == 0) {
707 clusterSize = GetEstimatedClusterSize();
708 }
709 fStartEntry -= clusterSize;
710 }
711 }
712 } else {
713 // Case of old files before November 9 2009 or trees that never auto-flushed.
714 fStartEntry = fNextEntry - GetEstimatedClusterSize();
715 }
716 if (fStartEntry < 0) {
717 fStartEntry = 0;
718 }
719 return fStartEntry;
720}
721
722////////////////////////////////////////////////////////////////////////////////
723////////////////////////////////////////////////////////////////////////////////
724////////////////////////////////////////////////////////////////////////////////
725
726////////////////////////////////////////////////////////////////////////////////
727/// Default constructor and I/O constructor.
728///
729/// Note: We do *not* insert ourself into the current directory.
730///
733: TNamed()
734, TAttLine()
735, TAttFill()
736, TAttMarker()
737, fEntries(0)
738, fTotBytes(0)
739, fZipBytes(0)
740, fSavedBytes(0)
741, fFlushedBytes(0)
742, fWeight(1)
744, fScanField(25)
745, fUpdate(0)
749, fMaxEntries(0)
750, fMaxEntryLoop(0)
752, fAutoSave( -300000000)
753, fAutoFlush(-30000000)
754, fEstimate(1000000)
755, fClusterRangeEnd(nullptr)
756, fClusterSize(nullptr)
757, fCacheSize(0)
758, fChainOffset(0)
759, fReadEntry(-1)
760, fTotalBuffers(0)
761, fPacketSize(100)
762, fNfill(0)
763, fDebug(0)
764, fDebugMin(0)
765, fDebugMax(9999999)
766, fMakeClass(0)
767, fFileNumber(0)
768, fNotify(nullptr)
769, fDirectory(nullptr)
770, fBranches()
771, fLeaves()
772, fAliases(nullptr)
773, fEventList(nullptr)
774, fEntryList(nullptr)
775, fIndexValues()
776, fIndex()
777, fTreeIndex(nullptr)
778, fFriends(nullptr)
779, fExternalFriends(nullptr)
780, fPerfStats(nullptr)
781, fUserInfo(nullptr)
782, fPlayer(nullptr)
783, fClones(nullptr)
784, fBranchRef(nullptr)
786, fTransientBuffer(nullptr)
790, fIMTEnabled(ROOT::IsImplicitMTEnabled())
792{
793 fMaxEntries = 1000000000;
794 fMaxEntries *= 1000;
795
796 fMaxEntryLoop = 1000000000;
797 fMaxEntryLoop *= 1000;
798
799 fBranches.SetOwner(true);
800}
801
802////////////////////////////////////////////////////////////////////////////////
803/// Normal tree constructor.
804///
805/// The tree is created in the current directory.
806/// Use the various functions Branch below to add branches to this tree.
807///
808/// If the first character of title is a "/", the function assumes a folder name.
809/// In this case, it creates automatically branches following the folder hierarchy.
810/// splitlevel may be used in this case to control the split level.
812TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */,
813 TDirectory* dir /* = gDirectory*/)
814: TNamed(name, title)
815, TAttLine()
816, TAttFill()
817, TAttMarker()
818, fEntries(0)
819, fTotBytes(0)
820, fZipBytes(0)
821, fSavedBytes(0)
822, fFlushedBytes(0)
823, fWeight(1)
824, fTimerInterval(0)
825, fScanField(25)
826, fUpdate(0)
827, fDefaultEntryOffsetLen(1000)
828, fNClusterRange(0)
829, fMaxClusterRange(0)
830, fMaxEntries(0)
831, fMaxEntryLoop(0)
832, fMaxVirtualSize(0)
833, fAutoSave( -300000000)
834, fAutoFlush(-30000000)
835, fEstimate(1000000)
836, fClusterRangeEnd(nullptr)
837, fClusterSize(nullptr)
838, fCacheSize(0)
839, fChainOffset(0)
840, fReadEntry(-1)
841, fTotalBuffers(0)
842, fPacketSize(100)
843, fNfill(0)
844, fDebug(0)
845, fDebugMin(0)
846, fDebugMax(9999999)
847, fMakeClass(0)
848, fFileNumber(0)
849, fNotify(nullptr)
850, fDirectory(dir)
851, fBranches()
852, fLeaves()
853, fAliases(nullptr)
854, fEventList(nullptr)
855, fEntryList(nullptr)
856, fIndexValues()
857, fIndex()
858, fTreeIndex(nullptr)
859, fFriends(nullptr)
860, fExternalFriends(nullptr)
861, fPerfStats(nullptr)
862, fUserInfo(nullptr)
863, fPlayer(nullptr)
864, fClones(nullptr)
865, fBranchRef(nullptr)
866, fFriendLockStatus(0)
867, fTransientBuffer(nullptr)
868, fCacheDoAutoInit(true)
869, fCacheDoClusterPrefetch(false)
870, fCacheUserSet(false)
871, fIMTEnabled(ROOT::IsImplicitMTEnabled())
872, fNEntriesSinceSorting(0)
873{
874 // TAttLine state.
878
879 // TAttFill state.
882
883 // TAttMarkerState.
887
888 fMaxEntries = 1000000000;
889 fMaxEntries *= 1000;
890
891 fMaxEntryLoop = 1000000000;
892 fMaxEntryLoop *= 1000;
893
894 // Insert ourself into the current directory.
895 // FIXME: This is very annoying behaviour, we should
896 // be able to choose to not do this like we
897 // can with a histogram.
898 if (fDirectory) fDirectory->Append(this);
899
900 fBranches.SetOwner(true);
901
902 // If title starts with "/" and is a valid folder name, a superbranch
903 // is created.
904 // FIXME: Why?
905 if (strlen(title) > 2) {
906 if (title[0] == '/') {
907 Branch(title+1,32000,splitlevel);
908 }
909 }
910}
911
912////////////////////////////////////////////////////////////////////////////////
913/// Destructor.
916{
917 if (auto link = dynamic_cast<TNotifyLinkBase*>(fNotify)) {
918 link->Clear();
919 }
920 if (fAllocationCount && (gDebug > 0)) {
921 Info("TTree::~TTree", "For tree %s, allocation count is %u.", GetName(), fAllocationCount.load());
922#ifdef R__TRACK_BASKET_ALLOC_TIME
923 Info("TTree::~TTree", "For tree %s, allocation time is %lluus.", GetName(), fAllocationTime.load());
924#endif
925 }
926
927 if (fDirectory) {
928 // We are in a directory, which may possibly be a file.
929 if (fDirectory->GetList()) {
930 // Remove us from the directory listing.
931 fDirectory->Remove(this);
932 }
933 //delete the file cache if it points to this Tree
934 TFile *file = fDirectory->GetFile();
935 MoveReadCache(file,nullptr);
936 }
937
938 // Remove the TTree from any list (linked to to the list of Cleanups) to avoid the unnecessary call to
939 // this RecursiveRemove while we delete our content.
941 ResetBit(kMustCleanup); // Don't redo it.
942
943 // We don't own the leaves in fLeaves, the branches do.
944 fLeaves.Clear();
945 // I'm ready to destroy any objects allocated by
946 // SetAddress() by my branches. If I have clones,
947 // tell them to zero their pointers to this shared
948 // memory.
949 if (fClones && fClones->GetEntries()) {
950 // I have clones.
951 // I am about to delete the objects created by
952 // SetAddress() which we are sharing, so tell
953 // the clones to release their pointers to them.
954 for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
955 TTree* clone = (TTree*) lnk->GetObject();
956 // clone->ResetBranchAddresses();
957
958 // Reset only the branch we have set the address of.
959 CopyAddresses(clone,true);
960 }
961 }
962 // Get rid of our branches, note that this will also release
963 // any memory allocated by TBranchElement::SetAddress().
965
966 // The TBranch destructor is using fDirectory to detect whether it
967 // owns the TFile that contains its data (See TBranch::~TBranch)
968 fDirectory = nullptr;
969
970 // FIXME: We must consider what to do with the reset of these if we are a clone.
971 delete fPlayer;
972 fPlayer = nullptr;
973 if (fExternalFriends) {
974 using namespace ROOT::Detail;
976 fetree->Reset();
977 fExternalFriends->Clear("nodelete");
979 }
980 if (fFriends) {
981 fFriends->Delete();
982 delete fFriends;
983 fFriends = nullptr;
984 }
985 if (fAliases) {
986 fAliases->Delete();
987 delete fAliases;
988 fAliases = nullptr;
989 }
990 if (fUserInfo) {
991 fUserInfo->Delete();
992 delete fUserInfo;
993 fUserInfo = nullptr;
994 }
995 if (fClones) {
996 // Clone trees should no longer be removed from fClones when they are deleted.
997 {
999 gROOT->GetListOfCleanups()->Remove(fClones);
1000 }
1001 // Note: fClones does not own its content.
1002 delete fClones;
1003 fClones = nullptr;
1004 }
1005 if (fEntryList) {
1006 if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==nullptr) {
1007 // Delete the entry list if it is marked to be deleted and it is not also
1008 // owned by a directory. (Otherwise we would need to make sure that a
1009 // TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
1010 delete fEntryList;
1011 fEntryList=nullptr;
1012 }
1013 }
1014 delete fTreeIndex;
1015 fTreeIndex = nullptr;
1016 delete fBranchRef;
1017 fBranchRef = nullptr;
1018 delete [] fClusterRangeEnd;
1019 fClusterRangeEnd = nullptr;
1020 delete [] fClusterSize;
1021 fClusterSize = nullptr;
1022
1023 if (fTransientBuffer) {
1024 delete fTransientBuffer;
1025 fTransientBuffer = nullptr;
1026 }
1027}
1028
1029////////////////////////////////////////////////////////////////////////////////
1030/// Returns the transient buffer currently used by this TTree for reading/writing baskets.
1042}
1043
1044////////////////////////////////////////////////////////////////////////////////
1045/// Add branch with name bname to the Tree cache.
1046/// If bname="*" all branches are added to the cache.
1047/// if subbranches is true all the branches of the subbranches are
1048/// also put to the cache.
1049///
1050/// Returns:
1051/// - 0 branch added or already included
1052/// - -1 on error
1054Int_t TTree::AddBranchToCache(const char*bname, bool subbranches)
1055{
1056 if (!GetTree()) {
1057 if (LoadTree(0)<0) {
1058 Error("AddBranchToCache","Could not load a tree");
1059 return -1;
1060 }
1061 }
1062 if (GetTree()) {
1063 if (GetTree() != this) {
1064 return GetTree()->AddBranchToCache(bname, subbranches);
1065 }
1066 } else {
1067 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1068 return -1;
1069 }
1070
1071 TFile *f = GetCurrentFile();
1072 if (!f) {
1073 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1074 return -1;
1075 }
1076 TTreeCache *tc = GetReadCache(f,true);
1077 if (!tc) {
1078 Error("AddBranchToCache", "No cache is available, branch not added");
1079 return -1;
1080 }
1081 return tc->AddBranch(bname,subbranches);
1082}
1083
1084////////////////////////////////////////////////////////////////////////////////
1085/// Add branch b to the Tree cache.
1086/// if subbranches is true all the branches of the subbranches are
1087/// also put to the cache.
1088///
1089/// Returns:
1090/// - 0 branch added or already included
1091/// - -1 on error
1094{
1095 if (!GetTree()) {
1096 if (LoadTree(0)<0) {
1097 Error("AddBranchToCache","Could not load a tree");
1098 return -1;
1099 }
1100 }
1101 if (GetTree()) {
1102 if (GetTree() != this) {
1103 Int_t res = GetTree()->AddBranchToCache(b, subbranches);
1104 if (res<0) {
1105 Error("AddBranchToCache", "Error adding branch");
1106 }
1107 return res;
1108 }
1109 } else {
1110 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1111 return -1;
1112 }
1113
1114 TFile *f = GetCurrentFile();
1115 if (!f) {
1116 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1117 return -1;
1118 }
1119 TTreeCache *tc = GetReadCache(f,true);
1120 if (!tc) {
1121 Error("AddBranchToCache", "No cache is available, branch not added");
1122 return -1;
1123 }
1124 return tc->AddBranch(b,subbranches);
1125}
1126
1127////////////////////////////////////////////////////////////////////////////////
1128/// Remove the branch with name 'bname' from the Tree cache.
1129/// If bname="*" all branches are removed from the cache.
1130/// if subbranches is true all the branches of the subbranches are
1131/// also removed from the cache.
1132///
1133/// Returns:
1134/// - 0 branch dropped or not in cache
1135/// - -1 on error
1137Int_t TTree::DropBranchFromCache(const char*bname, bool subbranches)
1138{
1139 if (!GetTree()) {
1140 if (LoadTree(0)<0) {
1141 Error("DropBranchFromCache","Could not load a tree");
1142 return -1;
1143 }
1144 }
1145 if (GetTree()) {
1146 if (GetTree() != this) {
1147 return GetTree()->DropBranchFromCache(bname, subbranches);
1148 }
1149 } else {
1150 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1151 return -1;
1152 }
1153
1154 TFile *f = GetCurrentFile();
1155 if (!f) {
1156 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1157 return -1;
1158 }
1159 TTreeCache *tc = GetReadCache(f,true);
1160 if (!tc) {
1161 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1162 return -1;
1163 }
1164 return tc->DropBranch(bname,subbranches);
1165}
1166
1167////////////////////////////////////////////////////////////////////////////////
1168/// Remove the branch b from the Tree cache.
1169/// if subbranches is true all the branches of the subbranches are
1170/// also removed from the cache.
1171///
1172/// Returns:
1173/// - 0 branch dropped or not in cache
1174/// - -1 on error
1177{
1178 if (!GetTree()) {
1179 if (LoadTree(0)<0) {
1180 Error("DropBranchFromCache","Could not load a tree");
1181 return -1;
1182 }
1183 }
1184 if (GetTree()) {
1185 if (GetTree() != this) {
1186 Int_t res = GetTree()->DropBranchFromCache(b, subbranches);
1187 if (res<0) {
1188 Error("DropBranchFromCache", "Error dropping branch");
1189 }
1190 return res;
1191 }
1192 } else {
1193 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1194 return -1;
1195 }
1196
1197 TFile *f = GetCurrentFile();
1198 if (!f) {
1199 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1200 return -1;
1201 }
1202 TTreeCache *tc = GetReadCache(f,true);
1203 if (!tc) {
1204 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1205 return -1;
1206 }
1207 return tc->DropBranch(b,subbranches);
1208}
1209
1210////////////////////////////////////////////////////////////////////////////////
1211/// Add a cloned tree to our list of trees to be notified whenever we change
1212/// our branch addresses or when we are deleted.
1214void TTree::AddClone(TTree* clone)
1215{
1216 if (!fClones) {
1217 fClones = new TList();
1218 fClones->SetOwner(false);
1219 // So that the clones are automatically removed from the list when
1220 // they are deleted.
1221 {
1223 gROOT->GetListOfCleanups()->Add(fClones);
1224 }
1225 }
1226 if (!fClones->FindObject(clone)) {
1227 fClones->Add(clone);
1228 }
1229}
1230
1231// Check whether mainTree and friendTree can be friends w.r.t. the kEntriesReshuffled bit.
1232// In particular, if any has the bit set, then friendTree must have a TTreeIndex and the
1233// branches used for indexing must be present in mainTree.
1234// Return true if the trees can be friends, false otherwise.
1236{
1239 const auto friendHasValidIndex = [&] {
1240 auto idx = friendTree.GetTreeIndex();
1241 return idx ? idx->IsValidFor(&mainTree) : false;
1242 }();
1243
1245 const auto reshuffledTreeName = isMainReshuffled ? mainTree.GetName() : friendTree.GetName();
1246 const auto msg =
1247 "Tree '%s' has the kEntriesReshuffled bit set and cannot have friends nor can be added as a friend unless the "
1248 "main tree has a TTreeIndex on the friend tree '%s'. You can also unset the bit manually if you know what you "
1249 "are doing; note that you risk associating wrong TTree entries of the friend with those of the main TTree!";
1250 Error("AddFriend", msg, reshuffledTreeName, friendTree.GetName());
1251 return false;
1252 }
1253 return true;
1254}
1255
1256////////////////////////////////////////////////////////////////////////////////
1257/// Add a TFriendElement to the list of friends.
1258///
1259/// This function:
1260/// - opens a file if filename is specified
1261/// - reads a Tree with name treename from the file (current directory)
1262/// - adds the Tree to the list of friends
1263/// see other AddFriend functions
1264///
1265/// A TFriendElement TF describes a TTree object TF in a file.
1266/// When a TFriendElement TF is added to the list of friends of an
1267/// existing TTree T, any variable from TF can be referenced in a query
1268/// to T.
1269///
1270/// A tree keeps a list of friends. In the context of a tree (or a chain),
1271/// friendship means unrestricted access to the friends data. In this way
1272/// it is much like adding another branch to the tree without taking the risk
1273/// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
1274/// method. The tree in the diagram below has two friends (friend_tree1 and
1275/// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
1276///
1277/// \image html ttree_friend1.png
1278///
1279/// The AddFriend method has two parameters, the first is the tree name and the
1280/// second is the name of the ROOT file where the friend tree is saved.
1281/// AddFriend automatically opens the friend file. If no file name is given,
1282/// the tree called ft1 is assumed to be in the same file as the original tree.
1283///
1284/// tree.AddFriend("ft1","friendfile1.root");
1285/// If the friend tree has the same name as the original tree, you can give it
1286/// an alias in the context of the friendship:
1287///
1288/// tree.AddFriend("tree1 = tree","friendfile1.root");
1289/// Once the tree has friends, we can use TTree::Draw as if the friend's
1290/// variables were in the original tree. To specify which tree to use in
1291/// the Draw method, use the syntax:
1292/// ~~~ {.cpp}
1293/// <treeName>.<branchname>.<varname>
1294/// ~~~
1295/// If the variablename is enough to uniquely identify the variable, you can
1296/// leave out the tree and/or branch name.
1297/// For example, these commands generate a 3-d scatter plot of variable "var"
1298/// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
1299/// TTree ft2.
1300/// ~~~ {.cpp}
1301/// tree.AddFriend("ft1","friendfile1.root");
1302/// tree.AddFriend("ft2","friendfile2.root");
1303/// tree.Draw("var:ft1.v1:ft2.v2");
1304/// ~~~
1305/// \image html ttree_friend2.png
1306///
1307/// The picture illustrates the access of the tree and its friends with a
1308/// Draw command.
1309/// When AddFriend is called, the ROOT file is automatically opened and the
1310/// friend tree (ft1) is read into memory. The new friend (ft1) is added to
1311/// the list of friends of tree.
1312/// The number of entries in the friend must be equal or greater to the number
1313/// of entries of the original tree. If the friend tree has fewer entries a
1314/// warning is given and the missing entries are not included in the histogram.
1315/// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
1316/// When the tree is written to file (TTree::Write), the friends list is saved
1317/// with it. And when the tree is retrieved, the trees on the friends list are
1318/// also retrieved and the friendship restored.
1319/// When a tree is deleted, the elements of the friend list are also deleted.
1320/// It is possible to declare a friend tree that has the same internal
1321/// structure (same branches and leaves) as the original tree, and compare the
1322/// same values by specifying the tree.
1323/// ~~~ {.cpp}
1324/// tree.Draw("var:ft1.var:ft2.var")
1325/// ~~~
1327TFriendElement *TTree::AddFriend(const char *treename, const char *filename)
1328{
1329 if (!fFriends) {
1330 fFriends = new TList();
1331 }
1333
1334 TTree *t = fe->GetTree();
1335 bool canAddFriend = true;
1336 if (t) {
1337 canAddFriend = CheckReshuffling(*this, *t);
1338 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1339 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename,
1341 }
1342 } else {
1343 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, filename);
1344 canAddFriend = false;
1345 }
1346
1347 if (canAddFriend)
1348 fFriends->Add(fe);
1349 return fe;
1350}
1351
1352////////////////////////////////////////////////////////////////////////////////
1353/// Add a TFriendElement to the list of friends.
1354///
1355/// The TFile is managed by the user (e.g. the user must delete the file).
1356/// For complete description see AddFriend(const char *, const char *).
1357/// This function:
1358/// - reads a Tree with name treename from the file
1359/// - adds the Tree to the list of friends
1361TFriendElement *TTree::AddFriend(const char *treename, TFile *file)
1362{
1363 if (!fFriends) {
1364 fFriends = new TList();
1365 }
1366 TFriendElement *fe = new TFriendElement(this, treename, file);
1367 R__ASSERT(fe);
1368 TTree *t = fe->GetTree();
1369 bool canAddFriend = true;
1370 if (t) {
1371 canAddFriend = CheckReshuffling(*this, *t);
1372 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1373 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename,
1374 file->GetName(), t->GetEntries(), fEntries);
1375 }
1376 } else {
1377 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, file->GetName());
1378 canAddFriend = false;
1379 }
1380
1381 if (canAddFriend)
1382 fFriends->Add(fe);
1383 return fe;
1384}
1385
1386////////////////////////////////////////////////////////////////////////////////
1387/// Add a TFriendElement to the list of friends.
1388///
1389/// The TTree is managed by the user (e.g., the user must delete the file).
1390/// For a complete description see AddFriend(const char *, const char *).
1392TFriendElement *TTree::AddFriend(TTree *tree, const char *alias, bool warn)
1393{
1394 if (!tree) {
1395 return nullptr;
1396 }
1397 if (!fFriends) {
1398 fFriends = new TList();
1399 }
1400 TFriendElement *fe = new TFriendElement(this, tree, alias);
1401 R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
1402 TTree *t = fe->GetTree();
1403 if (warn && (t->GetEntries() < fEntries)) {
1404 Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld",
1405 tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(),
1406 fEntries);
1407 }
1408 if (CheckReshuffling(*this, *t))
1409 fFriends->Add(fe);
1410 else
1411 tree->RemoveExternalFriend(fe);
1412 return fe;
1413}
1414
1415////////////////////////////////////////////////////////////////////////////////
1416/// AutoSave tree header every fAutoSave bytes.
1417///
1418/// When large Trees are produced, it is safe to activate the AutoSave
1419/// procedure. Some branches may have buffers holding many entries.
1420/// If fAutoSave is negative, AutoSave is automatically called by
1421/// TTree::Fill when the number of bytes generated since the previous
1422/// AutoSave is greater than -fAutoSave bytes.
1423/// If fAutoSave is positive, AutoSave is automatically called by
1424/// TTree::Fill every N entries.
1425/// This function may also be invoked by the user.
1426/// Each AutoSave generates a new key on the file.
1427/// Once the key with the tree header has been written, the previous cycle
1428/// (if any) is deleted.
1429///
1430/// Note that calling TTree::AutoSave too frequently (or similarly calling
1431/// TTree::SetAutoSave with a small value) is an expensive operation.
1432/// You should make tests for your own application to find a compromise
1433/// between speed and the quantity of information you may loose in case of
1434/// a job crash.
1435///
1436/// In case your program crashes before closing the file holding this tree,
1437/// the file will be automatically recovered when you will connect the file
1438/// in UPDATE mode.
1439/// The Tree will be recovered at the status corresponding to the last AutoSave.
1440///
1441/// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
1442/// This allows another process to analyze the Tree while the Tree is being filled.
1443///
1444/// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
1445/// the current basket are closed-out and written to disk individually.
1446///
1447/// By default the previous header is deleted after having written the new header.
1448/// if option contains "Overwrite", the previous Tree header is deleted
1449/// before written the new header. This option is slightly faster, but
1450/// the default option is safer in case of a problem (disk quota exceeded)
1451/// when writing the new header.
1452///
1453/// The function returns the number of bytes written to the file.
1454/// if the number of bytes is null, an error has occurred while writing
1455/// the header to the file.
1456///
1457/// ## How to write a Tree in one process and view it from another process
1458///
1459/// The following two scripts illustrate how to do this.
1460/// The script treew.C is executed by process1, treer.C by process2
1461///
1462/// script treew.C:
1463/// ~~~ {.cpp}
1464/// void treew() {
1465/// TFile f("test.root","recreate");
1466/// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
1467/// Float_t px, py, pz;
1468/// for ( Int_t i=0; i<10000000; i++) {
1469/// gRandom->Rannor(px,py);
1470/// pz = px*px + py*py;
1471/// Float_t random = gRandom->Rndm(1);
1472/// ntuple->Fill(px,py,pz,random,i);
1473/// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
1474/// }
1475/// }
1476/// ~~~
1477/// script treer.C:
1478/// ~~~ {.cpp}
1479/// void treer() {
1480/// TFile f("test.root");
1481/// TTree *ntuple = (TTree*)f.Get("ntuple");
1482/// TCanvas c1;
1483/// Int_t first = 0;
1484/// while(1) {
1485/// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
1486/// else ntuple->Draw("px>>+hpx","","",10000000,first);
1487/// first = (Int_t)ntuple->GetEntries();
1488/// c1.Update();
1489/// gSystem->Sleep(1000); //sleep 1 second
1490/// ntuple->Refresh();
1491/// }
1492/// }
1493/// ~~~
1496{
1497 if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
1498 if (gDebug > 0) {
1499 Info("AutoSave", "Tree:%s after %lld bytes written\n",GetName(),GetTotBytes());
1500 }
1501 TString opt = option;
1502 opt.ToLower();
1503
1504 if (opt.Contains("flushbaskets")) {
1505 if (gDebug > 0) Info("AutoSave", "calling FlushBaskets \n");
1507 }
1508
1510
1511 TKey *key = (TKey*)fDirectory->GetListOfKeys()->FindObject(GetName());
1513 if (opt.Contains("overwrite")) {
1514 nbytes = fDirectory->WriteTObject(this,"","overwrite");
1515 } else {
1516 nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
1517 if (nbytes && key && strcmp(ClassName(), key->GetClassName()) == 0) {
1518 key->Delete();
1519 delete key;
1520 }
1521 }
1522 // save StreamerInfo
1523 TFile *file = fDirectory->GetFile();
1524 if (file) file->WriteStreamerInfo();
1525
1526 if (opt.Contains("saveself")) {
1528 //the following line is required in case GetUserInfo contains a user class
1529 //for which the StreamerInfo must be written. One could probably be a bit faster (Rene)
1530 if (file) file->WriteHeader();
1531 }
1532
1533 return nbytes;
1534}
1535
1536namespace {
1537 // This error message is repeated several times in the code. We write it once.
1538 const char* writeStlWithoutProxyMsg = "The class requested (%s) for the branch \"%s\""
1539 " is an instance of an stl collection and does not have a compiled CollectionProxy."
1540 " Please generate the dictionary for this collection (%s) to avoid to write corrupted data.";
1541}
1542
1543////////////////////////////////////////////////////////////////////////////////
1544/// Same as TTree::Branch() with added check that addobj matches className.
1545///
1546/// \see TTree::Branch()
1547///
1549TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
1550{
1551 TClass* claim = TClass::GetClass(classname);
1552 if (!ptrClass) {
1553 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1555 claim->GetName(), branchname, claim->GetName());
1556 return nullptr;
1557 }
1558 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1559 }
1560 TClass* actualClass = nullptr;
1561 void** addr = (void**) addobj;
1562 if (addr) {
1563 actualClass = ptrClass->GetActualClass(*addr);
1564 }
1565 if (ptrClass && claim) {
1566 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1567 // Note we currently do not warn in case of splicing or over-expectation).
1568 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1569 // The type is the same according to the C++ type_info, we must be in the case of
1570 // a template of Double32_t. This is actually a correct case.
1571 } else {
1572 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
1573 claim->GetName(), branchname, ptrClass->GetName());
1574 }
1575 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1576 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1577 // The type is the same according to the C++ type_info, we must be in the case of
1578 // a template of Double32_t. This is actually a correct case.
1579 } else {
1580 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1581 actualClass->GetName(), branchname, claim->GetName());
1582 }
1583 }
1584 }
1585 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1587 claim->GetName(), branchname, claim->GetName());
1588 return nullptr;
1589 }
1590 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1591}
1592
1593////////////////////////////////////////////////////////////////////////////////
1594/// Same as TTree::Branch but automatic detection of the class name.
1595/// \see TTree::Branch
1598{
1599 if (!ptrClass) {
1600 Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
1601 return nullptr;
1602 }
1603 TClass* actualClass = nullptr;
1604 void** addr = (void**) addobj;
1605 if (addr && *addr) {
1606 actualClass = ptrClass->GetActualClass(*addr);
1607 if (!actualClass) {
1608 Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
1609 branchname, ptrClass->GetName());
1611 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1612 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
1613 return nullptr;
1614 }
1615 } else {
1617 }
1618 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1620 actualClass->GetName(), branchname, actualClass->GetName());
1621 return nullptr;
1622 }
1623 return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
1624}
1625
1626////////////////////////////////////////////////////////////////////////////////
1627/// Same as TTree::Branch but automatic detection of the class name.
1628/// \see TTree::Branch
1630TBranch* TTree::BranchImpRef(const char* branchname, const char *classname, TClass* ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
1631{
1632 TClass* claim = TClass::GetClass(classname);
1633 if (!ptrClass) {
1634 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1636 claim->GetName(), branchname, claim->GetName());
1637 return nullptr;
1638 } else if (claim == nullptr) {
1639 Error("Branch", "The pointer specified for %s is not of a class known to ROOT and %s is not a known class", branchname, classname);
1640 return nullptr;
1641 }
1642 ptrClass = claim;
1643 }
1644 TClass* actualClass = nullptr;
1645 if (!addobj) {
1646 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1647 return nullptr;
1648 }
1649 actualClass = ptrClass->GetActualClass(addobj);
1650 if (ptrClass && claim) {
1651 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1652 // Note we currently do not warn in case of splicing or over-expectation).
1653 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1654 // The type is the same according to the C++ type_info, we must be in the case of
1655 // a template of Double32_t. This is actually a correct case.
1656 } else {
1657 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the object passed (%s)",
1658 claim->GetName(), branchname, ptrClass->GetName());
1659 }
1660 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1661 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1662 // The type is the same according to the C++ type_info, we must be in the case of
1663 // a template of Double32_t. This is actually a correct case.
1664 } else {
1665 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1666 actualClass->GetName(), branchname, claim->GetName());
1667 }
1668 }
1669 }
1670 if (!actualClass) {
1671 Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
1672 branchname, ptrClass->GetName());
1674 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1675 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
1676 return nullptr;
1677 }
1678 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1680 actualClass->GetName(), branchname, actualClass->GetName());
1681 return nullptr;
1682 }
1683 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, false, bufsize, splitlevel);
1684}
1685
1686////////////////////////////////////////////////////////////////////////////////
1687/// Same as TTree::Branch but automatic detection of the class name.
1688/// \see TTree::Branch
1691{
1692 if (!ptrClass) {
1693 if (datatype == kOther_t || datatype == kNoType_t) {
1694 Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
1695 } else {
1697 return Branch(branchname,addobj,varname.Data(),bufsize);
1698 }
1699 return nullptr;
1700 }
1701 TClass* actualClass = nullptr;
1702 if (!addobj) {
1703 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1704 return nullptr;
1705 }
1706 actualClass = ptrClass->GetActualClass(addobj);
1707 if (!actualClass) {
1708 Warning("Branch", "The actual TClass corresponding to the object provided for the definition of the branch \"%s\" is missing.\n\tThe object will be truncated down to its %s part",
1709 branchname, ptrClass->GetName());
1711 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1712 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s", actualClass->GetName(), branchname, ptrClass->GetName());
1713 return nullptr;
1714 }
1715 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1717 actualClass->GetName(), branchname, actualClass->GetName());
1718 return nullptr;
1719 }
1720 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, false, bufsize, splitlevel);
1721}
1722
1723////////////////////////////////////////////////////////////////////////////////
1724// Wrapper to turn Branch call with an std::array into the relevant leaf list
1725// call
1726TBranch *TTree::BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize,
1727 Int_t /* splitlevel */)
1728{
1729 if (datatype == kOther_t || datatype == kNoType_t) {
1730 Error("Branch",
1731 "The inner type of the std::array passed specified for %s is not of a class or type known to ROOT",
1732 branchname);
1733 } else {
1735 varname.Form("%s[%d]/%c", branchname, (int)N, DataTypeToChar(datatype));
1736 return Branch(branchname, addobj, varname.Data(), bufsize);
1737 }
1738 return nullptr;
1739}
1740
1741////////////////////////////////////////////////////////////////////////////////
1742/// Deprecated function. Use next function instead.
1744Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
1745{
1746 return Branch((TCollection*) li, bufsize, splitlevel);
1747}
1748
1749////////////////////////////////////////////////////////////////////////////////
1750/// Create one branch for each element in the collection.
1751///
1752/// Each entry in the collection becomes a top level branch if the
1753/// corresponding class is not a collection. If it is a collection, the entry
1754/// in the collection becomes in turn top level branches, etc.
1755/// The splitlevel is decreased by 1 every time a new collection is found.
1756/// For example if list is a TObjArray*
1757/// - if splitlevel = 1, one top level branch is created for each element
1758/// of the TObjArray.
1759/// - if splitlevel = 2, one top level branch is created for each array element.
1760/// if, in turn, one of the array elements is a TCollection, one top level
1761/// branch will be created for each element of this collection.
1762///
1763/// In case a collection element is a TClonesArray, the special Tree constructor
1764/// for TClonesArray is called.
1765/// The collection itself cannot be a TClonesArray.
1766///
1767/// The function returns the total number of branches created.
1768///
1769/// If name is given, all branch names will be prefixed with name_.
1770///
1771/// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
1772///
1773/// IMPORTANT NOTE2: The branches created by this function will have names
1774/// corresponding to the collection or object names. It is important
1775/// to give names to collections to avoid misleading branch names or
1776/// identical branch names. By default collections have a name equal to
1777/// the corresponding class name, e.g. the default name for a TList is "TList".
1778///
1779/// And in general, in case two or more master branches contain subbranches
1780/// with identical names, one must add a "." (dot) character at the end
1781/// of the master branch name. This will force the name of the subbranches
1782/// to be of the form `master.subbranch` instead of simply `subbranch`.
1783/// This situation happens when the top level object
1784/// has two or more members referencing the same class.
1785/// Without the dot, the prefix will not be there and that might cause ambiguities.
1786/// For example, if a Tree has two branches B1 and B2 corresponding
1787/// to objects of the same class MyClass, one can do:
1788/// ~~~ {.cpp}
1789/// tree.Branch("B1.","MyClass",&b1,8000,1);
1790/// tree.Branch("B2.","MyClass",&b2,8000,1);
1791/// ~~~
1792/// if MyClass has 3 members a,b,c, the two instructions above will generate
1793/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
1794/// In other words, the trailing dot of the branch name is semantically relevant
1795/// and recommended.
1796///
1797/// Example:
1798/// ~~~ {.cpp}
1799/// {
1800/// TTree T("T","test list");
1801/// TList *list = new TList();
1802///
1803/// TObjArray *a1 = new TObjArray();
1804/// a1->SetName("a1");
1805/// list->Add(a1);
1806/// TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
1807/// TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
1808/// a1->Add(ha1a);
1809/// a1->Add(ha1b);
1810/// TObjArray *b1 = new TObjArray();
1811/// b1->SetName("b1");
1812/// list->Add(b1);
1813/// TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
1814/// TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
1815/// b1->Add(hb1a);
1816/// b1->Add(hb1b);
1817///
1818/// TObjArray *a2 = new TObjArray();
1819/// a2->SetName("a2");
1820/// list->Add(a2);
1821/// TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
1822/// TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
1823/// a2->Add(ha2a);
1824/// a2->Add(ha2b);
1825///
1826/// T.Branch(list,16000,2);
1827/// T.Print();
1828/// }
1829/// ~~~
1831Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
1832{
1833
1834 if (!li) {
1835 return 0;
1836 }
1837 TObject* obj = nullptr;
1838 Int_t nbranches = GetListOfBranches()->GetEntries();
1839 if (li->InheritsFrom(TClonesArray::Class())) {
1840 Error("Branch", "Cannot call this constructor for a TClonesArray");
1841 return 0;
1842 }
1843 Int_t nch = strlen(name);
1845 TIter next(li);
1846 while ((obj = next())) {
1848 TCollection* col = (TCollection*) obj;
1849 if (nch) {
1850 branchname.Form("%s_%s_", name, col->GetName());
1851 } else {
1852 branchname.Form("%s_", col->GetName());
1853 }
1854 Branch(col, bufsize, splitlevel - 1, branchname);
1855 } else {
1856 if (nch && (name[nch-1] == '_')) {
1857 branchname.Form("%s%s", name, obj->GetName());
1858 } else {
1859 if (nch) {
1860 branchname.Form("%s_%s", name, obj->GetName());
1861 } else {
1862 branchname.Form("%s", obj->GetName());
1863 }
1864 }
1865 if (splitlevel > 99) {
1866 branchname += ".";
1867 }
1868 Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
1869 }
1870 }
1871 return GetListOfBranches()->GetEntries() - nbranches;
1872}
1873
1874////////////////////////////////////////////////////////////////////////////////
1875/// Create one branch for each element in the folder.
1876/// Returns the total number of branches created.
1878Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
1879{
1880 TObject* ob = gROOT->FindObjectAny(foldername);
1881 if (!ob) {
1882 return 0;
1883 }
1884 if (ob->IsA() != TFolder::Class()) {
1885 return 0;
1886 }
1887 Int_t nbranches = GetListOfBranches()->GetEntries();
1888 TFolder* folder = (TFolder*) ob;
1889 TIter next(folder->GetListOfFolders());
1890 TObject* obj = nullptr;
1891 char* curname = new char[1000];
1892 char occur[20];
1893 while ((obj = next())) {
1894 snprintf(curname,1000, "%s/%s", foldername, obj->GetName());
1895 if (obj->IsA() == TFolder::Class()) {
1897 } else {
1898 void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
1899 for (Int_t i = 0; i < 1000; ++i) {
1900 if (curname[i] == 0) {
1901 break;
1902 }
1903 if (curname[i] == '/') {
1904 curname[i] = '.';
1905 }
1906 }
1907 Int_t noccur = folder->Occurence(obj);
1908 if (noccur > 0) {
1909 snprintf(occur,20, "_%d", noccur);
1910 strlcat(curname, occur,1000);
1911 }
1913 if (br) br->SetBranchFolder();
1914 }
1915 }
1916 delete[] curname;
1917 return GetListOfBranches()->GetEntries() - nbranches;
1918}
1919
1920////////////////////////////////////////////////////////////////////////////////
1921/// Create a new TTree Branch.
1922///
1923/// This Branch constructor is provided to support non-objects in
1924/// a Tree. The variables described in leaflist may be simple
1925/// variables or structures. // See the two following
1926/// constructors for writing objects in a Tree.
1927///
1928/// By default the branch buffers are stored in the same file as the Tree.
1929/// use TBranch::SetFile to specify a different file
1930///
1931/// * address is the address of the first item of a structure.
1932/// * leaflist is the concatenation of all the variable names and types
1933/// separated by a colon character :
1934/// The variable name and the variable type are separated by a slash (/).
1935/// The variable type may be 0,1 or 2 characters. If no type is given,
1936/// the type of the variable is assumed to be the same as the previous
1937/// variable. If the first variable does not have a type, it is assumed
1938/// of type F by default. The list of currently supported types is given below:
1939/// - `C` : a character string terminated by the 0 character
1940/// - `B` : an 8 bit signed integer (`Char_t`); Treated as a character when in an array.
1941/// - `b` : an 8 bit unsigned integer (`UChar_t`)
1942/// - `S` : a 16 bit signed integer (`Short_t`)
1943/// - `s` : a 16 bit unsigned integer (`UShort_t`)
1944/// - `I` : a 32 bit signed integer (`Int_t`)
1945/// - `i` : a 32 bit unsigned integer (`UInt_t`)
1946/// - `F` : a 32 bit floating point (`Float_t`)
1947/// - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
1948/// - `D` : a 64 bit floating point (`Double_t`)
1949/// - `d` : a 24 bit truncated floating point (`Double32_t`)
1950/// - `L` : a 64 bit signed integer (`Long64_t`)
1951/// - `l` : a 64 bit unsigned integer (`ULong64_t`)
1952/// - `G` : a long signed integer, stored as 64 bit (`Long_t`)
1953/// - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
1954/// - `O` : [the letter `o`, not a zero] a boolean (`bool`)
1955///
1956/// Arrays of values are supported with the following syntax:
1957/// - If leaf name has the form var[nelem], where nelem is alphanumeric, then
1958/// if nelem is a leaf name, it is used as the variable size of the array,
1959/// otherwise return 0.
1960/// The leaf referred to by nelem **MUST** be an int (/I),
1961/// - If leaf name has the form var[nelem], where nelem is a non-negative integer, then
1962/// it is used as the fixed size of the array.
1963/// - If leaf name has the form of a multi-dimensional array (e.g. var[nelem][nelem2])
1964/// where nelem and nelem2 are non-negative integer) then
1965/// it is used as a 2 dimensional array of fixed size.
1966/// - In case of the truncated floating point types (Float16_t and Double32_t) you can
1967/// furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
1968/// the type character. See `TStreamerElement::GetRange()` for further information.
1969///
1970/// Any of other form is not supported.
1971///
1972/// Note that the TTree will assume that all the item are contiguous in memory.
1973/// On some platform, this is not always true of the member of a struct or a class,
1974/// due to padding and alignment. Sorting your data member in order of decreasing
1975/// sizeof usually leads to their being contiguous in memory.
1976///
1977/// * bufsize is the buffer size in bytes for this branch
1978/// The default value is 32000 bytes and should be ok for most cases.
1979/// You can specify a larger value (e.g. 256000) if your Tree is not split
1980/// and each entry is large (Megabytes)
1981/// A small value for bufsize is optimum if you intend to access
1982/// the entries in the Tree randomly and your Tree is in split mode.
1984TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
1985{
1986 TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
1987 if (branch->IsZombie()) {
1988 delete branch;
1989 branch = nullptr;
1990 return nullptr;
1991 }
1993 return branch;
1994}
1995
1996////////////////////////////////////////////////////////////////////////////////
1997/// Create a new branch with the object of class classname at address addobj.
1998///
1999/// WARNING:
2000///
2001/// Starting with Root version 3.01, the Branch function uses the new style
2002/// branches (TBranchElement). To get the old behaviour, you can:
2003/// - call BranchOld or
2004/// - call TTree::SetBranchStyle(0)
2005///
2006/// Note that with the new style, classname does not need to derive from TObject.
2007/// It must derived from TObject if the branch style has been set to 0 (old)
2008///
2009/// Note: See the comments in TBranchElement::SetAddress() for a more
2010/// detailed discussion of the meaning of the addobj parameter in
2011/// the case of new-style branches.
2012///
2013/// Use splitlevel < 0 instead of splitlevel=0 when the class
2014/// has a custom Streamer
2015///
2016/// Note: if the split level is set to the default (99), TTree::Branch will
2017/// not issue a warning if the class can not be split.
2019TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2020{
2021 if (fgBranchStyle == 1) {
2022 return Bronch(name, classname, addobj, bufsize, splitlevel);
2023 } else {
2024 if (splitlevel < 0) {
2025 splitlevel = 0;
2026 }
2027 return BranchOld(name, classname, addobj, bufsize, splitlevel);
2028 }
2029}
2030
2031////////////////////////////////////////////////////////////////////////////////
2032/// Create a new TTree BranchObject.
2033///
2034/// Build a TBranchObject for an object of class classname.
2035/// addobj is the address of a pointer to an object of class classname.
2036/// IMPORTANT: classname must derive from TObject.
2037/// The class dictionary must be available (ClassDef in class header).
2038///
2039/// This option requires access to the library where the corresponding class
2040/// is defined. Accessing one single data member in the object implies
2041/// reading the full object.
2042/// See the next Branch constructor for a more efficient storage
2043/// in case the entry consists of arrays of identical objects.
2044///
2045/// By default the branch buffers are stored in the same file as the Tree.
2046/// use TBranch::SetFile to specify a different file
2047///
2048/// IMPORTANT NOTE about branch names:
2049///
2050/// And in general, in case two or more master branches contain subbranches
2051/// with identical names, one must add a "." (dot) character at the end
2052/// of the master branch name. This will force the name of the subbranches
2053/// to be of the form `master.subbranch` instead of simply `subbranch`.
2054/// This situation happens when the top level object
2055/// has two or more members referencing the same class.
2056/// For example, if a Tree has two branches B1 and B2 corresponding
2057/// to objects of the same class MyClass, one can do:
2058/// ~~~ {.cpp}
2059/// tree.Branch("B1.","MyClass",&b1,8000,1);
2060/// tree.Branch("B2.","MyClass",&b2,8000,1);
2061/// ~~~
2062/// if MyClass has 3 members a,b,c, the two instructions above will generate
2063/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2064///
2065/// bufsize is the buffer size in bytes for this branch
2066/// The default value is 32000 bytes and should be ok for most cases.
2067/// You can specify a larger value (e.g. 256000) if your Tree is not split
2068/// and each entry is large (Megabytes)
2069/// A small value for bufsize is optimum if you intend to access
2070/// the entries in the Tree randomly and your Tree is in split mode.
2072TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
2073{
2074 TClass* cl = TClass::GetClass(classname);
2075 if (!cl) {
2076 Error("BranchOld", "Cannot find class: '%s'", classname);
2077 return nullptr;
2078 }
2079 if (!cl->IsTObject()) {
2080 if (fgBranchStyle == 0) {
2081 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2082 "\tfgBranchStyle is set to zero requesting by default to use BranchOld.\n"
2083 "\tIf this is intentional use Bronch instead of Branch or BranchOld.", classname);
2084 } else {
2085 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2086 "\tYou can not use BranchOld to store objects of this type.",classname);
2087 }
2088 return nullptr;
2089 }
2090 TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
2092 if (!splitlevel) {
2093 return branch;
2094 }
2095 // We are going to fully split the class now.
2096 TObjArray* blist = branch->GetListOfBranches();
2097 const char* rdname = nullptr;
2098 const char* dname = nullptr;
2100 char** apointer = (char**) addobj;
2101 TObject* obj = (TObject*) *apointer;
2102 bool delobj = false;
2103 if (!obj) {
2104 obj = (TObject*) cl->New();
2105 delobj = true;
2106 }
2107 // Build the StreamerInfo if first time for the class.
2108 BuildStreamerInfo(cl, obj);
2109 // Loop on all public data members of the class and its base classes.
2111 Int_t isDot = 0;
2112 if (name[lenName-1] == '.') {
2113 isDot = 1;
2114 }
2115 TBranch* branch1 = nullptr;
2116 TRealData* rd = nullptr;
2117 TRealData* rdi = nullptr;
2119 TIter next(cl->GetListOfRealData());
2120 // Note: This loop results in a full split because the
2121 // real data list includes all data members of
2122 // data members.
2123 while ((rd = (TRealData*) next())) {
2124 if (rd->TestBit(TRealData::kTransient)) continue;
2125
2126 // Loop over all data members creating branches for each one.
2127 TDataMember* dm = rd->GetDataMember();
2128 if (!dm->IsPersistent()) {
2129 // Do not process members with an "!" as the first character in the comment field.
2130 continue;
2131 }
2132 if (rd->IsObject()) {
2133 // We skip data members of class type.
2134 // But we do build their real data, their
2135 // streamer info, and write their streamer
2136 // info to the current directory's file.
2137 // Oh yes, and we also do this for all of
2138 // their base classes.
2140 if (clm) {
2141 BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
2142 }
2143 continue;
2144 }
2145 rdname = rd->GetName();
2146 dname = dm->GetName();
2147 if (cl->CanIgnoreTObjectStreamer()) {
2148 // Skip the TObject base class data members.
2149 // FIXME: This prevents a user from ever
2150 // using these names themself!
2151 if (!strcmp(dname, "fBits")) {
2152 continue;
2153 }
2154 if (!strcmp(dname, "fUniqueID")) {
2155 continue;
2156 }
2157 }
2158 TDataType* dtype = dm->GetDataType();
2159 Int_t code = 0;
2160 if (dtype) {
2161 code = dm->GetDataType()->GetType();
2162 }
2163 // Encode branch name. Use real data member name
2165 if (isDot) {
2166 if (dm->IsaPointer()) {
2167 // FIXME: This is wrong! The asterisk is not usually in the front!
2168 branchname.Form("%s%s", name, &rdname[1]);
2169 } else {
2170 branchname.Form("%s%s", name, &rdname[0]);
2171 }
2172 }
2173 // FIXME: Change this to a string stream.
2175 Int_t offset = rd->GetThisOffset();
2176 char* pointer = ((char*) obj) + offset;
2177 if (dm->IsaPointer()) {
2178 // We have a pointer to an object or a pointer to an array of basic types.
2179 TClass* clobj = nullptr;
2180 if (!dm->IsBasic()) {
2182 }
2183 if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
2184 // We have a pointer to a clones array.
2185 char* cpointer = (char*) pointer;
2186 char** ppointer = (char**) cpointer;
2188 if (splitlevel != 2) {
2189 if (isDot) {
2191 } else {
2192 // FIXME: This is wrong! The asterisk is not usually in the front!
2193 branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
2194 }
2195 blist->Add(branch1);
2196 } else {
2197 if (isDot) {
2198 branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
2199 } else {
2200 // FIXME: This is wrong! The asterisk is not usually in the front!
2201 branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
2202 }
2203 blist->Add(branch1);
2204 }
2205 } else if (clobj) {
2206 // We have a pointer to an object.
2207 //
2208 // It must be a TObject object.
2209 if (!clobj->IsTObject()) {
2210 continue;
2211 }
2212 branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
2213 if (isDot) {
2214 branch1->SetName(branchname);
2215 } else {
2216 // FIXME: This is wrong! The asterisk is not usually in the front!
2217 // Do not use the first character (*).
2218 branch1->SetName(&branchname.Data()[1]);
2219 }
2220 blist->Add(branch1);
2221 } else {
2222 // We have a pointer to an array of basic types.
2223 //
2224 // Check the comments in the text of the code for an index specification.
2225 const char* index = dm->GetArrayIndex();
2226 if (index[0]) {
2227 // We are a pointer to a varying length array of basic types.
2228 //check that index is a valid data member name
2229 //if member is part of an object (e.g. fA and index=fN)
2230 //index must be changed from fN to fA.fN
2231 TString aindex (rd->GetName());
2232 Ssiz_t rdot = aindex.Last('.');
2233 if (rdot>=0) {
2234 aindex.Remove(rdot+1);
2235 aindex.Append(index);
2236 }
2237 nexti.Reset();
2238 while ((rdi = (TRealData*) nexti())) {
2239 if (rdi->TestBit(TRealData::kTransient)) continue;
2240
2241 if (!strcmp(rdi->GetName(), index)) {
2242 break;
2243 }
2244 if (!strcmp(rdi->GetName(), aindex)) {
2245 index = rdi->GetName();
2246 break;
2247 }
2248 }
2249
2250 char vcode = DataTypeToChar((EDataType)code);
2251 // Note that we differentiate between strings and
2252 // char array by the fact that there is NO specified
2253 // size for a string (see next if (code == 1)
2254
2255 if (vcode) {
2256 leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
2257 } else {
2258 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2259 leaflist = "";
2260 }
2261 } else {
2262 // We are possibly a character string.
2263 if (code == 1) {
2264 // We are a character string.
2265 leaflist.Form("%s/%s", dname, "C");
2266 } else {
2267 // Invalid array specification.
2268 // FIXME: We need an error message here.
2269 continue;
2270 }
2271 }
2272 // There are '*' in both the branchname and leaflist, remove them.
2273 TString bname( branchname );
2274 bname.ReplaceAll("*","");
2275 leaflist.ReplaceAll("*","");
2276 // Add the branch to the tree and indicate that the address
2277 // is that of a pointer to be dereferenced before using.
2278 branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
2279 TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
2281 leaf->SetAddress((void**) pointer);
2282 blist->Add(branch1);
2283 }
2284 } else if (dm->IsBasic()) {
2285 // We have a basic type.
2286
2287 char vcode = DataTypeToChar((EDataType)code);
2288 if (vcode) {
2289 leaflist.Form("%s/%c", rdname, vcode);
2290 } else {
2291 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2292 leaflist = "";
2293 }
2294 branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
2295 branch1->SetTitle(rdname);
2296 blist->Add(branch1);
2297 } else {
2298 // We have a class type.
2299 // Note: This cannot happen due to the rd->IsObject() test above.
2300 // FIXME: Put an error message here just in case.
2301 }
2302 if (branch1) {
2303 branch1->SetOffset(offset);
2304 } else {
2305 Warning("BranchOld", "Cannot process member: '%s'", rdname);
2306 }
2307 }
2308 if (delobj) {
2309 delete obj;
2310 obj = nullptr;
2311 }
2312 return branch;
2313}
2314
2315////////////////////////////////////////////////////////////////////////////////
2316/// Build the optional branch supporting the TRefTable.
2317/// This branch will keep all the information to find the branches
2318/// containing referenced objects.
2319///
2320/// At each Tree::Fill, the branch numbers containing the
2321/// referenced objects are saved to the TBranchRef basket.
2322/// When the Tree header is saved (via TTree::Write), the branch
2323/// is saved keeping the information with the pointers to the branches
2324/// having referenced objects.
2327{
2328 if (!fBranchRef) {
2329 fBranchRef = new TBranchRef(this);
2330 }
2331 return fBranchRef;
2332}
2333
2334////////////////////////////////////////////////////////////////////////////////
2335/// Create a new TTree BranchElement.
2336///
2337/// ## WARNING about this new function
2338///
2339/// This function is designed to replace the internal
2340/// implementation of the old TTree::Branch (whose implementation
2341/// has been moved to BranchOld).
2342///
2343/// NOTE: The 'Bronch' method supports only one possible calls
2344/// signature (where the object type has to be specified
2345/// explicitly and the address must be the address of a pointer).
2346/// For more flexibility use 'Branch'. Use Bronch only in (rare)
2347/// cases (likely to be legacy cases) where both the new and old
2348/// implementation of Branch needs to be used at the same time.
2349///
2350/// This function is far more powerful than the old Branch
2351/// function. It supports the full C++, including STL and has
2352/// the same behaviour in split or non-split mode. classname does
2353/// not have to derive from TObject. The function is based on
2354/// the new TStreamerInfo.
2355///
2356/// Build a TBranchElement for an object of class classname.
2357///
2358/// addr is the address of a pointer to an object of class
2359/// classname. The class dictionary must be available (ClassDef
2360/// in class header).
2361///
2362/// Note: See the comments in TBranchElement::SetAddress() for a more
2363/// detailed discussion of the meaning of the addr parameter.
2364///
2365/// This option requires access to the library where the
2366/// corresponding class is defined. Accessing one single data
2367/// member in the object implies reading the full object.
2368///
2369/// By default the branch buffers are stored in the same file as the Tree.
2370/// use TBranch::SetFile to specify a different file
2371///
2372/// IMPORTANT NOTE about branch names:
2373///
2374/// And in general, in case two or more master branches contain subbranches
2375/// with identical names, one must add a "." (dot) character at the end
2376/// of the master branch name. This will force the name of the subbranches
2377/// to be of the form `master.subbranch` instead of simply `subbranch`.
2378/// This situation happens when the top level object
2379/// has two or more members referencing the same class.
2380/// For example, if a Tree has two branches B1 and B2 corresponding
2381/// to objects of the same class MyClass, one can do:
2382/// ~~~ {.cpp}
2383/// tree.Branch("B1.","MyClass",&b1,8000,1);
2384/// tree.Branch("B2.","MyClass",&b2,8000,1);
2385/// ~~~
2386/// if MyClass has 3 members a,b,c, the two instructions above will generate
2387/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2388///
2389/// bufsize is the buffer size in bytes for this branch
2390/// The default value is 32000 bytes and should be ok for most cases.
2391/// You can specify a larger value (e.g. 256000) if your Tree is not split
2392/// and each entry is large (Megabytes)
2393/// A small value for bufsize is optimum if you intend to access
2394/// the entries in the Tree randomly and your Tree is in split mode.
2395///
2396/// Use splitlevel < 0 instead of splitlevel=0 when the class
2397/// has a custom Streamer
2398///
2399/// Note: if the split level is set to the default (99), TTree::Branch will
2400/// not issue a warning if the class can not be split.
2402TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2403{
2404 return BronchExec(name, classname, addr, true, bufsize, splitlevel);
2405}
2406
2407////////////////////////////////////////////////////////////////////////////////
2408/// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
2410TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, bool isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2411{
2412 TClass* cl = TClass::GetClass(classname);
2413 if (!cl) {
2414 Error("Bronch", "Cannot find class:%s", classname);
2415 return nullptr;
2416 }
2417
2418 //if splitlevel <= 0 and class has a custom Streamer, we must create
2419 //a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
2420 //with the custom Streamer. The penalty is that one cannot process
2421 //this Tree without the class library containing the class.
2422
2423 char* objptr = nullptr;
2424 if (!isptrptr) {
2425 objptr = (char*)addr;
2426 } else if (addr) {
2427 objptr = *((char**) addr);
2428 }
2429
2430 if (cl == TClonesArray::Class()) {
2432 if (!clones) {
2433 Error("Bronch", "Pointer to TClonesArray is null");
2434 return nullptr;
2435 }
2436 if (!clones->GetClass()) {
2437 Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
2438 return nullptr;
2439 }
2440 if (!clones->GetClass()->HasDataMemberInfo()) {
2441 Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
2442 return nullptr;
2443 }
2444 bool hasCustomStreamer = clones->GetClass()->HasCustomStreamerMember();
2445 if (splitlevel > 0) {
2447 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
2448 } else {
2449 if (hasCustomStreamer) clones->BypassStreamer(false);
2450 TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,/*compress=*/ -1,isptrptr);
2452 return branch;
2453 }
2454 }
2455
2456 if (cl->GetCollectionProxy()) {
2458 //if (!collProxy) {
2459 // Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
2460 //}
2461 TClass* inklass = collProxy->GetValueClass();
2462 if (!inklass && (collProxy->GetType() == 0)) {
2463 Error("Bronch", "%s with no class defined in branch: %s", classname, name);
2464 return nullptr;
2465 }
2466 if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == nullptr)) {
2468 if ((stl != ROOT::kSTLmap) && (stl != ROOT::kSTLmultimap)) {
2469 if (!inklass->HasDataMemberInfo()) {
2470 Error("Bronch", "Container with no dictionary defined in branch: %s", name);
2471 return nullptr;
2472 }
2473 if (inklass->HasCustomStreamerMember()) {
2474 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
2475 }
2476 }
2477 }
2478 //-------------------------------------------------------------------------
2479 // If the splitting switch is enabled, the split level is big enough and
2480 // the collection contains pointers we can split it
2481 //////////////////////////////////////////////////////////////////////////
2482
2483 TBranch *branch;
2484 if( splitlevel > kSplitCollectionOfPointers && collProxy->HasPointers() )
2486 else
2489 if (isptrptr) {
2490 branch->SetAddress(addr);
2491 } else {
2492 branch->SetObject(addr);
2493 }
2494 return branch;
2495 }
2496
2497 bool hasCustomStreamer = false;
2498 if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
2499 Error("Bronch", "Cannot find dictionary for class: %s", classname);
2500 return nullptr;
2501 }
2502
2503 if (!cl->GetCollectionProxy() && cl->HasCustomStreamerMember()) {
2504 // Not an STL container and the linkdef file had a "-" after the class name.
2505 hasCustomStreamer = true;
2506 }
2507
2508 if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->IsTObject())) {
2511 return branch;
2512 }
2513
2514 if (cl == TClonesArray::Class()) {
2515 // Special case of TClonesArray.
2516 // No dummy object is created.
2517 // The streamer info is not rebuilt unoptimized.
2518 // No dummy top-level branch is created.
2519 // No splitting is attempted.
2522 if (isptrptr) {
2523 branch->SetAddress(addr);
2524 } else {
2525 branch->SetObject(addr);
2526 }
2527 return branch;
2528 }
2529
2530 //
2531 // If we are not given an object to use as an i/o buffer
2532 // then create a temporary one which we will delete just
2533 // before returning.
2534 //
2535
2536 bool delobj = false;
2537
2538 if (!objptr) {
2539 objptr = (char*) cl->New();
2540 delobj = true;
2541 }
2542
2543 //
2544 // Avoid splitting unsplittable classes.
2545 //
2546
2547 if ((splitlevel > 0) && !cl->CanSplit()) {
2548 if (splitlevel != 99) {
2549 Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
2550 }
2551 splitlevel = 0;
2552 }
2553
2554 //
2555 // Make sure the streamer info is built and fetch it.
2556 //
2557 // If we are splitting, then make sure the streamer info
2558 // is built unoptimized (data members are not combined).
2559 //
2560
2562 if (!sinfo) {
2563 Error("Bronch", "Cannot build the StreamerInfo for class: %s", cl->GetName());
2564 return nullptr;
2565 }
2566
2567 //
2568 // Create a dummy top level branch object.
2569 //
2570
2571 Int_t id = -1;
2572 if (splitlevel > 0) {
2573 id = -2;
2574 }
2577
2578 //
2579 // Do splitting, if requested.
2580 //
2581
2583 branch->Unroll(name, cl, sinfo, objptr, bufsize, splitlevel);
2584 }
2585
2586 //
2587 // Setup our offsets into the user's i/o buffer.
2588 //
2589
2590 if (isptrptr) {
2591 branch->SetAddress(addr);
2592 } else {
2593 branch->SetObject(addr);
2594 }
2595
2596 if (delobj) {
2597 cl->Destructor(objptr);
2598 objptr = nullptr;
2599 }
2600
2601 return branch;
2602}
2603
2604////////////////////////////////////////////////////////////////////////////////
2605/// Browse content of the TTree.
2608{
2610 if (fUserInfo) {
2611 if (strcmp("TList",fUserInfo->GetName())==0) {
2612 fUserInfo->SetName("UserInfo");
2613 b->Add(fUserInfo);
2614 fUserInfo->SetName("TList");
2615 } else {
2616 b->Add(fUserInfo);
2617 }
2618 }
2619}
2620
2621////////////////////////////////////////////////////////////////////////////////
2622/// Build a Tree Index (default is TTreeIndex).
2623/// See a description of the parameters and functionality in
2624/// TTreeIndex::TTreeIndex().
2625///
2626/// The return value is the number of entries in the Index (< 0 indicates failure).
2627///
2628/// A TTreeIndex object pointed by fTreeIndex is created.
2629/// This object will be automatically deleted by the TTree destructor.
2630/// If an index is already existing, this is replaced by the new one without being
2631/// deleted. This behaviour prevents the deletion of a previously external index
2632/// assigned to the TTree via the TTree::SetTreeIndex() method.
2633/// \see TTree::SetTreeIndex()
2635Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */)
2636{
2638 if (fTreeIndex->IsZombie()) {
2639 delete fTreeIndex;
2640 fTreeIndex = nullptr;
2641 return 0;
2642 }
2643 return fTreeIndex->GetN();
2644}
2645
2646////////////////////////////////////////////////////////////////////////////////
2647/// Build StreamerInfo for class cl.
2648/// pointer is an optional argument that may contain a pointer to an object of cl.
2650TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, bool canOptimize /* = true */ )
2651{
2652 if (!cl) {
2653 return nullptr;
2654 }
2655 cl->BuildRealData(pointer);
2657
2658 // Create StreamerInfo for all base classes.
2659 TBaseClass* base = nullptr;
2660 TIter nextb(cl->GetListOfBases());
2661 while((base = (TBaseClass*) nextb())) {
2662 if (base->IsSTLContainer()) {
2663 continue;
2664 }
2665 TClass* clm = TClass::GetClass(base->GetName());
2667 }
2668 if (sinfo && fDirectory) {
2669 sinfo->ForceWriteInfo(fDirectory->GetFile());
2670 }
2671 return sinfo;
2672}
2673
2674////////////////////////////////////////////////////////////////////////////////
2675/// Enable the TTreeCache unless explicitly disabled for this TTree by
2676/// a prior call to `SetCacheSize(0)`.
2677/// If the environment variable `ROOT_TTREECACHE_SIZE` or the rootrc config
2678/// `TTreeCache.Size` has been set to zero, this call will over-ride them with
2679/// a value of 1.0 (i.e. use a cache size to hold 1 cluster)
2680///
2681/// Return true if there is a cache attached to the `TTree` (either pre-exisiting
2682/// or created as part of this call)
2683bool TTree::EnableCache()
2684{
2685 TFile* file = GetCurrentFile();
2686 if (!file)
2687 return false;
2688 // Check for an existing cache
2689 TTreeCache* pf = GetReadCache(file);
2690 if (pf)
2691 return true;
2692 if (fCacheUserSet && fCacheSize == 0)
2693 return false;
2694 return (0 == SetCacheSizeAux(true, -1));
2695}
2696
2697////////////////////////////////////////////////////////////////////////////////
2698/// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
2699/// Create a new file. If the original file is named "myfile.root",
2700/// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
2701///
2702/// Returns a pointer to the new file.
2703///
2704/// Currently, the automatic change of file is restricted
2705/// to the case where the tree is in the top level directory.
2706/// The file should not contain sub-directories.
2707///
2708/// Before switching to a new file, the tree header is written
2709/// to the current file, then the current file is closed.
2710///
2711/// To process the multiple files created by ChangeFile, one must use
2712/// a TChain.
2713///
2714/// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
2715/// By default a Root session starts with fFileNumber=0. One can set
2716/// fFileNumber to a different value via TTree::SetFileNumber.
2717/// In case a file named "_N" already exists, the function will try
2718/// a file named "__N", then "___N", etc.
2719///
2720/// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
2721/// The default value of fgMaxTreeSize is 100 Gigabytes.
2722///
2723/// If the current file contains other objects like TH1 and TTree,
2724/// these objects are automatically moved to the new file.
2725///
2726/// \warning Be careful when writing the final Tree header to the file!
2727/// Don't do:
2728/// ~~~ {.cpp}
2729/// TFile *file = new TFile("myfile.root","recreate");
2730/// TTree *T = new TTree("T","title");
2731/// T->Fill(); // Loop
2732/// file->Write();
2733/// file->Close();
2734/// ~~~
2735/// \warning but do the following:
2736/// ~~~ {.cpp}
2737/// TFile *file = new TFile("myfile.root","recreate");
2738/// TTree *T = new TTree("T","title");
2739/// T->Fill(); // Loop
2740/// file = T->GetCurrentFile(); // To get the pointer to the current file
2741/// file->Write();
2742/// file->Close();
2743/// ~~~
2744///
2745/// \note This method is never called if the input file is a `TMemFile` or derivate.
2748{
2749 // Changing file clashes with the design of TMemFile and derivates, see #6523,
2750 // as well as with TFileMerger operations, see #6640.
2751 if ((dynamic_cast<TMemFile *>(file)) || file->TestBit(TFile::kCancelTTreeChangeRequest))
2752 return file;
2753 file->cd();
2754 Write();
2755 Reset();
2756 constexpr auto kBufSize = 2000;
2757 char* fname = new char[kBufSize];
2758 ++fFileNumber;
2759 char uscore[10];
2760 for (Int_t i = 0; i < 10; ++i) {
2761 uscore[i] = 0;
2762 }
2763 Int_t nus = 0;
2764 // Try to find a suitable file name that does not already exist.
2765 while (nus < 10) {
2766 uscore[nus] = '_';
2767 fname[0] = 0;
2768 strlcpy(fname, file->GetName(), kBufSize);
2769
2770 if (fFileNumber > 1) {
2771 char* cunder = strrchr(fname, '_');
2772 if (cunder) {
2774 const char* cdot = strrchr(file->GetName(), '.');
2775 if (cdot) {
2777 }
2778 } else {
2779 char fcount[21];
2780 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2782 }
2783 } else {
2784 char* cdot = strrchr(fname, '.');
2785 if (cdot) {
2787 strlcat(fname, strrchr(file->GetName(), '.'), kBufSize);
2788 } else {
2789 char fcount[21];
2790 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2792 }
2793 }
2795 break;
2796 }
2797 ++nus;
2798 Warning("ChangeFile", "file %s already exists, trying with %d underscores", fname, nus + 1);
2799 }
2801 TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
2802 if (newfile == nullptr) {
2803 Error("Fill","Failed to open new file %s, continuing as a memory tree.",fname);
2804 } else {
2805 Printf("Fill: Switching to new file: %s", fname);
2806 }
2807 // The current directory may contain histograms and trees.
2808 // These objects must be moved to the new file.
2809 TBranch* branch = nullptr;
2810 TObject* obj = nullptr;
2811 while ((obj = file->GetList()->First())) {
2812 file->Remove(obj);
2813 // Histogram: just change the directory.
2814 if (obj->InheritsFrom("TH1")) {
2815 gROOT->ProcessLine(TString::Format("((%s*)0x%zx)->SetDirectory((TDirectory*)0x%zx);", obj->ClassName(), (size_t) obj, (size_t) newfile));
2816 continue;
2817 }
2818 // Tree: must save all trees in the old file, reset them.
2819 if (obj->InheritsFrom(TTree::Class())) {
2820 TTree* t = (TTree*) obj;
2821 if (t != this) {
2822 t->AutoSave();
2823 t->Reset();
2825 }
2828 while ((branch = (TBranch*)nextb())) {
2829 branch->SetFile(newfile);
2830 }
2831 if (t->GetBranchRef()) {
2832 t->GetBranchRef()->SetFile(newfile);
2833 }
2834 continue;
2835 }
2836 // Not a TH1 or a TTree, move object to new file.
2837 if (newfile) newfile->Append(obj);
2838 file->Remove(obj);
2839 }
2840 file->TObject::Delete();
2841 file = nullptr;
2842 delete[] fname;
2843 fname = nullptr;
2844 return newfile;
2845}
2846
2847////////////////////////////////////////////////////////////////////////////////
2848/// Check whether or not the address described by the last 3 parameters
2849/// matches the content of the branch. If a Data Model Evolution conversion
2850/// is involved, reset the fInfo of the branch.
2851/// The return values are:
2852//
2853/// - kMissingBranch (-5) : Missing branch
2854/// - kInternalError (-4) : Internal error (could not find the type corresponding to a data type number)
2855/// - kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
2856/// - kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
2857/// - kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
2858/// - kMatch (0) : perfect match
2859/// - kMatchConversion (1) : match with (I/O) conversion
2860/// - kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
2861/// - kMakeClass (3) : MakeClass mode so we can not check.
2862/// - kVoidPtr (4) : void* passed so no check was made.
2863/// - kNoCheck (5) : Underlying TBranch not yet available so no check was made.
2864/// In addition this can be multiplexed with the two bits:
2865/// - kNeedEnableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to be in Decomposed Object (aka MakeClass) mode.
2866/// - kNeedDisableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to not be in Decomposed Object (aka MakeClass) mode.
2867/// This bits can be masked out by using kDecomposedObjMask
2870{
2871 if (GetMakeClass()) {
2872 // If we are in MakeClass mode so we do not really use classes.
2873 return kMakeClass;
2874 }
2875
2876 // Let's determine what we need!
2877 TClass* expectedClass = nullptr;
2879 if (0 != branch->GetExpectedType(expectedClass,expectedType) ) {
2880 // Something went wrong, the warning message has already been issued.
2881 return kInternalError;
2882 }
2883 bool isBranchElement = branch->InheritsFrom( TBranchElement::Class() );
2884 if (expectedClass && datatype == kOther_t && ptrClass == nullptr) {
2885 if (isBranchElement) {
2887 bEl->SetTargetClass( expectedClass->GetName() );
2888 }
2889 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
2890 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2891 "The class expected (%s) refers to an stl collection and do not have a compiled CollectionProxy. "
2892 "Please generate the dictionary for this class (%s)",
2893 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2895 }
2896 if (!expectedClass->IsLoaded()) {
2897 // The originally expected class does not have a dictionary, it is then plausible that the pointer being passed is the right type
2898 // (we really don't know). So let's express that.
2899 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2900 "The class expected (%s) does not have a dictionary and needs to be emulated for I/O purposes but is being passed a compiled object."
2901 "Please generate the dictionary for this class (%s)",
2902 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2903 } else {
2904 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2905 "This is probably due to a missing dictionary, the original data class for this branch is %s.", branch->GetName(), expectedClass->GetName());
2906 }
2907 return kClassMismatch;
2908 }
2909 if (expectedClass && ptrClass && (branch->GetMother() == branch)) {
2910 // Top Level branch
2911 if (!isptr) {
2912 Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
2913 }
2914 }
2915 if (expectedType == kFloat16_t) {
2917 }
2918 if (expectedType == kDouble32_t) {
2920 }
2921 if (datatype == kFloat16_t) {
2923 }
2924 if (datatype == kDouble32_t) {
2926 }
2927
2928 /////////////////////////////////////////////////////////////////////////////
2929 // Deal with the class renaming
2930 /////////////////////////////////////////////////////////////////////////////
2931
2932 if( expectedClass && ptrClass &&
2935 ptrClass->GetSchemaRules() &&
2936 ptrClass->GetSchemaRules()->HasRuleWithSourceClass( expectedClass->GetName() ) ) {
2938
2939 if ( ptrClass->GetCollectionProxy() && expectedClass->GetCollectionProxy() ) {
2940 if (gDebug > 7)
2941 Info("SetBranchAddress", "Matching STL collection (at least according to the SchemaRuleSet when "
2942 "reading a %s into a %s",expectedClass->GetName(),ptrClass->GetName());
2943
2944 bEl->SetTargetClass( ptrClass->GetName() );
2945 return kMatchConversion;
2946
2947 } else if ( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
2948 !ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
2949 Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" by the branch: %s", ptrClass->GetName(), bEl->GetClassName(), branch->GetName());
2950
2951 bEl->SetTargetClass( expectedClass->GetName() );
2952 return kClassMismatch;
2953 }
2954 else {
2955
2956 bEl->SetTargetClass( ptrClass->GetName() );
2957 return kMatchConversion;
2958 }
2959
2960 } else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
2961
2962 if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
2964 expectedClass->GetCollectionProxy()->GetValueClass() &&
2965 ptrClass->GetCollectionProxy()->GetValueClass() )
2966 {
2967 // In case of collection, we know how to convert them, if we know how to convert their content.
2968 // NOTE: we need to extend this to std::pair ...
2969
2970 TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
2971 TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
2972
2973 if (inmemValueClass->GetSchemaRules() &&
2974 inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
2975 {
2977 bEl->SetTargetClass( ptrClass->GetName() );
2979 }
2980 }
2981
2982 Error("SetBranchAddress", "The pointer type given (%s) does not correspond to the class needed (%s) by the branch: %s", ptrClass->GetName(), expectedClass->GetName(), branch->GetName());
2983 if (isBranchElement) {
2985 bEl->SetTargetClass( expectedClass->GetName() );
2986 }
2987 return kClassMismatch;
2988
2989 } else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
2990 if (datatype != kChar_t) {
2991 // For backward compatibility we assume that (char*) was just a cast and/or a generic address
2992 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s",
2994 return kMismatch;
2995 }
2996 } else if ((expectedClass && (datatype != kOther_t && datatype != kNoType_t && datatype != kInt_t)) ||
2998 // Sometime a null pointer can look an int, avoid complaining in that case.
2999 if (expectedClass) {
3000 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" by the branch: %s",
3001 TDataType::GetTypeName(datatype), datatype, expectedClass->GetName(), branch->GetName());
3002 if (isBranchElement) {
3004 bEl->SetTargetClass( expectedClass->GetName() );
3005 }
3006 } else {
3007 // In this case, it is okay if the first data member is of the right type (to support the case where we are being passed
3008 // a struct).
3009 bool found = false;
3010 if (ptrClass->IsLoaded()) {
3011 TIter next(ptrClass->GetListOfRealData());
3012 TRealData *rdm;
3013 while ((rdm = (TRealData*)next())) {
3014 if (rdm->GetThisOffset() == 0) {
3015 TDataType *dmtype = rdm->GetDataMember()->GetDataType();
3016 if (dmtype) {
3017 EDataType etype = (EDataType)dmtype->GetType();
3018 if (etype == expectedType) {
3019 found = true;
3020 }
3021 }
3022 break;
3023 }
3024 }
3025 } else {
3026 TIter next(ptrClass->GetListOfDataMembers());
3027 TDataMember *dm;
3028 while ((dm = (TDataMember*)next())) {
3029 if (dm->GetOffset() == 0) {
3030 TDataType *dmtype = dm->GetDataType();
3031 if (dmtype) {
3032 EDataType etype = (EDataType)dmtype->GetType();
3033 if (etype == expectedType) {
3034 found = true;
3035 }
3036 }
3037 break;
3038 }
3039 }
3040 }
3041 if (found) {
3042 // let's check the size.
3043 TLeaf *last = (TLeaf*)branch->GetListOfLeaves()->Last();
3044 long len = last->GetOffset() + last->GetLenType() * last->GetLen();
3045 if (len <= ptrClass->Size()) {
3046 return kMatch;
3047 }
3048 }
3049 Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" (%d) by the branch: %s",
3051 }
3052 return kMismatch;
3053 }
3054 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
3055 Error("SetBranchAddress", writeStlWithoutProxyMsg,
3056 expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
3057 if (isBranchElement) {
3059 bEl->SetTargetClass( expectedClass->GetName() );
3060 }
3062 }
3063 if (isBranchElement) {
3064 if (expectedClass) {
3066 bEl->SetTargetClass( expectedClass->GetName() );
3067 } else if (expectedType != kNoType_t && expectedType != kOther_t) {
3069 }
3070 }
3071 return kMatch;
3072}
3073
3074////////////////////////////////////////////////////////////////////////////////
3075/// Create a clone of this tree and copy nentries.
3076///
3077/// By default copy all entries.
3078/// The compression level of the cloned tree is set to the destination
3079/// file's compression level.
3080///
3081/// NOTE: Only active branches are copied. See TTree::SetBranchStatus for more
3082/// information and usage regarding the (de)activation of branches. More
3083/// examples are provided in the tutorials listed below.
3084///
3085/// NOTE: If the TTree is a TChain, the structure of the first TTree
3086/// is used for the copy.
3087///
3088/// IMPORTANT: The cloned tree stays connected with this tree until
3089/// this tree is deleted. In particular, any changes in
3090/// branch addresses in this tree are forwarded to the
3091/// clone trees, unless a branch in a clone tree has had
3092/// its address changed, in which case that change stays in
3093/// effect. When this tree is deleted, all the addresses of
3094/// the cloned tree are reset to their default values.
3095///
3096/// If 'option' contains the word 'fast' and nentries is -1, the
3097/// cloning will be done without unzipping or unstreaming the baskets
3098/// (i.e., a direct copy of the raw bytes on disk).
3099///
3100/// When 'fast' is specified, 'option' can also contain a sorting
3101/// order for the baskets in the output file.
3102///
3103/// There are currently 3 supported sorting order:
3104///
3105/// - SortBasketsByOffset (the default)
3106/// - SortBasketsByBranch
3107/// - SortBasketsByEntry
3108///
3109/// When using SortBasketsByOffset the baskets are written in the
3110/// output file in the same order as in the original file (i.e. the
3111/// baskets are sorted by their offset in the original file; Usually
3112/// this also means that the baskets are sorted by the index/number of
3113/// the _last_ entry they contain)
3114///
3115/// When using SortBasketsByBranch all the baskets of each individual
3116/// branches are stored contiguously. This tends to optimize reading
3117/// speed when reading a small number (1->5) of branches, since all
3118/// their baskets will be clustered together instead of being spread
3119/// across the file. However it might decrease the performance when
3120/// reading more branches (or the full entry).
3121///
3122/// When using SortBasketsByEntry the baskets with the lowest starting
3123/// entry are written first. (i.e. the baskets are sorted by the
3124/// index/number of the first entry they contain). This means that on
3125/// the file the baskets will be in the order in which they will be
3126/// needed when reading the whole tree sequentially.
3127///
3128/// For examples of CloneTree, see tutorials:
3129///
3130/// - copytree.C:
3131/// A macro to copy a subset of a TTree to a new TTree.
3132/// The input file has been generated by the program in
3133/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3134///
3135/// - copytree2.C:
3136/// A macro to copy a subset of a TTree to a new TTree.
3137/// One branch of the new Tree is written to a separate file.
3138/// The input file has been generated by the program in
3139/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3141TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
3142{
3143 // Options
3144 bool fastClone = false;
3145
3146 TString opt = option;
3147 opt.ToLower();
3148 if (opt.Contains("fast")) {
3149 fastClone = true;
3150 }
3151
3152 // If we are a chain, switch to the first tree.
3153 if (fEntries > 0) {
3154 const auto res = LoadTree(0);
3155 if (res < -2 || res == -1) {
3156 // -1 is not accepted, it happens when no trees were defined
3157 // -2 is the only acceptable error, when the chain has zero entries, but tree(s) were defined
3158 // Other errors (-3, ...) are not accepted
3159 Error("CloneTree", "returning nullptr since LoadTree failed with code %lld.", res);
3160 return nullptr;
3161 }
3162 }
3163
3164 // Note: For a tree we get the this pointer, for
3165 // a chain we get the chain's current tree.
3166 TTree* thistree = GetTree();
3167
3168 // We will use this to override the IO features on the cloned branches.
3170 ;
3171
3172 // Note: For a chain, the returned clone will be
3173 // a clone of the chain's first tree.
3174 TTree* newtree = (TTree*) thistree->Clone();
3175 if (!newtree) {
3176 return nullptr;
3177 }
3178
3179 // The clone should not delete any objects allocated by SetAddress().
3180 TObjArray* branches = newtree->GetListOfBranches();
3181 Int_t nb = branches->GetEntriesFast();
3182 for (Int_t i = 0; i < nb; ++i) {
3183 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3184 if (br->InheritsFrom(TBranchElement::Class())) {
3185 ((TBranchElement*) br)->ResetDeleteObject();
3186 }
3187 }
3188
3189 // Add the new tree to the list of clones so that
3190 // we can later inform it of changes to branch addresses.
3191 thistree->AddClone(newtree);
3192 if (thistree != this) {
3193 // In case this object is a TChain, add the clone
3194 // also to the TChain's list of clones.
3196 }
3197
3198 newtree->Reset();
3199
3200 TDirectory* ndir = newtree->GetDirectory();
3201 TFile* nfile = nullptr;
3202 if (ndir) {
3203 nfile = ndir->GetFile();
3204 }
3205 Int_t newcomp = -1;
3206 if (nfile) {
3207 newcomp = nfile->GetCompressionSettings();
3208 }
3209
3210 //
3211 // Delete non-active branches from the clone.
3212 //
3213 // Note: If we are a chain, this does nothing
3214 // since chains have no leaves.
3215 TObjArray* leaves = newtree->GetListOfLeaves();
3216 Int_t nleaves = leaves->GetEntriesFast();
3217 for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
3218 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
3219 if (!leaf) {
3220 continue;
3221 }
3222 TBranch* branch = leaf->GetBranch();
3223 if (branch && (newcomp > -1)) {
3224 branch->SetCompressionSettings(newcomp);
3225 }
3226 if (branch) branch->SetIOFeatures(features);
3227 if (!branch || !branch->TestBit(kDoNotProcess)) {
3228 continue;
3229 }
3230 // size might change at each iteration of the loop over the leaves.
3231 nb = branches->GetEntriesFast();
3232 for (Long64_t i = 0; i < nb; ++i) {
3233 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3234 if (br == branch) {
3235 branches->RemoveAt(i);
3236 delete br;
3237 br = nullptr;
3238 branches->Compress();
3239 break;
3240 }
3241 TObjArray* lb = br->GetListOfBranches();
3242 Int_t nb1 = lb->GetEntriesFast();
3243 for (Int_t j = 0; j < nb1; ++j) {
3244 TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
3245 if (!b1) {
3246 continue;
3247 }
3248 if (b1 == branch) {
3249 lb->RemoveAt(j);
3250 delete b1;
3251 b1 = nullptr;
3252 lb->Compress();
3253 break;
3254 }
3256 Int_t nb2 = lb1->GetEntriesFast();
3257 for (Int_t k = 0; k < nb2; ++k) {
3258 TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
3259 if (!b2) {
3260 continue;
3261 }
3262 if (b2 == branch) {
3263 lb1->RemoveAt(k);
3264 delete b2;
3265 b2 = nullptr;
3266 lb1->Compress();
3267 break;
3268 }
3269 }
3270 }
3271 }
3272 }
3273 leaves->Compress();
3274
3275 // Copy MakeClass status.
3276 newtree->SetMakeClass(fMakeClass);
3277
3278 // Copy branch addresses.
3280
3281 //
3282 // Copy entries if requested.
3283 //
3284
3285 if (nentries != 0) {
3286 if (fastClone && (nentries < 0)) {
3287 if ( newtree->CopyEntries( this, -1, option, false ) < 0 ) {
3288 // There was a problem!
3289 Error("CloneTTree", "TTree has not been cloned\n");
3290 delete newtree;
3291 newtree = nullptr;
3292 return nullptr;
3293 }
3294 } else {
3295 newtree->CopyEntries( this, nentries, option, false );
3296 }
3297 }
3298
3299 return newtree;
3300}
3301
3302////////////////////////////////////////////////////////////////////////////////
3303/// Set branch addresses of passed tree equal to ours.
3304/// If undo is true, reset the branch addresses instead of copying them.
3305/// This ensures 'separation' of a cloned tree from its original.
3307void TTree::CopyAddresses(TTree* tree, bool undo)
3308{
3309 // Copy branch addresses starting from branches.
3311 Int_t nbranches = branches->GetEntriesFast();
3312 for (Int_t i = 0; i < nbranches; ++i) {
3313 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
3314 if (branch->TestBit(kDoNotProcess)) {
3315 continue;
3316 }
3317 if (undo) {
3318 TBranch* br = tree->GetBranch(branch->GetName());
3319 tree->ResetBranchAddress(br);
3320 } else {
3321 char* addr = branch->GetAddress();
3322 if (!addr) {
3323 if (branch->IsA() == TBranch::Class()) {
3324 // If the branch was created using a leaflist, the branch itself may not have
3325 // an address but the leaf might already.
3326 TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
3327 if (!firstleaf || firstleaf->GetValuePointer()) {
3328 // Either there is no leaf (and thus no point in copying the address)
3329 // or the leaf has an address but we can not copy it via the branche
3330 // this will be copied via the next loop (over the leaf).
3331 continue;
3332 }
3333 }
3334 // Note: This may cause an object to be allocated.
3335 branch->SetAddress(nullptr);
3336 addr = branch->GetAddress();
3337 }
3338 TBranch* br = tree->GetBranch(branch->GetFullName());
3339 if (br) {
3340 if (br->GetMakeClass() != branch->GetMakeClass())
3341 br->SetMakeClass(branch->GetMakeClass());
3342 br->SetAddress(addr);
3343 // The copy does not own any object allocated by SetAddress().
3344 if (br->InheritsFrom(TBranchElement::Class())) {
3345 ((TBranchElement*) br)->ResetDeleteObject();
3346 }
3347 } else {
3348 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3349 }
3350 }
3351 }
3352
3353 // Copy branch addresses starting from leaves.
3354 TObjArray* tleaves = tree->GetListOfLeaves();
3355 Int_t ntleaves = tleaves->GetEntriesFast();
3356 std::set<TLeaf*> updatedLeafCount;
3357 for (Int_t i = 0; i < ntleaves; ++i) {
3358 TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
3359 TBranch* tbranch = tleaf->GetBranch();
3360 TBranch* branch = GetBranch(tbranch->GetName());
3361 if (!branch) {
3362 continue;
3363 }
3364 TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
3365 if (!leaf) {
3366 continue;
3367 }
3368 if (branch->TestBit(kDoNotProcess)) {
3369 continue;
3370 }
3371 if (undo) {
3372 // Now we know whether the address has been transfered
3373 tree->ResetBranchAddress(tbranch);
3374 } else {
3375 TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
3376 bool needAddressReset = false;
3377 if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
3378 {
3379 // If it is an array and it was allocated by the leaf itself,
3380 // let's make sure it is large enough for the incoming data.
3381 if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
3382 leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
3383 updatedLeafCount.insert(leaf->GetLeafCount());
3384 needAddressReset = true;
3385 } else {
3386 needAddressReset = (updatedLeafCount.find(leaf->GetLeafCount()) != updatedLeafCount.end());
3387 }
3388 }
3389 if (needAddressReset && leaf->GetValuePointer()) {
3390 if (leaf->IsA() == TLeafElement::Class() && mother)
3391 mother->ResetAddress();
3392 else
3393 leaf->SetAddress(nullptr);
3394 }
3395 if (!branch->GetAddress() && !leaf->GetValuePointer()) {
3396 // We should attempts to set the address of the branch.
3397 // something like:
3398 //(TBranchElement*)branch->GetMother()->SetAddress(0)
3399 //plus a few more subtleties (see TBranchElement::GetEntry).
3400 //but for now we go the simplest route:
3401 //
3402 // Note: This may result in the allocation of an object.
3403 branch->SetupAddresses();
3404 }
3405 if (branch->GetAddress()) {
3406 tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
3407 TBranch* br = tree->GetBranch(branch->GetName());
3408 if (br) {
3409 if (br->IsA() != branch->IsA()) {
3410 Error(
3411 "CopyAddresses",
3412 "Branch kind mismatch between input tree '%s' and output tree '%s' for branch '%s': '%s' vs '%s'",
3413 tree->GetName(), br->GetTree()->GetName(), br->GetName(), branch->IsA()->GetName(),
3414 br->IsA()->GetName());
3415 }
3416 // The copy does not own any object allocated by SetAddress().
3417 // FIXME: We do too much here, br may not be a top-level branch.
3418 if (br->InheritsFrom(TBranchElement::Class())) {
3419 ((TBranchElement*) br)->ResetDeleteObject();
3420 }
3421 } else {
3422 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3423 }
3424 } else {
3425 tleaf->SetAddress(leaf->GetValuePointer());
3426 }
3427 }
3428 }
3429
3430 if (undo &&
3431 ( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
3432 ) {
3433 tree->ResetBranchAddresses();
3434 }
3435}
3436
3437namespace {
3438
3439 enum EOnIndexError { kDrop, kKeep, kBuild };
3440
3441 bool R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
3442 {
3443 // Return true if we should continue to handle indices, false otherwise.
3444
3445 bool withIndex = true;
3446
3447 if ( newtree->GetTreeIndex() ) {
3448 if ( oldtree->GetTree()->GetTreeIndex() == nullptr ) {
3449 switch (onIndexError) {
3450 case kDrop:
3451 delete newtree->GetTreeIndex();
3452 newtree->SetTreeIndex(nullptr);
3453 withIndex = false;
3454 break;
3455 case kKeep:
3456 // Nothing to do really.
3457 break;
3458 case kBuild:
3459 // Build the index then copy it
3460 if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
3461 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3462 // Clean up
3463 delete oldtree->GetTree()->GetTreeIndex();
3464 oldtree->GetTree()->SetTreeIndex(nullptr);
3465 }
3466 break;
3467 }
3468 } else {
3469 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3470 }
3471 } else if ( oldtree->GetTree()->GetTreeIndex() != nullptr ) {
3472 // We discover the first index in the middle of the chain.
3473 switch (onIndexError) {
3474 case kDrop:
3475 // Nothing to do really.
3476 break;
3477 case kKeep: {
3478 TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
3479 index->SetTree(newtree);
3480 newtree->SetTreeIndex(index);
3481 break;
3482 }
3483 case kBuild:
3484 if (newtree->GetEntries() == 0) {
3485 // Start an index.
3486 TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
3487 index->SetTree(newtree);
3488 newtree->SetTreeIndex(index);
3489 } else {
3490 // Build the index so far.
3491 if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
3492 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3493 }
3494 }
3495 break;
3496 }
3497 } else if ( onIndexError == kDrop ) {
3498 // There is no index on this or on tree->GetTree(), we know we have to ignore any further
3499 // index
3500 withIndex = false;
3501 }
3502 return withIndex;
3503 }
3504}
3505
3506////////////////////////////////////////////////////////////////////////////////
3507/// Copy nentries from given tree to this tree.
3508/// This routines assumes that the branches that intended to be copied are
3509/// already connected. The typical case is that this tree was created using
3510/// tree->CloneTree(0).
3511///
3512/// By default copy all entries.
3513///
3514/// Returns number of bytes copied to this tree.
3515///
3516/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
3517/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
3518/// raw bytes on disk).
3519///
3520/// When 'fast' is specified, 'option' can also contains a sorting order for the
3521/// baskets in the output file.
3522///
3523/// There are currently 3 supported sorting order:
3524///
3525/// - SortBasketsByOffset (the default)
3526/// - SortBasketsByBranch
3527/// - SortBasketsByEntry
3528///
3529/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
3530///
3531/// If the tree or any of the underlying tree of the chain has an index, that index and any
3532/// index in the subsequent underlying TTree objects will be merged.
3533///
3534/// There are currently three 'options' to control this merging:
3535/// - NoIndex : all the TTreeIndex object are dropped.
3536/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
3537/// they are all dropped.
3538/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
3539/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
3540/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
3542Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */, bool needCopyAddresses /* = false */)
3543{
3544 if (!tree) {
3545 return 0;
3546 }
3547 // Options
3548 TString opt = option;
3549 opt.ToLower();
3550 bool fastClone = opt.Contains("fast");
3551 bool withIndex = !opt.Contains("noindex");
3552 EOnIndexError onIndexError;
3553 if (opt.Contains("asisindex")) {
3555 } else if (opt.Contains("buildindex")) {
3557 } else if (opt.Contains("dropindex")) {
3559 } else {
3561 }
3562 Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
3563 Long64_t cacheSize = -1;
3565 // If the parse faile, cacheSize stays at -1.
3566 Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
3570 Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
3572 double m;
3573 const char *munit = nullptr;
3574 ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
3575
3576 Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
3577 }
3578 }
3579 if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %lld\n",cacheSize);
3580
3581 Long64_t nbytes = 0;
3582 Long64_t treeEntries = tree->GetEntriesFast();
3583 if (nentries < 0) {
3585 } else if (nentries > treeEntries) {
3587 }
3588
3590 // Quickly copy the basket without decompression and streaming.
3592 for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
3593 if (tree->LoadTree(i) < 0) {
3594 break;
3595 }
3596 if ( withIndex ) {
3597 withIndex = R__HandleIndex( onIndexError, this, tree );
3598 }
3599 if (this->GetDirectory()) {
3600 TFile* file2 = this->GetDirectory()->GetFile();
3601 if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
3602 if (this->GetDirectory() == (TDirectory*) file2) {
3603 this->ChangeFile(file2);
3604 }
3605 }
3606 }
3607 TTreeCloner cloner(tree->GetTree(), this, option, TTreeCloner::kNoWarnings);
3608 if (cloner.IsValid()) {
3609 this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
3610 if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
3611 cloner.Exec();
3612 } else {
3613 if (i == 0) {
3614 Warning("CopyEntries","%s",cloner.GetWarning());
3615 // If the first cloning does not work, something is really wrong
3616 // (since apriori the source and target are exactly the same structure!)
3617 return -1;
3618 } else {
3619 if (cloner.NeedConversion()) {
3620 TTree *localtree = tree->GetTree();
3621 Long64_t tentries = localtree->GetEntries();
3622 if (needCopyAddresses) {
3623 // Copy MakeClass status.
3624 tree->SetMakeClass(fMakeClass);
3625 // Copy branch addresses.
3626 CopyAddresses(tree);
3627 }
3628 for (Long64_t ii = 0; ii < tentries; ii++) {
3629 if (localtree->GetEntry(ii) <= 0) {
3630 break;
3631 }
3632 this->Fill();
3633 }
3634 if (needCopyAddresses)
3635 tree->ResetBranchAddresses();
3636 if (this->GetTreeIndex()) {
3637 this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), true);
3638 }
3639 } else {
3640 Warning("CopyEntries","%s",cloner.GetWarning());
3641 if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
3642 Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
3643 } else {
3644 Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
3645 }
3646 }
3647 }
3648 }
3649
3650 }
3651 if (this->GetTreeIndex()) {
3652 this->GetTreeIndex()->Append(nullptr,false); // Force the sorting
3653 }
3654 nbytes = GetTotBytes() - totbytes;
3655 } else {
3656 if (nentries < 0) {
3658 } else if (nentries > treeEntries) {
3660 }
3661 if (needCopyAddresses) {
3662 // Copy MakeClass status.
3663 tree->SetMakeClass(fMakeClass);
3664 // Copy branch addresses.
3665 CopyAddresses(tree);
3666 }
3667 Int_t treenumber = -1;
3668 for (Long64_t i = 0; i < nentries; i++) {
3669 if (tree->LoadTree(i) < 0) {
3670 break;
3671 }
3672 if (treenumber != tree->GetTreeNumber()) {
3673 if ( withIndex ) {
3674 withIndex = R__HandleIndex( onIndexError, this, tree );
3675 }
3676 treenumber = tree->GetTreeNumber();
3677 }
3678 if (tree->GetEntry(i) <= 0) {
3679 break;
3680 }
3681 nbytes += this->Fill();
3682 }
3683 if (needCopyAddresses)
3684 tree->ResetBranchAddresses();
3685 if (this->GetTreeIndex()) {
3686 this->GetTreeIndex()->Append(nullptr,false); // Force the sorting
3687 }
3688 }
3689 return nbytes;
3690}
3691
3692////////////////////////////////////////////////////////////////////////////////
3693/// Copy a tree with selection.
3694///
3695/// ### Important:
3696///
3697/// The returned copied tree stays connected with the original tree
3698/// until the original tree is deleted. In particular, any changes
3699/// to the branch addresses in the original tree are also made to
3700/// the copied tree. Any changes made to the branch addresses of the
3701/// copied tree are overridden anytime the original tree changes its
3702/// branch addresses. When the original tree is deleted, all the
3703/// branch addresses of the copied tree are set to zero.
3704///
3705/// For examples of CopyTree, see the tutorials:
3706///
3707/// - copytree.C:
3708/// Example macro to copy a subset of a tree to a new tree.
3709/// The input file was generated by running the program in
3710/// $ROOTSYS/test/Event in this way:
3711/// ~~~ {.cpp}
3712/// ./Event 1000 1 1 1
3713/// ~~~
3714/// - copytree2.C
3715/// Example macro to copy a subset of a tree to a new tree.
3716/// One branch of the new tree is written to a separate file.
3717/// The input file was generated by running the program in
3718/// $ROOTSYS/test/Event in this way:
3719/// ~~~ {.cpp}
3720/// ./Event 1000 1 1 1
3721/// ~~~
3722/// - copytree3.C
3723/// Example macro to copy a subset of a tree to a new tree.
3724/// Only selected entries are copied to the new tree.
3725/// NOTE that only the active branches are copied.
3727TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
3728{
3729 GetPlayer();
3730 if (fPlayer) {
3732 }
3733 return nullptr;
3734}
3735
3736////////////////////////////////////////////////////////////////////////////////
3737/// Create a basket for this tree and given branch.
3740{
3741 if (!branch) {
3742 return nullptr;
3743 }
3744 return new TBasket(branch->GetName(), GetName(), branch);
3745}
3746
3747////////////////////////////////////////////////////////////////////////////////
3748/// Delete this tree from memory or/and disk.
3749///
3750/// - if option == "all" delete Tree object from memory AND from disk
3751/// all baskets on disk are deleted. All keys with same name
3752/// are deleted.
3753/// - if option =="" only Tree object in memory is deleted.
3755void TTree::Delete(Option_t* option /* = "" */)
3756{
3757 TFile *file = GetCurrentFile();
3758
3759 // delete all baskets and header from file
3760 if (file && option && !strcmp(option,"all")) {
3761 if (!file->IsWritable()) {
3762 Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
3763 return;
3764 }
3765
3766 //find key and import Tree header in memory
3767 TKey *key = fDirectory->GetKey(GetName());
3768 if (!key) return;
3769
3771 file->cd();
3772
3773 //get list of leaves and loop on all the branches baskets
3774 TIter next(GetListOfLeaves());
3775 TLeaf *leaf;
3776 char header[16];
3777 Int_t ntot = 0;
3778 Int_t nbask = 0;
3780 while ((leaf = (TLeaf*)next())) {
3781 TBranch *branch = leaf->GetBranch();
3782 Int_t nbaskets = branch->GetMaxBaskets();
3783 for (Int_t i=0;i<nbaskets;i++) {
3784 Long64_t pos = branch->GetBasketSeek(i);
3785 if (!pos) continue;
3786 TFile *branchFile = branch->GetFile();
3787 if (!branchFile) continue;
3788 branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
3789 if (nbytes <= 0) continue;
3790 branchFile->MakeFree(pos,pos+nbytes-1);
3791 ntot += nbytes;
3792 nbask++;
3793 }
3794 }
3795
3796 // delete Tree header key and all keys with the same name
3797 // A Tree may have been saved many times. Previous cycles are invalid.
3798 while (key) {
3799 ntot += key->GetNbytes();
3800 key->Delete();
3801 delete key;
3802 key = fDirectory->GetKey(GetName());
3803 }
3804 if (dirsav) dirsav->cd();
3805 if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
3806 }
3807
3808 if (fDirectory) {
3809 fDirectory->Remove(this);
3810 //delete the file cache if it points to this Tree
3811 MoveReadCache(file,nullptr);
3812 fDirectory = nullptr;
3814 }
3815
3816 // Delete object from CINT symbol table so it can not be used anymore.
3817 gCling->DeleteGlobal(this);
3818
3819 // Warning: We have intentional invalidated this object while inside a member function!
3820 delete this;
3821}
3822
3823 ///////////////////////////////////////////////////////////////////////////////
3824 /// Called by TKey and TObject::Clone to automatically add us to a directory
3825 /// when we are read from a file.
3828{
3829 if (fDirectory == dir) return;
3830 if (fDirectory) {
3831 fDirectory->Remove(this);
3832 // Delete or move the file cache if it points to this Tree
3833 TFile *file = fDirectory->GetFile();
3834 MoveReadCache(file,dir);
3835 }
3836 fDirectory = dir;
3837 TBranch* b = nullptr;
3838 TIter next(GetListOfBranches());
3839 while((b = (TBranch*) next())) {
3840 b->UpdateFile();
3841 }
3842 if (fBranchRef) {
3844 }
3845 if (fDirectory) fDirectory->Append(this);
3846}
3847
3848////////////////////////////////////////////////////////////////////////////////
3849/// Draw expression varexp for specified entries.
3850///
3851/// \return -1 in case of error or number of selected events in case of success.
3852///
3853/// This function accepts TCut objects as arguments.
3854/// Useful to use the string operator +
3855///
3856/// Example:
3857///
3858/// ~~~ {.cpp}
3859/// ntuple.Draw("x",cut1+cut2+cut3);
3860/// ~~~
3861
3866}
3867
3868/////////////////////////////////////////////////////////////////////////////////////////
3869/// \brief Draw expression varexp for entries and objects that pass a (optional) selection.
3870///
3871/// \return -1 in case of error or number of selected events in case of success.
3872///
3873/// \param [in] varexp
3874/// \parblock
3875/// A string that takes one of these general forms:
3876/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
3877/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
3878/// on the y-axis versus "e2" on the x-axis
3879/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3880/// vs "e2" vs "e3" on the z-, y-, x-axis, respectively
3881/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3882/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
3883/// (to create histograms in the 2, 3, and 4 dimensional case,
3884/// see section "Saving the result of Draw to an histogram")
3885/// - "e1:e2:e3:e4:e5" with option "GL5D" produces a 5D plot using OpenGL. `gStyle->SetCanvasPreferGL(true)` is needed.
3886/// - Any number of variables no fewer than two can be used with the options "CANDLE" and "PARA"
3887/// - An arbitrary number of variables can be used with the option "GOFF"
3888///
3889/// Examples:
3890/// - "x": the simplest case, it draws a 1-Dim histogram of column x
3891/// - "sqrt(x)", "x*y/z": draw histogram with the values of the specified numerical expression across TTree events
3892/// - "y:sqrt(x)": 2-Dim histogram of y versus sqrt(x)
3893/// - "px:py:pz:2.5*E": produces a 3-d scatter-plot of px vs py ps pz
3894/// and the color number of each marker will be 2.5*E.
3895/// If the color number is negative it is set to 0.
3896/// If the color number is greater than the current number of colors
3897/// it is set to the highest color number. The default number of
3898/// colors is 50. See TStyle::SetPalette for setting a new color palette.
3899///
3900/// The expressions can use all the operations and built-in functions
3901/// supported by TFormula (see TFormula::Analyze()), including free
3902/// functions taking numerical arguments (e.g. TMath::Bessel()).
3903/// In addition, you can call member functions taking numerical
3904/// arguments. For example, these are two valid expressions:
3905/// ~~~ {.cpp}
3906/// TMath::BreitWigner(fPx,3,2)
3907/// event.GetHistogram()->GetXaxis()->GetXmax()
3908/// ~~~
3909/// \endparblock
3910/// \param [in] selection
3911/// \parblock
3912/// A string containing a selection expression.
3913/// In a selection all usual C++ mathematical and logical operators are allowed.
3914/// The value corresponding to the selection expression is used as a weight
3915/// to fill the histogram (a weight of 0 is equivalent to not filling the histogram).\n
3916/// \n
3917/// Examples:
3918/// - "x<y && sqrt(z)>3.2": returns a weight = 0 or 1
3919/// - "(x+y)*(sqrt(z)>3.2)": returns a weight = x+y if sqrt(z)>3.2, 0 otherwise\n
3920/// \n
3921/// If the selection expression returns an array, it is iterated over in sync with the
3922/// array returned by the varexp argument (as described below in "Drawing expressions using arrays and array
3923/// elements"). For example, if, for a given event, varexp evaluates to
3924/// `{1., 2., 3.}` and selection evaluates to `{0, 1, 0}`, the resulting histogram is filled with the value 2. For example, for each event here we perform a simple object selection:
3925/// ~~~{.cpp}
3926/// // Muon_pt is an array: fill a histogram with the array elements > 100 in each event
3927/// tree->Draw('Muon_pt', 'Muon_pt > 100')
3928/// ~~~
3929/// \endparblock
3930/// \param [in] option
3931/// \parblock
3932/// The drawing option.
3933/// - When an histogram is produced it can be any histogram drawing option
3934/// listed in THistPainter.
3935/// - when no option is specified:
3936/// - the default histogram drawing option is used
3937/// if the expression is of the form "e1".
3938/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
3939/// unbinned 2D or 3D points is drawn respectively.
3940/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
3941/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
3942/// palette.
3943/// - If option COL is specified when varexp has three fields:
3944/// ~~~ {.cpp}
3945/// tree.Draw("e1:e2:e3","","col");
3946/// ~~~
3947/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
3948/// color palette. The colors for e3 are evaluated once in linear scale before
3949/// painting. Therefore changing the pad to log scale along Z as no effect
3950/// on the colors.
3951/// - if expression has more than four fields the option "PARA"or "CANDLE"
3952/// can be used.
3953/// - If option contains the string "goff", no graphics is generated.
3954/// \endparblock
3955/// \param [in] nentries The number of entries to process (default is all)
3956/// \param [in] firstentry The first entry to process (default is 0)
3957///
3958/// ### Drawing expressions using arrays and array elements
3959///
3960/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
3961/// or a TClonesArray.
3962/// In a TTree::Draw expression you can now access fMatrix using the following
3963/// syntaxes:
3964///
3965/// | String passed | What is used for each entry of the tree
3966/// |-----------------|--------------------------------------------------------|
3967/// | `fMatrix` | the 9 elements of fMatrix |
3968/// | `fMatrix[][]` | the 9 elements of fMatrix |
3969/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
3970/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3971/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
3972/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
3973///
3974/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
3975///
3976/// In summary, if a specific index is not specified for a dimension, TTree::Draw
3977/// will loop through all the indices along this dimension. Leaving off the
3978/// last (right most) dimension of specifying then with the two characters '[]'
3979/// is equivalent. For variable size arrays (and TClonesArray) the range
3980/// of the first dimension is recalculated for each entry of the tree.
3981/// You can also specify the index as an expression of any other variables from the
3982/// tree.
3983///
3984/// TTree::Draw also now properly handling operations involving 2 or more arrays.
3985///
3986/// Let assume a second matrix fResults[5][2], here are a sample of some
3987/// of the possible combinations, the number of elements they produce and
3988/// the loop used:
3989///
3990/// | expression | element(s) | Loop |
3991/// |----------------------------------|------------|--------------------------|
3992/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
3993/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
3994/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
3995/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
3996/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
3997/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
3998/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
3999/// | `fMatrix[][fResult[][]]` | 30 | on 1st dim of fMatrix then on both dimensions of fResults. The value if fResults[j][k] is used as the second index of fMatrix.|
4000///
4001///
4002/// In summary, TTree::Draw loops through all unspecified dimensions. To
4003/// figure out the range of each loop, we match each unspecified dimension
4004/// from left to right (ignoring ALL dimensions for which an index has been
4005/// specified), in the equivalent loop matched dimensions use the same index
4006/// and are restricted to the smallest range (of only the matched dimensions).
4007/// When involving variable arrays, the range can of course be different
4008/// for each entry of the tree.
4009///
4010/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
4011/// ~~~ {.cpp}
4012/// for (Int_t i0; i < min(3,2); i++) {
4013/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
4014/// }
4015/// ~~~
4016/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
4017/// ~~~ {.cpp}
4018/// for (Int_t i0; i < min(3,5); i++) {
4019/// for (Int_t i1; i1 < 2; i1++) {
4020/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
4021/// }
4022/// }
4023/// ~~~
4024/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
4025/// ~~~ {.cpp}
4026/// for (Int_t i0; i < min(3,5); i++) {
4027/// for (Int_t i1; i1 < min(3,2); i1++) {
4028/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
4029/// }
4030/// }
4031/// ~~~
4032/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
4033/// ~~~ {.cpp}
4034/// for (Int_t i0; i0 < 3; i0++) {
4035/// for (Int_t j2; j2 < 5; j2++) {
4036/// for (Int_t j3; j3 < 2; j3++) {
4037/// i1 = fResults[j2][j3];
4038/// use the value of fMatrix[i0][i1]
4039/// }
4040/// }
4041/// ~~~
4042/// ### Retrieving the result of Draw
4043///
4044/// By default a temporary histogram called `htemp` is created. It will be:
4045///
4046/// - A TH1F* in case of a mono-dimensional distribution: `Draw("e1")`,
4047/// - A TH2F* in case of a bi-dimensional distribution: `Draw("e1:e2")`,
4048/// - A TH3F* in case of a three-dimensional distribution: `Draw("e1:e2:e3")`.
4049///
4050/// In the one dimensional case the `htemp` is filled and drawn whatever the drawing
4051/// option is.
4052///
4053/// In the two and three dimensional cases, with the default drawing option (`""`),
4054/// a cloud of points is drawn and the histogram `htemp` is not filled. For all the other
4055/// drawing options `htemp` will be filled.
4056///
4057/// In all cases `htemp` can be retrieved by calling:
4058///
4059/// ~~~ {.cpp}
4060/// auto htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
4061/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp"); // 2D
4062/// auto htemp = (TH3F*)gPad->GetPrimitive("htemp"); // 3D
4063/// ~~~
4064///
4065/// In the two dimensional case (`Draw("e1;e2")`), with the default drawing option, the
4066/// data is filled into a TGraph named `Graph`. This TGraph can be retrieved by
4067/// calling
4068///
4069/// ~~~ {.cpp}
4070/// auto graph = (TGraph*)gPad->GetPrimitive("Graph");
4071/// ~~~
4072///
4073/// For the three and four dimensional cases, with the default drawing option, an unnamed
4074/// TPolyMarker3D is produced, and therefore cannot be retrieved.
4075///
4076/// In all cases `htemp` can be used to access the axes. For instance in the 2D case:
4077///
4078/// ~~~ {.cpp}
4079/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp");
4080/// auto xaxis = htemp->GetXaxis();
4081/// ~~~
4082///
4083/// When the option `"A"` is used (with TGraph painting option) to draw a 2D
4084/// distribution:
4085/// ~~~ {.cpp}
4086/// tree.Draw("e1:e2","","A*");
4087/// ~~~
4088/// a scatter plot is produced (with stars in that case) but the axis creation is
4089/// delegated to TGraph and `htemp` is not created.
4090///
4091/// ### Saving the result of Draw to a histogram
4092///
4093/// If `varexp` contains `>>hnew` (following the variable(s) name(s)),
4094/// the new histogram called `hnew` is created and it is kept in the current
4095/// directory (and also the current pad). This works for all dimensions.
4096///
4097/// Example:
4098/// ~~~ {.cpp}
4099/// tree.Draw("sqrt(x)>>hsqrt","y>0")
4100/// ~~~
4101/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
4102/// directory. To retrieve it do:
4103/// ~~~ {.cpp}
4104/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
4105/// ~~~
4106/// The binning information is taken from the environment variables
4107/// ~~~ {.cpp}
4108/// Hist.Binning.?D.?
4109/// ~~~
4110/// In addition, the name of the histogram can be followed by up to 9
4111/// numbers between '(' and ')', where the numbers describe the
4112/// following:
4113///
4114/// - 1 - bins in x-direction
4115/// - 2 - lower limit in x-direction
4116/// - 3 - upper limit in x-direction
4117/// - 4-6 same for y-direction
4118/// - 7-9 same for z-direction
4119///
4120/// When a new binning is used the new value will become the default.
4121/// Values can be skipped.
4122///
4123/// Example:
4124/// ~~~ {.cpp}
4125/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
4126/// // plot sqrt(x) between 10 and 20 using 500 bins
4127/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
4128/// // plot sqrt(x) against sin(y)
4129/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
4130/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
4131/// ~~~
4132/// By default, the specified histogram is reset.
4133/// To continue to append data to an existing histogram, use "+" in front
4134/// of the histogram name.
4135///
4136/// A '+' in front of the histogram name is ignored, when the name is followed by
4137/// binning information as described in the previous paragraph.
4138/// ~~~ {.cpp}
4139/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
4140/// ~~~
4141/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
4142/// and 3-D histograms.
4143///
4144/// ### Accessing collection objects
4145///
4146/// TTree::Draw default's handling of collections is to assume that any
4147/// request on a collection pertain to it content. For example, if fTracks
4148/// is a collection of Track objects, the following:
4149/// ~~~ {.cpp}
4150/// tree->Draw("event.fTracks.fPx");
4151/// ~~~
4152/// will plot the value of fPx for each Track objects inside the collection.
4153/// Also
4154/// ~~~ {.cpp}
4155/// tree->Draw("event.fTracks.size()");
4156/// ~~~
4157/// would plot the result of the member function Track::size() for each
4158/// Track object inside the collection.
4159/// To access information about the collection itself, TTree::Draw support
4160/// the '@' notation. If a variable which points to a collection is prefixed
4161/// or postfixed with '@', the next part of the expression will pertain to
4162/// the collection object. For example:
4163/// ~~~ {.cpp}
4164/// tree->Draw("event.@fTracks.size()");
4165/// ~~~
4166/// will plot the size of the collection referred to by `fTracks` (i.e the number
4167/// of Track objects).
4168///
4169/// ### Drawing 'objects'
4170///
4171/// When a class has a member function named AsDouble or AsString, requesting
4172/// to directly draw the object will imply a call to one of the 2 functions.
4173/// If both AsDouble and AsString are present, AsDouble will be used.
4174/// AsString can return either a char*, a std::string or a TString.s
4175/// For example, the following
4176/// ~~~ {.cpp}
4177/// tree->Draw("event.myTTimeStamp");
4178/// ~~~
4179/// will draw the same histogram as
4180/// ~~~ {.cpp}
4181/// tree->Draw("event.myTTimeStamp.AsDouble()");
4182/// ~~~
4183/// In addition, when the object is a type TString or std::string, TTree::Draw
4184/// will call respectively `TString::Data` and `std::string::c_str()`
4185///
4186/// If the object is a TBits, the histogram will contain the index of the bit
4187/// that are turned on.
4188///
4189/// ### Retrieving information about the tree itself.
4190///
4191/// You can refer to the tree (or chain) containing the data by using the
4192/// string 'This'.
4193/// You can then could any TTree methods. For example:
4194/// ~~~ {.cpp}
4195/// tree->Draw("This->GetReadEntry()");
4196/// ~~~
4197/// will display the local entry numbers be read.
4198/// ~~~ {.cpp}
4199/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
4200/// ~~~
4201/// will display the name of the first 'user info' object.
4202///
4203/// ### Special functions and variables
4204///
4205/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
4206/// to access the entry number being read. For example to draw every
4207/// other entry use:
4208/// ~~~ {.cpp}
4209/// tree.Draw("myvar","Entry$%2==0");
4210/// ~~~
4211/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
4212/// - `LocalEntry$` : return the current entry number in the current tree of a
4213/// chain (`== GetTree()->GetReadEntry()`)
4214/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
4215/// - `LocalEntries$` : return the total number of entries in the current tree
4216/// of a chain (== GetTree()->TTree::GetEntries())
4217/// - `Length$` : return the total number of element of this formula for this
4218/// entry (`==TTreeFormula::GetNdata()`)
4219/// - `Iteration$` : return the current iteration over this formula for this
4220/// entry (i.e. varies from 0 to `Length$`).
4221/// - `Length$(formula )` : return the total number of element of the formula
4222/// given as a parameter.
4223/// - `Sum$(formula )` : return the sum of the value of the elements of the
4224/// formula given as a parameter. For example the mean for all the elements in
4225/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
4226/// - `Min$(formula )` : return the minimum (within one TTree entry) of the value of the
4227/// elements of the formula given as a parameter.
4228/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
4229/// elements of the formula given as a parameter.
4230/// - `MinIf$(formula,condition)`
4231/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
4232/// of the value of the elements of the formula given as a parameter
4233/// if they match the condition. If no element matches the condition,
4234/// the result is zero. To avoid the resulting peak at zero, use the
4235/// pattern:
4236/// ~~~ {.cpp}
4237/// tree->Draw("MinIf$(formula,condition)","condition");
4238/// ~~~
4239/// which will avoid calculation `MinIf$` for the entries that have no match
4240/// for the condition.
4241/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
4242/// for the current iteration otherwise return the value of "alternate".
4243/// For example, with arr1[3] and arr2[2]
4244/// ~~~ {.cpp}
4245/// tree->Draw("arr1+Alt$(arr2,0)");
4246/// ~~~
4247/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
4248/// Or with a variable size array arr3
4249/// ~~~ {.cpp}
4250/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
4251/// ~~~
4252/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
4253/// As a comparison
4254/// ~~~ {.cpp}
4255/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
4256/// ~~~
4257/// will draw the sum arr3 for the index 0 to 2 only if the
4258/// actual_size_of_arr3 is greater or equal to 3.
4259/// Note that the array in 'primary' is flattened/linearized thus using
4260/// `Alt$` with multi-dimensional arrays of different dimensions in unlikely
4261/// to yield the expected results. To visualize a bit more what elements
4262/// would be matched by TTree::Draw, TTree::Scan can be used:
4263/// ~~~ {.cpp}
4264/// tree->Scan("arr1:Alt$(arr2,0)");
4265/// ~~~
4266/// will print on one line the value of arr1 and (arr2,0) that will be
4267/// matched by
4268/// ~~~ {.cpp}
4269/// tree->Draw("arr1-Alt$(arr2,0)");
4270/// ~~~
4271/// The ternary operator is not directly supported in TTree::Draw however, to plot the
4272/// equivalent of `var2<20 ? -99 : var1`, you can use:
4273/// ~~~ {.cpp}
4274/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
4275/// ~~~
4276///
4277/// ### Drawing a user function accessing the TTree data directly
4278///
4279/// If the formula contains a file name, TTree::MakeProxy will be used
4280/// to load and execute this file. In particular it will draw the
4281/// result of a function with the same name as the file. The function
4282/// will be executed in a context where the name of the branches can
4283/// be used as a C++ variable.
4284///
4285/// For example draw px using the file hsimple.root (generated by the
4286/// hsimple.C tutorial), we need a file named hsimple.cxx:
4287/// ~~~ {.cpp}
4288/// double hsimple() {
4289/// return px;
4290/// }
4291/// ~~~
4292/// MakeProxy can then be used indirectly via the TTree::Draw interface
4293/// as follow:
4294/// ~~~ {.cpp}
4295/// new TFile("hsimple.root")
4296/// ntuple->Draw("hsimple.cxx");
4297/// ~~~
4298/// A more complete example is available in the tutorials directory:
4299/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
4300/// which reimplement the selector found in `h1analysis.C`
4301///
4302/// The main features of this facility are:
4303///
4304/// * on-demand loading of branches
4305/// * ability to use the 'branchname' as if it was a data member
4306/// * protection against array out-of-bound
4307/// * ability to use the branch data as object (when the user code is available)
4308///
4309/// See TTree::MakeProxy for more details.
4310///
4311/// ### Making a Profile histogram
4312///
4313/// In case of a 2-Dim expression, one can generate a TProfile histogram
4314/// instead of a TH2F histogram by specifying option=prof or option=profs
4315/// or option=profi or option=profg ; the trailing letter select the way
4316/// the bin error are computed, See TProfile2D::SetErrorOption for
4317/// details on the differences.
4318/// The option=prof is automatically selected in case of y:x>>pf
4319/// where pf is an existing TProfile histogram.
4320///
4321/// ### Making a 2D Profile histogram
4322///
4323/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
4324/// instead of a TH3F histogram by specifying option=prof or option=profs.
4325/// or option=profi or option=profg ; the trailing letter select the way
4326/// the bin error are computed, See TProfile2D::SetErrorOption for
4327/// details on the differences.
4328/// The option=prof is automatically selected in case of z:y:x>>pf
4329/// where pf is an existing TProfile2D histogram.
4330///
4331/// ### Making a 5D plot using GL
4332///
4333/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
4334/// using OpenGL. See $ROOTSYS/tutorials/io/tree/tree502_staff.C as example.
4335///
4336/// ### Making a parallel coordinates plot
4337///
4338/// In case of a 2-Dim or more expression with the option=para, one can generate
4339/// a parallel coordinates plot. With that option, the number of dimensions is
4340/// arbitrary. Giving more than 4 variables without the option=para or
4341/// option=candle or option=goff will produce an error.
4342///
4343/// ### Making a candle sticks chart
4344///
4345/// In case of a 2-Dim or more expression with the option=candle, one can generate
4346/// a candle sticks chart. With that option, the number of dimensions is
4347/// arbitrary. Giving more than 4 variables without the option=para or
4348/// option=candle or option=goff will produce an error.
4349///
4350/// ### Normalizing the output histogram to 1
4351///
4352/// When option contains "norm" the output histogram is normalized to 1.
4353///
4354/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
4355///
4356/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
4357/// instead of histogramming one variable.
4358/// If varexp0 has the form >>elist , a TEventList object named "elist"
4359/// is created in the current directory. elist will contain the list
4360/// of entry numbers satisfying the current selection.
4361/// If option "entrylist" is used, a TEntryList object is created
4362/// If the selection contains arrays, vectors or any container class and option
4363/// "entrylistarray" is used, a TEntryListArray object is created
4364/// containing also the subentries satisfying the selection, i.e. the indices of
4365/// the branches which hold containers classes.
4366/// Example:
4367/// ~~~ {.cpp}
4368/// tree.Draw(">>yplus","y>0")
4369/// ~~~
4370/// will create a TEventList object named "yplus" in the current directory.
4371/// In an interactive session, one can type (after TTree::Draw)
4372/// ~~~ {.cpp}
4373/// yplus.Print("all")
4374/// ~~~
4375/// to print the list of entry numbers in the list.
4376/// ~~~ {.cpp}
4377/// tree.Draw(">>yplus", "y>0", "entrylist")
4378/// ~~~
4379/// will create a TEntryList object names "yplus" in the current directory
4380/// ~~~ {.cpp}
4381/// tree.Draw(">>yplus", "y>0", "entrylistarray")
4382/// ~~~
4383/// will create a TEntryListArray object names "yplus" in the current directory
4384///
4385/// By default, the specified entry list is reset.
4386/// To continue to append data to an existing list, use "+" in front
4387/// of the list name;
4388/// ~~~ {.cpp}
4389/// tree.Draw(">>+yplus","y>0")
4390/// ~~~
4391/// will not reset yplus, but will enter the selected entries at the end
4392/// of the existing list.
4393///
4394/// ### Using a TEventList, TEntryList or TEntryListArray as Input
4395///
4396/// Once a TEventList or a TEntryList object has been generated, it can be used as input
4397/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
4398/// current event list
4399///
4400/// Example 1:
4401/// ~~~ {.cpp}
4402/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
4403/// tree->SetEventList(elist);
4404/// tree->Draw("py");
4405/// ~~~
4406/// Example 2:
4407/// ~~~ {.cpp}
4408/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
4409/// tree->SetEntryList(elist);
4410/// tree->Draw("py");
4411/// ~~~
4412/// If a TEventList object is used as input, a new TEntryList object is created
4413/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
4414/// for this transformation. This new object is owned by the chain and is deleted
4415/// with it, unless the user extracts it by calling GetEntryList() function.
4416/// See also comments to SetEventList() function of TTree and TChain.
4417///
4418/// If arrays are used in the selection criteria and TEntryListArray is not used,
4419/// all the entries that have at least one element of the array that satisfy the selection
4420/// are entered in the list.
4421///
4422/// Example:
4423/// ~~~ {.cpp}
4424/// tree.Draw(">>pyplus","fTracks.fPy>0");
4425/// tree->SetEventList(pyplus);
4426/// tree->Draw("fTracks.fPy");
4427/// ~~~
4428/// will draw the fPy of ALL tracks in event with at least one track with
4429/// a positive fPy.
4430///
4431/// To select only the elements that did match the original selection
4432/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
4433///
4434/// Example:
4435/// ~~~ {.cpp}
4436/// tree.Draw(">>pyplus","fTracks.fPy>0");
4437/// pyplus->SetReapplyCut(true);
4438/// tree->SetEventList(pyplus);
4439/// tree->Draw("fTracks.fPy");
4440/// ~~~
4441/// will draw the fPy of only the tracks that have a positive fPy.
4442///
4443/// To draw only the elements that match a selection in case of arrays,
4444/// you can also use TEntryListArray (faster in case of a more general selection).
4445///
4446/// Example:
4447/// ~~~ {.cpp}
4448/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
4449/// tree->SetEntryList(pyplus);
4450/// tree->Draw("fTracks.fPy");
4451/// ~~~
4452/// will draw the fPy of only the tracks that have a positive fPy,
4453/// but without redoing the selection.
4454///
4455/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
4456///
4457/// ### How to obtain more info from TTree::Draw
4458///
4459/// Once TTree::Draw has been called, it is possible to access useful
4460/// information still stored in the TTree object via the following functions:
4461///
4462/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
4463/// - GetV1() // returns a pointer to the double array of V1
4464/// - GetV2() // returns a pointer to the double array of V2
4465/// - GetV3() // returns a pointer to the double array of V3
4466/// - GetV4() // returns a pointer to the double array of V4
4467/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
4468///
4469/// where V1,V2,V3 correspond to the expressions in
4470/// ~~~ {.cpp}
4471/// TTree::Draw("V1:V2:V3:V4",selection);
4472/// ~~~
4473/// If the expression has more than 4 component use GetVal(index)
4474///
4475/// Example:
4476/// ~~~ {.cpp}
4477/// Root > ntuple->Draw("py:px","pz>4");
4478/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
4479/// ntuple->GetV2(), ntuple->GetV1());
4480/// Root > gr->Draw("ap"); //draw graph in current pad
4481/// ~~~
4482///
4483/// A more complete complete tutorial (treegetval.C) shows how to use the
4484/// GetVal() method.
4485///
4486/// creates a TGraph object with a number of points corresponding to the
4487/// number of entries selected by the expression "pz>4", the x points of the graph
4488/// being the px values of the Tree and the y points the py values.
4489///
4490/// Important note: By default TTree::Draw creates the arrays obtained
4491/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
4492/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
4493/// values calculated.
4494/// By default fEstimate=1000000 and can be modified
4495/// via TTree::SetEstimate. To keep in memory all the results (in case
4496/// where there is only one result per entry), use
4497/// ~~~ {.cpp}
4498/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
4499/// ~~~
4500/// You must call SetEstimate if the expected number of selected rows
4501/// you need to look at is greater than 1000000.
4502///
4503/// You can use the option "goff" to turn off the graphics output
4504/// of TTree::Draw in the above example.
4505///
4506/// ### Automatic interface to TTree::Draw via the TTreeViewer
4507///
4508/// A complete graphical interface to this function is implemented
4509/// in the class TTreeViewer.
4510/// To start the TTreeViewer, three possibilities:
4511/// - select TTree context menu item "StartViewer"
4512/// - type the command "TTreeViewer TV(treeName)"
4513/// - execute statement "tree->StartViewer();"
4516{
4517 GetPlayer();
4518 if (fPlayer)
4520 return -1;
4521}
4522
4523////////////////////////////////////////////////////////////////////////////////
4524/// Remove some baskets from memory.
4526void TTree::DropBaskets()
4527{
4528 TBranch* branch = nullptr;
4530 for (Int_t i = 0; i < nb; ++i) {
4532 branch->DropBaskets("all");
4533 }
4534}
4535
4536////////////////////////////////////////////////////////////////////////////////
4537/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
4540{
4541 // Be careful not to remove current read/write buffers.
4543 for (Int_t i = 0; i < nleaves; ++i) {
4545 TBranch* branch = (TBranch*) leaf->GetBranch();
4546 Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
4547 for (Int_t j = 0; j < nbaskets - 1; ++j) {
4548 if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
4549 continue;
4550 }
4551 TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
4552 if (basket) {
4553 basket->DropBuffers();
4555 return;
4556 }
4557 }
4558 }
4559 }
4560}
4561
4562////////////////////////////////////////////////////////////////////////////////
4563/// Fill all branches.
4564///
4565/// This function loops on all the branches of this tree. For
4566/// each branch, it copies to the branch buffer (basket) the current
4567/// values of the leaves data types. If a leaf is a simple data type,
4568/// a simple conversion to a machine independent format has to be done.
4569///
4570/// This machine independent version of the data is copied into a
4571/// basket (each branch has its own basket). When a basket is full
4572/// (32k worth of data by default), it is then optionally compressed
4573/// and written to disk (this operation is also called committing or
4574/// 'flushing' the basket). The committed baskets are then
4575/// immediately removed from memory.
4576///
4577/// The function returns the number of bytes committed to the
4578/// individual branches.
4579///
4580/// If a write error occurs, the number of bytes returned is -1.
4581///
4582/// If no data are written, because, e.g., the branch is disabled,
4583/// the number of bytes returned is 0.
4584///
4585/// __The baskets are flushed and the Tree header saved at regular intervals__
4586///
4587/// At regular intervals, when the amount of data written so far is
4588/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
4589/// This makes future reading faster as it guarantees that baskets belonging to nearby
4590/// entries will be on the same disk region.
4591/// When the first call to flush the baskets happen, we also take this opportunity
4592/// to optimize the baskets buffers.
4593/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
4594/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
4595/// in case the program writing the Tree crashes.
4596/// The decisions to FlushBaskets and Auto Save can be made based either on the number
4597/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
4598/// written (fAutoFlush and fAutoSave positive).
4599/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
4600/// base on the number of events written instead of the number of bytes written.
4601///
4602/// \note Calling `TTree::FlushBaskets` too often increases the IO time.
4603///
4604/// \note Calling `TTree::AutoSave` too often increases the IO time and also the
4605/// file size.
4606///
4607/// \note This method calls `TTree::ChangeFile` when the tree reaches a size
4608/// greater than `TTree::fgMaxTreeSize`. This doesn't happen if the tree is
4609/// attached to a `TMemFile` or derivate.
4612{
4613 Int_t nbytes = 0;
4614 Int_t nwrite = 0;
4615 Int_t nerror = 0;
4617
4618 // Case of one single super branch. Automatically update
4619 // all the branch addresses if a new object was created.
4620 if (nbranches == 1)
4621 ((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
4622
4623 if (fBranchRef)
4624 fBranchRef->Clear();
4625
4626#ifdef R__USE_IMT
4629 if (useIMT) {
4630 fIMTFlush = true;
4631 fIMTZipBytes.store(0);
4632 fIMTTotBytes.store(0);
4633 }
4634#endif
4635
4636 for (Int_t i = 0; i < nbranches; ++i) {
4637 // Loop over all branches, filling and accumulating bytes written and error counts.
4639
4640 if (branch->TestBit(kDoNotProcess))
4641 continue;
4642
4643#ifndef R__USE_IMT
4644 nwrite = branch->FillImpl(nullptr);
4645#else
4646 nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
4647#endif
4648 if (nwrite < 0) {
4649 if (nerror < 2) {
4650 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
4651 " This error is symptomatic of a Tree created as a memory-resident Tree\n"
4652 " Instead of doing:\n"
4653 " TTree *T = new TTree(...)\n"
4654 " TFile *f = new TFile(...)\n"
4655 " you should do:\n"
4656 " TFile *f = new TFile(...)\n"
4657 " TTree *T = new TTree(...)\n\n",
4658 GetName(), branch->GetName(), nwrite, fEntries + 1);
4659 } else {
4660 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
4661 fEntries + 1);
4662 }
4663 ++nerror;
4664 } else {
4665 nbytes += nwrite;
4666 }
4667 }
4668
4669#ifdef R__USE_IMT
4670 if (fIMTFlush) {
4671 imtHelper.Wait();
4672 fIMTFlush = false;
4673 const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
4674 const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
4675 nbytes += imtHelper.GetNbytes();
4676 nerror += imtHelper.GetNerrors();
4677 }
4678#endif
4679
4680 if (fBranchRef)
4681 fBranchRef->Fill();
4682
4683 ++fEntries;
4684
4685 if (fEntries > fMaxEntries)
4686 KeepCircular();
4687
4688 if (gDebug > 0)
4689 Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
4691
4692 bool autoFlush = false;
4693 bool autoSave = false;
4694
4695 if (fAutoFlush != 0 || fAutoSave != 0) {
4696 // Is it time to flush or autosave baskets?
4697 if (fFlushedBytes == 0) {
4698 // If fFlushedBytes == 0, it means we never flushed or saved, so
4699 // we need to check if it's time to do it and recompute the values
4700 // of fAutoFlush and fAutoSave in terms of the number of entries.
4701 // Decision can be based initially either on the number of bytes
4702 // or the number of entries written.
4704
4705 if (fAutoFlush)
4707
4708 if (fAutoSave)
4709 autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
4710
4711 if (autoFlush || autoSave) {
4712 // First call FlushBasket to make sure that fTotBytes is up to date.
4714 autoFlush = false; // avoid auto flushing again later
4715
4716 // When we are in one-basket-per-cluster mode, there is no need to optimize basket:
4717 // they will automatically grow to the size needed for an event cluster (with the basket
4718 // shrinking preventing them from growing too much larger than the actually-used space).
4720 OptimizeBaskets(GetTotBytes(), 1, "");
4721 if (gDebug > 0)
4722 Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
4724 }
4726 fAutoFlush = fEntries; // Use test on entries rather than bytes
4727
4728 // subsequently in run
4729 if (fAutoSave < 0) {
4730 // Set fAutoSave to the largest integer multiple of
4731 // fAutoFlush events such that fAutoSave*fFlushedBytes
4732 // < (minus the input value of fAutoSave)
4734 if (zipBytes != 0) {
4736 } else if (totBytes != 0) {
4738 } else {
4740 TTree::Class()->WriteBuffer(b, (TTree *)this);
4741 Long64_t total = b.Length();
4743 }
4744 } else if (fAutoSave > 0) {
4746 }
4747
4748 if (fAutoSave != 0 && fEntries >= fAutoSave)
4749 autoSave = true;
4750
4751 if (gDebug > 0)
4752 Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
4753 }
4754 } else {
4755 // Check if we need to auto flush
4756 if (fAutoFlush) {
4757 if (fNClusterRange == 0)
4758 autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
4759 else
4761 }
4762 // Check if we need to auto save
4763 if (fAutoSave)
4764 autoSave = fEntries % fAutoSave == 0;
4765 }
4766 }
4767
4768 if (autoFlush) {
4770 if (gDebug > 0)
4771 Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
4774 }
4775
4776 if (autoSave) {
4777 AutoSave(); // does not call FlushBasketsImpl() again
4778 if (gDebug > 0)
4779 Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
4781 }
4782
4783 // Check that output file is still below the maximum size.
4784 // If above, close the current file and continue on a new file.
4785 // Currently, the automatic change of file is restricted
4786 // to the case where the tree is in the top level directory.
4787 if (fDirectory)
4788 if (TFile *file = fDirectory->GetFile())
4789 if (static_cast<TDirectory *>(file) == fDirectory && (file->GetEND() > fgMaxTreeSize))
4790 ChangeFile(file);
4791
4792 return nerror == 0 ? nbytes : -1;
4793}
4794
4795////////////////////////////////////////////////////////////////////////////////
4796/// Search in the array for a branch matching the branch name,
4797/// with the branch possibly expressed as a 'full' path name (with dots).
4799static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
4800 if (list==nullptr || branchname == nullptr || branchname[0] == '\0') return nullptr;
4801
4802 Int_t nbranches = list->GetEntries();
4803
4805
4806 for(Int_t index = 0; index < nbranches; ++index) {
4807 TBranch *where = (TBranch*)list->UncheckedAt(index);
4808
4809 const char *name = where->GetName();
4810 UInt_t len = strlen(name);
4811 if (len && name[len-1]==']') {
4812 const char *dim = strchr(name,'[');
4813 if (dim) {
4814 len = dim - name;
4815 }
4816 }
4817 if (brlen == len && strncmp(branchname,name,len)==0) {
4818 return where;
4819 }
4820 TBranch *next = nullptr;
4821 if ((brlen >= len) && (branchname[len] == '.')
4822 && strncmp(name, branchname, len) == 0) {
4823 // The prefix subbranch name match the branch name.
4824
4825 next = where->FindBranch(branchname);
4826 if (!next) {
4827 next = where->FindBranch(branchname+len+1);
4828 }
4829 if (next) return next;
4830 }
4831 const char *dot = strchr((char*)branchname,'.');
4832 if (dot) {
4833 if (len==(size_t)(dot-branchname) &&
4834 strncmp(branchname,name,dot-branchname)==0 ) {
4835 return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
4836 }
4837 }
4838 }
4839 return nullptr;
4840}
4841
4842////////////////////////////////////////////////////////////////////////////////
4843/// Return the branch that correspond to the path 'branchname', which can
4844/// include the name of the tree or the omitted name of the parent branches.
4845/// In case of ambiguity, returns the first match.
4848{
4849 // We already have been visited while recursively looking
4850 // through the friends tree, let return
4852 return nullptr;
4853 }
4854
4855 if (!branchname)
4856 return nullptr;
4857
4858 TBranch* branch = nullptr;
4859 // If the first part of the name match the TTree name, look for the right part in the
4860 // list of branches.
4861 // This will allow the branchname to be preceded by
4862 // the name of this tree.
4863 if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
4865 if (branch) return branch;
4866 }
4867 // If we did not find it, let's try to find the full name in the list of branches.
4869 if (branch) return branch;
4870
4871 // If we still did not find, let's try to find it within each branch assuming it does not the branch name.
4872 TIter next(GetListOfBranches());
4873 while ((branch = (TBranch*) next())) {
4874 TBranch* nestedbranch = branch->FindBranch(branchname);
4875 if (nestedbranch) {
4876 return nestedbranch;
4877 }
4878 }
4879
4880 // Search in list of friends.
4881 if (!fFriends) {
4882 return nullptr;
4883 }
4884 TFriendLock lock(this, kFindBranch);
4886 TFriendElement* fe = nullptr;
4887 while ((fe = (TFriendElement*) nextf())) {
4888 TTree* t = fe->GetTree();
4889 if (!t) {
4890 continue;
4891 }
4892 // If the alias is present replace it with the real name.
4893 const char *subbranch = strstr(branchname, fe->GetName());
4894 if (subbranch != branchname) {
4895 subbranch = nullptr;
4896 }
4897 if (subbranch) {
4898 subbranch += strlen(fe->GetName());
4899 if (*subbranch != '.') {
4900 subbranch = nullptr;
4901 } else {
4902 ++subbranch;
4903 }
4904 }
4905 std::ostringstream name;
4906 if (subbranch) {
4907 name << t->GetName() << "." << subbranch;
4908 } else {
4909 name << branchname;
4910 }
4911 branch = t->FindBranch(name.str().c_str());
4912 if (branch) {
4913 return branch;
4914 }
4915 }
4916 return nullptr;
4917}
4918
4919////////////////////////////////////////////////////////////////////////////////
4920/// Find leaf..
4922TLeaf* TTree::FindLeaf(const char* searchname)
4923{
4924 if (!searchname)
4925 return nullptr;
4926
4927 // We already have been visited while recursively looking
4928 // through the friends tree, let's return.
4930 return nullptr;
4931 }
4932
4933 // This will allow the branchname to be preceded by
4934 // the name of this tree.
4935 const char* subsearchname = strstr(searchname, GetName());
4936 if (subsearchname != searchname) {
4937 subsearchname = nullptr;
4938 }
4939 if (subsearchname) {
4941 if (*subsearchname != '.') {
4942 subsearchname = nullptr;
4943 } else {
4944 ++subsearchname;
4945 if (subsearchname[0] == 0) {
4946 subsearchname = nullptr;
4947 }
4948 }
4949 }
4950
4955
4956 const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
4957
4958 // For leaves we allow for one level up to be prefixed to the name.
4959 TIter next(GetListOfLeaves());
4960 TLeaf* leaf = nullptr;
4961 while ((leaf = (TLeaf*) next())) {
4962 leafname = leaf->GetName();
4963 Ssiz_t dim = leafname.First('[');
4964 if (dim >= 0) leafname.Remove(dim);
4965
4966 if (leafname == searchname) {
4967 return leaf;
4968 }
4970 return leaf;
4971 }
4972 // The TLeafElement contains the branch name
4973 // in its name, let's use the title.
4974 leaftitle = leaf->GetTitle();
4975 dim = leaftitle.First('[');
4976 if (dim >= 0) leaftitle.Remove(dim);
4977
4978 if (leaftitle == searchname) {
4979 return leaf;
4980 }
4982 return leaf;
4983 }
4984 if (!searchnameHasDot)
4985 continue;
4986 TBranch* branch = leaf->GetBranch();
4987 if (branch) {
4988 longname.Form("%s.%s",branch->GetName(),leafname.Data());
4989 dim = longname.First('[');
4990 if (dim>=0) longname.Remove(dim);
4991 if (longname == searchname) {
4992 return leaf;
4993 }
4995 return leaf;
4996 }
4997 longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
4998 dim = longtitle.First('[');
4999 if (dim>=0) longtitle.Remove(dim);
5000 if (longtitle == searchname) {
5001 return leaf;
5002 }
5004 return leaf;
5005 }
5006 // The following is for the case where the branch is only
5007 // a sub-branch. Since we do not see it through
5008 // TTree::GetListOfBranches, we need to see it indirectly.
5009 // This is the less sturdy part of this search ... it may
5010 // need refining ...
5011 if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
5012 return leaf;
5013 }
5014 if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
5015 return leaf;
5016 }
5017 }
5018 }
5019 // Search in list of friends.
5020 if (!fFriends) {
5021 return nullptr;
5022 }
5023 TFriendLock lock(this, kFindLeaf);
5025 TFriendElement* fe = nullptr;
5026 while ((fe = (TFriendElement*) nextf())) {
5027 TTree* t = fe->GetTree();
5028 if (!t) {
5029 continue;
5030 }
5031 // If the alias is present replace it with the real name.
5032 subsearchname = strstr(searchname, fe->GetName());
5033 if (subsearchname != searchname) {
5034 subsearchname = nullptr;
5035 }
5036 if (subsearchname) {
5037 subsearchname += strlen(fe->GetName());
5038 if (*subsearchname != '.') {
5039 subsearchname = nullptr;
5040 } else {
5041 ++subsearchname;
5042 }
5043 }
5044 if (subsearchname) {
5045 leafname.Form("%s.%s",t->GetName(),subsearchname);
5046 } else {
5048 }
5049 leaf = t->FindLeaf(leafname);
5050 if (leaf) {
5051 return leaf;
5052 }
5053 }
5054 return nullptr;
5055}
5056
5057////////////////////////////////////////////////////////////////////////////////
5058/// Fit a projected item(s) from a tree.
5059///
5060/// funcname is a TF1 function.
5061///
5062/// See TTree::Draw() for explanations of the other parameters.
5063///
5064/// By default the temporary histogram created is called htemp.
5065/// If varexp contains >>hnew , the new histogram created is called hnew
5066/// and it is kept in the current directory.
5067///
5068/// The function returns the number of selected entries.
5069///
5070/// Example:
5071/// ~~~ {.cpp}
5072/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
5073/// ~~~
5074/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
5075/// directory.
5076///
5077/// See also TTree::UnbinnedFit
5078///
5079/// ## Return status
5080///
5081/// The function returns the status of the histogram fit (see TH1::Fit)
5082/// If no entries were selected, the function returns -1;
5083/// (i.e. fitResult is null if the fit is OK)
5086{
5087 GetPlayer();
5088 if (fPlayer) {
5090 }
5091 return -1;
5092}
5093
5094namespace {
5095struct BoolRAIIToggle {
5096 bool &m_val;
5097
5098 BoolRAIIToggle(bool &val) : m_val(val) { m_val = true; }
5099 ~BoolRAIIToggle() { m_val = false; }
5100};
5101}
5102
5103////////////////////////////////////////////////////////////////////////////////
5104/// Write to disk all the basket that have not yet been individually written and
5105/// create an event cluster boundary (by default).
5106///
5107/// If the caller wishes to flush the baskets but not create an event cluster,
5108/// then set create_cluster to false.
5109///
5110/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
5111/// via TThreadExecutor to do this operation; one per basket compression. If the
5112/// caller utilizes TBB also, care must be taken to prevent deadlocks.
5113///
5114/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
5115/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
5116/// run another one of the user's tasks in this thread. If the second user task
5117/// tries to acquire A, then a deadlock will occur. The example call sequence
5118/// looks like this:
5119///
5120/// - User acquires mutex A
5121/// - User calls FlushBaskets.
5122/// - ROOT launches N tasks and calls wait.
5123/// - TBB schedules another user task, T2.
5124/// - T2 tries to acquire mutex A.
5125///
5126/// At this point, the thread will deadlock: the code may function with IMT-mode
5127/// disabled if the user assumed the legacy code never would run their own TBB
5128/// tasks.
5129///
5130/// SO: users of TBB who want to enable IMT-mode should carefully review their
5131/// locking patterns and make sure they hold no coarse-grained application
5132/// locks when they invoke ROOT.
5133///
5134/// Return the number of bytes written or -1 in case of write error.
5136{
5138 if (retval == -1) return retval;
5139
5140 if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
5141 return retval;
5142}
5143
5144////////////////////////////////////////////////////////////////////////////////
5145/// Internal implementation of the FlushBaskets algorithm.
5146/// Unlike the public interface, this does NOT create an explicit event cluster
5147/// boundary; it is up to the (internal) caller to determine whether that should
5148/// done.
5149///
5150/// Otherwise, the comments for FlushBaskets applies.
5153{
5154 if (!fDirectory) return 0;
5155 Int_t nbytes = 0;
5156 Int_t nerror = 0;
5157 TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
5158 Int_t nb = lb->GetEntriesFast();
5159
5160#ifdef R__USE_IMT
5162 if (useIMT) {
5163 // ROOT-9668: here we need to check if the size of fSortedBranches is different from the
5164 // size of the list of branches before triggering the initialisation of the fSortedBranches
5165 // container to cover two cases:
5166 // 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
5167 // 2. We flushed at least once already but a branch has been be added to the tree since then
5168 if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
5169
5170 BoolRAIIToggle sentry(fIMTFlush);
5171 fIMTZipBytes.store(0);
5172 fIMTTotBytes.store(0);
5173 std::atomic<Int_t> nerrpar(0);
5174 std::atomic<Int_t> nbpar(0);
5175 std::atomic<Int_t> pos(0);
5176
5177 auto mapFunction = [&]() {
5178 // The branch to process is obtained when the task starts to run.
5179 // This way, since branches are sorted, we make sure that branches
5180 // leading to big tasks are processed first. If we assigned the
5181 // branch at task creation time, the scheduler would not necessarily
5182 // respect our sorting.
5183 Int_t j = pos.fetch_add(1);
5184
5185 auto branch = fSortedBranches[j].second;
5186 if (R__unlikely(!branch)) { return; }
5187
5188 if (R__unlikely(gDebug > 0)) {
5189 std::stringstream ss;
5190 ss << std::this_thread::get_id();
5191 Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
5192 Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5193 }
5194
5195 Int_t nbtask = branch->FlushBaskets();
5196
5197 if (nbtask < 0) { nerrpar++; }
5198 else { nbpar += nbtask; }
5199 };
5200
5202 pool.Foreach(mapFunction, nb);
5203
5204 fIMTFlush = false;
5205 const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
5206 const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
5207
5208 return nerrpar ? -1 : nbpar.load();
5209 }
5210#endif
5211 for (Int_t j = 0; j < nb; j++) {
5212 TBranch* branch = (TBranch*) lb->UncheckedAt(j);
5213 if (branch) {
5214 Int_t nwrite = branch->FlushBaskets();
5215 if (nwrite<0) {
5216 ++nerror;
5217 } else {
5218 nbytes += nwrite;
5219 }
5220 }
5221 }
5222 if (nerror) {
5223 return -1;
5224 } else {
5225 return nbytes;
5226 }
5227}
5228
5229////////////////////////////////////////////////////////////////////////////////
5230/// Returns the expanded value of the alias. Search in the friends if any.
5232const char* TTree::GetAlias(const char* aliasName) const
5233{
5234 // We already have been visited while recursively looking
5235 // through the friends tree, let's return.
5237 return nullptr;
5238 }
5239 if (fAliases) {
5241 if (alias) {
5242 return alias->GetTitle();
5243 }
5244 }
5245 if (!fFriends) {
5246 return nullptr;
5247 }
5248 TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
5250 TFriendElement* fe = nullptr;
5251 while ((fe = (TFriendElement*) nextf())) {
5252 TTree* t = fe->GetTree();
5253 if (t) {
5254 const char* alias = t->GetAlias(aliasName);
5255 if (alias) {
5256 return alias;
5257 }
5258 const char* subAliasName = strstr(aliasName, fe->GetName());
5259 if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
5260 alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
5261 if (alias) {
5262 return alias;
5263 }
5264 }
5265 }
5266 }
5267 return nullptr;
5268}
5269
5270namespace {
5271/// Do a breadth first search through the implied hierarchy
5272/// of branches.
5273/// To avoid scanning through the list multiple time
5274/// we also remember the 'depth-first' match.
5275TBranch *R__GetBranch(const TObjArray &branches, const char *name)
5276{
5277 TBranch *result = nullptr;
5278 Int_t nb = branches.GetEntriesFast();
5279 for (Int_t i = 0; i < nb; i++) {
5280 TBranch* b = (TBranch*)branches.UncheckedAt(i);
5281 if (!b)
5282 continue;
5283 if (!strcmp(b->GetName(), name)) {
5284 return b;
5285 }
5286 if (!strcmp(b->GetFullName(), name)) {
5287 return b;
5288 }
5289 if (!result)
5290 result = R__GetBranch(*(b->GetListOfBranches()), name);
5291 }
5292 return result;
5293}
5294}
5295
5296////////////////////////////////////////////////////////////////////////////////
5297/// Return pointer to the branch with the given name in this tree or its friends.
5298/// The search is done breadth first.
5300TBranch* TTree::GetBranch(const char* name)
5301{
5302 // We already have been visited while recursively
5303 // looking through the friends tree, let's return.
5305 return nullptr;
5306 }
5307
5308 if (!name)
5309 return nullptr;
5310
5311 // Look for an exact match in the list of top level
5312 // branches.
5314 if (result)
5315 return result;
5316
5317 // Search using branches, breadth first.
5319 if (result)
5320 return result;
5321
5322 // Search using leaves.
5324 Int_t nleaves = leaves->GetEntriesFast();
5325 for (Int_t i = 0; i < nleaves; i++) {
5326 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
5327 TBranch* branch = leaf->GetBranch();
5328 if (!strcmp(branch->GetName(), name)) {
5329 return branch;
5330 }
5331 if (!strcmp(branch->GetFullName(), name)) {
5332 return branch;
5333 }
5334 }
5335
5336 if (!fFriends) {
5337 return nullptr;
5338 }
5339
5340 // Search in list of friends.
5341 TFriendLock lock(this, kGetBranch);
5342 TIter next(fFriends);
5343 TFriendElement* fe = nullptr;
5344 while ((fe = (TFriendElement*) next())) {
5345 TTree* t = fe->GetTree();
5346 if (t) {
5348 if (branch) {
5349 return branch;
5350 }
5351 }
5352 }
5353
5354 // Second pass in the list of friends when
5355 // the branch name is prefixed by the tree name.
5356 next.Reset();
5357 while ((fe = (TFriendElement*) next())) {
5358 TTree* t = fe->GetTree();
5359 if (!t) {
5360 continue;
5361 }
5362 const char* subname = strstr(name, fe->GetName());
5363 if (subname != name) {
5364 continue;
5365 }
5366 Int_t l = strlen(fe->GetName());
5367 subname += l;
5368 if (*subname != '.') {
5369 continue;
5370 }
5371 subname++;
5373 if (branch) {
5374 return branch;
5375 }
5376 }
5377 return nullptr;
5378}
5379
5380////////////////////////////////////////////////////////////////////////////////
5381/// Return status of branch with name branchname.
5382///
5383/// - 0 if branch is not activated
5384/// - 1 if branch is activated
5386bool TTree::GetBranchStatus(const char* branchname) const
5387{
5388 TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
5389 if (br) {
5390 return br->TestBit(kDoNotProcess) == 0;
5391 }
5392 return false;
5393}
5394
5395////////////////////////////////////////////////////////////////////////////////
5396/// Static function returning the current branch style.
5397///
5398/// - style = 0 old Branch
5399/// - style = 1 new Bronch
5404}
5405
5406////////////////////////////////////////////////////////////////////////////////
5407/// Used for automatic sizing of the cache.
5408///
5409/// Estimates a suitable size for the tree cache based on AutoFlush.
5410/// A cache sizing factor is taken from the configuration. If this yields zero
5411/// and withDefault is true the historical algorithm for default size is used.
5413Long64_t TTree::GetCacheAutoSize(bool withDefault /* = false */ )
5414{
5416 {
5417 Long64_t cacheSize = 0;
5418 if (fAutoFlush < 0) {
5419 cacheSize = Long64_t(-cacheFactor * fAutoFlush);
5420 } else if (fAutoFlush == 0) {
5422 if (medianClusterSize > 0)
5423 cacheSize = Long64_t(cacheFactor * 1.5 * medianClusterSize * GetZipBytes() / (fEntries + 1));
5424 else
5425 cacheSize = Long64_t(cacheFactor * 1.5 * 30000000); // use the default value of fAutoFlush
5426 } else {
5427 cacheSize = Long64_t(cacheFactor * 1.5 * fAutoFlush * GetZipBytes() / (fEntries + 1));
5428 }
5429 if (cacheSize >= (INT_MAX / 4)) {
5430 cacheSize = INT_MAX / 4;
5431 }
5432 return cacheSize;
5433 };
5434
5435 const char *stcs;
5436 Double_t cacheFactor = 0.0;
5437 if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
5438 cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
5439 } else {
5441 }
5442
5443 if (cacheFactor < 0.0) {
5444 // ignore negative factors
5445 cacheFactor = 0.0;
5446 }
5447
5449
5450 if (cacheSize < 0) {
5451 cacheSize = 0;
5452 }
5453
5454 if (cacheSize == 0 && withDefault) {
5455 cacheSize = calculateCacheSize(1.0);
5456 }
5457
5458 return cacheSize;
5459}
5460
5461////////////////////////////////////////////////////////////////////////////////
5462/// Return an iterator over the cluster of baskets starting at firstentry.
5463///
5464/// This iterator is not yet supported for TChain object.
5465/// ~~~ {.cpp}
5466/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
5467/// Long64_t clusterStart;
5468/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
5469/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
5470/// }
5471/// ~~~
5474{
5475 // create cache if wanted
5476 if (fCacheDoAutoInit)
5478
5479 return TClusterIterator(this,firstentry);
5480}
5481
5482////////////////////////////////////////////////////////////////////////////////
5483/// Return pointer to the current file.
5486{
5487 if (!fDirectory || fDirectory==gROOT) {
5488 return nullptr;
5489 }
5490 return fDirectory->GetFile();
5491}
5492
5493////////////////////////////////////////////////////////////////////////////////
5494/// Return the number of entries matching the selection.
5495/// Return -1 in case of errors.
5496///
5497/// If the selection uses any arrays or containers, we return the number
5498/// of entries where at least one element match the selection.
5499/// GetEntries is implemented using the selector class TSelectorEntries,
5500/// which can be used directly (see code in TTreePlayer::GetEntries) for
5501/// additional option.
5502/// If SetEventList was used on the TTree or TChain, only that subset
5503/// of entries will be considered.
5506{
5507 GetPlayer();
5508 if (fPlayer) {
5509 return fPlayer->GetEntries(selection);
5510 }
5511 return -1;
5512}
5513
5514////////////////////////////////////////////////////////////////////////////////
5515/// Return pointer to the 1st Leaf named name in any Branch of this Tree or
5516/// any branch in the list of friend trees.
5519{
5520 if (fEntries) return fEntries;
5521 if (!fFriends) return 0;
5523 if (!fr) return 0;
5524 TTree *t = fr->GetTree();
5525 if (t==nullptr) return 0;
5526 return t->GetEntriesFriend();
5527}
5528
5529////////////////////////////////////////////////////////////////////////////////
5530/// Read all branches of entry and return total number of bytes read.
5531///
5532/// - `getall = 0` : get only active branches
5533/// - `getall = 1` : get all branches
5534///
5535/// The function returns the number of bytes read from the input buffer.
5536/// If entry does not exist the function returns 0.
5537/// If an I/O error occurs, the function returns -1.
5538/// If all branches are disabled and getall == 0, it also returns 0
5539/// even if the specified entry exists in the tree, since zero bytes were read.
5540///
5541/// If the Tree has friends, also read the friends entry.
5542///
5543/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
5544/// For example, if you have a Tree with several hundred branches, and you
5545/// are interested only by branches named "a" and "b", do
5546/// ~~~ {.cpp}
5547/// mytree.SetBranchStatus("*",0); //disable all branches
5548/// mytree.SetBranchStatus("a",1);
5549/// mytree.SetBranchStatus("b",1);
5550/// ~~~
5551/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
5552///
5553/// __WARNING!!__
5554/// If your Tree has been created in split mode with a parent branch "parent.",
5555/// ~~~ {.cpp}
5556/// mytree.SetBranchStatus("parent",1);
5557/// ~~~
5558/// will not activate the sub-branches of "parent". You should do:
5559/// ~~~ {.cpp}
5560/// mytree.SetBranchStatus("parent*",1);
5561/// ~~~
5562/// Without the trailing dot in the branch creation you have no choice but to
5563/// call SetBranchStatus explicitly for each of the sub branches.
5564///
5565/// An alternative is to call directly
5566/// ~~~ {.cpp}
5567/// brancha.GetEntry(i)
5568/// branchb.GetEntry(i);
5569/// ~~~
5570/// ## IMPORTANT NOTE
5571///
5572/// By default, GetEntry reuses the space allocated by the previous object
5573/// for each branch. You can force the previous object to be automatically
5574/// deleted if you call mybranch.SetAutoDelete(true) (default is false).
5575///
5576/// Example:
5577///
5578/// Consider the example in $ROOTSYS/test/Event.h
5579/// The top level branch in the tree T is declared with:
5580/// ~~~ {.cpp}
5581/// Event *event = 0; //event must be null or point to a valid object
5582/// //it must be initialized
5583/// T.SetBranchAddress("event",&event);
5584/// ~~~
5585/// When reading the Tree, one can choose one of these 3 options:
5586///
5587/// ## OPTION 1
5588///
5589/// ~~~ {.cpp}
5590/// for (Long64_t i=0;i<nentries;i++) {
5591/// T.GetEntry(i);
5592/// // the object event has been filled at this point
5593/// }
5594/// ~~~
5595/// The default (recommended). At the first entry an object of the class
5596/// Event will be created and pointed by event. At the following entries,
5597/// event will be overwritten by the new data. All internal members that are
5598/// TObject* are automatically deleted. It is important that these members
5599/// be in a valid state when GetEntry is called. Pointers must be correctly
5600/// initialized. However these internal members will not be deleted if the
5601/// characters "->" are specified as the first characters in the comment
5602/// field of the data member declaration.
5603///
5604/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
5605/// In this case, it is assumed that the pointer is never null (case of
5606/// pointer TClonesArray *fTracks in the Event example). If "->" is not
5607/// specified, the pointer member is read via buf >> pointer. In this case
5608/// the pointer may be null. Note that the option with "->" is faster to
5609/// read or write and it also consumes less space in the file.
5610///
5611/// ## OPTION 2
5612///
5613/// The option AutoDelete is set
5614/// ~~~ {.cpp}
5615/// TBranch *branch = T.GetBranch("event");
5616/// branch->SetAddress(&event);
5617/// branch->SetAutoDelete(true);
5618/// for (Long64_t i=0;i<nentries;i++) {
5619/// T.GetEntry(i);
5620/// // the object event has been filled at this point
5621/// }
5622/// ~~~
5623/// In this case, at each iteration, the object event is deleted by GetEntry
5624/// and a new instance of Event is created and filled.
5625///
5626/// ## OPTION 3
5627///
5628/// ~~~ {.cpp}
5629/// Same as option 1, but you delete yourself the event.
5630///
5631/// for (Long64_t i=0;i<nentries;i++) {
5632/// delete event;
5633/// event = 0; // EXTREMELY IMPORTANT
5634/// T.GetEntry(i);
5635/// // the object event has been filled at this point
5636/// }
5637/// ~~~
5638/// It is strongly recommended to use the default option 1. It has the
5639/// additional advantage that functions like TTree::Draw (internally calling
5640/// TTree::GetEntry) will be functional even when the classes in the file are
5641/// not available.
5642///
5643/// Note: See the comments in TBranchElement::SetAddress() for the
5644/// object ownership policy of the underlying (user) data.
5647{
5648 // We already have been visited while recursively looking
5649 // through the friends tree, let return
5650 if (kGetEntry & fFriendLockStatus) return 0;
5651
5652 if (entry < 0 || entry >= fEntries) return 0;
5653 Int_t i;
5654 Int_t nbytes = 0;
5655 fReadEntry = entry;
5656
5657 // create cache if wanted
5658 if (fCacheDoAutoInit)
5660
5662 Int_t nb=0;
5663
5664 auto seqprocessing = [&]() {
5665 TBranch *branch;
5666 for (i=0;i<nbranches;i++) {
5668 nb = branch->GetEntry(entry, getall);
5669 if (nb < 0) break;
5670 nbytes += nb;
5671 }
5672 };
5673
5674#ifdef R__USE_IMT
5676 if (fSortedBranches.empty())
5678
5679 // Count branches are processed first and sequentially
5680 for (auto branch : fSeqBranches) {
5681 nb = branch->GetEntry(entry, getall);
5682 if (nb < 0) break;
5683 nbytes += nb;
5684 }
5685 if (nb < 0) return nb;
5686
5687 // Enable this IMT use case (activate its locks)
5689
5690 Int_t errnb = 0;
5691 std::atomic<Int_t> pos(0);
5692 std::atomic<Int_t> nbpar(0);
5693
5694 auto mapFunction = [&]() {
5695 // The branch to process is obtained when the task starts to run.
5696 // This way, since branches are sorted, we make sure that branches
5697 // leading to big tasks are processed first. If we assigned the
5698 // branch at task creation time, the scheduler would not necessarily
5699 // respect our sorting.
5700 Int_t j = pos.fetch_add(1);
5701
5702 Int_t nbtask = 0;
5703 auto branch = fSortedBranches[j].second;
5704
5705 if (gDebug > 0) {
5706 std::stringstream ss;
5707 ss << std::this_thread::get_id();
5708 Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
5709 Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5710 }
5711
5712 std::chrono::time_point<std::chrono::system_clock> start, end;
5713
5714 start = std::chrono::system_clock::now();
5715 nbtask = branch->GetEntry(entry, getall);
5716 end = std::chrono::system_clock::now();
5717
5718 Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
5719 fSortedBranches[j].first += tasktime;
5720
5721 if (nbtask < 0) errnb = nbtask;
5722 else nbpar += nbtask;
5723 };
5724
5726 pool.Foreach(mapFunction, fSortedBranches.size());
5727
5728 if (errnb < 0) {
5729 nb = errnb;
5730 }
5731 else {
5732 // Save the number of bytes read by the tasks
5733 nbytes += nbpar;
5734
5735 // Re-sort branches if necessary
5739 }
5740 }
5741 }
5742 else {
5743 seqprocessing();
5744 }
5745#else
5746 seqprocessing();
5747#endif
5748 if (nb < 0) return nb;
5749
5750 // GetEntry in list of friends
5751 if (!fFriends) return nbytes;
5752 TFriendLock lock(this,kGetEntry);
5755 while ((fe = (TFriendElement*)nextf())) {
5756 TTree *t = fe->GetTree();
5757 if (t) {
5758 if (fe->TestBit(TFriendElement::kFromChain)) {
5759 nb = t->GetEntry(t->GetReadEntry(),getall);
5760 } else {
5761 if ( t->LoadTreeFriend(entry,this) >= 0 ) {
5762 nb = t->GetEntry(t->GetReadEntry(),getall);
5763 } else nb = 0;
5764 }
5765 if (nb < 0) return nb;
5766 nbytes += nb;
5767 }
5768 }
5769 return nbytes;
5770}
5771
5772
5773////////////////////////////////////////////////////////////////////////////////
5774/// Divides the top-level branches into two vectors: (i) branches to be
5775/// processed sequentially and (ii) branches to be processed in parallel.
5776/// Even if IMT is on, some branches might need to be processed first and in a
5777/// sequential fashion: in the parallelization of GetEntry, those are the
5778/// branches that store the size of another branch for every entry
5779/// (e.g. the size of an array branch). If such branches were processed
5780/// in parallel with the rest, there could be two threads invoking
5781/// TBranch::GetEntry on one of them at the same time, since a branch that
5782/// depends on a size (or count) branch will also invoke GetEntry on the latter.
5783/// This method can be invoked several times during the event loop if the TTree
5784/// is being written, for example when adding new branches. In these cases, the
5785/// `checkLeafCount` parameter is false.
5786/// \param[in] checkLeafCount True if we need to check whether some branches are
5787/// count leaves.
5790{
5792
5793 // The special branch fBranchRef needs to be processed sequentially:
5794 // we add it once only.
5795 if (fBranchRef && fBranchRef != fSeqBranches[0]) {
5796 fSeqBranches.push_back(fBranchRef);
5797 }
5798
5799 // The branches to be processed sequentially are those that are the leaf count of another branch
5800 if (checkLeafCount) {
5801 for (Int_t i = 0; i < nbranches; i++) {
5803 auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
5804 if (leafCount) {
5805 auto countBranch = leafCount->GetBranch();
5806 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
5807 fSeqBranches.push_back(countBranch);
5808 }
5809 }
5810 }
5811 }
5812
5813 // Any branch that is not a leaf count can be safely processed in parallel when reading
5814 // We need to reset the vector to make sure we do not re-add several times the same branch.
5815 if (!checkLeafCount) {
5816 fSortedBranches.clear();
5817 }
5818 for (Int_t i = 0; i < nbranches; i++) {
5819 Long64_t bbytes = 0;
5821 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
5822 bbytes = branch->GetTotBytes("*");
5823 fSortedBranches.emplace_back(bbytes, branch);
5824 }
5825 }
5826
5827 // Initially sort parallel branches by size
5828 std::sort(fSortedBranches.begin(),
5829 fSortedBranches.end(),
5830 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5831 return a.first > b.first;
5832 });
5833
5834 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5835 fSortedBranches[i].first = 0LL;
5836 }
5837}
5838
5839////////////////////////////////////////////////////////////////////////////////
5840/// Sorts top-level branches by the last average task time recorded per branch.
5843{
5844 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5846 }
5847
5848 std::sort(fSortedBranches.begin(),
5849 fSortedBranches.end(),
5850 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5851 return a.first > b.first;
5852 });
5853
5854 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5855 fSortedBranches[i].first = 0LL;
5856 }
5857}
5858
5859////////////////////////////////////////////////////////////////////////////////
5860///Returns the entry list assigned to this tree
5863{
5864 return fEntryList;
5865}
5866
5867////////////////////////////////////////////////////////////////////////////////
5868/// Return entry number corresponding to entry.
5869///
5870/// if no TEntryList set returns entry
5871/// else returns the entry number corresponding to the list index=entry
5874{
5875 if (!fEntryList) {
5876 return entry;
5877 }
5878
5879 return fEntryList->GetEntry(entry);
5880}
5881
5882////////////////////////////////////////////////////////////////////////////////
5883/// Return entry number corresponding to major and minor number.
5884/// Note that this function returns only the entry number, not the data
5885/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5886/// the BuildIndex function has created a table of Long64_t* of sorted values
5887/// corresponding to val = major<<31 + minor;
5888/// The function performs binary search in this sorted table.
5889/// If it finds a pair that matches val, it returns directly the
5890/// index in the table.
5891/// If an entry corresponding to major and minor is not found, the function
5892/// returns the index of the major,minor pair immediately lower than the
5893/// requested value, ie it will return -1 if the pair is lower than
5894/// the first entry in the index.
5895///
5896/// See also GetEntryNumberWithIndex
5904}
5905
5906////////////////////////////////////////////////////////////////////////////////
5907/// Return entry number corresponding to major and minor number.
5908/// Note that this function returns only the entry number, not the data
5909/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5910/// the BuildIndex function has created a table of Long64_t* of sorted values
5911/// corresponding to val = major<<31 + minor;
5912/// The function performs binary search in this sorted table.
5913/// If it finds a pair that matches val, it returns directly the
5914/// index in the table, otherwise it returns -1.
5915///
5916/// See also GetEntryNumberWithBestIndex
5919{
5920 if (!fTreeIndex) {
5921 return -1;
5922 }
5924}
5925
5926////////////////////////////////////////////////////////////////////////////////
5927/// Read entry corresponding to major and minor number.
5928///
5929/// The function returns the total number of bytes read.
5930/// If the Tree has friend trees, the corresponding entry with
5931/// the index values (major,minor) is read. Note that the master Tree
5932/// and its friend may have different entry serial numbers corresponding
5933/// to (major,minor).
5936{
5937 // We already have been visited while recursively looking
5938 // through the friends tree, let's return.
5940 return 0;
5941 }
5943 if (serial < 0) {
5944 return -1;
5945 }
5946 // create cache if wanted
5947 if (fCacheDoAutoInit)
5949
5950 Int_t i;
5951 Int_t nbytes = 0;
5952 fReadEntry = serial;
5953 TBranch *branch;
5955 Int_t nb;
5956 for (i = 0; i < nbranches; ++i) {
5958 nb = branch->GetEntry(serial);
5959 if (nb < 0) return nb;
5960 nbytes += nb;
5961 }
5962 // GetEntry in list of friends
5963 if (!fFriends) return nbytes;
5966 TFriendElement* fe = nullptr;
5967 while ((fe = (TFriendElement*) nextf())) {
5968 TTree *t = fe->GetTree();
5969 if (t) {
5970 serial = t->GetEntryNumberWithIndex(major,minor);
5971 if (serial <0) return -nbytes;
5972 nb = t->GetEntry(serial);
5973 if (nb < 0) return nb;
5974 nbytes += nb;
5975 }
5976 }
5977 return nbytes;
5978}
5979
5980////////////////////////////////////////////////////////////////////////////////
5981/// Return a pointer to the TTree friend whose name or alias is `friendname`.
5983TTree* TTree::GetFriend(const char *friendname) const
5984{
5985
5986 // We already have been visited while recursively
5987 // looking through the friends tree, let's return.
5989 return nullptr;
5990 }
5991 if (!fFriends) {
5992 return nullptr;
5993 }
5994 TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
5996 TFriendElement* fe = nullptr;
5997 while ((fe = (TFriendElement*) nextf())) {
5998 if (strcmp(friendname,fe->GetName())==0
5999 || strcmp(friendname,fe->GetTreeName())==0) {
6000 return fe->GetTree();
6001 }
6002 }
6003 // After looking at the first level,
6004 // let's see if it is a friend of friends.
6005 nextf.Reset();
6006 fe = nullptr;
6007 while ((fe = (TFriendElement*) nextf())) {
6008 TTree *res = fe->GetTree()->GetFriend(friendname);
6009 if (res) {
6010 return res;
6011 }
6012 }
6013 return nullptr;
6014}
6015
6016////////////////////////////////////////////////////////////////////////////////
6017/// If the 'tree' is a friend, this method returns its alias name.
6018///
6019/// This alias is an alternate name for the tree.
6020///
6021/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
6022/// to specify in which particular tree the branch or leaf can be found if
6023/// the friend trees have branches or leaves with the same name as the master
6024/// tree.
6025///
6026/// It can also be used in conjunction with an alias created using
6027/// TTree::SetAlias in a TTreeFormula, e.g.:
6028/// ~~~ {.cpp}
6029/// maintree->Draw("treealias.fPx - treealias.myAlias");
6030/// ~~~
6031/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
6032/// was created using TTree::SetAlias on the friend tree.
6033///
6034/// However, note that 'treealias.myAlias' will be expanded literally,
6035/// without remembering that it comes from the aliased friend and thus
6036/// the branch name might not be disambiguated properly, which means
6037/// that you may not be able to take advantage of this feature.
6038///
6040const char* TTree::GetFriendAlias(TTree* tree) const
6041{
6042 if ((tree == this) || (tree == GetTree())) {
6043 return nullptr;
6044 }
6045
6046 // We already have been visited while recursively
6047 // looking through the friends tree, let's return.
6049 return nullptr;
6050 }
6051 if (!fFriends) {
6052 return nullptr;
6053 }
6054 TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
6056 TFriendElement* fe = nullptr;
6057 while ((fe = (TFriendElement*) nextf())) {
6058 TTree* t = fe->GetTree();
6059 if (t == tree) {
6060 return fe->GetName();
6061 }
6062 // Case of a chain:
6063 if (t && t->GetTree() == tree) {
6064 return fe->GetName();
6065 }
6066 }
6067 // After looking at the first level,
6068 // let's see if it is a friend of friends.
6069 nextf.Reset();
6070 fe = nullptr;
6071 while ((fe = (TFriendElement*) nextf())) {
6072 const char* res = fe->GetTree()->GetFriendAlias(tree);
6073 if (res) {
6074 return res;
6075 }
6076 }
6077 return nullptr;
6078}
6079
6080////////////////////////////////////////////////////////////////////////////////
6081/// Returns the current set of IO settings
6083{
6084 return fIOFeatures;
6085}
6086
6087////////////////////////////////////////////////////////////////////////////////
6088/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
6091{
6092 return new TTreeFriendLeafIter(this, dir);
6093}
6094
6095////////////////////////////////////////////////////////////////////////////////
6096/// Return pointer to the 1st Leaf named name in any Branch of this
6097/// Tree or any branch in the list of friend trees.
6098///
6099/// The leaf name can contain the name of a friend tree with the
6100/// syntax: friend_dir_and_tree.full_leaf_name
6101/// the friend_dir_and_tree can be of the form:
6102/// ~~~ {.cpp}
6103/// TDirectoryName/TreeName
6104/// ~~~
6106TLeaf* TTree::GetLeafImpl(const char* branchname, const char *leafname)
6107{
6108 TLeaf *leaf = nullptr;
6109 if (branchname) {
6111 if (branch) {
6112 leaf = branch->GetLeaf(leafname);
6113 if (leaf) {
6114 return leaf;
6115 }
6116 }
6117 }
6119 while ((leaf = (TLeaf*)nextl())) {
6120 if (strcmp(leaf->GetFullName(), leafname) != 0 && strcmp(leaf->GetName(), leafname) != 0)
6121 continue; // leafname does not match GetName() nor GetFullName(), this is not the right leaf
6122 if (branchname) {
6123 // check the branchname is also a match
6124 TBranch *br = leaf->GetBranch();
6125 // if a quick comparison with the branch full name is a match, we are done
6126 if (!strcmp(br->GetFullName(), branchname))
6127 return leaf;
6129 const char* brname = br->GetName();
6130 TBranch *mother = br->GetMother();
6132 if (mother != br) {
6133 const char *mothername = mother->GetName();
6135 if (!strcmp(mothername, branchname)) {
6136 return leaf;
6137 } else if (nbch > motherlen && strncmp(mothername,branchname,motherlen)==0 && (mothername[motherlen-1]=='.' || branchname[motherlen]=='.')) {
6138 // The left part of the requested name match the name of the mother, let's see if the right part match the name of the branch.
6140 // No it does not
6141 continue;
6142 } // else we have match so we can proceed.
6143 } else {
6144 // no match
6145 continue;
6146 }
6147 } else {
6148 continue;
6149 }
6150 }
6151 // The start of the branch name is identical to the content
6152 // of 'aname' before the first '/'.
6153 // Let's make sure that it is not longer (we are trying
6154 // to avoid having jet2/value match the branch jet23
6155 if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
6156 continue;
6157 }
6158 }
6159 return leaf;
6160 }
6161 if (!fFriends) return nullptr;
6162 TFriendLock lock(this,kGetLeaf);
6163 TIter next(fFriends);
6165 while ((fe = (TFriendElement*)next())) {
6166 TTree *t = fe->GetTree();
6167 if (t) {
6169 if (leaf) return leaf;
6170 }
6171 }
6172
6173 //second pass in the list of friends when the leaf name
6174 //is prefixed by the tree name
6176 next.Reset();
6177 while ((fe = (TFriendElement*)next())) {
6178 TTree *t = fe->GetTree();
6179 if (!t) continue;
6180 const char *subname = strstr(leafname,fe->GetName());
6181 if (subname != leafname) continue;
6182 Int_t l = strlen(fe->GetName());
6183 subname += l;
6184 if (*subname != '.') continue;
6185 subname++;
6188 if (leaf) return leaf;
6189 }
6190 return nullptr;
6191}
6192
6193////////////////////////////////////////////////////////////////////////////////
6194/// Return pointer to the 1st Leaf named name in any Branch of this
6195/// Tree or any branch in the list of friend trees.
6196///
6197/// The leaf name can contain the name of a friend tree with the
6198/// syntax: friend_dir_and_tree.full_leaf_name
6199/// the friend_dir_and_tree can be of the form:
6200///
6201/// TDirectoryName/TreeName
6203TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
6204{
6205 if (leafname == nullptr) return nullptr;
6206
6207 // We already have been visited while recursively looking
6208 // through the friends tree, let return
6210 return nullptr;
6211 }
6212
6214}
6215
6216////////////////////////////////////////////////////////////////////////////////
6217/// Return pointer to first leaf named "name" in any branch of this
6218/// tree or its friend trees.
6219///
6220/// \param[in] name may be in the form 'branch/leaf'
6221///
6223TLeaf* TTree::GetLeaf(const char *name)
6224{
6225 // Return nullptr if name is invalid or if we have
6226 // already been visited while searching friend trees
6227 if (!name || (kGetLeaf & fFriendLockStatus))
6228 return nullptr;
6229
6230 std::string path(name);
6231 const auto sep = path.find_last_of('/');
6232 if (sep != std::string::npos)
6233 return GetLeafImpl(path.substr(0, sep).c_str(), name+sep+1);
6234
6235 return GetLeafImpl(nullptr, name);
6236}
6237
6238////////////////////////////////////////////////////////////////////////////////
6239/// Return maximum of column with name columname.
6240/// if the Tree has an associated TEventList or TEntryList, the maximum
6241/// is computed for the entries in this list.
6244{
6245 TLeaf* leaf = this->GetLeaf(columname);
6246 if (!leaf) {
6247 return 0;
6248 }
6249
6250 // create cache if wanted
6251 if (fCacheDoAutoInit)
6253
6254 TBranch* branch = leaf->GetBranch();
6256 for (Long64_t i = 0; i < fEntries; ++i) {
6258 if (entryNumber < 0) break;
6259 branch->GetEntry(entryNumber);
6260 for (Int_t j = 0; j < leaf->GetLen(); ++j) {
6261 Double_t val = leaf->GetValue(j);
6262 if (val > cmax) {
6263 cmax = val;
6264 }
6265 }
6266 }
6267 return cmax;
6268}
6269
6270////////////////////////////////////////////////////////////////////////////////
6271/// Static function which returns the tree file size limit in bytes.
6276}
6277
6278////////////////////////////////////////////////////////////////////////////////
6279/// Return minimum of column with name columname.
6280/// if the Tree has an associated TEventList or TEntryList, the minimum
6281/// is computed for the entries in this list.
6284{
6285 TLeaf* leaf = this->GetLeaf(columname);
6286 if (!leaf) {
6287 return 0;
6288 }
6289
6290 // create cache if wanted
6291 if (fCacheDoAutoInit)
6293
6294 TBranch* branch = leaf->GetBranch();
6296 for (Long64_t i = 0; i < fEntries; ++i) {
6298 if (entryNumber < 0) break;
6299 branch->GetEntry(entryNumber);
6300 for (Int_t j = 0;j < leaf->GetLen(); ++j) {
6301 Double_t val = leaf->GetValue(j);
6302 if (val < cmin) {
6303 cmin = val;
6304 }
6305 }
6306 }
6307 return cmin;
6308}
6309
6310////////////////////////////////////////////////////////////////////////////////
6311/// Load the TTreePlayer (if not already done).
6314{
6315 if (fPlayer) {
6316 return fPlayer;
6317 }
6319 return fPlayer;
6320}
6321
6322////////////////////////////////////////////////////////////////////////////////
6323/// Find and return the TTreeCache registered with the file and which may
6324/// contain branches for us.
6327{
6328 TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6329 if (pe && pe->GetTree() != GetTree())
6330 pe = nullptr;
6331 return pe;
6332}
6333
6334////////////////////////////////////////////////////////////////////////////////
6335/// Find and return the TTreeCache registered with the file and which may
6336/// contain branches for us. If create is true and there is no cache
6337/// a new cache is created with default size.
6339TTreeCache *TTree::GetReadCache(TFile *file, bool create)
6340{
6341 TTreeCache *pe = GetReadCache(file);
6342 if (create && !pe) {
6343 if (fCacheDoAutoInit)
6344 SetCacheSizeAux(true, -1);
6345 pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6346 if (pe && pe->GetTree() != GetTree()) pe = nullptr;
6347 }
6348 return pe;
6349}
6350
6351////////////////////////////////////////////////////////////////////////////////
6352/// Return a pointer to the list containing user objects associated to this tree.
6353///
6354/// The list is automatically created if it does not exist.
6355///
6356/// WARNING: By default the TTree destructor will delete all objects added
6357/// to this list. If you do not want these objects to be deleted,
6358/// call:
6359///
6360/// mytree->GetUserInfo()->Clear();
6361///
6362/// before deleting the tree.
6365{
6366 if (!fUserInfo) {
6367 fUserInfo = new TList();
6368 fUserInfo->SetName("UserInfo");
6369 }
6370 return fUserInfo;
6371}
6372
6373////////////////////////////////////////////////////////////////////////////////
6374/// Appends the cluster range information stored in 'fromtree' to this tree,
6375/// including the value of fAutoFlush.
6376///
6377/// This is used when doing a fast cloning (by TTreeCloner).
6378/// See also fAutoFlush and fAutoSave if needed.
6381{
6382 Long64_t autoflush = fromtree->GetAutoFlush();
6383 if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
6384 // nothing to do
6385 } else if (fNClusterRange || fromtree->fNClusterRange) {
6386 Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
6387 if (newsize > fMaxClusterRange) {
6388 if (fMaxClusterRange) {
6390 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6392 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6394 } else {
6398 }
6399 }
6400 if (fEntries) {
6404 }
6405 for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
6406 fClusterRangeEnd[fNClusterRange] = fEntries + fromtree->fClusterRangeEnd[i];
6407 fClusterSize[fNClusterRange] = fromtree->fClusterSize[i];
6409 }
6411 } else {
6413 }
6415 if (autoflush > 0 && autosave > 0) {
6417 }
6418}
6419
6420////////////////////////////////////////////////////////////////////////////////
6421/// Keep a maximum of fMaxEntries in memory.
6424{
6427 for (Int_t i = 0; i < nb; ++i) {
6429 branch->KeepCircular(maxEntries);
6430 }
6431 if (fNClusterRange) {
6434 for(Int_t i = 0, j = 0; j < oldsize; ++j) {
6437 ++i;
6438 } else {
6440 }
6441 }
6442 }
6444 fReadEntry = -1;
6445}
6446
6447////////////////////////////////////////////////////////////////////////////////
6448/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
6449///
6450/// If maxmemory is non null and positive SetMaxVirtualSize is called
6451/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
6452/// The function returns the total number of baskets read into memory
6453/// if negative an error occurred while loading the branches.
6454/// This method may be called to force branch baskets in memory
6455/// when random access to branch entries is required.
6456/// If random access to only a few branches is required, you should
6457/// call directly TBranch::LoadBaskets.
6460{
6462
6463 TIter next(GetListOfLeaves());
6464 TLeaf *leaf;
6465 Int_t nimported = 0;
6466 while ((leaf=(TLeaf*)next())) {
6467 nimported += leaf->GetBranch()->LoadBaskets();//break;
6468 }
6469 return nimported;
6470}
6471
6472////////////////////////////////////////////////////////////////////////////////
6473/// Set current entry.
6474///
6475/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
6476/// Returns -6 if an error occurs in the notification callback (just as TChain::LoadTree()).
6477///
6478/// Calls fNotify->Notify() (if fNotify is not null) when starting the processing of a new tree.
6479///
6480/// \note This function is overloaded in TChain.
6482{
6483 // We have already been visited while recursively looking
6484 // through the friend trees, let's return
6486 // We need to return a negative value to avoid a circular list of friends
6487 // to think that there is always an entry somewhere in the list.
6488 return -1;
6489 }
6490
6491 // create cache if wanted
6492 if (fCacheDoAutoInit && entry >=0)
6494
6495 if (fNotify) {
6496 if (fReadEntry < 0) {
6497 fNotify->Notify();
6498 }
6499 }
6500 fReadEntry = entry;
6501
6502 bool friendHasEntry = false;
6503 if (fFriends) {
6504 // Set current entry in friends as well.
6505 //
6506 // An alternative would move this code to each of the
6507 // functions calling LoadTree (and to overload a few more).
6508 bool needUpdate = false;
6509 {
6510 // This scope is need to insure the lock is released at the right time
6512 TFriendLock lock(this, kLoadTree);
6513 TFriendElement* fe = nullptr;
6514 while ((fe = (TFriendElement*) nextf())) {
6515 if (fe->TestBit(TFriendElement::kFromChain)) {
6516 // This friend element was added by the chain that owns this
6517 // tree, the chain will deal with loading the correct entry.
6518 continue;
6519 }
6520 TTree* friendTree = fe->GetTree();
6521 if (friendTree) {
6522 if (friendTree->LoadTreeFriend(entry, this) >= 0) {
6523 friendHasEntry = true;
6524 }
6525 }
6526 if (fe->IsUpdated()) {
6527 needUpdate = true;
6528 fe->ResetUpdated();
6529 }
6530 } // for each friend
6531 }
6532 if (needUpdate) {
6533 //update list of leaves in all TTreeFormula of the TTreePlayer (if any)
6534 if (fPlayer) {
6536 }
6537 //Notify user if requested
6538 if (fNotify) {
6539 if(!fNotify->Notify()) return -6;
6540 }
6541 }
6542 }
6543
6544 if ((fReadEntry >= fEntries) && !friendHasEntry) {
6545 fReadEntry = -1;
6546 return -2;
6547 }
6548 return fReadEntry;
6549}
6550
6551////////////////////////////////////////////////////////////////////////////////
6552/// Load entry on behalf of our master tree, we may use an index.
6553///
6554/// Called by LoadTree() when the masterTree looks for the entry
6555/// number in a friend tree (us) corresponding to the passed entry
6556/// number in the masterTree.
6557///
6558/// If we have no index, our entry number and the masterTree entry
6559/// number are the same.
6560///
6561/// If we *do* have an index, we must find the (major, minor) value pair
6562/// in masterTree to locate our corresponding entry.
6563///
6571}
6572
6573////////////////////////////////////////////////////////////////////////////////
6574/// Generate a skeleton analysis class for this tree.
6575///
6576/// The following files are produced: classname.h and classname.C.
6577/// If classname is 0, classname will be called "nameoftree".
6578///
6579/// The generated code in classname.h includes the following:
6580///
6581/// - Identification of the original tree and the input file name.
6582/// - Definition of an analysis class (data members and member functions).
6583/// - The following member functions:
6584/// - constructor (by default opening the tree file),
6585/// - GetEntry(Long64_t entry),
6586/// - Init(TTree* tree) to initialize a new TTree,
6587/// - Show(Long64_t entry) to read and dump entry.
6588///
6589/// The generated code in classname.C includes only the main
6590/// analysis function Loop.
6591///
6592/// To use this function:
6593///
6594/// - Open your tree file (eg: TFile f("myfile.root");)
6595/// - T->MakeClass("MyClass");
6596///
6597/// where T is the name of the TTree in file myfile.root,
6598/// and MyClass.h, MyClass.C the name of the files created by this function.
6599/// In a ROOT session, you can do:
6600/// ~~~ {.cpp}
6601/// root > .L MyClass.C
6602/// root > MyClass* t = new MyClass;
6603/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
6604/// root > t->Show(); // Show values of entry 12.
6605/// root > t->Show(16); // Read and show values of entry 16.
6606/// root > t->Loop(); // Loop on all entries.
6607/// ~~~
6608/// NOTE: Do not use the code generated for a single TTree which is part
6609/// of a TChain to process that entire TChain. The maximum dimensions
6610/// calculated for arrays on the basis of a single TTree from the TChain
6611/// might be (will be!) too small when processing all of the TTrees in
6612/// the TChain. You must use myChain.MakeClass() to generate the code,
6613/// not myTree.MakeClass(...).
6615Int_t TTree::MakeClass(const char* classname, Option_t* option)
6616{
6617 GetPlayer();
6618 if (!fPlayer) {
6619 return 0;
6620 }
6621 return fPlayer->MakeClass(classname, option);
6622}
6623
6624////////////////////////////////////////////////////////////////////////////////
6625/// Generate a skeleton function for this tree.
6626///
6627/// The function code is written on filename.
6628/// If filename is 0, filename will be called nameoftree.C
6629///
6630/// The generated code includes the following:
6631/// - Identification of the original Tree and Input file name,
6632/// - Opening the Tree file,
6633/// - Declaration of Tree variables,
6634/// - Setting of branches addresses,
6635/// - A skeleton for the entry loop.
6636///
6637/// To use this function:
6638///
6639/// - Open your Tree file (eg: TFile f("myfile.root");)
6640/// - T->MakeCode("MyAnalysis.C");
6641///
6642/// where T is the name of the TTree in file myfile.root
6643/// and MyAnalysis.C the name of the file created by this function.
6644///
6645/// NOTE: Since the implementation of this function, a new and better
6646/// function TTree::MakeClass() has been developed.
6648Int_t TTree::MakeCode(const char* filename)
6649{
6650 Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
6651
6652 GetPlayer();
6653 if (!fPlayer) return 0;
6654 return fPlayer->MakeCode(filename);
6655}
6656
6657////////////////////////////////////////////////////////////////////////////////
6658/// Generate a skeleton analysis class for this Tree using TBranchProxy.
6659///
6660/// TBranchProxy is the base of a class hierarchy implementing an
6661/// indirect access to the content of the branches of a TTree.
6662///
6663/// "proxyClassname" is expected to be of the form:
6664/// ~~~ {.cpp}
6665/// [path/]fileprefix
6666/// ~~~
6667/// The skeleton will then be generated in the file:
6668/// ~~~ {.cpp}
6669/// fileprefix.h
6670/// ~~~
6671/// located in the current directory or in 'path/' if it is specified.
6672/// The class generated will be named 'fileprefix'
6673///
6674/// "macrofilename" and optionally "cutfilename" are expected to point
6675/// to source files which will be included by the generated skeleton.
6676/// Method of the same name as the file(minus the extension and path)
6677/// will be called by the generated skeleton's Process method as follow:
6678/// ~~~ {.cpp}
6679/// [if (cutfilename())] htemp->Fill(macrofilename());
6680/// ~~~
6681/// "option" can be used select some of the optional features during
6682/// the code generation. The possible options are:
6683///
6684/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
6685///
6686/// 'maxUnrolling' controls how deep in the class hierarchy does the
6687/// system 'unroll' classes that are not split. Unrolling a class
6688/// allows direct access to its data members (this emulates the behavior
6689/// of TTreeFormula).
6690///
6691/// The main features of this skeleton are:
6692///
6693/// * on-demand loading of branches
6694/// * ability to use the 'branchname' as if it was a data member
6695/// * protection against array out-of-bounds errors
6696/// * ability to use the branch data as an object (when the user code is available)
6697///
6698/// For example with Event.root, if
6699/// ~~~ {.cpp}
6700/// Double_t somePx = fTracks.fPx[2];
6701/// ~~~
6702/// is executed by one of the method of the skeleton,
6703/// somePx will updated with the current value of fPx of the 3rd track.
6704///
6705/// Both macrofilename and the optional cutfilename are expected to be
6706/// the name of source files which contain at least a free standing
6707/// function with the signature:
6708/// ~~~ {.cpp}
6709/// x_t macrofilename(); // i.e function with the same name as the file
6710/// ~~~
6711/// and
6712/// ~~~ {.cpp}
6713/// y_t cutfilename(); // i.e function with the same name as the file
6714/// ~~~
6715/// x_t and y_t needs to be types that can convert respectively to a double
6716/// and a bool (because the skeleton uses:
6717///
6718/// if (cutfilename()) htemp->Fill(macrofilename());
6719///
6720/// These two functions are run in a context such that the branch names are
6721/// available as local variables of the correct (read-only) type.
6722///
6723/// Note that if you use the same 'variable' twice, it is more efficient
6724/// to 'cache' the value. For example:
6725/// ~~~ {.cpp}
6726/// Int_t n = fEventNumber; // Read fEventNumber
6727/// if (n<10 || n>10) { ... }
6728/// ~~~
6729/// is more efficient than
6730/// ~~~ {.cpp}
6731/// if (fEventNumber<10 || fEventNumber>10)
6732/// ~~~
6733/// Also, optionally, the generated selector will also call methods named
6734/// macrofilename_methodname in each of 6 main selector methods if the method
6735/// macrofilename_methodname exist (Where macrofilename is stripped of its
6736/// extension).
6737///
6738/// Concretely, with the script named h1analysisProxy.C,
6739///
6740/// - The method calls the method (if it exist)
6741/// - Begin -> void h1analysisProxy_Begin(TTree*);
6742/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
6743/// - Notify -> bool h1analysisProxy_Notify();
6744/// - Process -> bool h1analysisProxy_Process(Long64_t);
6745/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
6746/// - Terminate -> void h1analysisProxy_Terminate();
6747///
6748/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
6749/// it is included before the declaration of the proxy class. This can
6750/// be used in particular to insure that the include files needed by
6751/// the macro file are properly loaded.
6752///
6753/// The default histogram is accessible via the variable named 'htemp'.
6754///
6755/// If the library of the classes describing the data in the branch is
6756/// loaded, the skeleton will add the needed `include` statements and
6757/// give the ability to access the object stored in the branches.
6758///
6759/// To draw px using the file hsimple.root (generated by the
6760/// hsimple.C tutorial), we need a file named hsimple.cxx:
6761/// ~~~ {.cpp}
6762/// double hsimple() {
6763/// return px;
6764/// }
6765/// ~~~
6766/// MakeProxy can then be used indirectly via the TTree::Draw interface
6767/// as follow:
6768/// ~~~ {.cpp}
6769/// new TFile("hsimple.root")
6770/// ntuple->Draw("hsimple.cxx");
6771/// ~~~
6772/// A more complete example is available in the tutorials directory:
6773/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
6774/// which reimplement the selector found in h1analysis.C
6776Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
6777{
6778 GetPlayer();
6779 if (!fPlayer) return 0;
6781}
6782
6783////////////////////////////////////////////////////////////////////////////////
6784/// Generate skeleton selector class for this tree.
6785///
6786/// The following files are produced: selector.h and selector.C.
6787/// If selector is 0, the selector will be called "nameoftree".
6788/// The option can be used to specify the branches that will have a data member.
6789/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
6790/// members and branch pointers instead of TTreeReaders).
6791/// - If option is empty, readers will be generated for each leaf.
6792/// - If option is "@", readers will be generated for the topmost branches.
6793/// - Individual branches can also be picked by their name:
6794/// - "X" generates readers for leaves of X.
6795/// - "@X" generates a reader for X as a whole.
6796/// - "@X;Y" generates a reader for X as a whole and also readers for the
6797/// leaves of Y.
6798/// - For further examples see the figure below.
6799///
6800/// \image html ttree_makeselector_option_examples.png
6801///
6802/// The generated code in selector.h includes the following:
6803/// - Identification of the original Tree and Input file name
6804/// - Definition of selector class (data and functions)
6805/// - The following class functions:
6806/// - constructor and destructor
6807/// - void Begin(TTree *tree)
6808/// - void SlaveBegin(TTree *tree)
6809/// - void Init(TTree *tree)
6810/// - bool Notify()
6811/// - bool Process(Long64_t entry)
6812/// - void Terminate()
6813/// - void SlaveTerminate()
6814///
6815/// The class selector derives from TSelector.
6816/// The generated code in selector.C includes empty functions defined above.
6817///
6818/// To use this function:
6819///
6820/// - connect your Tree file (eg: `TFile f("myfile.root");`)
6821/// - `T->MakeSelector("myselect");`
6822///
6823/// where T is the name of the Tree in file myfile.root
6824/// and myselect.h, myselect.C the name of the files created by this function.
6825/// In a ROOT session, you can do:
6826/// ~~~ {.cpp}
6827/// root > T->Process("myselect.C")
6828/// ~~~
6830Int_t TTree::MakeSelector(const char* selector, Option_t* option)
6831{
6832 TString opt(option);
6833 if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
6834 return MakeClass(selector, "selector");
6835 } else {
6836 GetPlayer();
6837 if (!fPlayer) return 0;
6838 return fPlayer->MakeReader(selector, option);
6839 }
6840}
6841
6842////////////////////////////////////////////////////////////////////////////////
6843/// Check if adding nbytes to memory we are still below MaxVirtualsize.
6846{
6848 return false;
6849 }
6850 return true;
6851}
6852
6853////////////////////////////////////////////////////////////////////////////////
6854/// Static function merging the trees in the TList into a new tree.
6855///
6856/// Trees in the list can be memory or disk-resident trees.
6857/// The new tree is created in the current directory (memory if gROOT).
6858/// Trees with no branches will be skipped, the branch structure
6859/// will be taken from the first non-zero-branch Tree of {li}
6862{
6863 if (!li) return nullptr;
6864 TIter next(li);
6865 TTree *newtree = nullptr;
6866 TObject *obj;
6867
6868 while ((obj=next())) {
6869 if (!obj->InheritsFrom(TTree::Class())) continue;
6870 TTree *tree = (TTree*)obj;
6871 if (tree->GetListOfBranches()->IsEmpty()) {
6872 if (gDebug > 2) {
6873 tree->Warning("MergeTrees","TTree %s has no branches, skipping.", tree->GetName());
6874 }
6875 continue; // Completely ignore the empty trees.
6876 }
6877 Long64_t nentries = tree->GetEntries();
6878 if (newtree && nentries == 0)
6879 continue; // If we already have the structure and we have no entry, save time and skip
6880 if (!newtree) {
6881 newtree = (TTree*)tree->CloneTree(-1, options);
6882 if (!newtree) continue;
6883
6884 // Once the cloning is done, separate the trees,
6885 // to avoid as many side-effects as possible
6886 // The list of clones is guaranteed to exist since we
6887 // just cloned the tree.
6888 tree->GetListOfClones()->Remove(newtree);
6889 tree->ResetBranchAddresses();
6890 newtree->ResetBranchAddresses();
6891 continue;
6892 }
6893 if (nentries == 0)
6894 continue;
6895 newtree->CopyEntries(tree, -1, options, true);
6896 }
6897 if (newtree && newtree->GetTreeIndex()) {
6898 newtree->GetTreeIndex()->Append(nullptr,false); // Force the sorting
6899 }
6900 return newtree;
6901}
6902
6903////////////////////////////////////////////////////////////////////////////////
6904/// Merge the trees in the TList into this tree.
6905///
6906/// Returns the total number of entries in the merged tree.
6907/// Trees with no branches will be skipped, the branch structure
6908/// will be taken from the first non-zero-branch Tree of {this+li}
6911{
6912 if (fBranches.IsEmpty()) {
6913 if (!li || li->IsEmpty())
6914 return 0; // Nothing to do ....
6915 // Let's find the first non-empty
6916 TIter next(li);
6917 TTree *tree;
6918 while ((tree = (TTree *)next())) {
6919 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
6920 if (gDebug > 2) {
6921 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
6922 }
6923 continue;
6924 }
6925 // We could come from a list made up of different names, the first one still wins
6926 tree->SetName(this->GetName());
6927 auto prevEntries = tree->GetEntries();
6928 auto result = tree->Merge(li, options);
6929 if (result != prevEntries) {
6930 // If there is no additional entries, the first write was enough.
6931 tree->Write();
6932 }
6933 // Make sure things are really written out to disk before attempting any reading.
6934 if (tree->GetCurrentFile()) {
6935 tree->GetCurrentFile()->Flush();
6936 // Read back the complete info in this TTree, so that caller does not
6937 // inadvertently write the empty tree.
6938 tree->GetDirectory()->ReadTObject(this, this->GetName());
6939 }
6940 return result;
6941 }
6942 return 0; // All trees have empty branches
6943 }
6944 if (!li) return 0;
6946 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
6947 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
6948 // Also since this is part of a merging operation, the output file is not as precious as in
6949 // the general case since the input file should still be around.
6950 fAutoSave = 0;
6951 TIter next(li);
6952 TTree *tree;
6953 while ((tree = (TTree*)next())) {
6954 if (tree==this) continue;
6955 if (!tree->InheritsFrom(TTree::Class())) {
6956 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
6958 return -1;
6959 }
6960
6961 Long64_t nentries = tree->GetEntries();
6962 if (nentries == 0) continue;
6963
6964 CopyEntries(tree, -1, options, true);
6965 }
6967 return GetEntries();
6968}
6969
6970////////////////////////////////////////////////////////////////////////////////
6971/// Merge the trees in the TList into this tree.
6972/// If info->fIsFirst is true, first we clone this TTree info the directory
6973/// info->fOutputDirectory and then overlay the new TTree information onto
6974/// this TTree object (so that this TTree object is now the appropriate to
6975/// use for further merging).
6976/// Trees with no branches will be skipped, the branch structure
6977/// will be taken from the first non-zero-branch Tree of {this+li}
6978///
6979/// Returns the total number of entries in the merged tree.
6982{
6983 if (fBranches.IsEmpty()) {
6984 if (!li || li->IsEmpty())
6985 return 0; // Nothing to do ....
6986 // Let's find the first non-empty
6987 TIter next(li);
6988 TTree *tree;
6989 while ((tree = (TTree *)next())) {
6990 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
6991 if (gDebug > 2) {
6992 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
6993 }
6994 continue;
6995 }
6996 // We could come from a list made up of different names, the first one still wins
6997 tree->SetName(this->GetName());
6998 auto prevEntries = tree->GetEntries();
6999 auto result = tree->Merge(li, info);
7000 if (result != prevEntries) {
7001 // If there is no additional entries, the first write was enough.
7002 tree->Write();
7003 }
7004 // Make sure things are really written out to disk before attempting any reading.
7005 info->fOutputDirectory->GetFile()->Flush();
7006 // Read back the complete info in this TTree, so that TFileMerge does not
7007 // inadvertently write the empty tree.
7008 info->fOutputDirectory->ReadTObject(this, this->GetName());
7009 return result;
7010 }
7011 return 0; // All trees have empty branches
7012 }
7013 const char *options = info ? info->fOptions.Data() : "";
7014 if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
7015 if (GetCurrentFile() == nullptr) {
7016 // In memory TTree, all we need to do is ... write it.
7017 SetDirectory(info->fOutputDirectory);
7019 fDirectory->WriteTObject(this);
7020 } else if (info->fOptions.Contains("fast")) {
7021 InPlaceClone(info->fOutputDirectory);
7022 } else {
7023 TDirectory::TContext ctxt(info->fOutputDirectory);
7025 TTree *newtree = CloneTree(-1, options);
7026 if (info->fIOFeatures)
7027 fIOFeatures = *(info->fIOFeatures);
7028 else
7030 if (newtree) {
7031 newtree->Write();
7032 delete newtree;
7033 }
7034 // Make sure things are really written out to disk before attempting any reading.
7035 info->fOutputDirectory->GetFile()->Flush();
7036 info->fOutputDirectory->ReadTObject(this,this->GetName());
7037 }
7038 }
7039 if (!li) return 0;
7041 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
7042 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
7043 // Also since this is part of a merging operation, the output file is not as precious as in
7044 // the general case since the input file should still be around.
7045 fAutoSave = 0;
7046 TIter next(li);
7047 TTree *tree;
7048 while ((tree = (TTree*)next())) {
7049 if (tree==this) continue;
7050 if (!tree->InheritsFrom(TTree::Class())) {
7051 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
7053 return -1;
7054 }
7055
7056 CopyEntries(tree, -1, options, true);
7057 }
7059 return GetEntries();
7060}
7061
7062////////////////////////////////////////////////////////////////////////////////
7063/// Move a cache from a file to the current file in dir.
7064/// if src is null no operation is done, if dir is null or there is no
7065/// current file the cache is deleted.
7068{
7069 if (!src) return;
7070 TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : nullptr;
7071 if (src == dst) return;
7072
7074 if (dst) {
7075 src->SetCacheRead(nullptr,this);
7076 dst->SetCacheRead(pf, this);
7077 } else {
7078 if (pf) {
7079 pf->WaitFinishPrefetch();
7080 }
7081 src->SetCacheRead(nullptr,this);
7082 delete pf;
7083 }
7084}
7085
7086////////////////////////////////////////////////////////////////////////////////
7087/// Copy the content to a new new file, update this TTree with the new
7088/// location information and attach this TTree to the new directory.
7089///
7090/// options: Indicates a basket sorting method, see TTreeCloner::TTreeCloner for
7091/// details
7092///
7093/// If new and old directory are in the same file, the data is untouched,
7094/// this "just" does a call to SetDirectory.
7095/// Equivalent to an "in place" cloning of the TTree.
7096bool TTree::InPlaceClone(TDirectory *newdirectory, const char *options)
7097{
7098 if (!newdirectory) {
7100 SetDirectory(nullptr);
7101 return true;
7102 }
7103 if (newdirectory->GetFile() == GetCurrentFile()) {
7105 return true;
7106 }
7107 TTreeCloner cloner(this, newdirectory, options);
7108 if (cloner.IsValid())
7109 return cloner.Exec();
7110 else
7111 return false;
7112}
7113
7114////////////////////////////////////////////////////////////////////////////////
7115/// Function called when loading a new class library.
7117bool TTree::Notify()
7118{
7119 TIter next(GetListOfLeaves());
7120 TLeaf* leaf = nullptr;
7121 while ((leaf = (TLeaf*) next())) {
7122 leaf->Notify();
7123 leaf->GetBranch()->Notify();
7124 }
7125 return true;
7126}
7127
7128////////////////////////////////////////////////////////////////////////////////
7129/// This function may be called after having filled some entries in a Tree.
7130/// Using the information in the existing branch buffers, it will reassign
7131/// new branch buffer sizes to optimize time and memory.
7132///
7133/// The function computes the best values for branch buffer sizes such that
7134/// the total buffer sizes is less than maxMemory and nearby entries written
7135/// at the same time.
7136/// In case the branch compression factor for the data written so far is less
7137/// than compMin, the compression is disabled.
7138///
7139/// if option ="d" an analysis report is printed.
7142{
7143 //Flush existing baskets if the file is writable
7144 if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
7145
7146 TString opt( option );
7147 opt.ToLower();
7148 bool pDebug = opt.Contains("d");
7149 TObjArray *leaves = this->GetListOfLeaves();
7150 Int_t nleaves = leaves->GetEntries();
7152
7153 if (nleaves == 0 || treeSize == 0) {
7154 // We're being called too early, we really have nothing to do ...
7155 return;
7156 }
7158 UInt_t bmin = 512;
7159 UInt_t bmax = 256000;
7160 Double_t memFactor = 1;
7163
7164 //we make two passes
7165 //one pass to compute the relative branch buffer sizes
7166 //a second pass to compute the absolute values
7167 for (Int_t pass =0;pass<2;pass++) {
7168 oldMemsize = 0; //to count size of baskets in memory with old buffer size
7169 newMemsize = 0; //to count size of baskets in memory with new buffer size
7170 oldBaskets = 0; //to count number of baskets with old buffer size
7171 newBaskets = 0; //to count number of baskets with new buffer size
7172 for (i=0;i<nleaves;i++) {
7173 TLeaf *leaf = (TLeaf*)leaves->At(i);
7174 TBranch *branch = leaf->GetBranch();
7175 Double_t totBytes = (Double_t)branch->GetTotBytes();
7178 if (branch->GetEntries() == 0) {
7179 // There is no data, so let's make a guess ...
7181 } else {
7182 sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
7183 }
7184 Int_t oldBsize = branch->GetBasketSize();
7187 Int_t nb = branch->GetListOfBranches()->GetEntries();
7188 if (nb > 0) {
7190 continue;
7191 }
7192 Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
7193 if (bsize < 0) bsize = bmax;
7194 if (bsize > bmax) bsize = bmax;
7196 if (pass) { // only on the second pass so that it doesn't interfere with scaling
7197 // If there is an entry offset, it will be stored in the same buffer as the object data; hence,
7198 // we must bump up the size of the branch to account for this extra footprint.
7199 // If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
7200 // the value of GetEntries().
7201 Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
7202 if (branch->GetEntryOffsetLen()) {
7203 newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
7204 }
7205 // We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
7206 // with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
7207 // resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
7208 // at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
7209 // stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
7210 // structures we found a factor of 2 fewer baskets needed in the new scheme.
7211 // rounds up, increases basket size to ensure all entries fit into single basket as intended
7212 newBsize = newBsize - newBsize%512 + 512;
7213 }
7215 if (newBsize < bmin) newBsize = bmin;
7216 if (newBsize > 10000000) newBsize = bmax;
7217 if (pass) {
7218 if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
7219 branch->SetBasketSize(newBsize);
7220 }
7222 // For this number to be somewhat accurate when newBsize is 'low'
7223 // we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
7224 // not let it be lower than 100+TBranch::fEntryOffsetLen.
7226 if (pass == 0) continue;
7227 //Reset the compression level in case the compression factor is small
7228 Double_t comp = 1;
7229 if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
7230 if (comp > 1 && comp < minComp) {
7231 if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
7233 }
7234 }
7235 // coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
7237 if (memFactor > 100) memFactor = 100;
7240 static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
7241
7242 // Really, really never go lower than 8 bytes (we use this number
7243 // so that the calculation of the number of basket is consistent
7244 // but in fact SetBasketSize will not let the size go below
7245 // TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
7246 // (The 2nd part being a slight over estimate of the key length.
7247 static const UInt_t hardmin = 8;
7250 }
7251 if (pDebug) {
7252 Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
7253 Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
7254 }
7255}
7256
7257////////////////////////////////////////////////////////////////////////////////
7258/// Interface to the Principal Components Analysis class.
7259///
7260/// Create an instance of TPrincipal
7261///
7262/// Fill it with the selected variables
7263///
7264/// - if option "n" is specified, the TPrincipal object is filled with
7265/// normalized variables.
7266/// - If option "p" is specified, compute the principal components
7267/// - If option "p" and "d" print results of analysis
7268/// - If option "p" and "h" generate standard histograms
7269/// - If option "p" and "c" generate code of conversion functions
7270/// - return a pointer to the TPrincipal object. It is the user responsibility
7271/// - to delete this object.
7272/// - The option default value is "np"
7273///
7274/// see TTree::Draw for explanation of the other parameters.
7275///
7276/// The created object is named "principal" and a reference to it
7277/// is added to the list of specials Root objects.
7278/// you can retrieve a pointer to the created object via:
7279/// ~~~ {.cpp}
7280/// TPrincipal *principal =
7281/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
7282/// ~~~
7285{
7286 GetPlayer();
7287 if (fPlayer) {
7289 }
7290 return nullptr;
7291}
7292
7293////////////////////////////////////////////////////////////////////////////////
7294/// Print a summary of the tree contents.
7295///
7296/// - If option contains "all" friend trees are also printed.
7297/// - If option contains "toponly" only the top level branches are printed.
7298/// - If option contains "clusters" information about the cluster of baskets is printed.
7299///
7300/// Wildcarding can be used to print only a subset of the branches, e.g.,
7301/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
7303void TTree::Print(Option_t* option) const
7304{
7305 // We already have been visited while recursively looking
7306 // through the friends tree, let's return.
7307 if (kPrint & fFriendLockStatus) {
7308 return;
7309 }
7310 Int_t s = 0;
7311 Int_t skey = 0;
7312 if (fDirectory) {
7313 TKey* key = fDirectory->GetKey(GetName());
7314 if (key) {
7315 skey = key->GetKeylen();
7316 s = key->GetNbytes();
7317 }
7318 }
7321 if (zipBytes > 0) {
7322 total += GetTotBytes();
7323 }
7325 TTree::Class()->WriteBuffer(b, (TTree*) this);
7326 total += b.Length();
7327 Long64_t file = zipBytes + s;
7328 Float_t cx = 1;
7329 if (zipBytes) {
7330 cx = (GetTotBytes() + 0.00001) / zipBytes;
7331 }
7332 Printf("******************************************************************************");
7333 Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
7334 Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
7335 Printf("* : : Tree compression factor = %6.2f *", cx);
7336 Printf("******************************************************************************");
7337
7338 // Avoid many check of option validity
7339 if (!option)
7340 option = "";
7341
7342 if (strncmp(option,"clusters",std::char_traits<char>::length("clusters"))==0) {
7343 Printf("%-16s %-16s %-16s %8s %20s",
7344 "Cluster Range #", "Entry Start", "Last Entry", "Size", "Number of clusters");
7345 Int_t index= 0;
7348 bool estimated = false;
7349 bool unknown = false;
7351 Long64_t nclusters = 0;
7352 if (recordedSize > 0) {
7353 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / recordedSize);
7354 Printf("%-16d %-16lld %-16lld %8lld %10lld",
7355 ind, start, end, recordedSize, nclusters);
7356 } else {
7357 // NOTE: const_cast ... DO NOT Merge for now
7358 TClusterIterator iter((TTree*)this, start);
7359 iter.Next();
7360 auto estimated_size = iter.GetNextEntry() - start;
7361 if (estimated_size > 0) {
7362 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / estimated_size);
7363 Printf("%-16d %-16lld %-16lld %8lld %10lld (estimated)",
7364 ind, start, end, recordedSize, nclusters);
7365 estimated = true;
7366 } else {
7367 Printf("%-16d %-16lld %-16lld %8lld (unknown)",
7368 ind, start, end, recordedSize);
7369 unknown = true;
7370 }
7371 }
7372 start = end + 1;
7374 };
7375 if (fNClusterRange) {
7376 for( ; index < fNClusterRange; ++index) {
7379 }
7380 }
7382 if (unknown) {
7383 Printf("Total number of clusters: (unknown)");
7384 } else {
7385 Printf("Total number of clusters: %lld %s", totalClusters, estimated ? "(estimated)" : "");
7386 }
7387 return;
7388 }
7389
7390 Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
7391 Int_t l;
7392 TBranch* br = nullptr;
7393 TLeaf* leaf = nullptr;
7394 if (strstr(option, "toponly")) {
7395 Long64_t *count = new Long64_t[nl];
7396 Int_t keep =0;
7397 for (l=0;l<nl;l++) {
7398 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7399 br = leaf->GetBranch();
7400 // branch is its own (top level) mother only for the top level branches.
7401 if (br != br->GetMother()) {
7402 count[l] = -1;
7403 count[keep] += br->GetZipBytes();
7404 } else {
7405 keep = l;
7406 count[keep] = br->GetZipBytes();
7407 }
7408 }
7409 for (l=0;l<nl;l++) {
7410 if (count[l] < 0) continue;
7411 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7412 br = leaf->GetBranch();
7413 Printf("branch: %-20s %9lld",br->GetName(),count[l]);
7414 }
7415 delete [] count;
7416 } else {
7417 TString reg = "*";
7418 if (strlen(option) && strchr(option,'*')) reg = option;
7419 TRegexp re(reg,true);
7420 TIter next(const_cast<TTree*>(this)->GetListOfBranches());
7422 while ((br= (TBranch*)next())) {
7423 TString st = br->GetName();
7424 st.ReplaceAll("/","_");
7425 if (st.Index(re) == kNPOS) continue;
7426 br->Print(option);
7427 }
7428 }
7429
7430 //print TRefTable (if one)
7432
7433 //print friends if option "all"
7434 if (!fFriends || !strstr(option,"all")) return;
7436 TFriendLock lock(const_cast<TTree*>(this),kPrint);
7437 TFriendElement *fr;
7438 while ((fr = (TFriendElement*)nextf())) {
7439 TTree * t = fr->GetTree();
7440 if (t) t->Print(option);
7441 }
7442}
7443
7444////////////////////////////////////////////////////////////////////////////////
7445/// Print statistics about the TreeCache for this tree.
7446/// Like:
7447/// ~~~ {.cpp}
7448/// ******TreeCache statistics for file: cms2.root ******
7449/// Reading 73921562 bytes in 716 transactions
7450/// Average transaction = 103.242405 Kbytes
7451/// Number of blocks in current cache: 202, total size : 6001193
7452/// ~~~
7453/// if option = "a" the list of blocks in the cache is printed
7456{
7457 TFile *f = GetCurrentFile();
7458 if (!f) return;
7460 if (tc) tc->Print(option);
7461}
7462
7463////////////////////////////////////////////////////////////////////////////////
7464/// Process this tree executing the TSelector code in the specified filename.
7465/// The return value is -1 in case of error and TSelector::GetStatus() in
7466/// in case of success.
7467///
7468/// The code in filename is loaded (interpreted or compiled, see below),
7469/// filename must contain a valid class implementation derived from TSelector,
7470/// where TSelector has the following member functions:
7471///
7472/// - `Begin()`: called every time a loop on the tree starts,
7473/// a convenient place to create your histograms.
7474/// - `SlaveBegin()`: called after Begin(), when on PROOF called only on the
7475/// slave servers.
7476/// - `Process()`: called for each event, in this function you decide what
7477/// to read and fill your histograms.
7478/// - `SlaveTerminate`: called at the end of the loop on the tree, when on PROOF
7479/// called only on the slave servers.
7480/// - `Terminate()`: called at the end of the loop on the tree,
7481/// a convenient place to draw/fit your histograms.
7482///
7483/// If filename is of the form file.C, the file will be interpreted.
7484///
7485/// If filename is of the form file.C++, the file file.C will be compiled
7486/// and dynamically loaded.
7487///
7488/// If filename is of the form file.C+, the file file.C will be compiled
7489/// and dynamically loaded. At next call, if file.C is older than file.o
7490/// and file.so, the file.C is not compiled, only file.so is loaded.
7491///
7492/// ## NOTE1
7493///
7494/// It may be more interesting to invoke directly the other Process function
7495/// accepting a TSelector* as argument.eg
7496/// ~~~ {.cpp}
7497/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
7498/// selector->CallSomeFunction(..);
7499/// mytree.Process(selector,..);
7500/// ~~~
7501/// ## NOTE2
7502//
7503/// One should not call this function twice with the same selector file
7504/// in the same script. If this is required, proceed as indicated in NOTE1,
7505/// by getting a pointer to the corresponding TSelector,eg
7506///
7507/// ### Workaround 1
7508///
7509/// ~~~ {.cpp}
7510/// void stubs1() {
7511/// TSelector *selector = TSelector::GetSelector("h1test.C");
7512/// TFile *f1 = new TFile("stubs_nood_le1.root");
7513/// TTree *h1 = (TTree*)f1->Get("h1");
7514/// h1->Process(selector);
7515/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7516/// TTree *h2 = (TTree*)f2->Get("h1");
7517/// h2->Process(selector);
7518/// }
7519/// ~~~
7520/// or use ACLIC to compile the selector
7521///
7522/// ### Workaround 2
7523///
7524/// ~~~ {.cpp}
7525/// void stubs2() {
7526/// TFile *f1 = new TFile("stubs_nood_le1.root");
7527/// TTree *h1 = (TTree*)f1->Get("h1");
7528/// h1->Process("h1test.C+");
7529/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7530/// TTree *h2 = (TTree*)f2->Get("h1");
7531/// h2->Process("h1test.C+");
7532/// }
7533/// ~~~
7536{
7537 GetPlayer();
7538 if (fPlayer) {
7540 }
7541 return -1;
7542}
7543
7544////////////////////////////////////////////////////////////////////////////////
7545/// Process this tree executing the code in the specified selector.
7546/// The return value is -1 in case of error and TSelector::GetStatus() in
7547/// in case of success.
7548///
7549/// The TSelector class has the following member functions:
7550///
7551/// - `Begin()`: called every time a loop on the tree starts,
7552/// a convenient place to create your histograms.
7553/// - `SlaveBegin()`: called after Begin(), when on PROOF called only on the
7554/// slave servers.
7555/// - `Process()`: called for each event, in this function you decide what
7556/// to read and fill your histograms.
7557/// - `SlaveTerminate`: called at the end of the loop on the tree, when on PROOF
7558/// called only on the slave servers.
7559/// - `Terminate()`: called at the end of the loop on the tree,
7560/// a convenient place to draw/fit your histograms.
7561///
7562/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
7563/// of the EventList, starting at firstentry, otherwise the loop is on the
7564/// specified Tree entries.
7567{
7568 GetPlayer();
7569 if (fPlayer) {
7570 return fPlayer->Process(selector, option, nentries, firstentry);
7571 }
7572 return -1;
7573}
7574
7575////////////////////////////////////////////////////////////////////////////////
7576/// Make a projection of a tree using selections.
7577///
7578/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
7579/// projection of the tree will be filled in histogram hname.
7580/// Note that the dimension of hname must match with the dimension of varexp.
7581///
7584{
7585 TString var;
7586 var.Form("%s>>%s", varexp, hname);
7587 TString opt("goff");
7588 if (option) {
7589 opt.Form("%sgoff", option);
7590 }
7592 return nsel;
7593}
7594
7595////////////////////////////////////////////////////////////////////////////////
7596/// Loop over entries and return a TSQLResult object containing entries following selection.
7599{
7600 GetPlayer();
7601 if (fPlayer) {
7603 }
7604 return nullptr;
7605}
7606
7607////////////////////////////////////////////////////////////////////////////////
7608/// Create or simply read branches from filename.
7609///
7610/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
7611/// is given in the first line of the file with a syntax like
7612/// ~~~ {.cpp}
7613/// A/D:Table[2]/F:Ntracks/I:astring/C
7614/// ~~~
7615/// otherwise branchDescriptor must be specified with the above syntax.
7616///
7617/// - If the type of the first variable is not specified, it is assumed to be "/F"
7618/// - If the type of any other variable is not specified, the type of the previous
7619/// variable is assumed. eg
7620/// - `x:y:z` (all variables are assumed of type "F")
7621/// - `x/D:y:z` (all variables are of type "D")
7622/// - `x:y/D:z` (x is type "F", y and z of type "D")
7623///
7624/// delimiter allows for the use of another delimiter besides whitespace.
7625/// This provides support for direct import of common data file formats
7626/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
7627/// branch description is taken from the first line in the file, but
7628/// delimiter is used for the branch names tokenization rather than ':'.
7629/// Note however that if the values in the first line do not use the
7630/// /[type] syntax, all variables are assumed to be of type "F".
7631/// If the filename ends with extensions .csv or .CSV and a delimiter is
7632/// not specified (besides ' '), the delimiter is automatically set to ','.
7633///
7634/// Lines in the input file starting with "#" are ignored. Leading whitespace
7635/// for each column data is skipped. Empty lines are skipped.
7636///
7637/// A TBranch object is created for each variable in the expression.
7638/// The total number of rows read from the file is returned.
7639///
7640/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
7641///
7642/// To fill a TTree with multiple input text files, proceed as indicated above
7643/// for the first input file and omit the second argument for subsequent calls
7644/// ~~~ {.cpp}
7645/// T.ReadFile("file1.dat","branch descriptor");
7646/// T.ReadFile("file2.dat");
7647/// ~~~
7649Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
7650{
7651 if (!filename || !*filename) {
7652 Error("ReadFile","File name not specified");
7653 return 0;
7654 }
7655
7656 std::ifstream in;
7657 in.open(filename);
7658 if (!in.good()) {
7659 Error("ReadFile","Cannot open file: %s",filename);
7660 return 0;
7661 }
7662 const char* ext = strrchr(filename, '.');
7663 if(ext && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
7664 delimiter = ',';
7665 }
7667}
7668
7669////////////////////////////////////////////////////////////////////////////////
7670/// Determine which newline this file is using.
7671/// Return '\r' for Windows '\r\n' as that already terminates.
7673char TTree::GetNewlineValue(std::istream &inputStream)
7674{
7675 Long_t inPos = inputStream.tellg();
7676 char newline = '\n';
7677 while(true) {
7678 char c = 0;
7679 inputStream.get(c);
7680 if(!inputStream.good()) {
7681 Error("ReadStream","Error reading stream: no newline found.");
7682 return 0;
7683 }
7684 if(c == newline) break;
7685 if(c == '\r') {
7686 newline = '\r';
7687 break;
7688 }
7689 }
7690 inputStream.clear();
7691 inputStream.seekg(inPos);
7692 return newline;
7693}
7694
7695////////////////////////////////////////////////////////////////////////////////
7696/// Create or simply read branches from an input stream.
7697///
7698/// \see TTree::ReadFile
7700Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
7701{
7702 char newline = 0;
7703 std::stringstream ss;
7704 std::istream *inTemp;
7705 Long_t inPos = inputStream.tellg();
7706 if (!inputStream.good()) {
7707 Error("ReadStream","Error reading stream");
7708 return 0;
7709 }
7710 if (inPos == -1) {
7711 ss << std::cin.rdbuf();
7713 inTemp = &ss;
7714 } else {
7717 }
7718 std::istream& in = *inTemp;
7719 Long64_t nlines = 0;
7720
7721 TBranch *branch = nullptr;
7723 if (nbranches == 0) {
7724 char *bdname = new char[4000];
7725 char *bd = new char[100000];
7726 Int_t nch = 0;
7728 // branch Descriptor is null, read its definition from the first line in the file
7729 if (!nch) {
7730 do {
7731 in.getline(bd, 100000, newline);
7732 if (!in.good()) {
7733 delete [] bdname;
7734 delete [] bd;
7735 Error("ReadStream","Error reading stream");
7736 return 0;
7737 }
7738 char *cursor = bd;
7739 while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
7740 ++cursor;
7741 }
7742 if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
7743 break;
7744 }
7745 } while (true);
7746 ++nlines;
7747 nch = strlen(bd);
7748 } else {
7749 strlcpy(bd,branchDescriptor,100000);
7750 }
7751
7752 //parse the branch descriptor and create a branch for each element
7753 //separated by ":"
7754 void *address = &bd[90000];
7755 char *bdcur = bd;
7756 TString desc="", olddesc="F";
7757 char bdelim = ':';
7758 if(delimiter != ' ') {
7759 bdelim = delimiter;
7760 if (strchr(bdcur,bdelim)==nullptr && strchr(bdcur,':') != nullptr) {
7761 // revert to the default
7762 bdelim = ':';
7763 }
7764 }
7765 while (bdcur) {
7766 char *colon = strchr(bdcur,bdelim);
7767 if (colon) *colon = 0;
7768 strlcpy(bdname,bdcur,4000);
7769 char *slash = strchr(bdname,'/');
7770 if (slash) {
7771 *slash = 0;
7772 desc = bdcur;
7773 olddesc = slash+1;
7774 } else {
7775 desc.Form("%s/%s",bdname,olddesc.Data());
7776 }
7777 char *bracket = strchr(bdname,'[');
7778 if (bracket) {
7779 *bracket = 0;
7780 }
7781 branch = new TBranch(this,bdname,address,desc.Data(),32000);
7782 if (branch->IsZombie()) {
7783 delete branch;
7784 Warning("ReadStream","Illegal branch definition: %s",bdcur);
7785 } else {
7787 branch->SetAddress(nullptr);
7788 }
7789 if (!colon)break;
7790 bdcur = colon+1;
7791 }
7792 delete [] bdname;
7793 delete [] bd;
7794 }
7795
7797
7798 if (gDebug > 1) {
7799 Info("ReadStream", "Will use branches:");
7800 for (int i = 0 ; i < nbranches; ++i) {
7801 TBranch* br = (TBranch*) fBranches.At(i);
7802 Info("ReadStream", " %s: %s [%s]", br->GetName(),
7803 br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
7804 }
7805 if (gDebug > 3) {
7806 Info("ReadStream", "Dumping read tokens, format:");
7807 Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
7808 Info("ReadStream", " L: line number");
7809 Info("ReadStream", " B: branch number");
7810 Info("ReadStream", " gfbe: good / fail / bad / eof of token");
7811 Info("ReadStream", " GFBE: good / fail / bad / eof of file");
7812 Info("ReadStream", " T: Token being read");
7813 }
7814 }
7815
7816 //loop on all lines in the file
7817 Long64_t nGoodLines = 0;
7818 std::string line;
7819 const char sDelimBuf[2] = { delimiter, 0 };
7820 const char* sDelim = sDelimBuf;
7821 if (delimiter == ' ') {
7822 // ' ' really means whitespace
7823 sDelim = "[ \t]";
7824 }
7825 while(in.good()) {
7826 if (newline == '\r' && in.peek() == '\n') {
7827 // Windows, skip '\n':
7828 in.get();
7829 }
7830 std::getline(in, line, newline);
7831 ++nlines;
7832
7834 sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
7835 if (sLine.IsNull()) {
7836 if (gDebug > 2) {
7837 Info("ReadStream", "Skipping empty line number %lld", nlines);
7838 }
7839 continue; // silently skip empty lines
7840 }
7841 if (sLine[0] == '#') {
7842 if (gDebug > 2) {
7843 Info("ReadStream", "Skipping comment line number %lld: '%s'",
7844 nlines, line.c_str());
7845 }
7846 continue;
7847 }
7848 if (gDebug > 2) {
7849 Info("ReadStream", "Parsing line number %lld: '%s'",
7850 nlines, line.c_str());
7851 }
7852
7853 // Loop on branches and read the branch values into their buffer
7854 branch = nullptr;
7855 TString tok; // one column's data
7856 TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
7857 std::stringstream sToken; // string stream feeding leafData into leaves
7858 Ssiz_t pos = 0;
7859 Int_t iBranch = 0;
7860 bool goodLine = true; // whether the row can be filled into the tree
7861 Int_t remainingLeafLen = 0; // remaining columns for the current leaf
7862 while (goodLine && iBranch < nbranches
7863 && sLine.Tokenize(tok, pos, sDelim)) {
7864 tok = tok.Strip(TString::kLeading); // skip leading whitespace
7865 if (tok.IsNull() && delimiter == ' ') {
7866 // 1 2 should not be interpreted as 1,,,2 but 1, 2.
7867 // Thus continue until we have a non-empty token.
7868 continue;
7869 }
7870
7871 if (!remainingLeafLen) {
7872 // next branch!
7874 }
7875 TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
7876 if (!remainingLeafLen) {
7877 remainingLeafLen = leaf->GetLen();
7878 if (leaf->GetMaximum() > 0) {
7879 // This is a dynamic leaf length, i.e. most likely a TLeafC's
7880 // string size. This still translates into one token:
7881 remainingLeafLen = 1;
7882 }
7883
7884 leafData = tok;
7885 } else {
7886 // append token to laf data:
7887 leafData += " ";
7888 leafData += tok;
7889 }
7891 if (remainingLeafLen) {
7892 // need more columns for this branch:
7893 continue;
7894 }
7895 ++iBranch;
7896
7897 // initialize stringstream with token
7898 sToken.clear();
7899 sToken.seekp(0, std::ios_base::beg);
7900 sToken.str(leafData.Data());
7901 sToken.seekg(0, std::ios_base::beg);
7902 leaf->ReadValue(sToken, 0 /* 0 = "all" */);
7903 if (gDebug > 3) {
7904 Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
7905 nlines, iBranch,
7906 (int)sToken.good(), (int)sToken.fail(),
7907 (int)sToken.bad(), (int)sToken.eof(),
7908 (int)in.good(), (int)in.fail(),
7909 (int)in.bad(), (int)in.eof(),
7910 sToken.str().c_str());
7911 }
7912
7913 // Error handling
7914 if (sToken.bad()) {
7915 // How could that happen for a stringstream?
7916 Warning("ReadStream",
7917 "Buffer error while reading data for branch %s on line %lld",
7918 branch->GetName(), nlines);
7919 } else if (!sToken.eof()) {
7920 if (sToken.fail()) {
7921 Warning("ReadStream",
7922 "Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
7923 tok.Data(), branch->GetName(), nlines);
7924 goodLine = false;
7925 } else {
7926 std::string remainder;
7927 std::getline(sToken, remainder, newline);
7928 if (!remainder.empty()) {
7929 Warning("ReadStream",
7930 "Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
7931 remainder.c_str(), branch->GetName(), nlines);
7932 }
7933 }
7934 }
7935 } // tokenizer loop
7936
7937 if (iBranch < nbranches) {
7938 Warning("ReadStream",
7939 "Read too few columns (%d < %d) in line %lld; ignoring line",
7941 goodLine = false;
7942 } else if (pos != kNPOS) {
7944 if (pos < sLine.Length()) {
7945 Warning("ReadStream",
7946 "Ignoring trailing \"%s\" while reading line %lld",
7947 sLine.Data() + pos - 1 /* also print delimiter */,
7948 nlines);
7949 }
7950 }
7951
7952 //we are now ready to fill the tree
7953 if (goodLine) {
7954 Fill();
7955 ++nGoodLines;
7956 }
7957 }
7958
7959 return nGoodLines;
7960}
7961
7962////////////////////////////////////////////////////////////////////////////////
7963/// Make sure that obj (which is being deleted or will soon be) is no
7964/// longer referenced by this TTree.
7967{
7968 if (obj == fEventList) {
7969 fEventList = nullptr;
7970 }
7971 if (obj == fEntryList) {
7972 fEntryList = nullptr;
7973 }
7974 if (fUserInfo) {
7976 }
7977 if (fPlayer == obj) {
7978 fPlayer = nullptr;
7979 }
7980 if (fTreeIndex == obj) {
7981 fTreeIndex = nullptr;
7982 }
7983 if (fAliases == obj) {
7984 fAliases = nullptr;
7985 } else if (fAliases) {
7987 }
7988 if (fFriends == obj) {
7989 fFriends = nullptr;
7990 } else if (fFriends) {
7992 }
7993}
7994
7995////////////////////////////////////////////////////////////////////////////////
7996/// Refresh contents of this tree and its branches from the current status on disk.
7997///
7998/// One can call this function in case the tree file is being
7999/// updated by another process.
8001void TTree::Refresh()
8002{
8003 if (!fDirectory->GetFile()) {
8004 return;
8005 }
8007 fDirectory->Remove(this);
8008 TTree* tree; fDirectory->GetObject(GetName(),tree);
8009 if (!tree) {
8010 return;
8011 }
8012 //copy info from tree header into this Tree
8013 fEntries = 0;
8014 fNClusterRange = 0;
8015 ImportClusterRanges(tree);
8016
8017 fAutoSave = tree->fAutoSave;
8018 fEntries = tree->fEntries;
8019 fTotBytes = tree->GetTotBytes();
8020 fZipBytes = tree->GetZipBytes();
8021 fSavedBytes = tree->fSavedBytes;
8022 fTotalBuffers = tree->fTotalBuffers.load();
8023
8024 //loop on all branches and update them
8026 for (Int_t i = 0; i < nleaves; i++) {
8028 TBranch* branch = (TBranch*) leaf->GetBranch();
8029 branch->Refresh(tree->GetBranch(branch->GetName()));
8030 }
8031 fDirectory->Remove(tree);
8032 fDirectory->Append(this);
8033 delete tree;
8034 tree = nullptr;
8035}
8036
8037////////////////////////////////////////////////////////////////////////////////
8038/// Record a TFriendElement that we need to warn when the chain switches to
8039/// a new file (typically this is because this chain is a friend of another
8040/// TChain)
8047}
8048
8049
8050////////////////////////////////////////////////////////////////////////////////
8051/// Removes external friend
8056}
8057
8058
8059////////////////////////////////////////////////////////////////////////////////
8060/// Remove a friend from the list of friends.
8063{
8064 // We already have been visited while recursively looking
8065 // through the friends tree, let return
8067 return;
8068 }
8069 if (!fFriends) {
8070 return;
8071 }
8072 TFriendLock lock(this, kRemoveFriend);
8074 TFriendElement* fe = nullptr;
8075 while ((fe = (TFriendElement*) nextf())) {
8076 TTree* friend_t = fe->GetTree();
8077 if (friend_t == oldFriend) {
8078 fFriends->Remove(fe);
8079 delete fe;
8080 fe = nullptr;
8081 }
8082 }
8083}
8084
8085////////////////////////////////////////////////////////////////////////////////
8086/// Reset baskets, buffers and entries count in all branches and leaves.
8089{
8090 fNotify = nullptr;
8091 fEntries = 0;
8092 fNClusterRange = 0;
8093 fTotBytes = 0;
8094 fZipBytes = 0;
8095 fFlushedBytes = 0;
8096 fSavedBytes = 0;
8097 fTotalBuffers = 0;
8098 fChainOffset = 0;
8099 fReadEntry = -1;
8100
8101 delete fTreeIndex;
8102 fTreeIndex = nullptr;
8103
8105 for (Int_t i = 0; i < nb; ++i) {
8107 branch->Reset(option);
8108 }
8109
8110 if (fBranchRef) {
8111 fBranchRef->Reset();
8112 }
8113}
8114
8115////////////////////////////////////////////////////////////////////////////////
8116/// Resets the state of this TTree after a merge (keep the customization but
8117/// forget the data).
8120{
8121 fEntries = 0;
8122 fNClusterRange = 0;
8123 fTotBytes = 0;
8124 fZipBytes = 0;
8125 fSavedBytes = 0;
8126 fFlushedBytes = 0;
8127 fTotalBuffers = 0;
8128 fChainOffset = 0;
8129 fReadEntry = -1;
8130
8131 delete fTreeIndex;
8132 fTreeIndex = nullptr;
8133
8135 for (Int_t i = 0; i < nb; ++i) {
8137 branch->ResetAfterMerge(info);
8138 }
8139
8140 if (fBranchRef) {
8142 }
8143}
8144
8145////////////////////////////////////////////////////////////////////////////////
8146/// Tell a branch to set its address to zero.
8147///
8148/// @note If the branch owns any objects, they are deleted.
8151{
8152 if (br && br->GetTree()) {
8153 br->ResetAddress();
8154 }
8155}
8156
8157////////////////////////////////////////////////////////////////////////////////
8158/// Tell all of our branches to drop their current objects and allocate new ones.
8161{
8162 // We already have been visited while recursively looking
8163 // through the friends tree, let return
8165 return;
8166 }
8168 Int_t nbranches = branches->GetEntriesFast();
8169 for (Int_t i = 0; i < nbranches; ++i) {
8170 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
8171 branch->ResetAddress();
8172 }
8173 if (fFriends) {
8176 auto *frTree = frEl->GetTree();
8177 if (frTree) {
8178 frTree->ResetBranchAddresses();
8179 }
8180 }
8181 }
8182}
8183
8184////////////////////////////////////////////////////////////////////////////////
8185/// Loop over tree entries and print entries passing selection. Interactive
8186/// pagination break is on by default.
8187///
8188/// - If varexp is 0 (or "") then print only first 8 columns.
8189/// - If varexp = "*" print all columns.
8190///
8191/// Otherwise a columns selection can be made using "var1:var2:var3".
8192///
8193/// \param firstentry first entry to scan
8194/// \param nentries total number of entries to scan (starting from firstentry). Defaults to all entries.
8195/// \note see TTree::SetScanField to control how many lines are printed between pagination breaks (Use 0 to disable pagination)
8196/// \see TTreePlayer::Scan
8199{
8200 GetPlayer();
8201 if (fPlayer) {
8203 }
8204 return -1;
8205}
8206
8207////////////////////////////////////////////////////////////////////////////////
8208/// Set a tree variable alias.
8209///
8210/// Set an alias for an expression/formula based on the tree 'variables'.
8211///
8212/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
8213/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
8214/// 'aliasFormula'.
8215///
8216/// If the content of 'aliasFormula' only contains symbol names, periods and
8217/// array index specification (for example event.fTracks[3]), then
8218/// the content of 'aliasName' can be used as the start of symbol.
8219///
8220/// If the alias 'aliasName' already existed, it is replaced by the new
8221/// value.
8222///
8223/// When being used, the alias can be preceded by an eventual 'Friend Alias'
8224/// (see TTree::GetFriendAlias)
8225///
8226/// Return true if it was added properly.
8227///
8228/// For example:
8229/// ~~~ {.cpp}
8230/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
8231/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
8232/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
8233/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
8234/// tree->Draw("y2-y1:x2-x1");
8235///
8236/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
8237/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
8238/// ~~~
8240bool TTree::SetAlias(const char* aliasName, const char* aliasFormula)
8241{
8242 if (!aliasName || !aliasFormula) {
8243 return false;
8244 }
8245 if (!aliasName[0] || !aliasFormula[0]) {
8246 return false;
8247 }
8248 if (!fAliases) {
8249 fAliases = new TList;
8250 } else {
8252 if (oldHolder) {
8253 oldHolder->SetTitle(aliasFormula);
8254 return true;
8255 }
8256 }
8259 return true;
8260}
8261
8262////////////////////////////////////////////////////////////////////////////////
8263/// This function may be called at the start of a program to change
8264/// the default value for fAutoFlush.
8265///
8266/// ### CASE 1 : autof > 0
8267///
8268/// autof is the number of consecutive entries after which TTree::Fill will
8269/// flush all branch buffers to disk.
8270///
8271/// ### CASE 2 : autof < 0
8272///
8273/// When filling the Tree the branch buffers will be flushed to disk when
8274/// more than autof bytes have been written to the file. At the first FlushBaskets
8275/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
8276///
8277/// Calling this function with autof<0 is interesting when it is hard to estimate
8278/// the size of one entry. This value is also independent of the Tree.
8279///
8280/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
8281/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
8282///
8283/// ### CASE 3 : autof = 0
8284///
8285/// The AutoFlush mechanism is disabled.
8286///
8287/// Flushing the buffers at regular intervals optimize the location of
8288/// consecutive entries on the disk by creating clusters of baskets.
8289///
8290/// A cluster of baskets is a set of baskets that contains all
8291/// the data for a (consecutive) set of entries and that is stored
8292/// consecutively on the disk. When reading all the branches, this
8293/// is the minimum set of baskets that the TTreeCache will read.
8295void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
8296{
8297 // Implementation note:
8298 //
8299 // A positive value of autoflush determines the size (in number of entries) of
8300 // a cluster of baskets.
8301 //
8302 // If the value of autoflush is changed over time (this happens in
8303 // particular when the TTree results from fast merging many trees),
8304 // we record the values of fAutoFlush in the data members:
8305 // fClusterRangeEnd and fClusterSize.
8306 // In the code we refer to a range of entries where the size of the
8307 // cluster of baskets is the same (i.e the value of AutoFlush was
8308 // constant) is called a ClusterRange.
8309 //
8310 // The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
8311 // active (used) values and have fMaxClusterRange allocated entries.
8312 //
8313 // fClusterRangeEnd contains the last entries number of a cluster range.
8314 // In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
8315 // fClusterSize contains the size in number of entries of all the cluster
8316 // within the given range.
8317 // The last range (and the only one if fNClusterRange is zero) start at
8318 // fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
8319 // size of the cluster in this range is given by the value of fAutoFlush.
8320 //
8321 // For example printing the beginning and end of each the ranges can be done by:
8322 //
8323 // Printf("%-16s %-16s %-16s %5s",
8324 // "Cluster Range #", "Entry Start", "Last Entry", "Size");
8325 // Int_t index= 0;
8326 // Long64_t clusterRangeStart = 0;
8327 // if (fNClusterRange) {
8328 // for( ; index < fNClusterRange; ++index) {
8329 // Printf("%-16d %-16lld %-16lld %5lld",
8330 // index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
8331 // clusterRangeStart = fClusterRangeEnd[index] + 1;
8332 // }
8333 // }
8334 // Printf("%-16d %-16lld %-16lld %5lld",
8335 // index, prevEntry, fEntries - 1, fAutoFlush);
8336 //
8337
8338 // Note: We store the entry number corresponding to the end of the cluster
8339 // rather than its start in order to avoid using the array if the cluster
8340 // size never varies (If there is only one value of AutoFlush for the whole TTree).
8341
8342 if( fAutoFlush != autof) {
8343 if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
8344 // The mechanism was already enabled, let's record the previous
8345 // cluster if needed.
8347 }
8348 fAutoFlush = autof;
8349 }
8350}
8351
8352////////////////////////////////////////////////////////////////////////////////
8353/// Mark the previous event as being at the end of the event cluster.
8354///
8355/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
8356/// is called, then the first cluster has 9 events.
8358{
8359 if (!fEntries) return;
8360
8361 if ( (fNClusterRange+1) > fMaxClusterRange ) {
8362 if (fMaxClusterRange) {
8363 // Resize arrays to hold a larger event cluster.
8366 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8368 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8370 } else {
8371 // Cluster ranges have never been initialized; create them now.
8372 fMaxClusterRange = 2;
8375 }
8376 }
8378 // If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
8379 if (fAutoFlush > 0) {
8380 // Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
8381 // will appropriately go to the next event range.
8383 // Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
8384 } else if (fNClusterRange == 0) {
8386 } else {
8388 }
8390}
8391
8392/// Estimate the median cluster size for the TTree.
8393/// This value provides e.g. a reasonable cache size default if other heuristics fail.
8394/// Clusters with size 0 and the very last cluster range, that might not have been committed to fClusterSize yet,
8395/// are ignored for the purposes of the calculation.
8397{
8398 std::vector<Long64_t> clusterSizesPerRange;
8400
8401 // We ignore cluster sizes of 0 for the purposes of this function.
8402 // We also ignore the very last cluster range which might not have been committed to fClusterSize.
8403 std::copy_if(fClusterSize, fClusterSize + fNClusterRange, std::back_inserter(clusterSizesPerRange),
8404 [](Long64_t size) { return size != 0; });
8405
8406 std::vector<double> nClustersInRange; // we need to store doubles because of the signature of TMath::Median
8407 nClustersInRange.reserve(clusterSizesPerRange.size());
8408
8409 auto clusterRangeStart = 0ll;
8410 for (int i = 0; i < fNClusterRange; ++i) {
8411 const auto size = fClusterSize[i];
8412 R__ASSERT(size >= 0);
8413 if (fClusterSize[i] == 0)
8414 continue;
8415 const auto nClusters = (1 + fClusterRangeEnd[i] - clusterRangeStart) / fClusterSize[i];
8416 nClustersInRange.emplace_back(nClusters);
8418 }
8419
8421 const auto medianClusterSize =
8423 return medianClusterSize;
8424}
8425
8426////////////////////////////////////////////////////////////////////////////////
8427/// In case of a program crash, it will be possible to recover the data in the
8428/// tree up to the last AutoSave point.
8429/// This function may be called before filling a TTree to specify when the
8430/// branch buffers and TTree header are flushed to disk as part of
8431/// TTree::Fill().
8432/// The default is -300000000, ie the TTree will write data to disk once it
8433/// exceeds 300 MBytes.
8434/// CASE 1: If fAutoSave is positive the watermark is reached when a multiple of
8435/// fAutoSave entries have been filled.
8436/// CASE 2: If fAutoSave is negative the watermark is reached when -fAutoSave
8437/// bytes can be written to the file.
8438/// CASE 3: If fAutoSave is 0, AutoSave() will never be called automatically
8439/// as part of TTree::Fill().
8444}
8445
8446////////////////////////////////////////////////////////////////////////////////
8447/// Set a branch's basket size.
8448///
8449/// bname is the name of a branch.
8450///
8451/// - if bname="*", apply to all branches.
8452/// - if bname="xxx*", apply to all branches with name starting with xxx
8453///
8454/// see TRegexp for wildcarding options
8455/// buffsize = branc basket size
8457void TTree::SetBasketSize(const char* bname, Int_t buffsize)
8458{
8460 TRegexp re(bname, true);
8461 Int_t nb = 0;
8462 for (Int_t i = 0; i < nleaves; i++) {
8464 TBranch* branch = (TBranch*) leaf->GetBranch();
8465 TString s = branch->GetName();
8466 if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
8467 continue;
8468 }
8469 nb++;
8470 branch->SetBasketSize(buffsize);
8471 }
8472 if (!nb) {
8473 Error("SetBasketSize", "unknown branch -> '%s'", bname);
8474 }
8475}
8476
8477////////////////////////////////////////////////////////////////////////////////
8478/// Change branch address, dealing with clone trees properly.
8479/// See TTree::CheckBranchAddressType for the semantic of the return value.
8480///
8481/// Note: See the comments in TBranchElement::SetAddress() for the
8482/// meaning of the addr parameter and the object ownership policy.
8484Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
8485{
8486 TBranch* branch = GetBranch(bname);
8487 if (!branch) {
8488 if (ptr) *ptr = nullptr;
8489 Error("SetBranchAddress", "unknown branch -> %s", bname);
8490 return kMissingBranch;
8491 }
8492 return SetBranchAddressImp(branch,addr,ptr);
8493}
8494
8495////////////////////////////////////////////////////////////////////////////////
8496/// Verify the validity of the type of addr before calling SetBranchAddress.
8497/// See TTree::CheckBranchAddressType for the semantic of the return value.
8498///
8499/// Note: See the comments in TBranchElement::SetAddress() for the
8500/// meaning of the addr parameter and the object ownership policy.
8502Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, bool isptr)
8503{
8504 return SetBranchAddress(bname, addr, nullptr, ptrClass, datatype, isptr);
8505}
8506
8507////////////////////////////////////////////////////////////////////////////////
8508/// Verify the validity of the type of addr before calling SetBranchAddress.
8509/// See TTree::CheckBranchAddressType for the semantic of the return value.
8510///
8511/// Note: See the comments in TBranchElement::SetAddress() for the
8512/// meaning of the addr parameter and the object ownership policy.
8514Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, bool isptr)
8515{
8516 TBranch* branch = GetBranch(bname);
8517 if (!branch) {
8518 if (ptr) *ptr = nullptr;
8519 Error("SetBranchAddress", "unknown branch -> %s", bname);
8520 return kMissingBranch;
8521 }
8522
8524
8525 // This will set the value of *ptr to branch.
8526 if (res >= 0) {
8527 // The check succeeded.
8528 if ((res & kNeedEnableDecomposedObj) && !branch->GetMakeClass())
8529 branch->SetMakeClass(true);
8531 } else {
8532 if (ptr) *ptr = nullptr;
8533 }
8534 return res;
8535}
8536
8537////////////////////////////////////////////////////////////////////////////////
8538/// Change branch address, dealing with clone trees properly.
8539/// See TTree::CheckBranchAddressType for the semantic of the return value.
8540///
8541/// Note: See the comments in TBranchElement::SetAddress() for the
8542/// meaning of the addr parameter and the object ownership policy.
8545{
8546 if (ptr) {
8547 *ptr = branch;
8548 }
8549 if (fClones) {
8550 void* oldAddr = branch->GetAddress();
8551 TIter next(fClones);
8552 TTree* clone = nullptr;
8553 const char *bname = branch->GetName();
8554 while ((clone = (TTree*) next())) {
8555 TBranch* cloneBr = clone->GetBranch(bname);
8556 if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
8557 cloneBr->SetAddress(addr);
8558 }
8559 }
8560 }
8561 branch->SetAddress(addr);
8562 return kVoidPtr;
8563}
8564
8565////////////////////////////////////////////////////////////////////////////////
8566/// Set branch status to Process or DoNotProcess.
8567///
8568/// When reading a Tree, by default, all branches are read.
8569/// One can speed up considerably the analysis phase by activating
8570/// only the branches that hold variables involved in a query.
8571///
8572/// bname is the name of a branch.
8573///
8574/// - if bname="*", apply to all branches.
8575/// - if bname="xxx*", apply to all branches with name starting with xxx
8576///
8577/// see TRegexp for wildcarding options
8578///
8579/// - status = 1 branch will be processed
8580/// - = 0 branch will not be processed
8581///
8582/// Example:
8583///
8584/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
8585/// when doing T.GetEntry(i) all branches are read for entry i.
8586/// to read only the branches c and e, one can do
8587/// ~~~ {.cpp}
8588/// T.SetBranchStatus("*",0); //disable all branches
8589/// T.SetBranchStatus("c",1);
8590/// T.setBranchStatus("e",1);
8591/// T.GetEntry(i);
8592/// ~~~
8593/// bname is interpreted as a wild-carded TRegexp (see TRegexp::MakeWildcard).
8594/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
8595/// "b", but not any other branch with an "a" followed at some point by a
8596/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
8597/// support '|', and so you cannot select, e.g. track and shower branches
8598/// with "track|shower".
8599///
8600/// __WARNING! WARNING! WARNING!__
8601///
8602/// SetBranchStatus is matching the branch based on match of the branch
8603/// 'name' and not on the branch hierarchy! In order to be able to
8604/// selectively enable a top level object that is 'split' you need to make
8605/// sure the name of the top level branch is prefixed to the sub-branches'
8606/// name (by adding a dot ('.') at the end of the Branch creation and use the
8607/// corresponding bname.
8608///
8609/// I.e If your Tree has been created in split mode with a parent branch "parent."
8610/// (note the trailing dot).
8611/// ~~~ {.cpp}
8612/// T.SetBranchStatus("parent",1);
8613/// ~~~
8614/// will not activate the sub-branches of "parent". You should do:
8615/// ~~~ {.cpp}
8616/// T.SetBranchStatus("parent*",1);
8617/// ~~~
8618/// Without the trailing dot in the branch creation you have no choice but to
8619/// call SetBranchStatus explicitly for each of the sub branches.
8620///
8621/// An alternative to this function is to read directly and only
8622/// the interesting branches. Example:
8623/// ~~~ {.cpp}
8624/// TBranch *brc = T.GetBranch("c");
8625/// TBranch *bre = T.GetBranch("e");
8626/// brc->GetEntry(i);
8627/// bre->GetEntry(i);
8628/// ~~~
8629/// If found is not 0, the number of branch(es) found matching the regular
8630/// expression is returned in *found AND the error message 'unknown branch'
8631/// is suppressed.
8633void TTree::SetBranchStatus(const char* bname, bool status, UInt_t* found)
8634{
8635 // We already have been visited while recursively looking
8636 // through the friends tree, let return
8638 return;
8639 }
8640
8641 if (!bname || !*bname) {
8642 Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
8643 return;
8644 }
8645
8647 TLeaf *leaf, *leafcount;
8648
8649 Int_t i,j;
8651 TRegexp re(bname,true);
8652 Int_t nb = 0;
8653
8654 // first pass, loop on all branches
8655 // for leafcount branches activate/deactivate in function of status
8656 for (i=0;i<nleaves;i++) {
8658 branch = (TBranch*)leaf->GetBranch();
8659 TString s = branch->GetName();
8660 if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
8662 longname.Form("%s.%s",GetName(),branch->GetName());
8663 if (strcmp(bname,branch->GetName())
8664 && longname != bname
8665 && s.Index(re) == kNPOS) continue;
8666 }
8667 nb++;
8668 if (status) branch->ResetBit(kDoNotProcess);
8669 else branch->SetBit(kDoNotProcess);
8670 leafcount = leaf->GetLeafCount();
8671 if (leafcount) {
8672 bcount = leafcount->GetBranch();
8673 if (status) bcount->ResetBit(kDoNotProcess);
8674 else bcount->SetBit(kDoNotProcess);
8675 }
8676 }
8677 if (nb==0 && !strchr(bname,'*')) {
8678 branch = GetBranch(bname);
8679 if (branch) {
8680 if (status) branch->ResetBit(kDoNotProcess);
8681 else branch->SetBit(kDoNotProcess);
8682 ++nb;
8683 }
8684 }
8685
8686 //search in list of friends
8688 if (fFriends) {
8689 TFriendLock lock(this,kSetBranchStatus);
8692 TString name;
8693 while ((fe = (TFriendElement*)nextf())) {
8694 TTree *t = fe->GetTree();
8695 if (!t) continue;
8696
8697 // If the alias is present replace it with the real name.
8698 const char *subbranch = strstr(bname,fe->GetName());
8699 if (subbranch!=bname) subbranch = nullptr;
8700 if (subbranch) {
8701 subbranch += strlen(fe->GetName());
8702 if ( *subbranch != '.' ) subbranch = nullptr;
8703 else subbranch ++;
8704 }
8705 if (subbranch) {
8706 name.Form("%s.%s",t->GetName(),subbranch);
8707 } else {
8708 name = bname;
8709 }
8710 t->SetBranchStatus(name,status, &foundInFriend);
8711 }
8712 }
8713 if (!nb && !foundInFriend) {
8714 if (!found) {
8715 if (status) {
8716 if (strchr(bname,'*') != nullptr)
8717 Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8718 else
8719 Error("SetBranchStatus", "unknown branch -> %s", bname);
8720 } else {
8721 if (strchr(bname,'*') != nullptr)
8722 Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8723 else
8724 Warning("SetBranchStatus", "unknown branch -> %s", bname);
8725 }
8726 }
8727 return;
8728 }
8729 if (found) *found = nb + foundInFriend;
8730
8731 // second pass, loop again on all branches
8732 // activate leafcount branches for active branches only
8733 for (i = 0; i < nleaves; i++) {
8735 branch = (TBranch*)leaf->GetBranch();
8736 if (!branch->TestBit(kDoNotProcess)) {
8737 leafcount = leaf->GetLeafCount();
8738 if (leafcount) {
8739 bcount = leafcount->GetBranch();
8740 bcount->ResetBit(kDoNotProcess);
8741 }
8742 } else {
8743 //Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
8744 Int_t nbranches = branch->GetListOfBranches()->GetEntries();
8745 for (j=0;j<nbranches;j++) {
8746 bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
8747 if (!bson) continue;
8748 if (!bson->TestBit(kDoNotProcess)) {
8749 if (bson->GetNleaves() <= 0) continue;
8750 branch->ResetBit(kDoNotProcess);
8751 break;
8752 }
8753 }
8754 }
8755 }
8756}
8757
8758////////////////////////////////////////////////////////////////////////////////
8759/// Set the current branch style. (static function)
8760///
8761/// - style = 0 old Branch
8762/// - style = 1 new Bronch
8767}
8768
8769////////////////////////////////////////////////////////////////////////////////
8770/// Set maximum size of the file cache .
8771//
8772/// - if cachesize = 0 the existing cache (if any) is deleted.
8773/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
8774/// the Tree (default is 30 MBytes).
8775///
8776/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
8777///
8778/// Returns:
8779/// - 0 size set, cache was created if possible
8780/// - -1 on error
8783{
8784 // remember that the user has requested an explicit cache setup
8785 fCacheUserSet = true;
8786
8787 return SetCacheSizeAux(false, cacheSize);
8788}
8789
8790////////////////////////////////////////////////////////////////////////////////
8791/// Set the size of the file cache and create it if possible.
8792///
8793/// If autocache is true:
8794/// this may be an autocreated cache, possibly enlarging an existing
8795/// autocreated cache. The size is calculated. The value passed in cacheSize:
8796/// - cacheSize = 0 make cache if default cache creation is enabled
8797/// - cacheSize = -1 make a default sized cache in any case
8798///
8799/// If autocache is false:
8800/// this is a user requested cache. cacheSize is used to size the cache.
8801/// This cache should never be automatically adjusted.
8802///
8803/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
8804///
8805/// Returns:
8806/// - 0 size set, or existing autosized cache almost large enough.
8807/// (cache was created if possible)
8808/// - -1 on error
8810Int_t TTree::SetCacheSizeAux(bool autocache /* = true */, Long64_t cacheSize /* = 0 */ )
8811{
8812 if (autocache) {
8813 // used as a once only control for automatic cache setup
8814 fCacheDoAutoInit = false;
8815 }
8816
8817 if (!autocache) {
8818 // negative size means the user requests the default
8819 if (cacheSize < 0) {
8820 cacheSize = GetCacheAutoSize(true);
8821 }
8822 } else {
8823 if (cacheSize == 0) {
8824 cacheSize = GetCacheAutoSize();
8825 } else if (cacheSize < 0) {
8826 cacheSize = GetCacheAutoSize(true);
8827 }
8828 }
8829
8830 TFile* file = GetCurrentFile();
8831 if (!file || GetTree() != this) {
8832 // if there's no file or we are not a plain tree (e.g. if we're a TChain)
8833 // do not create a cache, only record the size if one was given
8834 if (!autocache) {
8835 fCacheSize = cacheSize;
8836 }
8837 if (GetTree() != this) {
8838 return 0;
8839 }
8840 if (!autocache && cacheSize>0) {
8841 Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
8842 }
8843 return 0;
8844 }
8845
8846 // Check for an existing cache
8847 TTreeCache* pf = GetReadCache(file);
8848 if (pf) {
8849 if (autocache) {
8850 // reset our cache status tracking in case existing cache was added
8851 // by the user without using one of the TTree methods
8852 fCacheSize = pf->GetBufferSize();
8853 fCacheUserSet = !pf->IsAutoCreated();
8854
8855 if (fCacheUserSet) {
8856 // existing cache was created by the user, don't change it
8857 return 0;
8858 }
8859 } else {
8860 // update the cache to ensure it records the user has explicitly
8861 // requested it
8862 pf->SetAutoCreated(false);
8863 }
8864
8865 // if we're using an automatically calculated size and the existing
8866 // cache is already almost large enough don't resize
8867 if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
8868 // already large enough
8869 return 0;
8870 }
8871
8872 if (cacheSize == fCacheSize) {
8873 return 0;
8874 }
8875
8876 if (cacheSize == 0) {
8877 // delete existing cache
8878 pf->WaitFinishPrefetch();
8879 file->SetCacheRead(nullptr,this);
8880 delete pf;
8881 pf = nullptr;
8882 } else {
8883 // resize
8884 Int_t res = pf->SetBufferSize(cacheSize);
8885 if (res < 0) {
8886 return -1;
8887 }
8888 cacheSize = pf->GetBufferSize(); // update after potential clamp
8889 }
8890 } else {
8891 // no existing cache
8892 if (autocache) {
8893 if (fCacheUserSet) {
8894 // value was already set manually.
8895 if (fCacheSize == 0) return 0;
8896 // Expected a cache should exist; perhaps the user moved it
8897 // Do nothing more here.
8898 if (cacheSize) {
8899 Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
8900 }
8901 return -1;
8902 }
8903 }
8904 }
8905
8906 fCacheSize = cacheSize;
8907 if (cacheSize == 0 || pf) {
8908 return 0;
8909 }
8910
8911#ifdef R__USE_IMT
8913 pf = new TTreeCacheUnzip(this, cacheSize);
8914 else
8915#endif
8916 pf = new TTreeCache(this, cacheSize);
8917
8918 pf->SetAutoCreated(autocache);
8919
8920 return 0;
8921}
8922
8923////////////////////////////////////////////////////////////////////////////////
8924///interface to TTreeCache to set the cache entry range
8925///
8926/// Returns:
8927/// - 0 entry range set
8928/// - -1 on error
8931{
8932 if (!GetTree()) {
8933 if (LoadTree(0)<0) {
8934 Error("SetCacheEntryRange","Could not load a tree");
8935 return -1;
8936 }
8937 }
8938 if (GetTree()) {
8939 if (GetTree() != this) {
8940 return GetTree()->SetCacheEntryRange(first, last);
8941 }
8942 } else {
8943 Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
8944 return -1;
8945 }
8946
8947 TFile *f = GetCurrentFile();
8948 if (!f) {
8949 Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
8950 return -1;
8951 }
8952 TTreeCache *tc = GetReadCache(f,true);
8953 if (!tc) {
8954 Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
8955 return -1;
8956 }
8957 tc->SetEntryRange(first,last);
8958 return 0;
8959}
8960
8961////////////////////////////////////////////////////////////////////////////////
8962/// Interface to TTreeCache to set the number of entries for the learning phase
8967}
8968
8969////////////////////////////////////////////////////////////////////////////////
8970/// Enable/Disable circularity for this tree.
8971///
8972/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
8973/// per branch in memory.
8974/// Note that when this function is called (maxEntries>0) the Tree
8975/// must be empty or having only one basket per branch.
8976/// if maxEntries <= 0 the tree circularity is disabled.
8977///
8978/// #### NOTE 1:
8979/// Circular Trees are interesting in online real time environments
8980/// to store the results of the last maxEntries events.
8981/// #### NOTE 2:
8982/// Calling SetCircular with maxEntries <= 0 is necessary before
8983/// merging circular Trees that have been saved on files.
8984/// #### NOTE 3:
8985/// SetCircular with maxEntries <= 0 is automatically called
8986/// by TChain::Merge
8987/// #### NOTE 4:
8988/// A circular Tree can still be saved in a file. When read back,
8989/// it is still a circular Tree and can be filled again.
8992{
8993 if (maxEntries <= 0) {
8994 // Disable circularity.
8995 fMaxEntries = 1000000000;
8996 fMaxEntries *= 1000;
8998 //in case the Tree was originally created in gROOT, the branch
8999 //compression level was set to -1. If the Tree is now associated to
9000 //a file, reset the compression level to the file compression level
9001 if (fDirectory) {
9004 if (bfile) {
9005 compress = bfile->GetCompressionSettings();
9006 }
9008 for (Int_t i = 0; i < nb; i++) {
9010 branch->SetCompressionSettings(compress);
9011 }
9012 }
9013 } else {
9014 // Enable circularity.
9017 }
9018}
9019
9020////////////////////////////////////////////////////////////////////////////////
9021/// Set the debug level and the debug range.
9022///
9023/// For entries in the debug range, the functions TBranchElement::Fill
9024/// and TBranchElement::GetEntry will print the number of bytes filled
9025/// or read for each branch.
9027void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
9028{
9029 fDebug = level;
9030 fDebugMin = min;
9031 fDebugMax = max;
9032}
9033
9034////////////////////////////////////////////////////////////////////////////////
9035/// Update the default value for the branch's fEntryOffsetLen.
9036/// If updateExisting is true, also update all the existing branches.
9037/// If newdefault is less than 10, the new default value will be 10.
9040{
9041 if (newdefault < 10) {
9042 newdefault = 10;
9043 }
9045 if (updateExisting) {
9046 TIter next( GetListOfBranches() );
9047 TBranch *b;
9048 while ( ( b = (TBranch*)next() ) ) {
9049 b->SetEntryOffsetLen( newdefault, true );
9050 }
9051 if (fBranchRef) {
9053 }
9054 }
9055}
9056
9057////////////////////////////////////////////////////////////////////////////////
9058/// Change the tree's directory.
9059///
9060/// Remove reference to this tree from current directory and
9061/// add reference to new directory dir. The dir parameter can
9062/// be 0 in which case the tree does not belong to any directory.
9063///
9066{
9067 if (fDirectory == dir) {
9068 return;
9069 }
9070 if (fDirectory) {
9071 fDirectory->Remove(this);
9072
9073 // Delete or move the file cache if it points to this Tree
9074 TFile *file = fDirectory->GetFile();
9075 MoveReadCache(file,dir);
9076 }
9077 fDirectory = dir;
9078 if (fDirectory) {
9079 fDirectory->Append(this);
9080 }
9081 TFile* file = nullptr;
9082 if (fDirectory) {
9083 file = fDirectory->GetFile();
9084 }
9085 if (fBranchRef) {
9086 fBranchRef->SetFile(file);
9087 }
9088 TBranch* b = nullptr;
9089 TIter next(GetListOfBranches());
9090 while((b = (TBranch*) next())) {
9091 b->SetFile(file);
9092 }
9093}
9094
9095////////////////////////////////////////////////////////////////////////////////
9096/// Change number of entries in the tree.
9097///
9098/// If n >= 0, set number of entries in the tree = n.
9099///
9100/// If n < 0, set number of entries in the tree to match the
9101/// number of entries in each branch. (default for n is -1)
9102///
9103/// This function should be called only when one fills each branch
9104/// independently via TBranch::Fill without calling TTree::Fill.
9105/// Calling TTree::SetEntries() make sense only if the number of entries
9106/// in each branch is identical, a warning is issued otherwise.
9107/// The function returns the number of entries.
9108///
9111{
9112 // case 1 : force number of entries to n
9113 if (n >= 0) {
9114 fEntries = n;
9115 return n;
9116 }
9117
9118 // case 2; compute the number of entries from the number of entries in the branches
9119 TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
9121 Long64_t nMax = 0;
9122 TIter next(GetListOfBranches());
9123 while((b = (TBranch*) next())){
9124 Long64_t n2 = b->GetEntries();
9125 if (!bMin || n2 < nMin) {
9126 nMin = n2;
9127 bMin = b;
9128 }
9129 if (!bMax || n2 > nMax) {
9130 nMax = n2;
9131 bMax = b;
9132 }
9133 }
9134 if (bMin && nMin != nMax) {
9135 Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
9136 bMin->GetName(), nMin, bMax->GetName(), nMax);
9137 }
9138 fEntries = nMax;
9139 return fEntries;
9140}
9141
9142////////////////////////////////////////////////////////////////////////////////
9143/// Set an EntryList
9146{
9147 if (fEntryList) {
9148 //check if the previous entry list is owned by the tree
9150 delete fEntryList;
9151 }
9152 }
9153 fEventList = nullptr;
9154 if (!enlist) {
9155 fEntryList = nullptr;
9156 return;
9157 }
9159 fEntryList->SetTree(this);
9160
9161}
9162
9163////////////////////////////////////////////////////////////////////////////////
9164/// This function transfroms the given TEventList into a TEntryList
9165/// The new TEntryList is owned by the TTree and gets deleted when the tree
9166/// is deleted. This TEntryList can be returned by GetEntryList() function.
9169{
9171 if (fEntryList){
9173 TEntryList *tmp = fEntryList;
9174 fEntryList = nullptr; // Avoid problem with RecursiveRemove.
9175 delete tmp;
9176 } else {
9177 fEntryList = nullptr;
9178 }
9179 }
9180
9181 if (!evlist) {
9182 fEntryList = nullptr;
9183 fEventList = nullptr;
9184 return;
9185 }
9186
9188 char enlistname[100];
9189 snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
9190 fEntryList = new TEntryList(enlistname, evlist->GetTitle());
9191 fEntryList->SetDirectory(nullptr); // We own this.
9192 Int_t nsel = evlist->GetN();
9193 fEntryList->SetTree(this);
9195 for (Int_t i=0; i<nsel; i++){
9196 entry = evlist->GetEntry(i);
9198 }
9199 fEntryList->SetReapplyCut(evlist->GetReapplyCut());
9201}
9202
9203////////////////////////////////////////////////////////////////////////////////
9204/// Set number of entries to estimate variable limits.
9205/// If n is -1, the estimate is set to be the current maximum
9206/// for the tree (i.e. GetEntries() + 1)
9207/// If n is less than -1, the behavior is undefined.
9209void TTree::SetEstimate(Long64_t n /* = 1000000 */)
9210{
9211 if (n == 0) {
9212 n = 10000;
9213 } else if (n < 0) {
9214 n = fEntries - n;
9215 }
9216 fEstimate = n;
9217 GetPlayer();
9218 if (fPlayer) {
9220 }
9221}
9222
9223////////////////////////////////////////////////////////////////////////////////
9224/// Provide the end-user with the ability to enable/disable various experimental
9225/// IO features for this TTree.
9226///
9227/// Returns all the newly-set IO settings.
9230{
9231 // Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
9232 // error of their ways; this is just a safety check.
9234
9239
9241 return newSettings;
9242}
9243
9244////////////////////////////////////////////////////////////////////////////////
9245/// Set fFileNumber to number.
9246/// fFileNumber is used by TTree::Fill to set the file name
9247/// for a new file to be created when the current file exceeds fgTreeMaxSize.
9248/// (see TTree::ChangeFile)
9249/// if fFileNumber=10, the new file name will have a suffix "_11",
9250/// ie, fFileNumber is incremented before setting the file name
9252void TTree::SetFileNumber(Int_t number)
9253{
9254 if (fFileNumber < 0) {
9255 Warning("SetFileNumber", "file number must be positive. Set to 0");
9256 fFileNumber = 0;
9257 return;
9258 }
9259 fFileNumber = number;
9260}
9261
9262////////////////////////////////////////////////////////////////////////////////
9263/// Set all the branches in this TTree to be in decomposed object mode
9264/// (also known as MakeClass mode).
9265///
9266/// For MakeClass mode 0, the TTree expects the address where the data is stored
9267/// to be set by either the user or the TTree to the address of a full object
9268/// through the top level branch.
9269/// For MakeClass mode 1, this address is expected to point to a numerical type
9270/// or C-style array (variable or not) of numerical type, representing the
9271/// primitive data members.
9272/// The function's primary purpose is to allow the user to access the data
9273/// directly with numerical type variable rather than having to have the original
9274/// set of classes (or a reproduction thereof).
9275/// In other words, SetMakeClass sets the branch(es) into a
9276/// mode that allow its reading via a set of independant variables
9277/// (see the result of running TTree::MakeClass on your TTree) by changing the
9278/// interpretation of the address passed to SetAddress from being the beginning
9279/// of the object containing the data to being the exact location where the data
9280/// should be loaded. If you have the shared library corresponding to your object,
9281/// it is better if you do
9282/// `MyClass *objp = 0; tree->SetBranchAddress("toplevel",&objp);`, whereas
9283/// if you do not have the shared library but know your branch data type, e.g.
9284/// `Int_t* ptr = new Int_t[10];`, then:
9285/// `tree->SetMakeClass(1); tree->GetBranch("x")->SetAddress(ptr)` is the way to go.
9287void TTree::SetMakeClass(Int_t make)
9288{
9289 fMakeClass = make;
9290
9292 for (Int_t i = 0; i < nb; ++i) {
9294 branch->SetMakeClass(make);
9295 }
9296}
9297
9298////////////////////////////////////////////////////////////////////////////////
9299/// Set the maximum size in bytes of a Tree file (static function).
9300/// The default size is 100000000000LL, ie 100 Gigabytes.
9301///
9302/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
9303/// the function closes the current file and starts writing into
9304/// a new file with a name of the style "file_1.root" if the original
9305/// requested file name was "file.root".
9310}
9311
9312////////////////////////////////////////////////////////////////////////////////
9313/// Change the name of this tree.
9315void TTree::SetName(const char* name)
9316{
9317 if (gPad) {
9318 gPad->Modified();
9319 }
9320 // Trees are named objects in a THashList.
9321 // We must update hashlists if we change the name.
9322 TFile *file = nullptr;
9323 TTreeCache *pf = nullptr;
9324 if (fDirectory) {
9325 fDirectory->Remove(this);
9326 if ((file = GetCurrentFile())) {
9327 pf = GetReadCache(file);
9328 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9329 }
9330 }
9331 // This changes our hash value.
9332 fName = name;
9333 if (fDirectory) {
9334 fDirectory->Append(this);
9335 if (pf) {
9337 }
9338 }
9339}
9341void TTree::SetNotify(TObject *obj)
9342{
9343 if (obj && fNotify && dynamic_cast<TNotifyLinkBase *>(fNotify)) {
9344 auto *oldLink = static_cast<TNotifyLinkBase *>(fNotify);
9345 auto *newLink = dynamic_cast<TNotifyLinkBase *>(obj);
9346 if (!newLink) {
9347 Warning("TTree::SetNotify",
9348 "The tree or chain already has a fNotify registered and it is a TNotifyLink, while the new object is "
9349 "not a TNotifyLink. Setting fNotify to the new value will lead to an orphan linked list of "
9350 "TNotifyLinks and it is most likely not intended. If this is the intended goal, please call "
9351 "SetNotify(nullptr) first to silence this warning.");
9352 } else if (newLink->GetNext() != oldLink && oldLink->GetNext() != newLink) {
9353 // If newLink->GetNext() == oldLink then we are prepending the new head, as in TNotifyLink::PrependLink
9354 // If oldLink->GetNext() == newLink then we are removing the head of the list, as in TNotifyLink::RemoveLink
9355 // Otherwise newLink and oldLink are unrelated:
9356 Warning("TTree::SetNotify",
9357 "The tree or chain already has a TNotifyLink registered, and the new TNotifyLink `obj` does not link "
9358 "to it. Setting fNotify to the new value will lead to an orphan linked list of TNotifyLinks and it is "
9359 "most likely not intended. If this is the intended goal, please call SetNotify(nullptr) first to "
9360 "silence this warning.");
9361 }
9362 }
9363
9364 fNotify = obj;
9365}
9366
9367////////////////////////////////////////////////////////////////////////////////
9368/// Change the name and title of this tree.
9370void TTree::SetObject(const char* name, const char* title)
9371{
9372 if (gPad) {
9373 gPad->Modified();
9374 }
9375
9376 // Trees are named objects in a THashList.
9377 // We must update hashlists if we change the name
9378 TFile *file = nullptr;
9379 TTreeCache *pf = nullptr;
9380 if (fDirectory) {
9381 fDirectory->Remove(this);
9382 if ((file = GetCurrentFile())) {
9383 pf = GetReadCache(file);
9384 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9385 }
9386 }
9387 // This changes our hash value.
9388 fName = name;
9389 fTitle = title;
9390 if (fDirectory) {
9391 fDirectory->Append(this);
9392 if (pf) {
9394 }
9395 }
9396}
9397
9398////////////////////////////////////////////////////////////////////////////////
9399/// Enable or disable parallel unzipping of Tree buffers.
9402{
9403#ifdef R__USE_IMT
9404 if (GetTree() == nullptr) {
9406 if (!GetTree())
9407 return;
9408 }
9409 if (GetTree() != this) {
9410 GetTree()->SetParallelUnzip(opt, RelSize);
9411 return;
9412 }
9413 TFile* file = GetCurrentFile();
9414 if (!file)
9415 return;
9416
9417 TTreeCache* pf = GetReadCache(file);
9418 if (pf && !( opt ^ (nullptr != dynamic_cast<TTreeCacheUnzip*>(pf)))) {
9419 // done with opt and type are in agreement.
9420 return;
9421 }
9422 delete pf;
9423 auto cacheSize = GetCacheAutoSize(true);
9424 if (opt) {
9425 auto unzip = new TTreeCacheUnzip(this, cacheSize);
9426 unzip->SetUnzipBufferSize( Long64_t(cacheSize * RelSize) );
9427 } else {
9428 pf = new TTreeCache(this, cacheSize);
9429 }
9430#else
9431 (void)opt;
9432 (void)RelSize;
9433#endif
9434}
9435
9436////////////////////////////////////////////////////////////////////////////////
9437/// Set perf stats
9442}
9443
9444////////////////////////////////////////////////////////////////////////////////
9445/// The current TreeIndex is replaced by the new index.
9446/// Note that this function does not delete the previous index.
9447/// This gives the possibility to play with more than one index, e.g.,
9448/// ~~~ {.cpp}
9449/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
9450/// tree.SetTreeIndex(newIndex);
9451/// tree.Draw();
9452/// tree.SetTreeIndex(oldIndex);
9453/// tree.Draw(); etc
9454/// ~~~
9457{
9458 if (fTreeIndex) {
9459 fTreeIndex->SetTree(nullptr);
9460 }
9461 fTreeIndex = index;
9462}
9463
9464////////////////////////////////////////////////////////////////////////////////
9465/// Set tree weight.
9466///
9467/// The weight is used by TTree::Draw to automatically weight each
9468/// selected entry in the resulting histogram.
9469///
9470/// For example the equivalent of:
9471/// ~~~ {.cpp}
9472/// T.Draw("x", "w")
9473/// ~~~
9474/// is:
9475/// ~~~ {.cpp}
9476/// T.SetWeight(w);
9477/// T.Draw("x");
9478/// ~~~
9479/// This function is redefined by TChain::SetWeight. In case of a
9480/// TChain, an option "global" may be specified to set the same weight
9481/// for all trees in the TChain instead of the default behaviour
9482/// using the weights of each tree in the chain (see TChain::SetWeight).
9485{
9486 fWeight = w;
9487}
9488
9489////////////////////////////////////////////////////////////////////////////////
9490/// Print values of all active leaves for entry.
9491///
9492/// - if entry==-1, print current entry (default)
9493/// - if a leaf is an array, a maximum of lenmax elements is printed.
9496{
9497 if (entry != -1) {
9499 if (ret == -2) {
9500 Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
9501 return;
9502 } else if (ret == -1) {
9503 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9504 return;
9505 }
9506 ret = GetEntry(entry);
9507 if (ret == -1) {
9508 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9509 return;
9510 } else if (ret == 0) {
9511 Error("Show()", "Cannot read entry %lld (no data read)", entry);
9512 return;
9513 }
9514 }
9515 printf("======> EVENT:%lld\n", fReadEntry);
9517 Int_t nleaves = leaves->GetEntriesFast();
9518 Int_t ltype;
9519 for (Int_t i = 0; i < nleaves; i++) {
9520 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
9521 TBranch* branch = leaf->GetBranch();
9522 if (branch->TestBit(kDoNotProcess)) {
9523 continue;
9524 }
9525 Int_t len = leaf->GetLen();
9526 if (len <= 0) {
9527 continue;
9528 }
9530 if (leaf->IsA() == TLeafElement::Class()) {
9531 leaf->PrintValue(lenmax);
9532 continue;
9533 }
9534 if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
9535 continue;
9536 }
9537 ltype = 10;
9538 if (leaf->IsA() == TLeafF::Class()) {
9539 ltype = 5;
9540 }
9541 if (leaf->IsA() == TLeafD::Class()) {
9542 ltype = 5;
9543 }
9544 if (leaf->IsA() == TLeafC::Class()) {
9545 len = 1;
9546 ltype = 5;
9547 };
9548 printf(" %-15s = ", leaf->GetName());
9549 for (Int_t l = 0; l < len; l++) {
9550 leaf->PrintValue(l);
9551 if (l == (len - 1)) {
9552 printf("\n");
9553 continue;
9554 }
9555 printf(", ");
9556 if ((l % ltype) == 0) {
9557 printf("\n ");
9558 }
9559 }
9560 }
9561}
9562
9563////////////////////////////////////////////////////////////////////////////////
9564/// Start the TTreeViewer on this tree.
9565///
9566/// - ww is the width of the canvas in pixels
9567/// - wh is the height of the canvas in pixels
9569void TTree::StartViewer()
9570{
9571 GetPlayer();
9572 if (fPlayer) {
9573 fPlayer->StartViewer(600, 400);
9574 }
9575}
9576
9577////////////////////////////////////////////////////////////////////////////////
9578/// Stop the cache learning phase
9579///
9580/// Returns:
9581/// - 0 learning phase stopped or not active
9582/// - -1 on error
9585{
9586 if (!GetTree()) {
9587 if (LoadTree(0)<0) {
9588 Error("StopCacheLearningPhase","Could not load a tree");
9589 return -1;
9590 }
9591 }
9592 if (GetTree()) {
9593 if (GetTree() != this) {
9594 return GetTree()->StopCacheLearningPhase();
9595 }
9596 } else {
9597 Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
9598 return -1;
9599 }
9600
9601 TFile *f = GetCurrentFile();
9602 if (!f) {
9603 Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
9604 return -1;
9605 }
9606 TTreeCache *tc = GetReadCache(f,true);
9607 if (!tc) {
9608 Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
9609 return -1;
9610 }
9611 tc->StopLearningPhase();
9612 return 0;
9613}
9614
9615////////////////////////////////////////////////////////////////////////////////
9616/// Set the fTree member for all branches and sub branches.
9618static void TBranch__SetTree(TTree *tree, TObjArray &branches)
9619{
9620 Int_t nb = branches.GetEntriesFast();
9621 for (Int_t i = 0; i < nb; ++i) {
9622 TBranch* br = (TBranch*) branches.UncheckedAt(i);
9623 br->SetTree(tree);
9624
9625 Int_t writeBasket = br->GetWriteBasket();
9626 for (Int_t j = writeBasket; j >= 0; --j) {
9627 TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
9628 if (bk) {
9629 tree->IncrementTotalBuffers(bk->GetBufferSize());
9630 }
9631 }
9632
9633 TBranch__SetTree(tree,*br->GetListOfBranches());
9634 }
9635}
9636
9637////////////////////////////////////////////////////////////////////////////////
9638/// Set the fTree member for all friend elements.
9641{
9642 if (frlist) {
9643 TObjLink *lnk = frlist->FirstLink();
9644 while (lnk) {
9645 TFriendElement *elem = (TFriendElement*)lnk->GetObject();
9646 elem->fParentTree = tree;
9647 lnk = lnk->Next();
9648 }
9649 }
9650}
9651
9652////////////////////////////////////////////////////////////////////////////////
9653/// Stream a class object.
9656{
9657 if (b.IsReading()) {
9658 UInt_t R__s, R__c;
9659 if (fDirectory) {
9660 fDirectory->Remove(this);
9661 //delete the file cache if it points to this Tree
9662 TFile *file = fDirectory->GetFile();
9663 MoveReadCache(file,nullptr);
9664 }
9665 fDirectory = nullptr;
9666 fCacheDoAutoInit = true;
9667 fCacheUserSet = false;
9668 Version_t R__v = b.ReadVersion(&R__s, &R__c);
9669 if (R__v > 4) {
9670 b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
9671
9672 fBranches.SetOwner(true); // True needed only for R__v < 19 and most R__v == 19
9673
9674 if (fBranchRef) fBranchRef->SetTree(this);
9677
9678 if (fTreeIndex) {
9679 fTreeIndex->SetTree(this);
9680 }
9681 if (fIndex.fN) {
9682 Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
9683 fIndex.Set(0);
9684 fIndexValues.Set(0);
9685 }
9686 if (fEstimate <= 10000) {
9687 fEstimate = 1000000;
9688 }
9689
9690 if (fNClusterRange) {
9691 // The I/O allocated just enough memory to hold the
9692 // current set of ranges.
9694 }
9695
9696 // Throughs calls to `GetCacheAutoSize` or `EnableCache` (for example
9697 // by TTreePlayer::Process, the cache size will be automatically
9698 // determined unless the user explicitly call `SetCacheSize`
9699 fCacheSize = 0;
9700 fCacheUserSet = false;
9701
9703 return;
9704 }
9705 //====process old versions before automatic schema evolution
9706 Stat_t djunk;
9707 Int_t ijunk;
9712 b >> fScanField;
9715 b >> djunk; fEntries = (Long64_t)djunk;
9720 if (fEstimate <= 10000) fEstimate = 1000000;
9722 if (fBranchRef) fBranchRef->SetTree(this);
9726 if (R__v > 1) fIndexValues.Streamer(b);
9727 if (R__v > 2) fIndex.Streamer(b);
9728 if (R__v > 3) {
9730 OldInfoList.Streamer(b);
9731 OldInfoList.Delete();
9732 }
9733 fNClusterRange = 0;
9736 b.CheckByteCount(R__s, R__c, TTree::IsA());
9737 //====end of old versions
9738 } else {
9739 if (fBranchRef) {
9740 fBranchRef->Clear();
9741 }
9743 if (table) TRefTable::SetRefTable(nullptr);
9744
9745 b.WriteClassBuffer(TTree::Class(), this);
9746
9747 if (table) TRefTable::SetRefTable(table);
9748 }
9749}
9750
9751////////////////////////////////////////////////////////////////////////////////
9752/// Unbinned fit of one or more variable(s) from a tree.
9753///
9754/// funcname is a TF1 function.
9755///
9756/// \note see TTree::Draw for explanations of the other parameters.
9757///
9758/// Fit the variable varexp using the function funcname using the
9759/// selection cuts given by selection.
9760///
9761/// The list of fit options is given in parameter option.
9762///
9763/// - option = "Q" Quiet mode (minimum printing)
9764/// - option = "V" Verbose mode (default is between Q and V)
9765/// - option = "E" Perform better Errors estimation using Minos technique
9766/// - option = "M" More. Improve fit results
9767///
9768/// You can specify boundary limits for some or all parameters via
9769/// ~~~ {.cpp}
9770/// func->SetParLimits(p_number, parmin, parmax);
9771/// ~~~
9772/// if parmin>=parmax, the parameter is fixed
9773///
9774/// Note that you are not forced to fix the limits for all parameters.
9775/// For example, if you fit a function with 6 parameters, you can do:
9776/// ~~~ {.cpp}
9777/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
9778/// func->SetParLimits(4,-10,-4);
9779/// func->SetParLimits(5, 1,1);
9780/// ~~~
9781/// With this setup:
9782///
9783/// - Parameters 0->3 can vary freely
9784/// - Parameter 4 has boundaries [-10,-4] with initial value -8
9785/// - Parameter 5 is fixed to 100.
9786///
9787/// For the fit to be meaningful, the function must be self-normalized.
9788///
9789/// i.e. It must have the same integral regardless of the parameter
9790/// settings. Otherwise the fit will effectively just maximize the
9791/// area.
9792///
9793/// It is mandatory to have a normalization variable
9794/// which is fixed for the fit. e.g.
9795/// ~~~ {.cpp}
9796/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
9797/// f1->SetParameters(1, 3.1, 0.01);
9798/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
9799/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
9800/// ~~~
9801/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
9802///
9803/// Return status:
9804///
9805/// - The function return the status of the fit in the following form
9806/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
9807/// - The fitResult is 0 is the fit is OK.
9808/// - The fitResult is negative in case of an error not connected with the fit.
9809/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
9810/// - If the number of selected entries is null the function returns -1
9813{
9814 GetPlayer();
9815 if (fPlayer) {
9817 }
9818 return -1;
9819}
9820
9821////////////////////////////////////////////////////////////////////////////////
9822/// Replace current attributes by current style.
9845}
9846
9847////////////////////////////////////////////////////////////////////////////////
9848/// Write this object to the current directory. For more see TObject::Write
9849/// If option & kFlushBasket, call FlushBasket before writing the tree.
9851Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
9852{
9855 return 0;
9857}
9858
9859////////////////////////////////////////////////////////////////////////////////
9860/// Write this object to the current directory. For more see TObject::Write
9861/// If option & kFlushBasket, call FlushBasket before writing the tree.
9864{
9865 return ((const TTree*)this)->Write(name, option, bufsize);
9866}
9867
9868////////////////////////////////////////////////////////////////////////////////
9869/// \class TTreeFriendLeafIter
9870///
9871/// Iterator on all the leaves in a TTree and its friend
9872
9874
9875////////////////////////////////////////////////////////////////////////////////
9876/// Create a new iterator. By default the iteration direction
9877/// is kIterForward. To go backward use kIterBackward.
9880: fTree(const_cast<TTree*>(tree))
9881, fLeafIter(nullptr)
9882, fTreeIter(nullptr)
9883, fDirection(dir)
9884{
9885}
9886
9887////////////////////////////////////////////////////////////////////////////////
9888/// Copy constructor. Does NOT copy the 'cursor' location!
9891: TIterator(iter)
9892, fTree(iter.fTree)
9893, fLeafIter(nullptr)
9894, fTreeIter(nullptr)
9895, fDirection(iter.fDirection)
9896{
9897}
9898
9899////////////////////////////////////////////////////////////////////////////////
9900/// Overridden assignment operator. Does NOT copy the 'cursor' location!
9903{
9904 if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
9906 fDirection = rhs1.fDirection;
9907 }
9908 return *this;
9909}
9910
9911////////////////////////////////////////////////////////////////////////////////
9912/// Overridden assignment operator. Does NOT copy the 'cursor' location!
9915{
9916 if (this != &rhs) {
9917 fDirection = rhs.fDirection;
9918 }
9919 return *this;
9920}
9921
9922////////////////////////////////////////////////////////////////////////////////
9923/// Go the next friend element
9926{
9927 if (!fTree) return nullptr;
9928
9929 TObject * next;
9930 TTree * nextTree;
9931
9932 if (!fLeafIter) {
9933 TObjArray *list = fTree->GetListOfLeaves();
9934 if (!list) return nullptr; // Can happen with an empty chain.
9935 fLeafIter = list->MakeIterator(fDirection);
9936 if (!fLeafIter) return nullptr;
9937 }
9938
9939 next = fLeafIter->Next();
9940 if (!next) {
9941 if (!fTreeIter) {
9943 if (!list) return next;
9944 fTreeIter = list->MakeIterator(fDirection);
9945 if (!fTreeIter) return nullptr;
9946 }
9948 ///nextTree = (TTree*)fTreeIter->Next();
9949 if (nextFriend) {
9950 nextTree = const_cast<TTree*>(nextFriend->GetTree());
9951 if (!nextTree) return Next();
9953 fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
9954 if (!fLeafIter) return nullptr;
9955 next = fLeafIter->Next();
9956 }
9957 }
9958 return next;
9959}
9960
9961////////////////////////////////////////////////////////////////////////////////
9962/// Returns the object option stored in the list.
9965{
9966 if (fLeafIter) return fLeafIter->GetOption();
9967 return "";
9968}
#define R__unlikely(expr)
Definition RConfig.hxx:594
#define SafeDelete(p)
Definition RConfig.hxx:533
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
int Int_t
Definition RtypesCore.h:45
short Version_t
Definition RtypesCore.h:65
long Long_t
Definition RtypesCore.h:54
unsigned int UInt_t
Definition RtypesCore.h:46
float Float_t
Definition RtypesCore.h:57
double Double_t
Definition RtypesCore.h:59
constexpr Ssiz_t kNPOS
Definition RtypesCore.h:117
long long Long64_t
Definition RtypesCore.h:69
unsigned long long ULong64_t
Definition RtypesCore.h:70
const char Option_t
Definition RtypesCore.h:66
#define ClassImp(name)
Definition Rtypes.h:374
const Int_t kDoNotProcess
Definition TBranch.h:56
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
EDataType
Definition TDataType.h:28
@ kNoType_t
Definition TDataType.h:33
@ kFloat_t
Definition TDataType.h:31
@ kULong64_t
Definition TDataType.h:32
@ kInt_t
Definition TDataType.h:30
@ kchar
Definition TDataType.h:31
@ kLong_t
Definition TDataType.h:30
@ kDouble32_t
Definition TDataType.h:31
@ kShort_t
Definition TDataType.h:29
@ kBool_t
Definition TDataType.h:32
@ kBits
Definition TDataType.h:34
@ kULong_t
Definition TDataType.h:30
@ kLong64_t
Definition TDataType.h:32
@ kUShort_t
Definition TDataType.h:29
@ kDouble_t
Definition TDataType.h:31
@ kCharStar
Definition TDataType.h:34
@ kChar_t
Definition TDataType.h:29
@ kUChar_t
Definition TDataType.h:29
@ kCounter
Definition TDataType.h:34
@ kUInt_t
Definition TDataType.h:30
@ kFloat16_t
Definition TDataType.h:33
@ kOther_t
Definition TDataType.h:32
#define gDirectory
Definition TDirectory.h:384
R__EXTERN TEnv * gEnv
Definition TEnv.h:170
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
#define N
static unsigned int total
Option_t Option_t option
Option_t Option_t SetLineWidth
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t cursor
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 SetFillStyle
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 offset
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 SetLineColor
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
Option_t Option_t SetFillColor
Option_t Option_t SetMarkerStyle
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void reg
Option_t Option_t style
char name[80]
Definition TGX11.cxx:110
int nentries
R__EXTERN TInterpreter * gCling
TVirtualProofPlayer * fPlayer
Definition TProof.h:177
Int_t gDebug
Definition TROOT.cxx:597
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:406
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2503
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
constexpr Int_t kNEntriesResort
Definition TTree.cxx:440
static TBranch * R__FindBranchHelper(TObjArray *list, const char *branchname)
Search in the array for a branch matching the branch name, with the branch possibly expressed as a 'f...
Definition TTree.cxx:4798
static char DataTypeToChar(EDataType datatype)
Definition TTree.cxx:452
void TFriendElement__SetTree(TTree *tree, TList *frlist)
Set the fTree member for all friend elements.
Definition TTree.cxx:9639
bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
Definition TTree.cxx:1234
static void TBranch__SetTree(TTree *tree, TObjArray &branches)
Set the fTree member for all branches and sub branches.
Definition TTree.cxx:9617
constexpr Float_t kNEntriesResortInv
Definition TTree.cxx:441
#define R__LOCKGUARD(mutex)
#define gPad
#define snprintf
Definition civetweb.c:1540
A helper class for managing IMT work during TTree:Fill operations.
const_iterator end() const
TIOFeatures provides the end-user with the ability to change the IO behavior of data written via a TT...
UChar_t GetFeatures() const
bool Set(EIOFeatures bits)
Set a specific IO feature.
This class provides a simple interface to execute the same task multiple times in parallel threads,...
void Streamer(TBuffer &) override
Stream a TArrayD object.
Definition TArrayD.cxx:149
void Set(Int_t n) override
Set size of this array to n doubles.
Definition TArrayD.cxx:106
void Set(Int_t n) override
Set size of this array to n ints.
Definition TArrayI.cxx:105
void Streamer(TBuffer &) override
Stream a TArrayI object.
Definition TArrayI.cxx:148
Int_t fN
Definition TArray.h:38
Fill Area Attributes class.
Definition TAttFill.h:20
virtual void Streamer(TBuffer &)
virtual Color_t GetFillColor() const
Return the fill area color.
Definition TAttFill.h:31
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition TAttFill.h:32
Line Attributes class.
Definition TAttLine.h:20
virtual void Streamer(TBuffer &)
virtual Color_t GetLineColor() const
Return the line color.
Definition TAttLine.h:35
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:44
virtual Width_t GetLineWidth() const
Return the line width.
Definition TAttLine.h:37
virtual Style_t GetLineStyle() const
Return the line style.
Definition TAttLine.h:36
Marker Attributes class.
Definition TAttMarker.h:20
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition TAttMarker.h:33
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition TAttMarker.h:39
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition TAttMarker.h:32
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition TAttMarker.h:34
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition TAttMarker.h:41
virtual void Streamer(TBuffer &)
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition TAttMarker.h:46
Each class (see TClass) has a linked list of its base class(es).
Definition TBaseClass.h:33
ROOT::ESTLType IsSTLContainer()
Return which type (if any) of STL container the data member is.
Manages buffers for branches of a Tree.
Definition TBasket.h:34
A Branch for the case of an array of clone objects.
A Branch for the case of an object.
static TClass * Class()
A Branch for the case of an object.
A branch containing and managing a TRefTable for TRef autoloading.
Definition TBranchRef.h:34
void Reset(Option_t *option="") override
void Print(Option_t *option="") const override
Print the TRefTable branch.
void Clear(Option_t *option="") override
Clear entries in the TRefTable.
void ResetAfterMerge(TFileMergeInfo *) override
Reset a Branch after a Merge operation (drop data but keep customizations) TRefTable is cleared.
A Branch handling STL collection of pointers (vectors, lists, queues, sets and multisets) while stori...
Definition TBranchSTL.h:22
A TTree is a list of TBranches.
Definition TBranch.h:93
static TClass * Class()
TObjArray * GetListOfBranches()
Definition TBranch.h:246
virtual void SetTree(TTree *tree)
Definition TBranch.h:287
static void ResetCount()
Static function resetting fgCount.
Definition TBranch.cxx:2674
virtual void SetFile(TFile *file=nullptr)
Set file where this branch writes/reads its buffers.
Definition TBranch.cxx:2876
virtual void SetEntryOffsetLen(Int_t len, bool updateSubBranches=false)
Update the default value for the branch's fEntryOffsetLen if and only if it was already non zero (and...
Definition TBranch.cxx:2834
virtual void UpdateFile()
Refresh the value of fDirectory (i.e.
Definition TBranch.cxx:3317
Int_t Fill()
Definition TBranch.h:205
Using a TBrowser one can browse all ROOT objects.
Definition TBrowser.h:37
The concrete implementation of TBuffer for writing/reading to/from a ROOT file or socket.
Definition TBufferFile.h:47
Buffer base class used for serializing objects.
Definition TBuffer.h:43
void Expand(Int_t newsize, Bool_t copy=kTRUE)
Expand (or shrink) the I/O buffer to newsize bytes.
Definition TBuffer.cxx:223
Int_t BufferSize() const
Definition TBuffer.h:98
@ kWrite
Definition TBuffer.h:73
@ kRead
Definition TBuffer.h:73
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
Bool_t CanSplit() const
Return true if the data member of this TClass can be saved separately.
Definition TClass.cxx:2424
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2991
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:5104
Bool_t HasDataMemberInfo() const
Definition TClass.h:413
Bool_t HasCustomStreamerMember() const
The class has a Streamer method and it is implemented by the user or an older (not StreamerInfo based...
Definition TClass.h:515
void Destructor(void *obj, Bool_t dtorOnly=kFALSE)
Explicitly call destructor for object.
Definition TClass.cxx:5526
void BuildRealData(void *pointer=nullptr, Bool_t isTransient=kFALSE)
Build a full list of persistent data members.
Definition TClass.cxx:2136
TList * GetListOfRealData() const
Definition TClass.h:460
Bool_t CanIgnoreTObjectStreamer()
Definition TClass.h:399
TList * GetListOfBases()
Return list containing the TBaseClass(es) of a class.
Definition TClass.cxx:3750
Bool_t IsTObject() const
Return kTRUE is the class inherits from TObject.
Definition TClass.cxx:6064
TVirtualStreamerInfo * GetStreamerInfo(Int_t version=0, Bool_t isTransient=kFALSE) const
returns a pointer to the TVirtualStreamerInfo object for version If the object does not exist,...
Definition TClass.cxx:4713
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:3002
Version_t GetClassVersion() const
Definition TClass.h:427
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:3073
An array of clone (identical) objects.
static TClass * Class()
Collection abstract base class.
Definition TCollection.h:65
static TClass * Class()
void SetName(const char *name)
const char * GetName() const override
Return name of this collection.
virtual Int_t GetEntries() const
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
void Browse(TBrowser *b) override
Browse this collection (called by TBrowser).
A specialized string object used for TTree selections.
Definition TCut.h:25
All ROOT classes may have RTTI (run time type identification) support added.
Definition TDataMember.h:31
Bool_t IsPersistent() const
Definition TDataMember.h:91
Bool_t IsBasic() const
Return true if data member is a basic type, e.g. char, int, long...
Bool_t IsaPointer() const
Return true if data member is a pointer.
TDataType * GetDataType() const
Definition TDataMember.h:76
Longptr_t GetOffset() const
Get offset from "this".
const char * GetTypeName() const
Get the decayed type name of this data member, removing const and volatile qualifiers,...
const char * GetArrayIndex() const
If the data member is pointer and has a valid array size in its comments GetArrayIndex returns a stri...
const char * GetFullTypeName() const
Get the concrete type name of this data member, including const and volatile qualifiers.
Basic data type descriptor (datatype information is obtained from CINT).
Definition TDataType.h:44
Int_t GetType() const
Definition TDataType.h:68
TString GetTypeName()
Get basic type of typedef, e,g.: "class TDirectory*" -> "TDirectory".
Bool_t cd() override
Change current directory to "this" directory.
Bool_t IsWritable() const override
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
Describe directory structure in memory.
Definition TDirectory.h:45
virtual TList * GetList() const
Definition TDirectory.h:222
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
virtual Int_t WriteTObject(const TObject *obj, const char *name=nullptr, Option_t *="", Int_t=0)
Write an object with proper type checking.
virtual TFile * GetFile() const
Definition TDirectory.h:220
virtual Int_t ReadKeys(Bool_t=kTRUE)
Definition TDirectory.h:248
virtual Bool_t IsWritable() const
Definition TDirectory.h:237
virtual TKey * GetKey(const char *, Short_t=9999) const
Definition TDirectory.h:221
virtual void SaveSelf(Bool_t=kFALSE)
Definition TDirectory.h:255
virtual TList * GetListOfKeys() const
Definition TDirectory.h:223
void GetObject(const char *namecycle, T *&ptr)
Get an object with proper type checking.
Definition TDirectory.h:212
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
Streamer around an arbitrary STL like container, which implements basic container functionality.
A List of entry numbers in a TTree or TChain.
Definition TEntryList.h:26
virtual bool Enter(Long64_t entry, TTree *tree=nullptr)
Add entry #entry to the list.
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 TDirectory * GetDirectory() const
Definition TEntryList.h:77
virtual void SetReapplyCut(bool apply=false)
Definition TEntryList.h:108
virtual void SetDirectory(TDirectory *dir)
Add reference to directory dir. dir can be 0.
virtual Long64_t GetEntry(Long64_t index)
Return the number of the entry #index of this TEntryList in the TTree or TChain See also Next().
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:491
<div class="legacybox"><h2>Legacy Code</h2> TEventList is a legacy interface: there will be no bug fi...
Definition TEventList.h:31
A cache when reading files over the network.
virtual Int_t GetBufferSize() const
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
Definition TFile.h:131
virtual void SetCacheRead(TFileCacheRead *cache, TObject *tree=nullptr, ECacheAction action=kDisconnect)
Set a pointer to the read cache.
Definition TFile.cxx:2406
Int_t GetCompressionSettings() const
Definition TFile.h:484
Int_t GetCompressionLevel() const
Definition TFile.h:478
virtual void WriteStreamerInfo()
Write the list of TStreamerInfo as a single object in this file The class Streamer description for al...
Definition TFile.cxx:3834
@ kDoNotDisconnect
Definition TFile.h:149
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4131
virtual void WriteHeader()
Write File Header.
Definition TFile.cxx:2656
@ kCancelTTreeChangeRequest
Definition TFile.h:280
TFileCacheRead * GetCacheRead(const TObject *tree=nullptr) const
Return a pointer to the current read cache.
Definition TFile.cxx:1267
<div class="legacybox"><h2>Legacy Code</h2> TFolder is a legacy interface: there will be no bug fixes...
Definition TFolder.h:30
static TClass * Class()
A TFriendElement TF describes a TTree object TF in a file.
virtual TTree * GetTree()
Return pointer to friend TTree.
virtual Int_t DeleteGlobal(void *obj)=0
void Reset()
Iterator abstract base class.
Definition TIterator.h:30
virtual TObject * Next()=0
virtual Option_t * GetOption() const
Definition TIterator.h:40
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
void Delete(Option_t *option="") override
Delete an object from the file.
Definition TKey.cxx:538
Int_t GetKeylen() const
Definition TKey.h:84
Int_t GetNbytes() const
Definition TKey.h:86
virtual const char * GetClassName() const
Definition TKey.h:75
static TClass * Class()
static TClass * Class()
static TClass * Class()
static TClass * Class()
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition TLeaf.h:57
virtual Int_t GetLenType() const
Definition TLeaf.h:133
virtual Int_t GetLen() const
Return the number of effective elements of this leaf, for the current entry.
Definition TLeaf.cxx:404
@ kNewValue
Set if we own the value buffer and so must delete it ourselves.
Definition TLeaf.h:96
@ kIndirectAddress
Data member is a pointer to an array of basic types.
Definition TLeaf.h:95
virtual Int_t GetOffset() const
Definition TLeaf.h:137
A doubly linked list.
Definition TList.h:38
void Clear(Option_t *option="") override
Remove all objects from the list.
Definition TList.cxx:400
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:576
void RecursiveRemove(TObject *obj) override
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition TList.cxx:762
void Add(TObject *obj) override
Definition TList.h:81
TObject * Remove(TObject *obj) override
Remove object from the list.
Definition TList.cxx:820
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:468
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:355
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:19
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
void Streamer(TBuffer &) override
Stream an object of class TObject.
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
TString fTitle
Definition TNamed.h:33
TNamed()
Definition TNamed.h:38
TString fName
Definition TNamed.h:32
See TNotifyLink.
Definition TNotifyLink.h:47
An array of TObjects.
Definition TObjArray.h:31
Int_t GetEntriesFast() const
Definition TObjArray.h:58
Int_t GetEntriesUnsafe() const
Return the number of objects in array (i.e.
void Clear(Option_t *option="") override
Remove all objects from the array.
void Streamer(TBuffer &) override
Stream all objects in the array to or from the I/O buffer.
Int_t GetEntries() const override
Return the number of objects in array (i.e.
void Delete(Option_t *option="") override
Remove all objects from the array AND delete all heap based objects.
TObject * At(Int_t idx) const override
Definition TObjArray.h:164
TObject * UncheckedAt(Int_t i) const
Definition TObjArray.h:84
Bool_t IsEmpty() const override
Definition TObjArray.h:65
TObject * FindObject(const char *name) const override
Find an object in this collection using its name.
void Add(TObject *obj) override
Definition TObjArray.h:68
Mother of all ROOT objects.
Definition TObject.h:41
virtual Bool_t Notify()
This method must be overridden to handle object notification (the base implementation is no-op).
Definition TObject.cxx:612
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:457
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:205
@ kBitMask
Definition TObject.h:92
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1057
R__ALWAYS_INLINE Bool_t IsZombie() const
Definition TObject.h:159
virtual Int_t Write(const char *name=nullptr, Int_t option=0, Int_t bufsize=0)
Write this object to the current directory.
Definition TObject.cxx:964
@ kOnlyPrepStep
Used to request that the class specific implementation of TObject::Write just prepare the objects to ...
Definition TObject.h:112
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
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1099
virtual TClass * IsA() const
Definition TObject.h:249
void ResetBit(UInt_t f)
Definition TObject.h:204
@ kCanDelete
if object in a list can be deleted
Definition TObject.h:68
@ kMustCleanup
if object destructor must call RecursiveRemove()
Definition TObject.h:70
Principal Components Analysis (PCA)
Definition TPrincipal.h:21
The TRealData class manages the effective list of all data members for a given class.
Definition TRealData.h:30
A TRefTable maintains the association between a referenced object and the parent object supporting th...
Definition TRefTable.h:35
static void SetRefTable(TRefTable *table)
Static function setting the current TRefTable.
static TRefTable * GetRefTable()
Static function returning the current TRefTable.
Regular expression class.
Definition TRegexp.h:31
A TSelector object is used by the TTree::Draw, TTree::Scan, TTree::Process to navigate in a TTree and...
Definition TSelector.h:31
static void * ReAlloc(void *vp, size_t size, size_t oldsize)
Reallocate (i.e.
Definition TStorage.cxx:183
Describes a persistent version of a class.
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:417
void ToLower()
Change string to lower-case.
Definition TString.cxx:1182
static constexpr Ssiz_t kNPOS
Definition TString.h:278
Double_t Atof() const
Return floating-point value contained in string.
Definition TString.cxx:2054
const char * Data() const
Definition TString.h:376
Bool_t EqualTo(const char *cs, ECaseCompare cmp=kExact) const
Definition TString.h:645
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
@ kLeading
Definition TString.h:276
@ kTrailing
Definition TString.h:276
@ kIgnoreCase
Definition TString.h:277
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2378
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2356
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:632
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:651
void SetHistFillColor(Color_t color=1)
Definition TStyle.h:383
Color_t GetHistLineColor() const
Definition TStyle.h:235
Bool_t IsReading() const
Definition TStyle.h:300
void SetHistLineStyle(Style_t styl=0)
Definition TStyle.h:386
Style_t GetHistFillStyle() const
Definition TStyle.h:236
Color_t GetHistFillColor() const
Definition TStyle.h:234
void SetHistLineColor(Color_t color=1)
Definition TStyle.h:384
Style_t GetHistLineStyle() const
Definition TStyle.h:237
void SetHistFillStyle(Style_t styl=0)
Definition TStyle.h:385
Width_t GetHistLineWidth() const
Definition TStyle.h:238
void SetHistLineWidth(Width_t width=1)
Definition TStyle.h:387
A zero length substring is legal.
Definition TString.h:85
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1677
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1308
A TTreeCache which exploits parallelized decompression of its own content.
static bool IsParallelUnzip()
Static function that tells wether the multithreading unzipping is activated.
A cache to speed-up the reading of ROOT datasets.
Definition TTreeCache.h:32
static void SetLearnEntries(Int_t n=10)
Static function to set the number of entries to be used in learning mode The default value for n is 1...
Class implementing or helping the various TTree cloning method.
Definition TTreeCloner.h:31
Iterator on all the leaves in a TTree and its friend.
Definition TTree.h:717
TTree * fTree
tree being iterated
Definition TTree.h:720
TIterator & operator=(const TIterator &rhs) override
Overridden assignment operator. Does NOT copy the 'cursor' location!
Definition TTree.cxx:9901
TObject * Next() override
Go the next friend element.
Definition TTree.cxx:9924
TIterator * fLeafIter
current leaf sub-iterator.
Definition TTree.h:721
Option_t * GetOption() const override
Returns the object option stored in the list.
Definition TTree.cxx:9963
TIterator * fTreeIter
current tree sub-iterator.
Definition TTree.h:722
bool fDirection
iteration direction
Definition TTree.h:723
static TClass * Class()
Helper class to iterate over cluster of baskets.
Definition TTree.h:271
Long64_t GetEstimatedClusterSize()
Estimate the cluster size.
Definition TTree.cxx:605
Long64_t Previous()
Move on to the previous cluster and return the starting entry of this previous cluster.
Definition TTree.cxx:688
Long64_t Next()
Move on to the next cluster and return the starting entry of this next cluster.
Definition TTree.cxx:644
Long64_t GetNextEntry()
Definition TTree.h:308
TClusterIterator(TTree *tree, Long64_t firstEntry)
Regular constructor.
Definition TTree.cxx:554
Helper class to prevent infinite recursion in the usage of TTree Friends.
Definition TTree.h:188
TFriendLock & operator=(const TFriendLock &)
Assignment operator.
Definition TTree.cxx:520
TFriendLock(const TFriendLock &)
Copy constructor.
Definition TTree.cxx:510
UInt_t fMethodBit
Definition TTree.h:192
TTree * fTree
Definition TTree.h:191
~TFriendLock()
Restore the state of tree the same as before we set the lock.
Definition TTree.cxx:533
A TTree represents a columnar dataset.
Definition TTree.h:79
virtual Int_t Fill()
Fill all branches.
Definition TTree.cxx:4610
virtual TFriendElement * AddFriend(const char *treename, const char *filename="")
Add a TFriendElement to the list of friends.
Definition TTree.cxx:1326
TBranchRef * fBranchRef
Branch supporting the TRefTable (if any)
Definition TTree.h:136
TStreamerInfo * BuildStreamerInfo(TClass *cl, void *pointer=nullptr, bool canOptimize=true)
Build StreamerInfo for class cl.
Definition TTree.cxx:2649
virtual TBranch * FindBranch(const char *name)
Return the branch that correspond to the path 'branchname', which can include the name of the tree or...
Definition TTree.cxx:4846
virtual void SetBranchStatus(const char *bname, bool status=true, UInt_t *found=nullptr)
Set branch status to Process or DoNotProcess.
Definition TTree.cxx:8632
bool EnableCache()
Enable the TTreeCache unless explicitly disabled for this TTree by a prior call to SetCacheSize(0).
Definition TTree.cxx:2682
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition TTree.cxx:5299
static Int_t GetBranchStyle()
Static function returning the current branch style.
Definition TTree.cxx:5400
TList * fFriends
pointer to list of friend elements
Definition TTree.h:130
bool fIMTEnabled
! true if implicit multi-threading is enabled for this tree
Definition TTree.h:142
virtual bool GetBranchStatus(const char *branchname) const
Return status of branch with name branchname.
Definition TTree.cxx:5385
UInt_t fFriendLockStatus
! Record which method is locking the friend recursion
Definition TTree.h:137
virtual TLeaf * GetLeafImpl(const char *branchname, const char *leafname)
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition TTree.cxx:6105
Long64_t fTotBytes
Total number of bytes in all branches before compression.
Definition TTree.h:86
virtual Int_t FlushBaskets(bool create_cluster=true) const
Write to disk all the basket that have not yet been individually written and create an event cluster ...
Definition TTree.cxx:5134
Int_t fMaxClusterRange
! Memory allocated for the cluster range.
Definition TTree.h:96
virtual void Show(Long64_t entry=-1, Int_t lenmax=20)
Print values of all active leaves for entry.
Definition TTree.cxx:9494
TEventList * fEventList
! Pointer to event selection list (if one)
Definition TTree.h:125
virtual Long64_t GetAutoSave() const
Definition TTree.h:449
virtual Int_t StopCacheLearningPhase()
Stop the cache learning phase.
Definition TTree.cxx:9583
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:5645
std::vector< std::pair< Long64_t, TBranch * > > fSortedBranches
! Branches to be processed in parallel when IMT is on, sorted by average task time
Definition TTree.h:144
virtual void SetCircular(Long64_t maxEntries)
Enable/Disable circularity for this tree.
Definition TTree.cxx:8990
Long64_t fSavedBytes
Number of autosaved bytes.
Definition TTree.h:88
virtual Int_t AddBranchToCache(const char *bname, bool subbranches=false)
Add branch with name bname to the Tree cache.
Definition TTree.cxx:1053
Long64_t GetMedianClusterSize()
Estimate the median cluster size for the TTree.
Definition TTree.cxx:8395
virtual TClusterIterator GetClusterIterator(Long64_t firstentry)
Return an iterator over the cluster of baskets starting at firstentry.
Definition TTree.cxx:5472
virtual void ResetBranchAddress(TBranch *)
Tell a branch to set its address to zero.
Definition TTree.cxx:8149
bool fCacheUserSet
! true if the cache setting was explicitly given by user
Definition TTree.h:141
char GetNewlineValue(std::istream &inputStream)
Determine which newline this file is using.
Definition TTree.cxx:7672
TIOFeatures fIOFeatures
IO features to define for newly-written baskets and branches.
Definition TTree.h:114
virtual Long64_t GetEntryNumberWithIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5917
Long64_t fDebugMin
! First entry number to debug
Definition TTree.h:112
virtual Long64_t SetEntries(Long64_t n=-1)
Change number of entries in the tree.
Definition TTree.cxx:9109
virtual TObjArray * GetListOfLeaves()
Definition TTree.h:530
virtual TBranch * BranchOld(const char *name, const char *classname, void *addobj, Int_t bufsize=32000, Int_t splitlevel=1)
Create a new TTree BranchObject.
Definition TTree.cxx:2071
Long64_t GetCacheAutoSize(bool withDefault=false)
Used for automatic sizing of the cache.
Definition TTree.cxx:5412
virtual TBranch * BranchRef()
Build the optional branch supporting the TRefTable.
Definition TTree.cxx:2325
TFile * GetCurrentFile() const
Return pointer to the current file.
Definition TTree.cxx:5484
TList * fAliases
List of aliases for expressions based on the tree branches.
Definition TTree.h:124
virtual TTree * CopyTree(const char *selection, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Copy a tree with selection.
Definition TTree.cxx:3726
virtual Int_t DropBranchFromCache(const char *bname, bool subbranches=false)
Remove the branch with name 'bname' from the Tree cache.
Definition TTree.cxx:1136
virtual Int_t Fit(const char *funcname, const char *varexp, const char *selection="", Option_t *option="", Option_t *goption="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Fit a projected item(s) from a tree.
Definition TTree.cxx:5084
Long64_t * fClusterRangeEnd
[fNClusterRange] Last entry of a cluster range.
Definition TTree.h:103
void Streamer(TBuffer &) override
Stream a class object.
Definition TTree.cxx:9654
std::atomic< Long64_t > fIMTZipBytes
! Zip bytes for the IMT flush baskets.
Definition TTree.h:161
void RecursiveRemove(TObject *obj) override
Make sure that obj (which is being deleted or will soon be) is no longer referenced by this TTree.
Definition TTree.cxx:7965
TVirtualTreePlayer * GetPlayer()
Load the TTreePlayer (if not already done).
Definition TTree.cxx:6312
virtual Int_t MakeProxy(const char *classname, const char *macrofilename=nullptr, const char *cutfilename=nullptr, const char *option=nullptr, Int_t maxUnrolling=3)
Generate a skeleton analysis class for this Tree using TBranchProxy.
Definition TTree.cxx:6775
virtual Long64_t ReadStream(std::istream &inputStream, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from an input stream.
Definition TTree.cxx:7699
virtual void SetDebug(Int_t level=1, Long64_t min=0, Long64_t max=9999999)
Set the debug level and the debug range.
Definition TTree.cxx:9026
Int_t fScanField
Number of runs before prompting in Scan.
Definition TTree.h:92
void Draw(Option_t *opt) override
Default Draw method for all objects.
Definition TTree.h:432
virtual TTree * GetFriend(const char *) const
Return a pointer to the TTree friend whose name or alias is friendname.
Definition TTree.cxx:5982
virtual void SetNotify(TObject *obj)
Sets the address of the object to be notified when the tree is loaded.
Definition TTree.cxx:9340
virtual Double_t GetMaximum(const char *columname)
Return maximum of column with name columname.
Definition TTree.cxx:6242
virtual Long64_t GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5897
static void SetMaxTreeSize(Long64_t maxsize=100000000000LL)
Set the maximum size in bytes of a Tree file (static function).
Definition TTree.cxx:9306
void Print(Option_t *option="") const override
Print a summary of the tree contents.
Definition TTree.cxx:7302
virtual Int_t UnbinnedFit(const char *funcname, const char *varexp, const char *selection="", Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Unbinned fit of one or more variable(s) from a tree.
Definition TTree.cxx:9811
Int_t fNClusterRange
Number of Cluster range in addition to the one defined by 'AutoFlush'.
Definition TTree.h:95
virtual void PrintCacheStats(Option_t *option="") const
Print statistics about the TreeCache for this tree.
Definition TTree.cxx:7454
virtual Int_t BuildIndex(const char *majorname, const char *minorname="0")
Build a Tree Index (default is TTreeIndex).
Definition TTree.cxx:2634
TVirtualTreePlayer * fPlayer
! Pointer to current Tree player
Definition TTree.h:134
virtual TIterator * GetIteratorOnAllLeaves(bool dir=kIterForward)
Creates a new iterator that will go through all the leaves on the tree itself and its friend.
Definition TTree.cxx:6089
virtual void SetMakeClass(Int_t make)
Set all the branches in this TTree to be in decomposed object mode (also known as MakeClass mode).
Definition TTree.cxx:9286
virtual bool InPlaceClone(TDirectory *newdirectory, const char *options="")
Copy the content to a new new file, update this TTree with the new location information and attach th...
Definition TTree.cxx:7095
TObjArray fBranches
List of Branches.
Definition TTree.h:122
TDirectory * GetDirectory() const
Definition TTree.h:463
bool fCacheDoAutoInit
! true if cache auto creation or resize check is needed
Definition TTree.h:139
TTreeCache * GetReadCache(TFile *file) const
Find and return the TTreeCache registered with the file and which may contain branches for us.
Definition TTree.cxx:6325
Long64_t fEntries
Number of entries.
Definition TTree.h:84
virtual TFile * ChangeFile(TFile *file)
Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
Definition TTree.cxx:2746
virtual TEntryList * GetEntryList()
Returns the entry list assigned to this tree.
Definition TTree.cxx:5861
virtual void SetWeight(Double_t w=1, Option_t *option="")
Set tree weight.
Definition TTree.cxx:9483
void InitializeBranchLists(bool checkLeafCount)
Divides the top-level branches into two vectors: (i) branches to be processed sequentially and (ii) b...
Definition TTree.cxx:5788
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr=nullptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8483
Long64_t * fClusterSize
[fNClusterRange] Number of entries in each cluster for a given range.
Definition TTree.h:104
Long64_t fFlushedBytes
Number of auto-flushed bytes.
Definition TTree.h:89
virtual void SetPerfStats(TVirtualPerfStats *perf)
Set perf stats.
Definition TTree.cxx:9438
std::atomic< Long64_t > fIMTTotBytes
! Total bytes for the IMT flush baskets
Definition TTree.h:160
virtual void SetCacheLearnEntries(Int_t n=10)
Interface to TTreeCache to set the number of entries for the learning phase.
Definition TTree.cxx:8963
TEntryList * fEntryList
! Pointer to event selection list (if one)
Definition TTree.h:126
@ kSplitCollectionOfPointers
Definition TTree.h:267
virtual TVirtualIndex * GetTreeIndex() const
Definition TTree.h:559
TList * fExternalFriends
! List of TFriendsElement pointing to us and need to be notified of LoadTree. Content not owned.
Definition TTree.h:131
virtual Long64_t Merge(TCollection *list, Option_t *option="")
Merge the trees in the TList into this tree.
Definition TTree.cxx:6909
virtual void SetMaxVirtualSize(Long64_t size=0)
Definition TTree.h:666
virtual void DropBaskets()
Remove some baskets from memory.
Definition TTree.cxx:4525
virtual void SetAutoSave(Long64_t autos=-300000000)
In case of a program crash, it will be possible to recover the data in the tree up to the last AutoSa...
Definition TTree.cxx:8440
Long64_t fMaxEntryLoop
Maximum number of entries to process.
Definition TTree.h:98
virtual void SetParallelUnzip(bool opt=true, Float_t RelSize=-1)
Enable or disable parallel unzipping of Tree buffers.
Definition TTree.cxx:9400
virtual void SetDirectory(TDirectory *dir)
Change the tree's directory.
Definition TTree.cxx:9064
void SortBranchesByTime()
Sorts top-level branches by the last average task time recorded per branch.
Definition TTree.cxx:5841
void Delete(Option_t *option="") override
Delete this tree from memory or/and disk.
Definition TTree.cxx:3754
virtual TBranchRef * GetBranchRef() const
Definition TTree.h:451
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:7534
virtual TBranch * BranchImpRef(const char *branchname, const char *classname, TClass *ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
Same as TTree::Branch but automatic detection of the class name.
Definition TTree.cxx:1629
virtual void SetEventList(TEventList *list)
This function transfroms the given TEventList into a TEntryList The new TEntryList is owned by the TT...
Definition TTree.cxx:9167
void MoveReadCache(TFile *src, TDirectory *dir)
Move a cache from a file to the current file in dir.
Definition TTree.cxx:7066
Long64_t fAutoFlush
Auto-flush tree when fAutoFlush entries written or -fAutoFlush (compressed) bytes produced.
Definition TTree.h:101
Int_t fUpdate
Update frequency for EntryLoop.
Definition TTree.h:93
virtual void ResetAfterMerge(TFileMergeInfo *)
Resets the state of this TTree after a merge (keep the customization but forget the data).
Definition TTree.cxx:8118
virtual Long64_t GetEntries() const
Definition TTree.h:464
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition TTree.cxx:9208
Int_t fTimerInterval
Timer interval in milliseconds.
Definition TTree.h:91
Int_t fDebug
! Debug level
Definition TTree.h:111
Int_t SetCacheSizeAux(bool autocache=true, Long64_t cacheSize=0)
Set the size of the file cache and create it if possible.
Definition TTree.cxx:8809
virtual Long64_t AutoSave(Option_t *option="")
AutoSave tree header every fAutoSave bytes.
Definition TTree.cxx:1494
virtual Long64_t GetEntryNumber(Long64_t entry) const
Return entry number corresponding to entry.
Definition TTree.cxx:5872
virtual TTree * CloneTree(Long64_t nentries=-1, Option_t *option="")
Create a clone of this tree and copy nentries.
Definition TTree.cxx:3140
Int_t fFileNumber
! current file number (if file extensions)
Definition TTree.h:116
virtual TLeaf * GetLeaf(const char *branchname, const char *leafname)
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition TTree.cxx:6202
virtual Long64_t GetZipBytes() const
Definition TTree.h:586
TObjArray fLeaves
Direct pointers to individual branch leaves.
Definition TTree.h:123
virtual void Reset(Option_t *option="")
Reset baskets, buffers and entries count in all branches and leaves.
Definition TTree.cxx:8087
virtual void KeepCircular()
Keep a maximum of fMaxEntries in memory.
Definition TTree.cxx:6422
virtual void SetDefaultEntryOffsetLen(Int_t newdefault, bool updateExisting=false)
Update the default value for the branch's fEntryOffsetLen.
Definition TTree.cxx:9038
virtual void DirectoryAutoAdd(TDirectory *)
Called by TKey and TObject::Clone to automatically add us to a directory when we are read from a file...
Definition TTree.cxx:3826
Long64_t fMaxVirtualSize
Maximum total size of buffers kept in memory.
Definition TTree.h:99
virtual Long64_t GetTotBytes() const
Definition TTree.h:557
virtual Int_t MakeSelector(const char *selector=nullptr, Option_t *option="")
Generate skeleton selector class for this tree.
Definition TTree.cxx:6829
virtual void SetObject(const char *name, const char *title)
Change the name and title of this tree.
Definition TTree.cxx:9369
TVirtualPerfStats * fPerfStats
! pointer to the current perf stats object
Definition TTree.h:132
Double_t fWeight
Tree weight (see TTree::SetWeight)
Definition TTree.h:90
std::vector< TBranch * > fSeqBranches
! Branches to be processed sequentially when IMT is on
Definition TTree.h:145
Long64_t fDebugMax
! Last entry number to debug
Definition TTree.h:113
Int_t fDefaultEntryOffsetLen
Initial Length of fEntryOffset table in the basket buffers.
Definition TTree.h:94
TTree()
Default constructor and I/O constructor.
Definition TTree.cxx:731
Long64_t fAutoSave
Autosave tree when fAutoSave entries written or -fAutoSave (compressed) bytes produced.
Definition TTree.h:100
TBranch * Branch(const char *name, T *obj, Int_t bufsize=32000, Int_t splitlevel=99)
Add a new branch, and infer the data type from the type of obj being passed.
Definition TTree.h:354
std::atomic< UInt_t > fAllocationCount
indicates basket should be resized to exact memory usage, but causes significant
Definition TTree.h:152
virtual Int_t GetEntryWithIndex(Int_t major, Int_t minor=0)
Read entry corresponding to major and minor number.
Definition TTree.cxx:5934
static TTree * MergeTrees(TList *list, Option_t *option="")
Static function merging the trees in the TList into a new tree.
Definition TTree.cxx:6860
bool MemoryFull(Int_t nbytes)
Check if adding nbytes to memory we are still below MaxVirtualsize.
Definition TTree.cxx:6844
virtual Long64_t GetReadEntry() const
Definition TTree.h:550
virtual TObjArray * GetListOfBranches()
Definition TTree.h:529
Long64_t fZipBytes
Total number of bytes in all branches after compression.
Definition TTree.h:87
virtual TTree * GetTree() const
Definition TTree.h:558
TBuffer * fTransientBuffer
! Pointer to the current transient buffer.
Definition TTree.h:138
virtual void SetEntryList(TEntryList *list, Option_t *opt="")
Set an EntryList.
Definition TTree.cxx:9144
bool Notify() override
Function called when loading a new class library.
Definition TTree.cxx:7116
virtual void AddZipBytes(Int_t zip)
Definition TTree.h:333
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition TTree.cxx:6480
virtual Long64_t ReadFile(const char *filename, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from filename.
Definition TTree.cxx:7648
virtual const char * GetAlias(const char *aliasName) const
Returns the expanded value of the alias. Search in the friends if any.
Definition TTree.cxx:5231
ROOT::TIOFeatures SetIOFeatures(const ROOT::TIOFeatures &)
Provide the end-user with the ability to enable/disable various experimental IO features for this TTr...
Definition TTree.cxx:9228
virtual TBasket * CreateBasket(TBranch *)
Create a basket for this tree and given branch.
Definition TTree.cxx:3738
TList * fUserInfo
pointer to a list of user objects associated to this Tree
Definition TTree.h:133
virtual Double_t GetMinimum(const char *columname)
Return minimum of column with name columname.
Definition TTree.cxx:6282
virtual void RemoveFriend(TTree *)
Remove a friend from the list of friends.
Definition TTree.cxx:8061
virtual Long64_t GetEntriesFast() const
Return a number greater or equal to the total number of entries in the dataset.
Definition TTree.h:506
void Browse(TBrowser *) override
Browse content of the TTree.
Definition TTree.cxx:2606
virtual TList * GetUserInfo()
Return a pointer to the list containing user objects associated to this tree.
Definition TTree.cxx:6363
Long64_t fChainOffset
! Offset of 1st entry of this Tree in a TChain
Definition TTree.h:106
@ kOnlyFlushAtCluster
If set, the branch's buffers will grow until an event cluster boundary is hit, guaranteeing a basket ...
Definition TTree.h:257
@ kEntriesReshuffled
If set, signals that this TTree is the output of the processing of another TTree, and the entries are...
Definition TTree.h:262
@ kCircular
Definition TTree.h:253
virtual Long64_t GetEntriesFriend() const
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition TTree.cxx:5517
virtual TSQLResult * Query(const char *varexp="", const char *selection="", Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Loop over entries and return a TSQLResult object containing entries following selection.
Definition TTree.cxx:7597
virtual TBranch * Bronch(const char *name, const char *classname, void *addobj, Int_t bufsize=32000, Int_t splitlevel=99)
Create a new TTree BranchElement.
Definition TTree.cxx:2401
virtual void SetBasketSize(const char *bname, Int_t buffsize=16000)
Set a branch's basket size.
Definition TTree.cxx:8456
static void SetBranchStyle(Int_t style=1)
Set the current branch style.
Definition TTree.cxx:8763
~TTree() override
Destructor.
Definition TTree.cxx:914
void ImportClusterRanges(TTree *fromtree)
Appends the cluster range information stored in 'fromtree' to this tree, including the value of fAuto...
Definition TTree.cxx:6379
TClass * IsA() const override
Definition TTree.h:706
Long64_t fEstimate
Number of entries to estimate histogram limits.
Definition TTree.h:102
Int_t FlushBasketsImpl() const
Internal implementation of the FlushBaskets algorithm.
Definition TTree.cxx:5151
virtual Long64_t LoadTreeFriend(Long64_t entry, TTree *T)
Load entry on behalf of our master tree, we may use an index.
Definition TTree.cxx:6564
Int_t Write(const char *name=nullptr, Int_t option=0, Int_t bufsize=0) override
Write this object to the current directory.
Definition TTree.cxx:9862
TVirtualIndex * fTreeIndex
Pointer to the tree Index (if any)
Definition TTree.h:129
void UseCurrentStyle() override
Replace current attributes by current style.
Definition TTree.cxx:9823
TObject * fNotify
Object to be notified when loading a Tree.
Definition TTree.h:120
virtual TBranch * BranchImp(const char *branchname, const char *classname, TClass *ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
Same as TTree::Branch() with added check that addobj matches className.
Definition TTree.cxx:1548
Long64_t fCacheSize
! Maximum size of file buffers
Definition TTree.h:105
TList * fClones
! List of cloned trees which share our addresses
Definition TTree.h:135
std::atomic< Long64_t > fTotalBuffers
! Total number of bytes in branch buffers
Definition TTree.h:108
static TClass * Class()
@ kFindBranch
Definition TTree.h:212
@ kResetBranchAddresses
Definition TTree.h:225
@ kFindLeaf
Definition TTree.h:213
@ kGetEntryWithIndex
Definition TTree.h:217
@ kPrint
Definition TTree.h:222
@ kGetFriend
Definition TTree.h:218
@ kGetBranch
Definition TTree.h:215
@ kSetBranchStatus
Definition TTree.h:224
@ kLoadTree
Definition TTree.h:221
@ kGetEntry
Definition TTree.h:216
@ kGetLeaf
Definition TTree.h:220
@ kRemoveFriend
Definition TTree.h:223
@ kGetFriendAlias
Definition TTree.h:219
@ kGetAlias
Definition TTree.h:214
virtual void SetTreeIndex(TVirtualIndex *index)
The current TreeIndex is replaced by the new index.
Definition TTree.cxx:9455
virtual void OptimizeBaskets(ULong64_t maxMemory=10000000, Float_t minComp=1.1, Option_t *option="")
This function may be called after having filled some entries in a Tree.
Definition TTree.cxx:7140
virtual Long64_t Project(const char *hname, const char *varexp, const char *selection="", Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Make a projection of a tree using selections.
Definition TTree.cxx:7582
virtual Int_t SetCacheEntryRange(Long64_t first, Long64_t last)
interface to TTreeCache to set the cache entry range
Definition TTree.cxx:8929
static Long64_t GetMaxTreeSize()
Static function which returns the tree file size limit in bytes.
Definition TTree.cxx:6272
bool fCacheDoClusterPrefetch
! true if cache is prefetching whole clusters
Definition TTree.h:140
Int_t SetBranchAddressImp(TBranch *branch, void *addr, TBranch **ptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8543
virtual bool SetAlias(const char *aliasName, const char *aliasFormula)
Set a tree variable alias.
Definition TTree.cxx:8239
virtual void CopyAddresses(TTree *, bool undo=false)
Set branch addresses of passed tree equal to ours.
Definition TTree.cxx:3306
Long64_t fMaxEntries
Maximum number of entries in case of circular buffers.
Definition TTree.h:97
virtual void DropBuffers(Int_t nbytes)
Drop branch buffers to accommodate nbytes below MaxVirtualsize.
Definition TTree.cxx:4538
virtual TList * GetListOfFriends() const
Definition TTree.h:531
virtual void Refresh()
Refresh contents of this tree and its branches from the current status on disk.
Definition TTree.cxx:8000
virtual void SetAutoFlush(Long64_t autof=-30000000)
This function may be called at the start of a program to change the default value for fAutoFlush.
Definition TTree.cxx:8294
static Long64_t fgMaxTreeSize
Maximum size of a file containing a Tree.
Definition TTree.h:155
Long64_t fReadEntry
! Number of the entry being processed
Definition TTree.h:107
TArrayD fIndexValues
Sorted index values.
Definition TTree.h:127
void MarkEventCluster()
Mark the previous event as being at the end of the event cluster.
Definition TTree.cxx:8356
UInt_t fNEntriesSinceSorting
! Number of entries processed since the last re-sorting of branches
Definition TTree.h:143
virtual void SetFileNumber(Int_t number=0)
Set fFileNumber to number.
Definition TTree.cxx:9251
virtual TLeaf * FindLeaf(const char *name)
Find leaf..
Definition TTree.cxx:4921
virtual void StartViewer()
Start the TTreeViewer on this tree.
Definition TTree.cxx:9568
Int_t GetMakeClass() const
Definition TTree.h:536
virtual Int_t MakeCode(const char *filename=nullptr)
Generate a skeleton function for this tree.
Definition TTree.cxx:6647
bool fIMTFlush
! True if we are doing a multithreaded flush.
Definition TTree.h:159
TDirectory * fDirectory
! Pointer to directory holding this tree
Definition TTree.h:121
@ kNeedEnableDecomposedObj
Definition TTree.h:245
@ kClassMismatch
Definition TTree.h:238
@ kVoidPtr
Definition TTree.h:243
@ kMatchConversionCollection
Definition TTree.h:241
@ kMissingCompiledCollectionProxy
Definition TTree.h:236
@ kMismatch
Definition TTree.h:237
@ kMatchConversion
Definition TTree.h:240
@ kInternalError
Definition TTree.h:235
@ kMatch
Definition TTree.h:239
@ kMissingBranch
Definition TTree.h:234
@ kMakeClass
Definition TTree.h:242
static Int_t fgBranchStyle
Old/New branch style.
Definition TTree.h:154
virtual void ResetBranchAddresses()
Tell all of our branches to drop their current objects and allocate new ones.
Definition TTree.cxx:8159
Int_t fNfill
! Local for EntryLoop
Definition TTree.h:110
void SetName(const char *name) override
Change the name of this tree.
Definition TTree.cxx:9314
virtual void RegisterExternalFriend(TFriendElement *)
Record a TFriendElement that we need to warn when the chain switches to a new file (typically this is...
Definition TTree.cxx:8041
TArrayI fIndex
Index of sorted values.
Definition TTree.h:128
virtual Int_t SetCacheSize(Long64_t cachesize=-1)
Set maximum size of the file cache .
Definition TTree.cxx:8781
void AddClone(TTree *)
Add a cloned tree to our list of trees to be notified whenever we change our branch addresses or when...
Definition TTree.cxx:1213
virtual Int_t CheckBranchAddressType(TBranch *branch, TClass *ptrClass, EDataType datatype, bool ptr)
Check whether or not the address described by the last 3 parameters matches the content of the branch...
Definition TTree.cxx:2868
TBuffer * GetTransientBuffer(Int_t size)
Returns the transient buffer currently used by this TTree for reading/writing baskets.
Definition TTree.cxx:1031
ROOT::TIOFeatures GetIOFeatures() const
Returns the current set of IO settings.
Definition TTree.cxx:6081
virtual Int_t MakeClass(const char *classname=nullptr, Option_t *option="")
Generate a skeleton analysis class for this tree.
Definition TTree.cxx:6614
virtual const char * GetFriendAlias(TTree *) const
If the 'tree' is a friend, this method returns its alias name.
Definition TTree.cxx:6039
virtual void RemoveExternalFriend(TFriendElement *)
Removes external friend.
Definition TTree.cxx:8052
Int_t fPacketSize
! Number of entries in one packet for parallel root
Definition TTree.h:109
virtual TBranch * BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize, Int_t splitlevel)
Definition TTree.cxx:1725
virtual Long64_t Scan(const char *varexp="", const char *selection="", Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Loop over tree entries and print entries passing selection.
Definition TTree.cxx:8197
virtual TBranch * BronchExec(const char *name, const char *classname, void *addobj, bool isptrptr, Int_t bufsize, Int_t splitlevel)
Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);.
Definition TTree.cxx:2409
virtual void AddTotBytes(Int_t tot)
Definition TTree.h:332
virtual Long64_t CopyEntries(TTree *tree, Long64_t nentries=-1, Option_t *option="", bool needCopyAddresses=false)
Copy nentries from given tree to this tree.
Definition TTree.cxx:3541
Int_t fMakeClass
! not zero when processing code generated by MakeClass
Definition TTree.h:115
virtual Int_t LoadBaskets(Long64_t maxmemory=2000000000)
Read in memory all baskets from all branches up to the limit of maxmemory bytes.
Definition TTree.cxx:6458
static constexpr Long64_t kMaxEntries
Definition TTree.h:230
TPrincipal * Principal(const char *varexp="", const char *selection="", Option_t *option="np", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)
Interface to the Principal Components Analysis class.
Definition TTree.cxx:7283
virtual Long64_t GetAutoFlush() const
Definition TTree.h:448
Defines a common interface to inspect/change the contents of an object that represents a collection.
Abstract interface for Tree Index.
virtual Long64_t GetEntryNumberWithIndex(Long64_t major, Long64_t minor) const =0
virtual Long64_t GetEntryNumberFriend(const TTree *)=0
virtual void SetTree(TTree *T)=0
virtual Long64_t GetN() const =0
virtual Long64_t GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor) const =0
Provides the interface for the PROOF internal performance measurement and event tracing.
Abstract base class defining the interface for the plugins that implement Draw, Scan,...
virtual Long64_t Scan(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual void UpdateFormulaLeaves()=0
virtual Long64_t DrawSelect(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual Int_t MakeCode(const char *filename)=0
virtual Int_t UnbinnedFit(const char *formula, const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual Long64_t GetEntries(const char *)=0
virtual Int_t MakeProxy(const char *classname, const char *macrofilename=nullptr, const char *cutfilename=nullptr, const char *option=nullptr, Int_t maxUnrolling=3)=0
virtual TSQLResult * Query(const char *varexp, const char *selection, Option_t *option, Long64_t nentries, Long64_t firstentry)=0
virtual TPrincipal * Principal(const char *varexp="", const char *selection="", Option_t *option="np", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)=0
virtual void StartViewer(Int_t ww, Int_t wh)=0
virtual Int_t MakeReader(const char *classname, Option_t *option)=0
virtual TVirtualIndex * BuildIndex(const TTree *T, const char *majorname, const char *minorname)=0
virtual TTree * CopyTree(const char *selection, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)=0
virtual Long64_t Process(const char *filename, Option_t *option="", Long64_t nentries=kMaxEntries, Long64_t firstentry=0)=0
virtual void SetEstimate(Long64_t n)=0
static TVirtualTreePlayer * TreePlayer(TTree *obj)
Static function returning a pointer to a Tree player.
virtual Int_t MakeClass(const char *classname, const char *option)=0
virtual Int_t Fit(const char *formula, const char *varexp, const char *selection, Option_t *option, Option_t *goption, Long64_t nentries, Long64_t firstentry)=0
TLine * line
std::ostream & Info()
Definition hadd.cxx:171
const Int_t n
Definition legend1.C:16
Special implementation of ROOT::RRangeCast for TCollection, including a check that the cast target ty...
Definition TObject.h:393
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:570
ESTLType
Definition ESTLType.h:28
@ kSTLmap
Definition ESTLType.h:33
@ kSTLmultimap
Definition ESTLType.h:34
void CallRecursiveRemoveIfNeeded(TObject &obj)
call RecursiveRemove for obj if gROOT is valid and obj.TestBit(kMustCleanup) is true.
Definition TROOT.h:395
void ToHumanReadableSize(value_type bytes, Bool_t si, Double_t *coeff, const char **units)
Return the size expressed in 'human readable' format.
EFromHumanReadableSize FromHumanReadableSize(std::string_view str, T &value)
Convert strings like the following into byte counts 5MB, 5 MB, 5M, 3.7GB, 123b, 456kB,...
Short_t Max(Short_t a, Short_t b)
Returns the largest of a and b.
Definition TMathBase.h:250
Double_t Median(Long64_t n, const T *a, const Double_t *w=nullptr, Long64_t *work=nullptr)
Same as RMS.
Definition TMath.h:1352
Double_t Ceil(Double_t x)
Rounds x upward, returning the smallest integral value that is not less than x.
Definition TMath.h:672
Short_t Min(Short_t a, Short_t b)
Returns the smallest of a and b.
Definition TMathBase.h:198
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Binary search in an array of n values to locate value.
Definition TMathBase.h:347
TCanvas * slash()
Definition slash.C:1
@ kUseGlobal
Use the global compression algorithm.
Definition Compression.h:93
@ kInherit
Some objects use this value to denote that the compression algorithm should be inherited from the par...
Definition Compression.h:91
@ kUseCompiledDefault
Use the compile-time default setting.
Definition Compression.h:53
th1 Draw()
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4