Logo ROOT  
Reference Guide
 
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" */, bool long64major, bool long64minor)
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 if (auto it = fNamesToBranches.find(name); it != fNamesToBranches.end())
5318 return it->second;
5319
5320 // Search using branches, breadth first.
5322 if (result)
5323 return result;
5324
5325 // Search using leaves.
5327 Int_t nleaves = leaves->GetEntriesFast();
5328 for (Int_t i = 0; i < nleaves; i++) {
5329 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
5330 TBranch* branch = leaf->GetBranch();
5331 if (!strcmp(branch->GetName(), name)) {
5332 return branch;
5333 }
5334 if (!strcmp(branch->GetFullName(), name)) {
5335 return branch;
5336 }
5337 }
5338
5339 if (!fFriends) {
5340 return nullptr;
5341 }
5342
5343 // Search in list of friends.
5344 TFriendLock lock(this, kGetBranch);
5345 TIter next(fFriends);
5346 TFriendElement* fe = nullptr;
5347 while ((fe = (TFriendElement*) next())) {
5348 TTree* t = fe->GetTree();
5349 if (t) {
5351 if (branch) {
5352 return branch;
5353 }
5354 }
5355 }
5356
5357 // Second pass in the list of friends when
5358 // the branch name is prefixed by the tree name.
5359 next.Reset();
5360 while ((fe = (TFriendElement*) next())) {
5361 TTree* t = fe->GetTree();
5362 if (!t) {
5363 continue;
5364 }
5365 const char* subname = strstr(name, fe->GetName());
5366 if (subname != name) {
5367 continue;
5368 }
5369 Int_t l = strlen(fe->GetName());
5370 subname += l;
5371 if (*subname != '.') {
5372 continue;
5373 }
5374 subname++;
5376 if (branch) {
5377 return branch;
5378 }
5379 }
5380 return nullptr;
5381}
5382
5383////////////////////////////////////////////////////////////////////////////////
5384/// Return status of branch with name branchname.
5385///
5386/// - 0 if branch is not activated
5387/// - 1 if branch is activated
5389bool TTree::GetBranchStatus(const char* branchname) const
5390{
5391 TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
5392 if (br) {
5393 return br->TestBit(kDoNotProcess) == 0;
5394 }
5395 return false;
5396}
5397
5398////////////////////////////////////////////////////////////////////////////////
5399/// Static function returning the current branch style.
5400///
5401/// - style = 0 old Branch
5402/// - style = 1 new Bronch
5407}
5408
5409////////////////////////////////////////////////////////////////////////////////
5410/// Used for automatic sizing of the cache.
5411///
5412/// Estimates a suitable size for the tree cache based on AutoFlush.
5413/// A cache sizing factor is taken from the configuration. If this yields zero
5414/// and withDefault is true the historical algorithm for default size is used.
5416Long64_t TTree::GetCacheAutoSize(bool withDefault /* = false */ )
5417{
5419 {
5420 Long64_t cacheSize = 0;
5421 if (fAutoFlush < 0) {
5422 cacheSize = Long64_t(-cacheFactor * fAutoFlush);
5423 } else if (fAutoFlush == 0) {
5425 if (medianClusterSize > 0)
5426 cacheSize = Long64_t(cacheFactor * 1.5 * medianClusterSize * GetZipBytes() / (fEntries + 1));
5427 else
5428 cacheSize = Long64_t(cacheFactor * 1.5 * 30000000); // use the default value of fAutoFlush
5429 } else {
5430 cacheSize = Long64_t(cacheFactor * 1.5 * fAutoFlush * GetZipBytes() / (fEntries + 1));
5431 }
5432 if (cacheSize >= (INT_MAX / 4)) {
5433 cacheSize = INT_MAX / 4;
5434 }
5435 return cacheSize;
5436 };
5437
5438 const char *stcs;
5439 Double_t cacheFactor = 0.0;
5440 if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
5441 cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
5442 } else {
5444 }
5445
5446 if (cacheFactor < 0.0) {
5447 // ignore negative factors
5448 cacheFactor = 0.0;
5449 }
5450
5452
5453 if (cacheSize < 0) {
5454 cacheSize = 0;
5455 }
5456
5457 if (cacheSize == 0 && withDefault) {
5458 cacheSize = calculateCacheSize(1.0);
5459 }
5460
5461 return cacheSize;
5462}
5463
5464////////////////////////////////////////////////////////////////////////////////
5465/// Return an iterator over the cluster of baskets starting at firstentry.
5466///
5467/// This iterator is not yet supported for TChain object.
5468/// ~~~ {.cpp}
5469/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
5470/// Long64_t clusterStart;
5471/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
5472/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
5473/// }
5474/// ~~~
5477{
5478 // create cache if wanted
5479 if (fCacheDoAutoInit)
5481
5482 return TClusterIterator(this,firstentry);
5483}
5484
5485////////////////////////////////////////////////////////////////////////////////
5486/// Return pointer to the current file.
5489{
5490 if (!fDirectory || fDirectory==gROOT) {
5491 return nullptr;
5492 }
5493 return fDirectory->GetFile();
5494}
5495
5496////////////////////////////////////////////////////////////////////////////////
5497/// Return the number of entries matching the selection.
5498/// Return -1 in case of errors.
5499///
5500/// If the selection uses any arrays or containers, we return the number
5501/// of entries where at least one element match the selection.
5502/// GetEntries is implemented using the selector class TSelectorEntries,
5503/// which can be used directly (see code in TTreePlayer::GetEntries) for
5504/// additional option.
5505/// If SetEventList was used on the TTree or TChain, only that subset
5506/// of entries will be considered.
5509{
5510 GetPlayer();
5511 if (fPlayer) {
5512 return fPlayer->GetEntries(selection);
5513 }
5514 return -1;
5515}
5516
5517////////////////////////////////////////////////////////////////////////////////
5518/// Return pointer to the 1st Leaf named name in any Branch of this Tree or
5519/// any branch in the list of friend trees.
5522{
5523 if (fEntries) return fEntries;
5524 if (!fFriends) return 0;
5526 if (!fr) return 0;
5527 TTree *t = fr->GetTree();
5528 if (t==nullptr) return 0;
5529 return t->GetEntriesFriend();
5530}
5531
5532////////////////////////////////////////////////////////////////////////////////
5533/// Read all branches of entry and return total number of bytes read.
5534///
5535/// - `getall = 0` : get only active branches
5536/// - `getall = 1` : get all branches
5537///
5538/// The function returns the number of bytes read from the input buffer.
5539/// If entry does not exist the function returns 0.
5540/// If an I/O error occurs, the function returns -1.
5541/// If all branches are disabled and getall == 0, it also returns 0
5542/// even if the specified entry exists in the tree, since zero bytes were read.
5543///
5544/// If the Tree has friends, also read the friends entry.
5545///
5546/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
5547/// For example, if you have a Tree with several hundred branches, and you
5548/// are interested only by branches named "a" and "b", do
5549/// ~~~ {.cpp}
5550/// mytree.SetBranchStatus("*",0); //disable all branches
5551/// mytree.SetBranchStatus("a",1);
5552/// mytree.SetBranchStatus("b",1);
5553/// ~~~
5554/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
5555///
5556/// __WARNING!!__
5557/// If your Tree has been created in split mode with a parent branch "parent.",
5558/// ~~~ {.cpp}
5559/// mytree.SetBranchStatus("parent",1);
5560/// ~~~
5561/// will not activate the sub-branches of "parent". You should do:
5562/// ~~~ {.cpp}
5563/// mytree.SetBranchStatus("parent*",1);
5564/// ~~~
5565/// Without the trailing dot in the branch creation you have no choice but to
5566/// call SetBranchStatus explicitly for each of the sub branches.
5567///
5568/// An alternative is to call directly
5569/// ~~~ {.cpp}
5570/// brancha.GetEntry(i)
5571/// branchb.GetEntry(i);
5572/// ~~~
5573/// ## IMPORTANT NOTE
5574///
5575/// By default, GetEntry reuses the space allocated by the previous object
5576/// for each branch. You can force the previous object to be automatically
5577/// deleted if you call mybranch.SetAutoDelete(true) (default is false).
5578///
5579/// Example:
5580///
5581/// Consider the example in $ROOTSYS/test/Event.h
5582/// The top level branch in the tree T is declared with:
5583/// ~~~ {.cpp}
5584/// Event *event = 0; //event must be null or point to a valid object
5585/// //it must be initialized
5586/// T.SetBranchAddress("event",&event);
5587/// ~~~
5588/// When reading the Tree, one can choose one of these 3 options:
5589///
5590/// ## OPTION 1
5591///
5592/// ~~~ {.cpp}
5593/// for (Long64_t i=0;i<nentries;i++) {
5594/// T.GetEntry(i);
5595/// // the object event has been filled at this point
5596/// }
5597/// ~~~
5598/// The default (recommended). At the first entry an object of the class
5599/// Event will be created and pointed by event. At the following entries,
5600/// event will be overwritten by the new data. All internal members that are
5601/// TObject* are automatically deleted. It is important that these members
5602/// be in a valid state when GetEntry is called. Pointers must be correctly
5603/// initialized. However these internal members will not be deleted if the
5604/// characters "->" are specified as the first characters in the comment
5605/// field of the data member declaration.
5606///
5607/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
5608/// In this case, it is assumed that the pointer is never null (case of
5609/// pointer TClonesArray *fTracks in the Event example). If "->" is not
5610/// specified, the pointer member is read via buf >> pointer. In this case
5611/// the pointer may be null. Note that the option with "->" is faster to
5612/// read or write and it also consumes less space in the file.
5613///
5614/// ## OPTION 2
5615///
5616/// The option AutoDelete is set
5617/// ~~~ {.cpp}
5618/// TBranch *branch = T.GetBranch("event");
5619/// branch->SetAddress(&event);
5620/// branch->SetAutoDelete(true);
5621/// for (Long64_t i=0;i<nentries;i++) {
5622/// T.GetEntry(i);
5623/// // the object event has been filled at this point
5624/// }
5625/// ~~~
5626/// In this case, at each iteration, the object event is deleted by GetEntry
5627/// and a new instance of Event is created and filled.
5628///
5629/// ## OPTION 3
5630///
5631/// ~~~ {.cpp}
5632/// Same as option 1, but you delete yourself the event.
5633///
5634/// for (Long64_t i=0;i<nentries;i++) {
5635/// delete event;
5636/// event = 0; // EXTREMELY IMPORTANT
5637/// T.GetEntry(i);
5638/// // the object event has been filled at this point
5639/// }
5640/// ~~~
5641/// It is strongly recommended to use the default option 1. It has the
5642/// additional advantage that functions like TTree::Draw (internally calling
5643/// TTree::GetEntry) will be functional even when the classes in the file are
5644/// not available.
5645///
5646/// Note: See the comments in TBranchElement::SetAddress() for the
5647/// object ownership policy of the underlying (user) data.
5650{
5651 // We already have been visited while recursively looking
5652 // through the friends tree, let return
5653 if (kGetEntry & fFriendLockStatus) return 0;
5654
5655 if (entry < 0 || entry >= fEntries) return 0;
5656 Int_t i;
5657 Int_t nbytes = 0;
5658 fReadEntry = entry;
5659
5660 // create cache if wanted
5661 if (fCacheDoAutoInit)
5663
5665 Int_t nb=0;
5666
5667 auto seqprocessing = [&]() {
5668 TBranch *branch;
5669 for (i=0;i<nbranches;i++) {
5671 nb = branch->GetEntry(entry, getall);
5672 if (nb < 0) break;
5673 nbytes += nb;
5674 }
5675 };
5676
5677#ifdef R__USE_IMT
5679 if (fSortedBranches.empty())
5681
5682 // Count branches are processed first and sequentially
5683 for (auto branch : fSeqBranches) {
5684 nb = branch->GetEntry(entry, getall);
5685 if (nb < 0) break;
5686 nbytes += nb;
5687 }
5688 if (nb < 0) return nb;
5689
5690 // Enable this IMT use case (activate its locks)
5692
5693 Int_t errnb = 0;
5694 std::atomic<Int_t> pos(0);
5695 std::atomic<Int_t> nbpar(0);
5696
5697 auto mapFunction = [&]() {
5698 // The branch to process is obtained when the task starts to run.
5699 // This way, since branches are sorted, we make sure that branches
5700 // leading to big tasks are processed first. If we assigned the
5701 // branch at task creation time, the scheduler would not necessarily
5702 // respect our sorting.
5703 Int_t j = pos.fetch_add(1);
5704
5705 Int_t nbtask = 0;
5706 auto branch = fSortedBranches[j].second;
5707
5708 if (gDebug > 0) {
5709 std::stringstream ss;
5710 ss << std::this_thread::get_id();
5711 Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
5712 Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5713 }
5714
5715 std::chrono::time_point<std::chrono::system_clock> start, end;
5716
5717 start = std::chrono::system_clock::now();
5718 nbtask = branch->GetEntry(entry, getall);
5719 end = std::chrono::system_clock::now();
5720
5721 Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
5722 fSortedBranches[j].first += tasktime;
5723
5724 if (nbtask < 0) errnb = nbtask;
5725 else nbpar += nbtask;
5726 };
5727
5729 pool.Foreach(mapFunction, fSortedBranches.size());
5730
5731 if (errnb < 0) {
5732 nb = errnb;
5733 }
5734 else {
5735 // Save the number of bytes read by the tasks
5736 nbytes += nbpar;
5737
5738 // Re-sort branches if necessary
5742 }
5743 }
5744 }
5745 else {
5746 seqprocessing();
5747 }
5748#else
5749 seqprocessing();
5750#endif
5751 if (nb < 0) return nb;
5752
5753 // GetEntry in list of friends
5754 if (!fFriends) return nbytes;
5755 TFriendLock lock(this,kGetEntry);
5758 while ((fe = (TFriendElement*)nextf())) {
5759 TTree *t = fe->GetTree();
5760 if (t) {
5761 if (fe->TestBit(TFriendElement::kFromChain)) {
5762 nb = t->GetEntry(t->GetReadEntry(),getall);
5763 } else {
5764 if ( t->LoadTreeFriend(entry,this) >= 0 ) {
5765 nb = t->GetEntry(t->GetReadEntry(),getall);
5766 } else nb = 0;
5767 }
5768 if (nb < 0) return nb;
5769 nbytes += nb;
5770 }
5771 }
5772 return nbytes;
5773}
5774
5775
5776////////////////////////////////////////////////////////////////////////////////
5777/// Divides the top-level branches into two vectors: (i) branches to be
5778/// processed sequentially and (ii) branches to be processed in parallel.
5779/// Even if IMT is on, some branches might need to be processed first and in a
5780/// sequential fashion: in the parallelization of GetEntry, those are the
5781/// branches that store the size of another branch for every entry
5782/// (e.g. the size of an array branch). If such branches were processed
5783/// in parallel with the rest, there could be two threads invoking
5784/// TBranch::GetEntry on one of them at the same time, since a branch that
5785/// depends on a size (or count) branch will also invoke GetEntry on the latter.
5786/// This method can be invoked several times during the event loop if the TTree
5787/// is being written, for example when adding new branches. In these cases, the
5788/// `checkLeafCount` parameter is false.
5789/// \param[in] checkLeafCount True if we need to check whether some branches are
5790/// count leaves.
5793{
5795
5796 // The special branch fBranchRef needs to be processed sequentially:
5797 // we add it once only.
5798 if (fBranchRef && fBranchRef != fSeqBranches[0]) {
5799 fSeqBranches.push_back(fBranchRef);
5800 }
5801
5802 // The branches to be processed sequentially are those that are the leaf count of another branch
5803 if (checkLeafCount) {
5804 for (Int_t i = 0; i < nbranches; i++) {
5806 auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
5807 if (leafCount) {
5808 auto countBranch = leafCount->GetBranch();
5809 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
5810 fSeqBranches.push_back(countBranch);
5811 }
5812 }
5813 }
5814 }
5815
5816 // Any branch that is not a leaf count can be safely processed in parallel when reading
5817 // We need to reset the vector to make sure we do not re-add several times the same branch.
5818 if (!checkLeafCount) {
5819 fSortedBranches.clear();
5820 }
5821 for (Int_t i = 0; i < nbranches; i++) {
5822 Long64_t bbytes = 0;
5824 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
5825 bbytes = branch->GetTotBytes("*");
5826 fSortedBranches.emplace_back(bbytes, branch);
5827 }
5828 }
5829
5830 // Initially sort parallel branches by size
5831 std::sort(fSortedBranches.begin(),
5832 fSortedBranches.end(),
5833 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5834 return a.first > b.first;
5835 });
5836
5837 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5838 fSortedBranches[i].first = 0LL;
5839 }
5840}
5841
5842////////////////////////////////////////////////////////////////////////////////
5843/// Sorts top-level branches by the last average task time recorded per branch.
5846{
5847 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5849 }
5850
5851 std::sort(fSortedBranches.begin(),
5852 fSortedBranches.end(),
5853 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5854 return a.first > b.first;
5855 });
5856
5857 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5858 fSortedBranches[i].first = 0LL;
5859 }
5860}
5861
5862////////////////////////////////////////////////////////////////////////////////
5863///Returns the entry list assigned to this tree
5866{
5867 return fEntryList;
5868}
5869
5870////////////////////////////////////////////////////////////////////////////////
5871/// Return entry number corresponding to entry.
5872///
5873/// if no TEntryList set returns entry
5874/// else returns the entry number corresponding to the list index=entry
5877{
5878 if (!fEntryList) {
5879 return entry;
5880 }
5881
5882 return fEntryList->GetEntry(entry);
5883}
5884
5885////////////////////////////////////////////////////////////////////////////////
5886/// Return entry number corresponding to major and minor number.
5887/// Note that this function returns only the entry number, not the data
5888/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5889/// the BuildIndex function has created a table of Long64_t* of sorted values
5890/// corresponding to val = major<<31 + minor;
5891/// The function performs binary search in this sorted table.
5892/// If it finds a pair that matches val, it returns directly the
5893/// index in the table.
5894/// If an entry corresponding to major and minor is not found, the function
5895/// returns the index of the major,minor pair immediately lower than the
5896/// requested value, ie it will return -1 if the pair is lower than
5897/// the first entry in the index.
5898///
5899/// See also GetEntryNumberWithIndex
5907}
5908
5909////////////////////////////////////////////////////////////////////////////////
5910/// Return entry number corresponding to major and minor number.
5911/// Note that this function returns only the entry number, not the data
5912/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5913/// the BuildIndex function has created a table of Long64_t* of sorted values
5914/// corresponding to val = major<<31 + minor;
5915/// The function performs binary search in this sorted table.
5916/// If it finds a pair that matches val, it returns directly the
5917/// index in the table, otherwise it returns -1.
5918///
5919/// See also GetEntryNumberWithBestIndex
5922{
5923 if (!fTreeIndex) {
5924 return -1;
5925 }
5927}
5928
5929////////////////////////////////////////////////////////////////////////////////
5930/// Read entry corresponding to major and minor number.
5931///
5932/// The function returns the total number of bytes read.
5933/// If the Tree has friend trees, the corresponding entry with
5934/// the index values (major,minor) is read. Note that the master Tree
5935/// and its friend may have different entry serial numbers corresponding
5936/// to (major,minor).
5939{
5940 // We already have been visited while recursively looking
5941 // through the friends tree, let's return.
5943 return 0;
5944 }
5946 if (serial < 0) {
5947 return -1;
5948 }
5949 // create cache if wanted
5950 if (fCacheDoAutoInit)
5952
5953 Int_t i;
5954 Int_t nbytes = 0;
5955 fReadEntry = serial;
5956 TBranch *branch;
5958 Int_t nb;
5959 for (i = 0; i < nbranches; ++i) {
5961 nb = branch->GetEntry(serial);
5962 if (nb < 0) return nb;
5963 nbytes += nb;
5964 }
5965 // GetEntry in list of friends
5966 if (!fFriends) return nbytes;
5969 TFriendElement* fe = nullptr;
5970 while ((fe = (TFriendElement*) nextf())) {
5971 TTree *t = fe->GetTree();
5972 if (t) {
5973 serial = t->GetEntryNumberWithIndex(major,minor);
5974 if (serial <0) return -nbytes;
5975 nb = t->GetEntry(serial);
5976 if (nb < 0) return nb;
5977 nbytes += nb;
5978 }
5979 }
5980 return nbytes;
5981}
5982
5983////////////////////////////////////////////////////////////////////////////////
5984/// Return a pointer to the TTree friend whose name or alias is `friendname`.
5986TTree* TTree::GetFriend(const char *friendname) const
5987{
5988
5989 // We already have been visited while recursively
5990 // looking through the friends tree, let's return.
5992 return nullptr;
5993 }
5994 if (!fFriends) {
5995 return nullptr;
5996 }
5997 TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
5999 TFriendElement* fe = nullptr;
6000 while ((fe = (TFriendElement*) nextf())) {
6001 if (strcmp(friendname,fe->GetName())==0
6002 || strcmp(friendname,fe->GetTreeName())==0) {
6003 return fe->GetTree();
6004 }
6005 }
6006 // After looking at the first level,
6007 // let's see if it is a friend of friends.
6008 nextf.Reset();
6009 fe = nullptr;
6010 while ((fe = (TFriendElement*) nextf())) {
6011 TTree *res = fe->GetTree()->GetFriend(friendname);
6012 if (res) {
6013 return res;
6014 }
6015 }
6016 return nullptr;
6017}
6018
6019////////////////////////////////////////////////////////////////////////////////
6020/// If the 'tree' is a friend, this method returns its alias name.
6021///
6022/// This alias is an alternate name for the tree.
6023///
6024/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
6025/// to specify in which particular tree the branch or leaf can be found if
6026/// the friend trees have branches or leaves with the same name as the master
6027/// tree.
6028///
6029/// It can also be used in conjunction with an alias created using
6030/// TTree::SetAlias in a TTreeFormula, e.g.:
6031/// ~~~ {.cpp}
6032/// maintree->Draw("treealias.fPx - treealias.myAlias");
6033/// ~~~
6034/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
6035/// was created using TTree::SetAlias on the friend tree.
6036///
6037/// However, note that 'treealias.myAlias' will be expanded literally,
6038/// without remembering that it comes from the aliased friend and thus
6039/// the branch name might not be disambiguated properly, which means
6040/// that you may not be able to take advantage of this feature.
6041///
6043const char* TTree::GetFriendAlias(TTree* tree) const
6044{
6045 if ((tree == this) || (tree == GetTree())) {
6046 return nullptr;
6047 }
6048
6049 // We already have been visited while recursively
6050 // looking through the friends tree, let's return.
6052 return nullptr;
6053 }
6054 if (!fFriends) {
6055 return nullptr;
6056 }
6057 TFriendLock lock(const_cast<TTree*>(this), kGetFriendAlias);
6059 TFriendElement* fe = nullptr;
6060 while ((fe = (TFriendElement*) nextf())) {
6061 TTree* t = fe->GetTree();
6062 if (t == tree) {
6063 return fe->GetName();
6064 }
6065 // Case of a chain:
6066 if (t && t->GetTree() == tree) {
6067 return fe->GetName();
6068 }
6069 }
6070 // After looking at the first level,
6071 // let's see if it is a friend of friends.
6072 nextf.Reset();
6073 fe = nullptr;
6074 while ((fe = (TFriendElement*) nextf())) {
6075 const char* res = fe->GetTree()->GetFriendAlias(tree);
6076 if (res) {
6077 return res;
6078 }
6079 }
6080 return nullptr;
6081}
6082
6083////////////////////////////////////////////////////////////////////////////////
6084/// Returns the current set of IO settings
6086{
6087 return fIOFeatures;
6088}
6089
6090////////////////////////////////////////////////////////////////////////////////
6091/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
6094{
6095 return new TTreeFriendLeafIter(this, dir);
6096}
6097
6098////////////////////////////////////////////////////////////////////////////////
6099/// Return pointer to the 1st Leaf named name in any Branch of this
6100/// Tree or any branch in the list of friend trees.
6101///
6102/// The leaf name can contain the name of a friend tree with the
6103/// syntax: friend_dir_and_tree.full_leaf_name
6104/// the friend_dir_and_tree can be of the form:
6105/// ~~~ {.cpp}
6106/// TDirectoryName/TreeName
6107/// ~~~
6109TLeaf* TTree::GetLeafImpl(const char* branchname, const char *leafname)
6110{
6111 TLeaf *leaf = nullptr;
6112 if (branchname) {
6114 if (branch) {
6115 leaf = branch->GetLeaf(leafname);
6116 if (leaf) {
6117 return leaf;
6118 }
6119 }
6120 }
6122 while ((leaf = (TLeaf*)nextl())) {
6123 if (strcmp(leaf->GetFullName(), leafname) != 0 && strcmp(leaf->GetName(), leafname) != 0)
6124 continue; // leafname does not match GetName() nor GetFullName(), this is not the right leaf
6125 if (branchname) {
6126 // check the branchname is also a match
6127 TBranch *br = leaf->GetBranch();
6128 // if a quick comparison with the branch full name is a match, we are done
6129 if (!strcmp(br->GetFullName(), branchname))
6130 return leaf;
6132 const char* brname = br->GetName();
6133 TBranch *mother = br->GetMother();
6135 if (mother != br) {
6136 const char *mothername = mother->GetName();
6138 if (!strcmp(mothername, branchname)) {
6139 return leaf;
6140 } else if (nbch > motherlen && strncmp(mothername,branchname,motherlen)==0 && (mothername[motherlen-1]=='.' || branchname[motherlen]=='.')) {
6141 // 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.
6143 // No it does not
6144 continue;
6145 } // else we have match so we can proceed.
6146 } else {
6147 // no match
6148 continue;
6149 }
6150 } else {
6151 continue;
6152 }
6153 }
6154 // The start of the branch name is identical to the content
6155 // of 'aname' before the first '/'.
6156 // Let's make sure that it is not longer (we are trying
6157 // to avoid having jet2/value match the branch jet23
6158 if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
6159 continue;
6160 }
6161 }
6162 return leaf;
6163 }
6164 if (!fFriends) return nullptr;
6165 TFriendLock lock(this,kGetLeaf);
6166 TIter next(fFriends);
6168 while ((fe = (TFriendElement*)next())) {
6169 TTree *t = fe->GetTree();
6170 if (t) {
6172 if (leaf) return leaf;
6173 }
6174 }
6175
6176 //second pass in the list of friends when the leaf name
6177 //is prefixed by the tree name
6179 next.Reset();
6180 while ((fe = (TFriendElement*)next())) {
6181 TTree *t = fe->GetTree();
6182 if (!t) continue;
6183 const char *subname = strstr(leafname,fe->GetName());
6184 if (subname != leafname) continue;
6185 Int_t l = strlen(fe->GetName());
6186 subname += l;
6187 if (*subname != '.') continue;
6188 subname++;
6191 if (leaf) return leaf;
6192 }
6193 return nullptr;
6194}
6195
6196////////////////////////////////////////////////////////////////////////////////
6197/// Return pointer to the 1st Leaf named name in any Branch of this
6198/// Tree or any branch in the list of friend trees.
6199///
6200/// The leaf name can contain the name of a friend tree with the
6201/// syntax: friend_dir_and_tree.full_leaf_name
6202/// the friend_dir_and_tree can be of the form:
6203///
6204/// TDirectoryName/TreeName
6206TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
6207{
6208 if (leafname == nullptr) return nullptr;
6209
6210 // We already have been visited while recursively looking
6211 // through the friends tree, let return
6213 return nullptr;
6214 }
6215
6217}
6218
6219////////////////////////////////////////////////////////////////////////////////
6220/// Return pointer to first leaf named "name" in any branch of this
6221/// tree or its friend trees.
6222///
6223/// \param[in] name may be in the form 'branch/leaf'
6224///
6226TLeaf* TTree::GetLeaf(const char *name)
6227{
6228 // Return nullptr if name is invalid or if we have
6229 // already been visited while searching friend trees
6230 if (!name || (kGetLeaf & fFriendLockStatus))
6231 return nullptr;
6232
6233 std::string path(name);
6234 const auto sep = path.find_last_of('/');
6235 if (sep != std::string::npos)
6236 return GetLeafImpl(path.substr(0, sep).c_str(), name+sep+1);
6237
6238 return GetLeafImpl(nullptr, name);
6239}
6240
6241////////////////////////////////////////////////////////////////////////////////
6242/// Return maximum of column with name columname.
6243/// if the Tree has an associated TEventList or TEntryList, the maximum
6244/// is computed for the entries in this list.
6247{
6248 TLeaf* leaf = this->GetLeaf(columname);
6249 if (!leaf) {
6250 return 0;
6251 }
6252
6253 // create cache if wanted
6254 if (fCacheDoAutoInit)
6256
6257 TBranch* branch = leaf->GetBranch();
6259 for (Long64_t i = 0; i < fEntries; ++i) {
6261 if (entryNumber < 0) break;
6262 branch->GetEntry(entryNumber);
6263 for (Int_t j = 0; j < leaf->GetLen(); ++j) {
6264 Double_t val = leaf->GetValue(j);
6265 if (val > cmax) {
6266 cmax = val;
6267 }
6268 }
6269 }
6270 return cmax;
6271}
6272
6273////////////////////////////////////////////////////////////////////////////////
6274/// Static function which returns the tree file size limit in bytes.
6279}
6280
6281////////////////////////////////////////////////////////////////////////////////
6282/// Return minimum of column with name columname.
6283/// if the Tree has an associated TEventList or TEntryList, the minimum
6284/// is computed for the entries in this list.
6287{
6288 TLeaf* leaf = this->GetLeaf(columname);
6289 if (!leaf) {
6290 return 0;
6291 }
6292
6293 // create cache if wanted
6294 if (fCacheDoAutoInit)
6296
6297 TBranch* branch = leaf->GetBranch();
6299 for (Long64_t i = 0; i < fEntries; ++i) {
6301 if (entryNumber < 0) break;
6302 branch->GetEntry(entryNumber);
6303 for (Int_t j = 0;j < leaf->GetLen(); ++j) {
6304 Double_t val = leaf->GetValue(j);
6305 if (val < cmin) {
6306 cmin = val;
6307 }
6308 }
6309 }
6310 return cmin;
6311}
6312
6313////////////////////////////////////////////////////////////////////////////////
6314/// Load the TTreePlayer (if not already done).
6317{
6318 if (fPlayer) {
6319 return fPlayer;
6320 }
6322 return fPlayer;
6323}
6324
6325////////////////////////////////////////////////////////////////////////////////
6326/// Find and return the TTreeCache registered with the file and which may
6327/// contain branches for us.
6330{
6331 TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6332 if (pe && pe->GetTree() != GetTree())
6333 pe = nullptr;
6334 return pe;
6335}
6336
6337////////////////////////////////////////////////////////////////////////////////
6338/// Find and return the TTreeCache registered with the file and which may
6339/// contain branches for us. If create is true and there is no cache
6340/// a new cache is created with default size.
6342TTreeCache *TTree::GetReadCache(TFile *file, bool create)
6343{
6344 TTreeCache *pe = GetReadCache(file);
6345 if (create && !pe) {
6346 if (fCacheDoAutoInit)
6347 SetCacheSizeAux(true, -1);
6348 pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6349 if (pe && pe->GetTree() != GetTree()) pe = nullptr;
6350 }
6351 return pe;
6352}
6353
6354////////////////////////////////////////////////////////////////////////////////
6355/// Return a pointer to the list containing user objects associated to this tree.
6356///
6357/// The list is automatically created if it does not exist.
6358///
6359/// WARNING: By default the TTree destructor will delete all objects added
6360/// to this list. If you do not want these objects to be deleted,
6361/// call:
6362///
6363/// mytree->GetUserInfo()->Clear();
6364///
6365/// before deleting the tree.
6368{
6369 if (!fUserInfo) {
6370 fUserInfo = new TList();
6371 fUserInfo->SetName("UserInfo");
6372 }
6373 return fUserInfo;
6374}
6375
6376////////////////////////////////////////////////////////////////////////////////
6377/// Appends the cluster range information stored in 'fromtree' to this tree,
6378/// including the value of fAutoFlush.
6379///
6380/// This is used when doing a fast cloning (by TTreeCloner).
6381/// See also fAutoFlush and fAutoSave if needed.
6384{
6385 Long64_t autoflush = fromtree->GetAutoFlush();
6386 if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
6387 // nothing to do
6388 } else if (fNClusterRange || fromtree->fNClusterRange) {
6389 Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
6390 if (newsize > fMaxClusterRange) {
6391 if (fMaxClusterRange) {
6393 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6395 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6397 } else {
6401 }
6402 }
6403 if (fEntries) {
6407 }
6408 for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
6409 fClusterRangeEnd[fNClusterRange] = fEntries + fromtree->fClusterRangeEnd[i];
6410 fClusterSize[fNClusterRange] = fromtree->fClusterSize[i];
6412 }
6414 } else {
6416 }
6418 if (autoflush > 0 && autosave > 0) {
6420 }
6421}
6422
6423////////////////////////////////////////////////////////////////////////////////
6424/// Keep a maximum of fMaxEntries in memory.
6427{
6430 for (Int_t i = 0; i < nb; ++i) {
6432 branch->KeepCircular(maxEntries);
6433 }
6434 if (fNClusterRange) {
6437 for(Int_t i = 0, j = 0; j < oldsize; ++j) {
6440 ++i;
6441 } else {
6443 }
6444 }
6445 }
6447 fReadEntry = -1;
6448}
6449
6450////////////////////////////////////////////////////////////////////////////////
6451/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
6452///
6453/// If maxmemory is non null and positive SetMaxVirtualSize is called
6454/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
6455/// The function returns the total number of baskets read into memory
6456/// if negative an error occurred while loading the branches.
6457/// This method may be called to force branch baskets in memory
6458/// when random access to branch entries is required.
6459/// If random access to only a few branches is required, you should
6460/// call directly TBranch::LoadBaskets.
6463{
6465
6466 TIter next(GetListOfLeaves());
6467 TLeaf *leaf;
6468 Int_t nimported = 0;
6469 while ((leaf=(TLeaf*)next())) {
6470 nimported += leaf->GetBranch()->LoadBaskets();//break;
6471 }
6472 return nimported;
6473}
6474
6475////////////////////////////////////////////////////////////////////////////////
6476/// Set current entry.
6477///
6478/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
6479/// Returns -6 if an error occurs in the notification callback (just as TChain::LoadTree()).
6480///
6481/// Calls fNotify->Notify() (if fNotify is not null) when starting the processing of a new tree.
6482///
6483/// \note This function is overloaded in TChain.
6485{
6486 // We have already been visited while recursively looking
6487 // through the friend trees, let's return
6489 // We need to return a negative value to avoid a circular list of friends
6490 // to think that there is always an entry somewhere in the list.
6491 return -1;
6492 }
6493
6494 // create cache if wanted
6495 if (fCacheDoAutoInit && entry >=0)
6497
6498 if (fNotify) {
6499 if (fReadEntry < 0) {
6500 fNotify->Notify();
6501 }
6502 }
6503 fReadEntry = entry;
6504
6505 bool friendHasEntry = false;
6506 if (fFriends) {
6507 // Set current entry in friends as well.
6508 //
6509 // An alternative would move this code to each of the
6510 // functions calling LoadTree (and to overload a few more).
6511 bool needUpdate = false;
6512 {
6513 // This scope is need to insure the lock is released at the right time
6515 TFriendLock lock(this, kLoadTree);
6516 TFriendElement* fe = nullptr;
6517 while ((fe = (TFriendElement*) nextf())) {
6518 if (fe->TestBit(TFriendElement::kFromChain)) {
6519 // This friend element was added by the chain that owns this
6520 // tree, the chain will deal with loading the correct entry.
6521 continue;
6522 }
6523 TTree* friendTree = fe->GetTree();
6524 if (friendTree) {
6525 if (friendTree->LoadTreeFriend(entry, this) >= 0) {
6526 friendHasEntry = true;
6527 }
6528 }
6529 if (fe->IsUpdated()) {
6530 needUpdate = true;
6531 fe->ResetUpdated();
6532 }
6533 } // for each friend
6534 }
6535 if (needUpdate) {
6536 //update list of leaves in all TTreeFormula of the TTreePlayer (if any)
6537 if (fPlayer) {
6539 }
6540 //Notify user if requested
6541 if (fNotify) {
6542 if(!fNotify->Notify()) return -6;
6543 }
6544 }
6545 }
6546
6547 if ((fReadEntry >= fEntries) && !friendHasEntry) {
6548 fReadEntry = -1;
6549 return -2;
6550 }
6551 return fReadEntry;
6552}
6553
6554////////////////////////////////////////////////////////////////////////////////
6555/// Load entry on behalf of our master tree, we may use an index.
6556///
6557/// Called by LoadTree() when the masterTree looks for the entry
6558/// number in a friend tree (us) corresponding to the passed entry
6559/// number in the masterTree.
6560///
6561/// If we have no index, our entry number and the masterTree entry
6562/// number are the same.
6563///
6564/// If we *do* have an index, we must find the (major, minor) value pair
6565/// in masterTree to locate our corresponding entry.
6566///
6574}
6575
6576////////////////////////////////////////////////////////////////////////////////
6577/// Generate a skeleton analysis class for this tree.
6578///
6579/// The following files are produced: classname.h and classname.C.
6580/// If classname is 0, classname will be called "nameoftree".
6581///
6582/// The generated code in classname.h includes the following:
6583///
6584/// - Identification of the original tree and the input file name.
6585/// - Definition of an analysis class (data members and member functions).
6586/// - The following member functions:
6587/// - constructor (by default opening the tree file),
6588/// - GetEntry(Long64_t entry),
6589/// - Init(TTree* tree) to initialize a new TTree,
6590/// - Show(Long64_t entry) to read and dump entry.
6591///
6592/// The generated code in classname.C includes only the main
6593/// analysis function Loop.
6594///
6595/// To use this function:
6596///
6597/// - Open your tree file (eg: TFile f("myfile.root");)
6598/// - T->MakeClass("MyClass");
6599///
6600/// where T is the name of the TTree in file myfile.root,
6601/// and MyClass.h, MyClass.C the name of the files created by this function.
6602/// In a ROOT session, you can do:
6603/// ~~~ {.cpp}
6604/// root > .L MyClass.C
6605/// root > MyClass* t = new MyClass;
6606/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
6607/// root > t->Show(); // Show values of entry 12.
6608/// root > t->Show(16); // Read and show values of entry 16.
6609/// root > t->Loop(); // Loop on all entries.
6610/// ~~~
6611/// NOTE: Do not use the code generated for a single TTree which is part
6612/// of a TChain to process that entire TChain. The maximum dimensions
6613/// calculated for arrays on the basis of a single TTree from the TChain
6614/// might be (will be!) too small when processing all of the TTrees in
6615/// the TChain. You must use myChain.MakeClass() to generate the code,
6616/// not myTree.MakeClass(...).
6618Int_t TTree::MakeClass(const char* classname, Option_t* option)
6619{
6620 GetPlayer();
6621 if (!fPlayer) {
6622 return 0;
6623 }
6624 return fPlayer->MakeClass(classname, option);
6625}
6626
6627////////////////////////////////////////////////////////////////////////////////
6628/// Generate a skeleton function for this tree.
6629///
6630/// The function code is written on filename.
6631/// If filename is 0, filename will be called nameoftree.C
6632///
6633/// The generated code includes the following:
6634/// - Identification of the original Tree and Input file name,
6635/// - Opening the Tree file,
6636/// - Declaration of Tree variables,
6637/// - Setting of branches addresses,
6638/// - A skeleton for the entry loop.
6639///
6640/// To use this function:
6641///
6642/// - Open your Tree file (eg: TFile f("myfile.root");)
6643/// - T->MakeCode("MyAnalysis.C");
6644///
6645/// where T is the name of the TTree in file myfile.root
6646/// and MyAnalysis.C the name of the file created by this function.
6647///
6648/// NOTE: Since the implementation of this function, a new and better
6649/// function TTree::MakeClass() has been developed.
6651Int_t TTree::MakeCode(const char* filename)
6652{
6653 Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
6654
6655 GetPlayer();
6656 if (!fPlayer) return 0;
6657 return fPlayer->MakeCode(filename);
6658}
6659
6660////////////////////////////////////////////////////////////////////////////////
6661/// Generate a skeleton analysis class for this Tree using TBranchProxy.
6662///
6663/// TBranchProxy is the base of a class hierarchy implementing an
6664/// indirect access to the content of the branches of a TTree.
6665///
6666/// "proxyClassname" is expected to be of the form:
6667/// ~~~ {.cpp}
6668/// [path/]fileprefix
6669/// ~~~
6670/// The skeleton will then be generated in the file:
6671/// ~~~ {.cpp}
6672/// fileprefix.h
6673/// ~~~
6674/// located in the current directory or in 'path/' if it is specified.
6675/// The class generated will be named 'fileprefix'
6676///
6677/// "macrofilename" and optionally "cutfilename" are expected to point
6678/// to source files which will be included by the generated skeleton.
6679/// Method of the same name as the file(minus the extension and path)
6680/// will be called by the generated skeleton's Process method as follow:
6681/// ~~~ {.cpp}
6682/// [if (cutfilename())] htemp->Fill(macrofilename());
6683/// ~~~
6684/// "option" can be used select some of the optional features during
6685/// the code generation. The possible options are:
6686///
6687/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
6688///
6689/// 'maxUnrolling' controls how deep in the class hierarchy does the
6690/// system 'unroll' classes that are not split. Unrolling a class
6691/// allows direct access to its data members (this emulates the behavior
6692/// of TTreeFormula).
6693///
6694/// The main features of this skeleton are:
6695///
6696/// * on-demand loading of branches
6697/// * ability to use the 'branchname' as if it was a data member
6698/// * protection against array out-of-bounds errors
6699/// * ability to use the branch data as an object (when the user code is available)
6700///
6701/// For example with Event.root, if
6702/// ~~~ {.cpp}
6703/// Double_t somePx = fTracks.fPx[2];
6704/// ~~~
6705/// is executed by one of the method of the skeleton,
6706/// somePx will updated with the current value of fPx of the 3rd track.
6707///
6708/// Both macrofilename and the optional cutfilename are expected to be
6709/// the name of source files which contain at least a free standing
6710/// function with the signature:
6711/// ~~~ {.cpp}
6712/// x_t macrofilename(); // i.e function with the same name as the file
6713/// ~~~
6714/// and
6715/// ~~~ {.cpp}
6716/// y_t cutfilename(); // i.e function with the same name as the file
6717/// ~~~
6718/// x_t and y_t needs to be types that can convert respectively to a double
6719/// and a bool (because the skeleton uses:
6720///
6721/// if (cutfilename()) htemp->Fill(macrofilename());
6722///
6723/// These two functions are run in a context such that the branch names are
6724/// available as local variables of the correct (read-only) type.
6725///
6726/// Note that if you use the same 'variable' twice, it is more efficient
6727/// to 'cache' the value. For example:
6728/// ~~~ {.cpp}
6729/// Int_t n = fEventNumber; // Read fEventNumber
6730/// if (n<10 || n>10) { ... }
6731/// ~~~
6732/// is more efficient than
6733/// ~~~ {.cpp}
6734/// if (fEventNumber<10 || fEventNumber>10)
6735/// ~~~
6736/// Also, optionally, the generated selector will also call methods named
6737/// macrofilename_methodname in each of 6 main selector methods if the method
6738/// macrofilename_methodname exist (Where macrofilename is stripped of its
6739/// extension).
6740///
6741/// Concretely, with the script named h1analysisProxy.C,
6742///
6743/// - The method calls the method (if it exist)
6744/// - Begin -> void h1analysisProxy_Begin(TTree*);
6745/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
6746/// - Notify -> bool h1analysisProxy_Notify();
6747/// - Process -> bool h1analysisProxy_Process(Long64_t);
6748/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
6749/// - Terminate -> void h1analysisProxy_Terminate();
6750///
6751/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
6752/// it is included before the declaration of the proxy class. This can
6753/// be used in particular to insure that the include files needed by
6754/// the macro file are properly loaded.
6755///
6756/// The default histogram is accessible via the variable named 'htemp'.
6757///
6758/// If the library of the classes describing the data in the branch is
6759/// loaded, the skeleton will add the needed `include` statements and
6760/// give the ability to access the object stored in the branches.
6761///
6762/// To draw px using the file hsimple.root (generated by the
6763/// hsimple.C tutorial), we need a file named hsimple.cxx:
6764/// ~~~ {.cpp}
6765/// double hsimple() {
6766/// return px;
6767/// }
6768/// ~~~
6769/// MakeProxy can then be used indirectly via the TTree::Draw interface
6770/// as follow:
6771/// ~~~ {.cpp}
6772/// new TFile("hsimple.root")
6773/// ntuple->Draw("hsimple.cxx");
6774/// ~~~
6775/// A more complete example is available in the tutorials directory:
6776/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
6777/// which reimplement the selector found in h1analysis.C
6779Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
6780{
6781 GetPlayer();
6782 if (!fPlayer) return 0;
6784}
6785
6786////////////////////////////////////////////////////////////////////////////////
6787/// Generate skeleton selector class for this tree.
6788///
6789/// The following files are produced: selector.h and selector.C.
6790/// If selector is 0, the selector will be called "nameoftree".
6791/// The option can be used to specify the branches that will have a data member.
6792/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
6793/// members and branch pointers instead of TTreeReaders).
6794/// - If option is empty, readers will be generated for each leaf.
6795/// - If option is "@", readers will be generated for the topmost branches.
6796/// - Individual branches can also be picked by their name:
6797/// - "X" generates readers for leaves of X.
6798/// - "@X" generates a reader for X as a whole.
6799/// - "@X;Y" generates a reader for X as a whole and also readers for the
6800/// leaves of Y.
6801/// - For further examples see the figure below.
6802///
6803/// \image html ttree_makeselector_option_examples.png
6804///
6805/// The generated code in selector.h includes the following:
6806/// - Identification of the original Tree and Input file name
6807/// - Definition of selector class (data and functions)
6808/// - The following class functions:
6809/// - constructor and destructor
6810/// - void Begin(TTree *tree)
6811/// - void SlaveBegin(TTree *tree)
6812/// - void Init(TTree *tree)
6813/// - bool Notify()
6814/// - bool Process(Long64_t entry)
6815/// - void Terminate()
6816/// - void SlaveTerminate()
6817///
6818/// The class selector derives from TSelector.
6819/// The generated code in selector.C includes empty functions defined above.
6820///
6821/// To use this function:
6822///
6823/// - connect your Tree file (eg: `TFile f("myfile.root");`)
6824/// - `T->MakeSelector("myselect");`
6825///
6826/// where T is the name of the Tree in file myfile.root
6827/// and myselect.h, myselect.C the name of the files created by this function.
6828/// In a ROOT session, you can do:
6829/// ~~~ {.cpp}
6830/// root > T->Process("myselect.C")
6831/// ~~~
6833Int_t TTree::MakeSelector(const char* selector, Option_t* option)
6834{
6835 TString opt(option);
6836 if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
6837 return MakeClass(selector, "selector");
6838 } else {
6839 GetPlayer();
6840 if (!fPlayer) return 0;
6841 return fPlayer->MakeReader(selector, option);
6842 }
6843}
6844
6845////////////////////////////////////////////////////////////////////////////////
6846/// Check if adding nbytes to memory we are still below MaxVirtualsize.
6849{
6851 return false;
6852 }
6853 return true;
6854}
6855
6856////////////////////////////////////////////////////////////////////////////////
6857/// Static function merging the trees in the TList into a new tree.
6858///
6859/// Trees in the list can be memory or disk-resident trees.
6860/// The new tree is created in the current directory (memory if gROOT).
6861/// Trees with no branches will be skipped, the branch structure
6862/// will be taken from the first non-zero-branch Tree of {li}
6865{
6866 if (!li) return nullptr;
6867 TIter next(li);
6868 TTree *newtree = nullptr;
6869 TObject *obj;
6870
6871 while ((obj=next())) {
6872 if (!obj->InheritsFrom(TTree::Class())) continue;
6873 TTree *tree = (TTree*)obj;
6874 if (tree->GetListOfBranches()->IsEmpty()) {
6875 if (gDebug > 2) {
6876 tree->Warning("MergeTrees","TTree %s has no branches, skipping.", tree->GetName());
6877 }
6878 continue; // Completely ignore the empty trees.
6879 }
6880 Long64_t nentries = tree->GetEntries();
6881 if (newtree && nentries == 0)
6882 continue; // If we already have the structure and we have no entry, save time and skip
6883 if (!newtree) {
6884 newtree = (TTree*)tree->CloneTree(-1, options);
6885 if (!newtree) continue;
6886
6887 // Once the cloning is done, separate the trees,
6888 // to avoid as many side-effects as possible
6889 // The list of clones is guaranteed to exist since we
6890 // just cloned the tree.
6891 tree->GetListOfClones()->Remove(newtree);
6892 tree->ResetBranchAddresses();
6893 newtree->ResetBranchAddresses();
6894 continue;
6895 }
6896 if (nentries == 0)
6897 continue;
6898 newtree->CopyEntries(tree, -1, options, true);
6899 }
6900 if (newtree && newtree->GetTreeIndex()) {
6901 newtree->GetTreeIndex()->Append(nullptr,false); // Force the sorting
6902 }
6903 return newtree;
6904}
6905
6906////////////////////////////////////////////////////////////////////////////////
6907/// Merge the trees in the TList into this tree.
6908///
6909/// Returns the total number of entries in the merged tree.
6910/// Trees with no branches will be skipped, the branch structure
6911/// will be taken from the first non-zero-branch Tree of {this+li}
6914{
6915 if (fBranches.IsEmpty()) {
6916 if (!li || li->IsEmpty())
6917 return 0; // Nothing to do ....
6918 // Let's find the first non-empty
6919 TIter next(li);
6920 TTree *tree;
6921 while ((tree = (TTree *)next())) {
6922 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
6923 if (gDebug > 2) {
6924 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
6925 }
6926 continue;
6927 }
6928 // We could come from a list made up of different names, the first one still wins
6929 tree->SetName(this->GetName());
6930 auto prevEntries = tree->GetEntries();
6931 auto result = tree->Merge(li, options);
6932 if (result != prevEntries) {
6933 // If there is no additional entries, the first write was enough.
6934 tree->Write();
6935 }
6936 // Make sure things are really written out to disk before attempting any reading.
6937 if (tree->GetCurrentFile()) {
6938 tree->GetCurrentFile()->Flush();
6939 // Read back the complete info in this TTree, so that caller does not
6940 // inadvertently write the empty tree.
6941 tree->GetDirectory()->ReadTObject(this, this->GetName());
6942 }
6943 return result;
6944 }
6945 return 0; // All trees have empty branches
6946 }
6947 if (!li) return 0;
6949 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
6950 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
6951 // Also since this is part of a merging operation, the output file is not as precious as in
6952 // the general case since the input file should still be around.
6953 fAutoSave = 0;
6954 TIter next(li);
6955 TTree *tree;
6956 while ((tree = (TTree*)next())) {
6957 if (tree==this) continue;
6958 if (!tree->InheritsFrom(TTree::Class())) {
6959 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
6961 return -1;
6962 }
6963
6964 Long64_t nentries = tree->GetEntries();
6965 if (nentries == 0) continue;
6966
6967 CopyEntries(tree, -1, options, true);
6968 }
6970 return GetEntries();
6971}
6972
6973////////////////////////////////////////////////////////////////////////////////
6974/// Merge the trees in the TList into this tree.
6975/// If info->fIsFirst is true, first we clone this TTree info the directory
6976/// info->fOutputDirectory and then overlay the new TTree information onto
6977/// this TTree object (so that this TTree object is now the appropriate to
6978/// use for further merging).
6979/// Trees with no branches will be skipped, the branch structure
6980/// will be taken from the first non-zero-branch Tree of {this+li}
6981///
6982/// Returns the total number of entries in the merged tree.
6985{
6986 if (fBranches.IsEmpty()) {
6987 if (!li || li->IsEmpty())
6988 return 0; // Nothing to do ....
6989 // Let's find the first non-empty
6990 TIter next(li);
6991 TTree *tree;
6992 while ((tree = (TTree *)next())) {
6993 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
6994 if (gDebug > 2) {
6995 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
6996 }
6997 continue;
6998 }
6999 // We could come from a list made up of different names, the first one still wins
7000 tree->SetName(this->GetName());
7001 auto prevEntries = tree->GetEntries();
7002 auto result = tree->Merge(li, info);
7003 if (result != prevEntries) {
7004 // If there is no additional entries, the first write was enough.
7005 tree->Write();
7006 }
7007 // Make sure things are really written out to disk before attempting any reading.
7008 info->fOutputDirectory->GetFile()->Flush();
7009 // Read back the complete info in this TTree, so that TFileMerge does not
7010 // inadvertently write the empty tree.
7011 info->fOutputDirectory->ReadTObject(this, this->GetName());
7012 return result;
7013 }
7014 return 0; // All trees have empty branches
7015 }
7016 const char *options = info ? info->fOptions.Data() : "";
7017 if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
7018 if (GetCurrentFile() == nullptr) {
7019 // In memory TTree, all we need to do is ... write it.
7020 SetDirectory(info->fOutputDirectory);
7022 fDirectory->WriteTObject(this);
7023 } else if (info->fOptions.Contains("fast")) {
7024 InPlaceClone(info->fOutputDirectory);
7025 } else {
7026 TDirectory::TContext ctxt(info->fOutputDirectory);
7028 TTree *newtree = CloneTree(-1, options);
7029 if (info->fIOFeatures)
7030 fIOFeatures = *(info->fIOFeatures);
7031 else
7033 if (newtree) {
7034 newtree->Write();
7035 delete newtree;
7036 }
7037 // Make sure things are really written out to disk before attempting any reading.
7038 info->fOutputDirectory->GetFile()->Flush();
7039 info->fOutputDirectory->ReadTObject(this,this->GetName());
7040 }
7041 }
7042 if (!li) return 0;
7044 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
7045 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
7046 // Also since this is part of a merging operation, the output file is not as precious as in
7047 // the general case since the input file should still be around.
7048 fAutoSave = 0;
7049 TIter next(li);
7050 TTree *tree;
7051 while ((tree = (TTree*)next())) {
7052 if (tree==this) continue;
7053 if (!tree->InheritsFrom(TTree::Class())) {
7054 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
7056 return -1;
7057 }
7058
7059 CopyEntries(tree, -1, options, true);
7060 }
7062 return GetEntries();
7063}
7064
7065////////////////////////////////////////////////////////////////////////////////
7066/// Move a cache from a file to the current file in dir.
7067/// if src is null no operation is done, if dir is null or there is no
7068/// current file the cache is deleted.
7071{
7072 if (!src) return;
7073 TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : nullptr;
7074 if (src == dst) return;
7075
7077 if (dst) {
7078 src->SetCacheRead(nullptr,this);
7079 dst->SetCacheRead(pf, this);
7080 } else {
7081 if (pf) {
7082 pf->WaitFinishPrefetch();
7083 }
7084 src->SetCacheRead(nullptr,this);
7085 delete pf;
7086 }
7087}
7088
7089////////////////////////////////////////////////////////////////////////////////
7090/// Copy the content to a new new file, update this TTree with the new
7091/// location information and attach this TTree to the new directory.
7092///
7093/// options: Indicates a basket sorting method, see TTreeCloner::TTreeCloner for
7094/// details
7095///
7096/// If new and old directory are in the same file, the data is untouched,
7097/// this "just" does a call to SetDirectory.
7098/// Equivalent to an "in place" cloning of the TTree.
7099bool TTree::InPlaceClone(TDirectory *newdirectory, const char *options)
7100{
7101 if (!newdirectory) {
7103 SetDirectory(nullptr);
7104 return true;
7105 }
7106 if (newdirectory->GetFile() == GetCurrentFile()) {
7108 return true;
7109 }
7110 TTreeCloner cloner(this, newdirectory, options);
7111 if (cloner.IsValid())
7112 return cloner.Exec();
7113 else
7114 return false;
7115}
7116
7117////////////////////////////////////////////////////////////////////////////////
7118/// Function called when loading a new class library.
7120bool TTree::Notify()
7121{
7122 TIter next(GetListOfLeaves());
7123 TLeaf* leaf = nullptr;
7124 while ((leaf = (TLeaf*) next())) {
7125 leaf->Notify();
7126 leaf->GetBranch()->Notify();
7127 }
7128 return true;
7129}
7130
7131////////////////////////////////////////////////////////////////////////////////
7132/// This function may be called after having filled some entries in a Tree.
7133/// Using the information in the existing branch buffers, it will reassign
7134/// new branch buffer sizes to optimize time and memory.
7135///
7136/// The function computes the best values for branch buffer sizes such that
7137/// the total buffer sizes is less than maxMemory and nearby entries written
7138/// at the same time.
7139/// In case the branch compression factor for the data written so far is less
7140/// than compMin, the compression is disabled.
7141///
7142/// if option ="d" an analysis report is printed.
7145{
7146 //Flush existing baskets if the file is writable
7147 if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
7148
7149 TString opt( option );
7150 opt.ToLower();
7151 bool pDebug = opt.Contains("d");
7152 TObjArray *leaves = this->GetListOfLeaves();
7153 Int_t nleaves = leaves->GetEntries();
7155
7156 if (nleaves == 0 || treeSize == 0) {
7157 // We're being called too early, we really have nothing to do ...
7158 return;
7159 }
7161 UInt_t bmin = 512;
7162 UInt_t bmax = 256000;
7163 Double_t memFactor = 1;
7166
7167 //we make two passes
7168 //one pass to compute the relative branch buffer sizes
7169 //a second pass to compute the absolute values
7170 for (Int_t pass =0;pass<2;pass++) {
7171 oldMemsize = 0; //to count size of baskets in memory with old buffer size
7172 newMemsize = 0; //to count size of baskets in memory with new buffer size
7173 oldBaskets = 0; //to count number of baskets with old buffer size
7174 newBaskets = 0; //to count number of baskets with new buffer size
7175 for (i=0;i<nleaves;i++) {
7176 TLeaf *leaf = (TLeaf*)leaves->At(i);
7177 TBranch *branch = leaf->GetBranch();
7178 Double_t totBytes = (Double_t)branch->GetTotBytes();
7181 if (branch->GetEntries() == 0) {
7182 // There is no data, so let's make a guess ...
7184 } else {
7185 sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
7186 }
7187 Int_t oldBsize = branch->GetBasketSize();
7190 Int_t nb = branch->GetListOfBranches()->GetEntries();
7191 if (nb > 0) {
7193 continue;
7194 }
7195 Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
7196 if (bsize < 0) bsize = bmax;
7197 if (bsize > bmax) bsize = bmax;
7199 if (pass) { // only on the second pass so that it doesn't interfere with scaling
7200 // If there is an entry offset, it will be stored in the same buffer as the object data; hence,
7201 // we must bump up the size of the branch to account for this extra footprint.
7202 // If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
7203 // the value of GetEntries().
7204 Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
7205 if (branch->GetEntryOffsetLen()) {
7206 newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
7207 }
7208 // We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
7209 // with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
7210 // resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
7211 // at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
7212 // stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
7213 // structures we found a factor of 2 fewer baskets needed in the new scheme.
7214 // rounds up, increases basket size to ensure all entries fit into single basket as intended
7215 newBsize = newBsize - newBsize%512 + 512;
7216 }
7218 if (newBsize < bmin) newBsize = bmin;
7219 if (newBsize > 10000000) newBsize = bmax;
7220 if (pass) {
7221 if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
7222 branch->SetBasketSize(newBsize);
7223 }
7225 // For this number to be somewhat accurate when newBsize is 'low'
7226 // we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
7227 // not let it be lower than 100+TBranch::fEntryOffsetLen.
7229 if (pass == 0) continue;
7230 //Reset the compression level in case the compression factor is small
7231 Double_t comp = 1;
7232 if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
7233 if (comp > 1 && comp < minComp) {
7234 if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
7236 }
7237 }
7238 // coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
7240 if (memFactor > 100) memFactor = 100;
7243 static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
7244
7245 // Really, really never go lower than 8 bytes (we use this number
7246 // so that the calculation of the number of basket is consistent
7247 // but in fact SetBasketSize will not let the size go below
7248 // TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
7249 // (The 2nd part being a slight over estimate of the key length.
7250 static const UInt_t hardmin = 8;
7253 }
7254 if (pDebug) {
7255 Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
7256 Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
7257 }
7258}
7259
7260////////////////////////////////////////////////////////////////////////////////
7261/// Interface to the Principal Components Analysis class.
7262///
7263/// Create an instance of TPrincipal
7264///
7265/// Fill it with the selected variables
7266///
7267/// - if option "n" is specified, the TPrincipal object is filled with
7268/// normalized variables.
7269/// - If option "p" is specified, compute the principal components
7270/// - If option "p" and "d" print results of analysis
7271/// - If option "p" and "h" generate standard histograms
7272/// - If option "p" and "c" generate code of conversion functions
7273/// - return a pointer to the TPrincipal object. It is the user responsibility
7274/// - to delete this object.
7275/// - The option default value is "np"
7276///
7277/// see TTree::Draw for explanation of the other parameters.
7278///
7279/// The created object is named "principal" and a reference to it
7280/// is added to the list of specials Root objects.
7281/// you can retrieve a pointer to the created object via:
7282/// ~~~ {.cpp}
7283/// TPrincipal *principal =
7284/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
7285/// ~~~
7288{
7289 GetPlayer();
7290 if (fPlayer) {
7292 }
7293 return nullptr;
7294}
7295
7296////////////////////////////////////////////////////////////////////////////////
7297/// Print a summary of the tree contents.
7298///
7299/// - If option contains "all" friend trees are also printed.
7300/// - If option contains "toponly" only the top level branches are printed.
7301/// - If option contains "clusters" information about the cluster of baskets is printed.
7302///
7303/// Wildcarding can be used to print only a subset of the branches, e.g.,
7304/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
7306void TTree::Print(Option_t* option) const
7307{
7308 // We already have been visited while recursively looking
7309 // through the friends tree, let's return.
7310 if (kPrint & fFriendLockStatus) {
7311 return;
7312 }
7313 Int_t s = 0;
7314 Int_t skey = 0;
7315 if (fDirectory) {
7316 TKey* key = fDirectory->GetKey(GetName());
7317 if (key) {
7318 skey = key->GetKeylen();
7319 s = key->GetNbytes();
7320 }
7321 }
7324 if (zipBytes > 0) {
7325 total += GetTotBytes();
7326 }
7328 TTree::Class()->WriteBuffer(b, (TTree*) this);
7329 total += b.Length();
7330 Long64_t file = zipBytes + s;
7331 Float_t cx = 1;
7332 if (zipBytes) {
7333 cx = (GetTotBytes() + 0.00001) / zipBytes;
7334 }
7335 Printf("******************************************************************************");
7336 Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
7337 Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
7338 Printf("* : : Tree compression factor = %6.2f *", cx);
7339 Printf("******************************************************************************");
7340
7341 // Avoid many check of option validity
7342 if (!option)
7343 option = "";
7344
7345 if (strncmp(option,"clusters",std::char_traits<char>::length("clusters"))==0) {
7346 Printf("%-16s %-16s %-16s %8s %20s",
7347 "Cluster Range #", "Entry Start", "Last Entry", "Size", "Number of clusters");
7348 Int_t index= 0;
7351 bool estimated = false;
7352 bool unknown = false;
7354 Long64_t nclusters = 0;
7355 if (recordedSize > 0) {
7356 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / recordedSize);
7357 Printf("%-16d %-16lld %-16lld %8lld %10lld",
7358 ind, start, end, recordedSize, nclusters);
7359 } else {
7360 // NOTE: const_cast ... DO NOT Merge for now
7361 TClusterIterator iter((TTree*)this, start);
7362 iter.Next();
7363 auto estimated_size = iter.GetNextEntry() - start;
7364 if (estimated_size > 0) {
7365 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / estimated_size);
7366 Printf("%-16d %-16lld %-16lld %8lld %10lld (estimated)",
7367 ind, start, end, recordedSize, nclusters);
7368 estimated = true;
7369 } else {
7370 Printf("%-16d %-16lld %-16lld %8lld (unknown)",
7371 ind, start, end, recordedSize);
7372 unknown = true;
7373 }
7374 }
7375 start = end + 1;
7377 };
7378 if (fNClusterRange) {
7379 for( ; index < fNClusterRange; ++index) {
7382 }
7383 }
7385 if (unknown) {
7386 Printf("Total number of clusters: (unknown)");
7387 } else {
7388 Printf("Total number of clusters: %lld %s", totalClusters, estimated ? "(estimated)" : "");
7389 }
7390 return;
7391 }
7392
7393 Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
7394 Int_t l;
7395 TBranch* br = nullptr;
7396 TLeaf* leaf = nullptr;
7397 if (strstr(option, "toponly")) {
7398 Long64_t *count = new Long64_t[nl];
7399 Int_t keep =0;
7400 for (l=0;l<nl;l++) {
7401 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7402 br = leaf->GetBranch();
7403 // branch is its own (top level) mother only for the top level branches.
7404 if (br != br->GetMother()) {
7405 count[l] = -1;
7406 count[keep] += br->GetZipBytes();
7407 } else {
7408 keep = l;
7409 count[keep] = br->GetZipBytes();
7410 }
7411 }
7412 for (l=0;l<nl;l++) {
7413 if (count[l] < 0) continue;
7414 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7415 br = leaf->GetBranch();
7416 Printf("branch: %-20s %9lld",br->GetName(),count[l]);
7417 }
7418 delete [] count;
7419 } else {
7420 TString reg = "*";
7421 if (strlen(option) && strchr(option,'*')) reg = option;
7422 TRegexp re(reg,true);
7423 TIter next(const_cast<TTree*>(this)->GetListOfBranches());
7425 while ((br= (TBranch*)next())) {
7426 TString st = br->GetName();
7427 st.ReplaceAll("/","_");
7428 if (st.Index(re) == kNPOS) continue;
7429 br->Print(option);
7430 }
7431 }
7432
7433 //print TRefTable (if one)
7435
7436 //print friends if option "all"
7437 if (!fFriends || !strstr(option,"all")) return;
7439 TFriendLock lock(const_cast<TTree*>(this),kPrint);
7440 TFriendElement *fr;
7441 while ((fr = (TFriendElement*)nextf())) {
7442 TTree * t = fr->GetTree();
7443 if (t) t->Print(option);
7444 }
7445}
7446
7447////////////////////////////////////////////////////////////////////////////////
7448/// Print statistics about the TreeCache for this tree.
7449/// Like:
7450/// ~~~ {.cpp}
7451/// ******TreeCache statistics for file: cms2.root ******
7452/// Reading 73921562 bytes in 716 transactions
7453/// Average transaction = 103.242405 Kbytes
7454/// Number of blocks in current cache: 202, total size : 6001193
7455/// ~~~
7456/// if option = "a" the list of blocks in the cache is printed
7459{
7460 TFile *f = GetCurrentFile();
7461 if (!f) return;
7463 if (tc) tc->Print(option);
7464}
7465
7466////////////////////////////////////////////////////////////////////////////////
7467/// Process this tree executing the TSelector code in the specified filename.
7468/// The return value is -1 in case of error and TSelector::GetStatus() in
7469/// in case of success.
7470///
7471/// The code in filename is loaded (interpreted or compiled, see below),
7472/// filename must contain a valid class implementation derived from TSelector,
7473/// where TSelector has the following member functions:
7474///
7475/// - `Begin()`: called every time a loop on the tree starts,
7476/// a convenient place to create your histograms.
7477/// - `SlaveBegin()`: called after Begin(), when on PROOF called only on the
7478/// slave servers.
7479/// - `Process()`: called for each event, in this function you decide what
7480/// to read and fill your histograms.
7481/// - `SlaveTerminate`: called at the end of the loop on the tree, when on PROOF
7482/// called only on the slave servers.
7483/// - `Terminate()`: called at the end of the loop on the tree,
7484/// a convenient place to draw/fit your histograms.
7485///
7486/// If filename is of the form file.C, the file will be interpreted.
7487///
7488/// If filename is of the form file.C++, the file file.C will be compiled
7489/// and dynamically loaded.
7490///
7491/// If filename is of the form file.C+, the file file.C will be compiled
7492/// and dynamically loaded. At next call, if file.C is older than file.o
7493/// and file.so, the file.C is not compiled, only file.so is loaded.
7494///
7495/// ## NOTE1
7496///
7497/// It may be more interesting to invoke directly the other Process function
7498/// accepting a TSelector* as argument.eg
7499/// ~~~ {.cpp}
7500/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
7501/// selector->CallSomeFunction(..);
7502/// mytree.Process(selector,..);
7503/// ~~~
7504/// ## NOTE2
7505//
7506/// One should not call this function twice with the same selector file
7507/// in the same script. If this is required, proceed as indicated in NOTE1,
7508/// by getting a pointer to the corresponding TSelector,eg
7509///
7510/// ### Workaround 1
7511///
7512/// ~~~ {.cpp}
7513/// void stubs1() {
7514/// TSelector *selector = TSelector::GetSelector("h1test.C");
7515/// TFile *f1 = new TFile("stubs_nood_le1.root");
7516/// TTree *h1 = (TTree*)f1->Get("h1");
7517/// h1->Process(selector);
7518/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7519/// TTree *h2 = (TTree*)f2->Get("h1");
7520/// h2->Process(selector);
7521/// }
7522/// ~~~
7523/// or use ACLIC to compile the selector
7524///
7525/// ### Workaround 2
7526///
7527/// ~~~ {.cpp}
7528/// void stubs2() {
7529/// TFile *f1 = new TFile("stubs_nood_le1.root");
7530/// TTree *h1 = (TTree*)f1->Get("h1");
7531/// h1->Process("h1test.C+");
7532/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7533/// TTree *h2 = (TTree*)f2->Get("h1");
7534/// h2->Process("h1test.C+");
7535/// }
7536/// ~~~
7539{
7540 GetPlayer();
7541 if (fPlayer) {
7543 }
7544 return -1;
7545}
7546
7547////////////////////////////////////////////////////////////////////////////////
7548/// Process this tree executing the code in the specified selector.
7549/// The return value is -1 in case of error and TSelector::GetStatus() in
7550/// in case of success.
7551///
7552/// The TSelector class has the following member functions:
7553///
7554/// - `Begin()`: called every time a loop on the tree starts,
7555/// a convenient place to create your histograms.
7556/// - `SlaveBegin()`: called after Begin(), when on PROOF called only on the
7557/// slave servers.
7558/// - `Process()`: called for each event, in this function you decide what
7559/// to read and fill your histograms.
7560/// - `SlaveTerminate`: called at the end of the loop on the tree, when on PROOF
7561/// called only on the slave servers.
7562/// - `Terminate()`: called at the end of the loop on the tree,
7563/// a convenient place to draw/fit your histograms.
7564///
7565/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
7566/// of the EventList, starting at firstentry, otherwise the loop is on the
7567/// specified Tree entries.
7570{
7571 GetPlayer();
7572 if (fPlayer) {
7573 return fPlayer->Process(selector, option, nentries, firstentry);
7574 }
7575 return -1;
7576}
7577
7578////////////////////////////////////////////////////////////////////////////////
7579/// Make a projection of a tree using selections.
7580///
7581/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
7582/// projection of the tree will be filled in histogram hname.
7583/// Note that the dimension of hname must match with the dimension of varexp.
7584///
7587{
7588 TString var;
7589 var.Form("%s>>%s", varexp, hname);
7590 TString opt("goff");
7591 if (option) {
7592 opt.Form("%sgoff", option);
7593 }
7595 return nsel;
7596}
7597
7598////////////////////////////////////////////////////////////////////////////////
7599/// Loop over entries and return a TSQLResult object containing entries following selection.
7602{
7603 GetPlayer();
7604 if (fPlayer) {
7606 }
7607 return nullptr;
7608}
7609
7610////////////////////////////////////////////////////////////////////////////////
7611/// Create or simply read branches from filename.
7612///
7613/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
7614/// is given in the first line of the file with a syntax like
7615/// ~~~ {.cpp}
7616/// A/D:Table[2]/F:Ntracks/I:astring/C
7617/// ~~~
7618/// otherwise branchDescriptor must be specified with the above syntax.
7619///
7620/// - If the type of the first variable is not specified, it is assumed to be "/F"
7621/// - If the type of any other variable is not specified, the type of the previous
7622/// variable is assumed. eg
7623/// - `x:y:z` (all variables are assumed of type "F")
7624/// - `x/D:y:z` (all variables are of type "D")
7625/// - `x:y/D:z` (x is type "F", y and z of type "D")
7626///
7627/// delimiter allows for the use of another delimiter besides whitespace.
7628/// This provides support for direct import of common data file formats
7629/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
7630/// branch description is taken from the first line in the file, but
7631/// delimiter is used for the branch names tokenization rather than ':'.
7632/// Note however that if the values in the first line do not use the
7633/// /[type] syntax, all variables are assumed to be of type "F".
7634/// If the filename ends with extensions .csv or .CSV and a delimiter is
7635/// not specified (besides ' '), the delimiter is automatically set to ','.
7636///
7637/// Lines in the input file starting with "#" are ignored. Leading whitespace
7638/// for each column data is skipped. Empty lines are skipped.
7639///
7640/// A TBranch object is created for each variable in the expression.
7641/// The total number of rows read from the file is returned.
7642///
7643/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
7644///
7645/// To fill a TTree with multiple input text files, proceed as indicated above
7646/// for the first input file and omit the second argument for subsequent calls
7647/// ~~~ {.cpp}
7648/// T.ReadFile("file1.dat","branch descriptor");
7649/// T.ReadFile("file2.dat");
7650/// ~~~
7652Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
7653{
7654 if (!filename || !*filename) {
7655 Error("ReadFile","File name not specified");
7656 return 0;
7657 }
7658
7659 std::ifstream in;
7660 in.open(filename);
7661 if (!in.good()) {
7662 Error("ReadFile","Cannot open file: %s",filename);
7663 return 0;
7664 }
7665 const char* ext = strrchr(filename, '.');
7666 if(ext && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
7667 delimiter = ',';
7668 }
7670}
7671
7672////////////////////////////////////////////////////////////////////////////////
7673/// Determine which newline this file is using.
7674/// Return '\\r' for Windows '\\r\\n' as that already terminates.
7676char TTree::GetNewlineValue(std::istream &inputStream)
7677{
7678 Long_t inPos = inputStream.tellg();
7679 char newline = '\n';
7680 while(true) {
7681 char c = 0;
7682 inputStream.get(c);
7683 if(!inputStream.good()) {
7684 Error("ReadStream","Error reading stream: no newline found.");
7685 return 0;
7686 }
7687 if(c == newline) break;
7688 if(c == '\r') {
7689 newline = '\r';
7690 break;
7691 }
7692 }
7693 inputStream.clear();
7694 inputStream.seekg(inPos);
7695 return newline;
7696}
7697
7698////////////////////////////////////////////////////////////////////////////////
7699/// Create or simply read branches from an input stream.
7700///
7701/// \see TTree::ReadFile
7703Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
7704{
7705 char newline = 0;
7706 std::stringstream ss;
7707 std::istream *inTemp;
7708 Long_t inPos = inputStream.tellg();
7709 if (!inputStream.good()) {
7710 Error("ReadStream","Error reading stream");
7711 return 0;
7712 }
7713 if (inPos == -1) {
7714 ss << std::cin.rdbuf();
7716 inTemp = &ss;
7717 } else {
7720 }
7721 std::istream& in = *inTemp;
7722 Long64_t nlines = 0;
7723
7724 TBranch *branch = nullptr;
7726 if (nbranches == 0) {
7727 char *bdname = new char[4000];
7728 char *bd = new char[100000];
7729 Int_t nch = 0;
7731 // branch Descriptor is null, read its definition from the first line in the file
7732 if (!nch) {
7733 do {
7734 in.getline(bd, 100000, newline);
7735 if (!in.good()) {
7736 delete [] bdname;
7737 delete [] bd;
7738 Error("ReadStream","Error reading stream");
7739 return 0;
7740 }
7741 char *cursor = bd;
7742 while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
7743 ++cursor;
7744 }
7745 if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
7746 break;
7747 }
7748 } while (true);
7749 ++nlines;
7750 nch = strlen(bd);
7751 } else {
7752 strlcpy(bd,branchDescriptor,100000);
7753 }
7754
7755 //parse the branch descriptor and create a branch for each element
7756 //separated by ":"
7757 void *address = &bd[90000];
7758 char *bdcur = bd;
7759 TString desc="", olddesc="F";
7760 char bdelim = ':';
7761 if(delimiter != ' ') {
7762 bdelim = delimiter;
7763 if (strchr(bdcur,bdelim)==nullptr && strchr(bdcur,':') != nullptr) {
7764 // revert to the default
7765 bdelim = ':';
7766 }
7767 }
7768 while (bdcur) {
7769 char *colon = strchr(bdcur,bdelim);
7770 if (colon) *colon = 0;
7771 strlcpy(bdname,bdcur,4000);
7772 char *slash = strchr(bdname,'/');
7773 if (slash) {
7774 *slash = 0;
7775 desc = bdcur;
7776 olddesc = slash+1;
7777 } else {
7778 desc.Form("%s/%s",bdname,olddesc.Data());
7779 }
7780 char *bracket = strchr(bdname,'[');
7781 if (bracket) {
7782 *bracket = 0;
7783 }
7784 branch = new TBranch(this,bdname,address,desc.Data(),32000);
7785 if (branch->IsZombie()) {
7786 delete branch;
7787 Warning("ReadStream","Illegal branch definition: %s",bdcur);
7788 } else {
7790 branch->SetAddress(nullptr);
7791 }
7792 if (!colon)break;
7793 bdcur = colon+1;
7794 }
7795 delete [] bdname;
7796 delete [] bd;
7797 }
7798
7800
7801 if (gDebug > 1) {
7802 Info("ReadStream", "Will use branches:");
7803 for (int i = 0 ; i < nbranches; ++i) {
7804 TBranch* br = (TBranch*) fBranches.At(i);
7805 Info("ReadStream", " %s: %s [%s]", br->GetName(),
7806 br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
7807 }
7808 if (gDebug > 3) {
7809 Info("ReadStream", "Dumping read tokens, format:");
7810 Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
7811 Info("ReadStream", " L: line number");
7812 Info("ReadStream", " B: branch number");
7813 Info("ReadStream", " gfbe: good / fail / bad / eof of token");
7814 Info("ReadStream", " GFBE: good / fail / bad / eof of file");
7815 Info("ReadStream", " T: Token being read");
7816 }
7817 }
7818
7819 //loop on all lines in the file
7820 Long64_t nGoodLines = 0;
7821 std::string line;
7822 const char sDelimBuf[2] = { delimiter, 0 };
7823 const char* sDelim = sDelimBuf;
7824 if (delimiter == ' ') {
7825 // ' ' really means whitespace
7826 sDelim = "[ \t]";
7827 }
7828 while(in.good()) {
7829 if (newline == '\r' && in.peek() == '\n') {
7830 // Windows, skip '\n':
7831 in.get();
7832 }
7833 std::getline(in, line, newline);
7834 ++nlines;
7835
7837 sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
7838 if (sLine.IsNull()) {
7839 if (gDebug > 2) {
7840 Info("ReadStream", "Skipping empty line number %lld", nlines);
7841 }
7842 continue; // silently skip empty lines
7843 }
7844 if (sLine[0] == '#') {
7845 if (gDebug > 2) {
7846 Info("ReadStream", "Skipping comment line number %lld: '%s'",
7847 nlines, line.c_str());
7848 }
7849 continue;
7850 }
7851 if (gDebug > 2) {
7852 Info("ReadStream", "Parsing line number %lld: '%s'",
7853 nlines, line.c_str());
7854 }
7855
7856 // Loop on branches and read the branch values into their buffer
7857 branch = nullptr;
7858 TString tok; // one column's data
7859 TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
7860 std::stringstream sToken; // string stream feeding leafData into leaves
7861 Ssiz_t pos = 0;
7862 Int_t iBranch = 0;
7863 bool goodLine = true; // whether the row can be filled into the tree
7864 Int_t remainingLeafLen = 0; // remaining columns for the current leaf
7865 while (goodLine && iBranch < nbranches
7866 && sLine.Tokenize(tok, pos, sDelim)) {
7867 tok = tok.Strip(TString::kLeading); // skip leading whitespace
7868 if (tok.IsNull() && delimiter == ' ') {
7869 // 1 2 should not be interpreted as 1,,,2 but 1, 2.
7870 // Thus continue until we have a non-empty token.
7871 continue;
7872 }
7873
7874 if (!remainingLeafLen) {
7875 // next branch!
7877 }
7878 TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
7879 if (!remainingLeafLen) {
7880 remainingLeafLen = leaf->GetLen();
7881 if (leaf->GetMaximum() > 0) {
7882 // This is a dynamic leaf length, i.e. most likely a TLeafC's
7883 // string size. This still translates into one token:
7884 remainingLeafLen = 1;
7885 }
7886
7887 leafData = tok;
7888 } else {
7889 // append token to laf data:
7890 leafData += " ";
7891 leafData += tok;
7892 }
7894 if (remainingLeafLen) {
7895 // need more columns for this branch:
7896 continue;
7897 }
7898 ++iBranch;
7899
7900 // initialize stringstream with token
7901 sToken.clear();
7902 sToken.seekp(0, std::ios_base::beg);
7903 sToken.str(leafData.Data());
7904 sToken.seekg(0, std::ios_base::beg);
7905 leaf->ReadValue(sToken, 0 /* 0 = "all" */);
7906 if (gDebug > 3) {
7907 Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
7908 nlines, iBranch,
7909 (int)sToken.good(), (int)sToken.fail(),
7910 (int)sToken.bad(), (int)sToken.eof(),
7911 (int)in.good(), (int)in.fail(),
7912 (int)in.bad(), (int)in.eof(),
7913 sToken.str().c_str());
7914 }
7915
7916 // Error handling
7917 if (sToken.bad()) {
7918 // How could that happen for a stringstream?
7919 Warning("ReadStream",
7920 "Buffer error while reading data for branch %s on line %lld",
7921 branch->GetName(), nlines);
7922 } else if (!sToken.eof()) {
7923 if (sToken.fail()) {
7924 Warning("ReadStream",
7925 "Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
7926 tok.Data(), branch->GetName(), nlines);
7927 goodLine = false;
7928 } else {
7929 std::string remainder;
7930 std::getline(sToken, remainder, newline);
7931 if (!remainder.empty()) {
7932 Warning("ReadStream",
7933 "Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
7934 remainder.c_str(), branch->GetName(), nlines);
7935 }
7936 }
7937 }
7938 } // tokenizer loop
7939
7940 if (iBranch < nbranches) {
7941 Warning("ReadStream",
7942 "Read too few columns (%d < %d) in line %lld; ignoring line",
7944 goodLine = false;
7945 } else if (pos != kNPOS) {
7947 if (pos < sLine.Length()) {
7948 Warning("ReadStream",
7949 "Ignoring trailing \"%s\" while reading line %lld",
7950 sLine.Data() + pos - 1 /* also print delimiter */,
7951 nlines);
7952 }
7953 }
7954
7955 //we are now ready to fill the tree
7956 if (goodLine) {
7957 Fill();
7958 ++nGoodLines;
7959 }
7960 }
7961
7962 return nGoodLines;
7963}
7964
7965////////////////////////////////////////////////////////////////////////////////
7966/// Make sure that obj (which is being deleted or will soon be) is no
7967/// longer referenced by this TTree.
7970{
7971 if (obj == fEventList) {
7972 fEventList = nullptr;
7973 }
7974 if (obj == fEntryList) {
7975 fEntryList = nullptr;
7976 }
7977 if (fUserInfo) {
7979 }
7980 if (fPlayer == obj) {
7981 fPlayer = nullptr;
7982 }
7983 if (fTreeIndex == obj) {
7984 fTreeIndex = nullptr;
7985 }
7986 if (fAliases == obj) {
7987 fAliases = nullptr;
7988 } else if (fAliases) {
7990 }
7991 if (fFriends == obj) {
7992 fFriends = nullptr;
7993 } else if (fFriends) {
7995 }
7996}
7997
7998////////////////////////////////////////////////////////////////////////////////
7999/// Refresh contents of this tree and its branches from the current status on disk.
8000///
8001/// One can call this function in case the tree file is being
8002/// updated by another process.
8004void TTree::Refresh()
8005{
8006 if (!fDirectory->GetFile()) {
8007 return;
8008 }
8010 fDirectory->Remove(this);
8011 TTree* tree; fDirectory->GetObject(GetName(),tree);
8012 if (!tree) {
8013 return;
8014 }
8015 //copy info from tree header into this Tree
8016 fEntries = 0;
8017 fNClusterRange = 0;
8018 ImportClusterRanges(tree);
8019
8020 fAutoSave = tree->fAutoSave;
8021 fEntries = tree->fEntries;
8022 fTotBytes = tree->GetTotBytes();
8023 fZipBytes = tree->GetZipBytes();
8024 fSavedBytes = tree->fSavedBytes;
8025 fTotalBuffers = tree->fTotalBuffers.load();
8026
8027 //loop on all branches and update them
8029 for (Int_t i = 0; i < nleaves; i++) {
8031 TBranch* branch = (TBranch*) leaf->GetBranch();
8032 branch->Refresh(tree->GetBranch(branch->GetName()));
8033 }
8034 fDirectory->Remove(tree);
8035 fDirectory->Append(this);
8036 delete tree;
8037 tree = nullptr;
8038}
8039
8040////////////////////////////////////////////////////////////////////////////////
8041/// Record a TFriendElement that we need to warn when the chain switches to
8042/// a new file (typically this is because this chain is a friend of another
8043/// TChain)
8050}
8051
8052
8053////////////////////////////////////////////////////////////////////////////////
8054/// Removes external friend
8059}
8060
8061
8062////////////////////////////////////////////////////////////////////////////////
8063/// Remove a friend from the list of friends.
8066{
8067 // We already have been visited while recursively looking
8068 // through the friends tree, let return
8070 return;
8071 }
8072 if (!fFriends) {
8073 return;
8074 }
8075 TFriendLock lock(this, kRemoveFriend);
8077 TFriendElement* fe = nullptr;
8078 while ((fe = (TFriendElement*) nextf())) {
8079 TTree* friend_t = fe->GetTree();
8080 if (friend_t == oldFriend) {
8081 fFriends->Remove(fe);
8082 delete fe;
8083 fe = nullptr;
8084 }
8085 }
8086}
8087
8088////////////////////////////////////////////////////////////////////////////////
8089/// Reset baskets, buffers and entries count in all branches and leaves.
8092{
8093 fNotify = nullptr;
8094 fEntries = 0;
8095 fNClusterRange = 0;
8096 fTotBytes = 0;
8097 fZipBytes = 0;
8098 fFlushedBytes = 0;
8099 fSavedBytes = 0;
8100 fTotalBuffers = 0;
8101 fChainOffset = 0;
8102 fReadEntry = -1;
8103
8104 delete fTreeIndex;
8105 fTreeIndex = nullptr;
8106
8108 for (Int_t i = 0; i < nb; ++i) {
8110 branch->Reset(option);
8111 }
8112
8113 if (fBranchRef) {
8114 fBranchRef->Reset();
8115 }
8116}
8117
8118////////////////////////////////////////////////////////////////////////////////
8119/// Resets the state of this TTree after a merge (keep the customization but
8120/// forget the data).
8123{
8124 fEntries = 0;
8125 fNClusterRange = 0;
8126 fTotBytes = 0;
8127 fZipBytes = 0;
8128 fSavedBytes = 0;
8129 fFlushedBytes = 0;
8130 fTotalBuffers = 0;
8131 fChainOffset = 0;
8132 fReadEntry = -1;
8133
8134 delete fTreeIndex;
8135 fTreeIndex = nullptr;
8136
8138 for (Int_t i = 0; i < nb; ++i) {
8140 branch->ResetAfterMerge(info);
8141 }
8142
8143 if (fBranchRef) {
8145 }
8146}
8147
8148////////////////////////////////////////////////////////////////////////////////
8149/// Tell a branch to set its address to zero.
8150///
8151/// @note If the branch owns any objects, they are deleted.
8154{
8155 if (br && br->GetTree()) {
8156 br->ResetAddress();
8157 }
8158}
8159
8160////////////////////////////////////////////////////////////////////////////////
8161/// Tell all of our branches to drop their current objects and allocate new ones.
8164{
8165 // We already have been visited while recursively looking
8166 // through the friends tree, let return
8168 return;
8169 }
8171 Int_t nbranches = branches->GetEntriesFast();
8172 for (Int_t i = 0; i < nbranches; ++i) {
8173 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
8174 branch->ResetAddress();
8175 }
8176 if (fFriends) {
8179 auto *frTree = frEl->GetTree();
8180 if (frTree) {
8181 frTree->ResetBranchAddresses();
8182 }
8183 }
8184 }
8185}
8186
8187////////////////////////////////////////////////////////////////////////////////
8188/// Loop over tree entries and print entries passing selection. Interactive
8189/// pagination break is on by default.
8190///
8191/// - If varexp is 0 (or "") then print only first 8 columns.
8192/// - If varexp = "*" print all columns.
8193///
8194/// Otherwise a columns selection can be made using "var1:var2:var3".
8195///
8196/// \param firstentry first entry to scan
8197/// \param nentries total number of entries to scan (starting from firstentry). Defaults to all entries.
8198/// \note see TTree::SetScanField to control how many lines are printed between pagination breaks (Use 0 to disable pagination)
8199/// \see TTreePlayer::Scan
8202{
8203 GetPlayer();
8204 if (fPlayer) {
8206 }
8207 return -1;
8208}
8209
8210////////////////////////////////////////////////////////////////////////////////
8211/// Set a tree variable alias.
8212///
8213/// Set an alias for an expression/formula based on the tree 'variables'.
8214///
8215/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
8216/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
8217/// 'aliasFormula'.
8218///
8219/// If the content of 'aliasFormula' only contains symbol names, periods and
8220/// array index specification (for example event.fTracks[3]), then
8221/// the content of 'aliasName' can be used as the start of symbol.
8222///
8223/// If the alias 'aliasName' already existed, it is replaced by the new
8224/// value.
8225///
8226/// When being used, the alias can be preceded by an eventual 'Friend Alias'
8227/// (see TTree::GetFriendAlias)
8228///
8229/// Return true if it was added properly.
8230///
8231/// For example:
8232/// ~~~ {.cpp}
8233/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
8234/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
8235/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
8236/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
8237/// tree->Draw("y2-y1:x2-x1");
8238///
8239/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
8240/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
8241/// ~~~
8243bool TTree::SetAlias(const char* aliasName, const char* aliasFormula)
8244{
8245 if (!aliasName || !aliasFormula) {
8246 return false;
8247 }
8248 if (!aliasName[0] || !aliasFormula[0]) {
8249 return false;
8250 }
8251 if (!fAliases) {
8252 fAliases = new TList;
8253 } else {
8255 if (oldHolder) {
8256 oldHolder->SetTitle(aliasFormula);
8257 return true;
8258 }
8259 }
8262 return true;
8263}
8264
8265////////////////////////////////////////////////////////////////////////////////
8266/// This function may be called at the start of a program to change
8267/// the default value for fAutoFlush.
8268///
8269/// ### CASE 1 : autof > 0
8270///
8271/// autof is the number of consecutive entries after which TTree::Fill will
8272/// flush all branch buffers to disk.
8273///
8274/// ### CASE 2 : autof < 0
8275///
8276/// When filling the Tree the branch buffers will be flushed to disk when
8277/// more than autof bytes have been written to the file. At the first FlushBaskets
8278/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
8279///
8280/// Calling this function with autof<0 is interesting when it is hard to estimate
8281/// the size of one entry. This value is also independent of the Tree.
8282///
8283/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
8284/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
8285///
8286/// ### CASE 3 : autof = 0
8287///
8288/// The AutoFlush mechanism is disabled.
8289///
8290/// Flushing the buffers at regular intervals optimize the location of
8291/// consecutive entries on the disk by creating clusters of baskets.
8292///
8293/// A cluster of baskets is a set of baskets that contains all
8294/// the data for a (consecutive) set of entries and that is stored
8295/// consecutively on the disk. When reading all the branches, this
8296/// is the minimum set of baskets that the TTreeCache will read.
8298void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
8299{
8300 // Implementation note:
8301 //
8302 // A positive value of autoflush determines the size (in number of entries) of
8303 // a cluster of baskets.
8304 //
8305 // If the value of autoflush is changed over time (this happens in
8306 // particular when the TTree results from fast merging many trees),
8307 // we record the values of fAutoFlush in the data members:
8308 // fClusterRangeEnd and fClusterSize.
8309 // In the code we refer to a range of entries where the size of the
8310 // cluster of baskets is the same (i.e the value of AutoFlush was
8311 // constant) is called a ClusterRange.
8312 //
8313 // The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
8314 // active (used) values and have fMaxClusterRange allocated entries.
8315 //
8316 // fClusterRangeEnd contains the last entries number of a cluster range.
8317 // In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
8318 // fClusterSize contains the size in number of entries of all the cluster
8319 // within the given range.
8320 // The last range (and the only one if fNClusterRange is zero) start at
8321 // fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
8322 // size of the cluster in this range is given by the value of fAutoFlush.
8323 //
8324 // For example printing the beginning and end of each the ranges can be done by:
8325 //
8326 // Printf("%-16s %-16s %-16s %5s",
8327 // "Cluster Range #", "Entry Start", "Last Entry", "Size");
8328 // Int_t index= 0;
8329 // Long64_t clusterRangeStart = 0;
8330 // if (fNClusterRange) {
8331 // for( ; index < fNClusterRange; ++index) {
8332 // Printf("%-16d %-16lld %-16lld %5lld",
8333 // index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
8334 // clusterRangeStart = fClusterRangeEnd[index] + 1;
8335 // }
8336 // }
8337 // Printf("%-16d %-16lld %-16lld %5lld",
8338 // index, prevEntry, fEntries - 1, fAutoFlush);
8339 //
8340
8341 // Note: We store the entry number corresponding to the end of the cluster
8342 // rather than its start in order to avoid using the array if the cluster
8343 // size never varies (If there is only one value of AutoFlush for the whole TTree).
8344
8345 if( fAutoFlush != autof) {
8346 if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
8347 // The mechanism was already enabled, let's record the previous
8348 // cluster if needed.
8350 }
8351 fAutoFlush = autof;
8352 }
8353}
8354
8355////////////////////////////////////////////////////////////////////////////////
8356/// Mark the previous event as being at the end of the event cluster.
8357///
8358/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
8359/// is called, then the first cluster has 9 events.
8361{
8362 if (!fEntries) return;
8363
8364 if ( (fNClusterRange+1) > fMaxClusterRange ) {
8365 if (fMaxClusterRange) {
8366 // Resize arrays to hold a larger event cluster.
8369 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8371 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8373 } else {
8374 // Cluster ranges have never been initialized; create them now.
8375 fMaxClusterRange = 2;
8378 }
8379 }
8381 // If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
8382 if (fAutoFlush > 0) {
8383 // Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
8384 // will appropriately go to the next event range.
8386 // Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
8387 } else if (fNClusterRange == 0) {
8389 } else {
8391 }
8393}
8394
8395/// Estimate the median cluster size for the TTree.
8396/// This value provides e.g. a reasonable cache size default if other heuristics fail.
8397/// Clusters with size 0 and the very last cluster range, that might not have been committed to fClusterSize yet,
8398/// are ignored for the purposes of the calculation.
8400{
8401 std::vector<Long64_t> clusterSizesPerRange;
8403
8404 // We ignore cluster sizes of 0 for the purposes of this function.
8405 // We also ignore the very last cluster range which might not have been committed to fClusterSize.
8406 std::copy_if(fClusterSize, fClusterSize + fNClusterRange, std::back_inserter(clusterSizesPerRange),
8407 [](Long64_t size) { return size != 0; });
8408
8409 std::vector<double> nClustersInRange; // we need to store doubles because of the signature of TMath::Median
8410 nClustersInRange.reserve(clusterSizesPerRange.size());
8411
8412 auto clusterRangeStart = 0ll;
8413 for (int i = 0; i < fNClusterRange; ++i) {
8414 const auto size = fClusterSize[i];
8415 R__ASSERT(size >= 0);
8416 if (fClusterSize[i] == 0)
8417 continue;
8418 const auto nClusters = (1 + fClusterRangeEnd[i] - clusterRangeStart) / fClusterSize[i];
8419 nClustersInRange.emplace_back(nClusters);
8421 }
8422
8424 const auto medianClusterSize =
8426 return medianClusterSize;
8427}
8428
8429////////////////////////////////////////////////////////////////////////////////
8430/// In case of a program crash, it will be possible to recover the data in the
8431/// tree up to the last AutoSave point.
8432/// This function may be called before filling a TTree to specify when the
8433/// branch buffers and TTree header are flushed to disk as part of
8434/// TTree::Fill().
8435/// The default is -300000000, ie the TTree will write data to disk once it
8436/// exceeds 300 MBytes.
8437/// CASE 1: If fAutoSave is positive the watermark is reached when a multiple of
8438/// fAutoSave entries have been filled.
8439/// CASE 2: If fAutoSave is negative the watermark is reached when -fAutoSave
8440/// bytes can be written to the file.
8441/// CASE 3: If fAutoSave is 0, AutoSave() will never be called automatically
8442/// as part of TTree::Fill().
8447}
8448
8449////////////////////////////////////////////////////////////////////////////////
8450/// Set a branch's basket size.
8451///
8452/// bname is the name of a branch.
8453///
8454/// - if bname="*", apply to all branches.
8455/// - if bname="xxx*", apply to all branches with name starting with xxx
8456///
8457/// see TRegexp for wildcarding options
8458/// buffsize = branc basket size
8460void TTree::SetBasketSize(const char* bname, Int_t buffsize)
8461{
8463 TRegexp re(bname, true);
8464 Int_t nb = 0;
8465 for (Int_t i = 0; i < nleaves; i++) {
8467 TBranch* branch = (TBranch*) leaf->GetBranch();
8468 TString s = branch->GetName();
8469 if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
8470 continue;
8471 }
8472 nb++;
8473 branch->SetBasketSize(buffsize);
8474 }
8475 if (!nb) {
8476 Error("SetBasketSize", "unknown branch -> '%s'", bname);
8477 }
8478}
8479
8480////////////////////////////////////////////////////////////////////////////////
8481/// Change branch address, dealing with clone trees properly.
8482/// See TTree::CheckBranchAddressType for the semantic of the return value.
8483///
8484/// Note: See the comments in TBranchElement::SetAddress() for the
8485/// meaning of the addr parameter and the object ownership policy.
8487Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
8488{
8489 TBranch* branch = GetBranch(bname);
8490 if (!branch) {
8491 if (ptr) *ptr = nullptr;
8492 Error("SetBranchAddress", "unknown branch -> %s", bname);
8493 return kMissingBranch;
8494 }
8495 return SetBranchAddressImp(branch,addr,ptr);
8496}
8497
8498////////////////////////////////////////////////////////////////////////////////
8499/// Verify the validity of the type of addr before calling SetBranchAddress.
8500/// See TTree::CheckBranchAddressType for the semantic of the return value.
8501///
8502/// Note: See the comments in TBranchElement::SetAddress() for the
8503/// meaning of the addr parameter and the object ownership policy.
8505Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, bool isptr)
8506{
8507 return SetBranchAddress(bname, addr, nullptr, ptrClass, datatype, isptr);
8508}
8509
8510////////////////////////////////////////////////////////////////////////////////
8511/// Verify the validity of the type of addr before calling SetBranchAddress.
8512/// See TTree::CheckBranchAddressType for the semantic of the return value.
8513///
8514/// Note: See the comments in TBranchElement::SetAddress() for the
8515/// meaning of the addr parameter and the object ownership policy.
8517Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr, TClass* ptrClass, EDataType datatype, bool isptr)
8518{
8519 TBranch* branch = GetBranch(bname);
8520 if (!branch) {
8521 if (ptr) *ptr = nullptr;
8522 Error("SetBranchAddress", "unknown branch -> %s", bname);
8523 return kMissingBranch;
8524 }
8525
8527
8528 // This will set the value of *ptr to branch.
8529 if (res >= 0) {
8530 // The check succeeded.
8531 if ((res & kNeedEnableDecomposedObj) && !branch->GetMakeClass())
8532 branch->SetMakeClass(true);
8534 } else {
8535 if (ptr) *ptr = nullptr;
8536 }
8537 return res;
8538}
8539
8540////////////////////////////////////////////////////////////////////////////////
8541/// Change branch address, dealing with clone trees properly.
8542/// See TTree::CheckBranchAddressType for the semantic of the return value.
8543///
8544/// Note: See the comments in TBranchElement::SetAddress() for the
8545/// meaning of the addr parameter and the object ownership policy.
8548{
8549 if (ptr) {
8550 *ptr = branch;
8551 }
8552 if (fClones) {
8553 void* oldAddr = branch->GetAddress();
8554 TIter next(fClones);
8555 TTree* clone = nullptr;
8556 const char *bname = branch->GetName();
8557 while ((clone = (TTree*) next())) {
8558 TBranch* cloneBr = clone->GetBranch(bname);
8559 if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
8560 cloneBr->SetAddress(addr);
8561 }
8562 }
8563 }
8564 branch->SetAddress(addr);
8565 return kVoidPtr;
8566}
8567
8568////////////////////////////////////////////////////////////////////////////////
8569/// Set branch status to Process or DoNotProcess.
8570///
8571/// When reading a Tree, by default, all branches are read.
8572/// One can speed up considerably the analysis phase by activating
8573/// only the branches that hold variables involved in a query.
8574///
8575/// bname is the name of a branch.
8576///
8577/// - if bname="*", apply to all branches.
8578/// - if bname="xxx*", apply to all branches with name starting with xxx
8579///
8580/// see TRegexp for wildcarding options
8581///
8582/// - status = 1 branch will be processed
8583/// - = 0 branch will not be processed
8584///
8585/// Example:
8586///
8587/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
8588/// when doing T.GetEntry(i) all branches are read for entry i.
8589/// to read only the branches c and e, one can do
8590/// ~~~ {.cpp}
8591/// T.SetBranchStatus("*",0); //disable all branches
8592/// T.SetBranchStatus("c",1);
8593/// T.setBranchStatus("e",1);
8594/// T.GetEntry(i);
8595/// ~~~
8596/// bname is interpreted as a wild-carded TRegexp (see TRegexp::MakeWildcard).
8597/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
8598/// "b", but not any other branch with an "a" followed at some point by a
8599/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
8600/// support '|', and so you cannot select, e.g. track and shower branches
8601/// with "track|shower".
8602///
8603/// __WARNING! WARNING! WARNING!__
8604///
8605/// SetBranchStatus is matching the branch based on match of the branch
8606/// 'name' and not on the branch hierarchy! In order to be able to
8607/// selectively enable a top level object that is 'split' you need to make
8608/// sure the name of the top level branch is prefixed to the sub-branches'
8609/// name (by adding a dot ('.') at the end of the Branch creation and use the
8610/// corresponding bname.
8611///
8612/// I.e If your Tree has been created in split mode with a parent branch "parent."
8613/// (note the trailing dot).
8614/// ~~~ {.cpp}
8615/// T.SetBranchStatus("parent",1);
8616/// ~~~
8617/// will not activate the sub-branches of "parent". You should do:
8618/// ~~~ {.cpp}
8619/// T.SetBranchStatus("parent*",1);
8620/// ~~~
8621/// Without the trailing dot in the branch creation you have no choice but to
8622/// call SetBranchStatus explicitly for each of the sub branches.
8623///
8624/// An alternative to this function is to read directly and only
8625/// the interesting branches. Example:
8626/// ~~~ {.cpp}
8627/// TBranch *brc = T.GetBranch("c");
8628/// TBranch *bre = T.GetBranch("e");
8629/// brc->GetEntry(i);
8630/// bre->GetEntry(i);
8631/// ~~~
8632/// If found is not 0, the number of branch(es) found matching the regular
8633/// expression is returned in *found AND the error message 'unknown branch'
8634/// is suppressed.
8636void TTree::SetBranchStatus(const char* bname, bool status, UInt_t* found)
8637{
8638 // We already have been visited while recursively looking
8639 // through the friends tree, let return
8641 return;
8642 }
8643
8644 if (!bname || !*bname) {
8645 Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
8646 return;
8647 }
8648
8650 TLeaf *leaf, *leafcount;
8651
8652 Int_t i,j;
8654 TRegexp re(bname,true);
8655 Int_t nb = 0;
8656
8657 // first pass, loop on all branches
8658 // for leafcount branches activate/deactivate in function of status
8659 for (i=0;i<nleaves;i++) {
8661 branch = (TBranch*)leaf->GetBranch();
8662 TString s = branch->GetName();
8663 if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
8665 longname.Form("%s.%s",GetName(),branch->GetName());
8666 if (strcmp(bname,branch->GetName())
8667 && longname != bname
8668 && s.Index(re) == kNPOS) continue;
8669 }
8670 nb++;
8671 if (status) branch->ResetBit(kDoNotProcess);
8672 else branch->SetBit(kDoNotProcess);
8673 leafcount = leaf->GetLeafCount();
8674 if (leafcount) {
8675 bcount = leafcount->GetBranch();
8676 if (status) bcount->ResetBit(kDoNotProcess);
8677 else bcount->SetBit(kDoNotProcess);
8678 }
8679 }
8680 if (nb==0 && !strchr(bname,'*')) {
8681 branch = GetBranch(bname);
8682 if (branch) {
8683 if (status) branch->ResetBit(kDoNotProcess);
8684 else branch->SetBit(kDoNotProcess);
8685 ++nb;
8686 }
8687 }
8688
8689 //search in list of friends
8691 if (fFriends) {
8692 TFriendLock lock(this,kSetBranchStatus);
8695 TString name;
8696 while ((fe = (TFriendElement*)nextf())) {
8697 TTree *t = fe->GetTree();
8698 if (!t) continue;
8699
8700 // If the alias is present replace it with the real name.
8701 const char *subbranch = strstr(bname,fe->GetName());
8702 if (subbranch!=bname) subbranch = nullptr;
8703 if (subbranch) {
8704 subbranch += strlen(fe->GetName());
8705 if ( *subbranch != '.' ) subbranch = nullptr;
8706 else subbranch ++;
8707 }
8708 if (subbranch) {
8709 name.Form("%s.%s",t->GetName(),subbranch);
8710 } else {
8711 name = bname;
8712 }
8713 t->SetBranchStatus(name,status, &foundInFriend);
8714 }
8715 }
8716 if (!nb && !foundInFriend) {
8717 if (!found) {
8718 if (status) {
8719 if (strchr(bname,'*') != nullptr)
8720 Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8721 else
8722 Error("SetBranchStatus", "unknown branch -> %s", bname);
8723 } else {
8724 if (strchr(bname,'*') != nullptr)
8725 Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8726 else
8727 Warning("SetBranchStatus", "unknown branch -> %s", bname);
8728 }
8729 }
8730 return;
8731 }
8732 if (found) *found = nb + foundInFriend;
8733
8734 // second pass, loop again on all branches
8735 // activate leafcount branches for active branches only
8736 for (i = 0; i < nleaves; i++) {
8738 branch = (TBranch*)leaf->GetBranch();
8739 if (!branch->TestBit(kDoNotProcess)) {
8740 leafcount = leaf->GetLeafCount();
8741 if (leafcount) {
8742 bcount = leafcount->GetBranch();
8743 bcount->ResetBit(kDoNotProcess);
8744 }
8745 } else {
8746 //Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
8747 Int_t nbranches = branch->GetListOfBranches()->GetEntries();
8748 for (j=0;j<nbranches;j++) {
8749 bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
8750 if (!bson) continue;
8751 if (!bson->TestBit(kDoNotProcess)) {
8752 if (bson->GetNleaves() <= 0) continue;
8753 branch->ResetBit(kDoNotProcess);
8754 break;
8755 }
8756 }
8757 }
8758 }
8759}
8760
8761////////////////////////////////////////////////////////////////////////////////
8762/// Set the current branch style. (static function)
8763///
8764/// - style = 0 old Branch
8765/// - style = 1 new Bronch
8770}
8771
8772////////////////////////////////////////////////////////////////////////////////
8773/// Set maximum size of the file cache .
8774//
8775/// - if cachesize = 0 the existing cache (if any) is deleted.
8776/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
8777/// the Tree (default is 30 MBytes).
8778///
8779/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
8780///
8781/// Returns:
8782/// - 0 size set, cache was created if possible
8783/// - -1 on error
8786{
8787 // remember that the user has requested an explicit cache setup
8788 fCacheUserSet = true;
8789
8790 return SetCacheSizeAux(false, cacheSize);
8791}
8792
8793////////////////////////////////////////////////////////////////////////////////
8794/// Set the size of the file cache and create it if possible.
8795///
8796/// If autocache is true:
8797/// this may be an autocreated cache, possibly enlarging an existing
8798/// autocreated cache. The size is calculated. The value passed in cacheSize:
8799/// - cacheSize = 0 make cache if default cache creation is enabled
8800/// - cacheSize = -1 make a default sized cache in any case
8801///
8802/// If autocache is false:
8803/// this is a user requested cache. cacheSize is used to size the cache.
8804/// This cache should never be automatically adjusted.
8805///
8806/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
8807///
8808/// Returns:
8809/// - 0 size set, or existing autosized cache almost large enough.
8810/// (cache was created if possible)
8811/// - -1 on error
8813Int_t TTree::SetCacheSizeAux(bool autocache /* = true */, Long64_t cacheSize /* = 0 */ )
8814{
8815 if (autocache) {
8816 // used as a once only control for automatic cache setup
8817 fCacheDoAutoInit = false;
8818 }
8819
8820 if (!autocache) {
8821 // negative size means the user requests the default
8822 if (cacheSize < 0) {
8823 cacheSize = GetCacheAutoSize(true);
8824 }
8825 } else {
8826 if (cacheSize == 0) {
8827 cacheSize = GetCacheAutoSize();
8828 } else if (cacheSize < 0) {
8829 cacheSize = GetCacheAutoSize(true);
8830 }
8831 }
8832
8833 TFile* file = GetCurrentFile();
8834 if (!file || GetTree() != this) {
8835 // if there's no file or we are not a plain tree (e.g. if we're a TChain)
8836 // do not create a cache, only record the size if one was given
8837 if (!autocache) {
8838 fCacheSize = cacheSize;
8839 }
8840 if (GetTree() != this) {
8841 return 0;
8842 }
8843 if (!autocache && cacheSize>0) {
8844 Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
8845 }
8846 return 0;
8847 }
8848
8849 // Check for an existing cache
8850 TTreeCache* pf = GetReadCache(file);
8851 if (pf) {
8852 if (autocache) {
8853 // reset our cache status tracking in case existing cache was added
8854 // by the user without using one of the TTree methods
8855 fCacheSize = pf->GetBufferSize();
8856 fCacheUserSet = !pf->IsAutoCreated();
8857
8858 if (fCacheUserSet) {
8859 // existing cache was created by the user, don't change it
8860 return 0;
8861 }
8862 } else {
8863 // update the cache to ensure it records the user has explicitly
8864 // requested it
8865 pf->SetAutoCreated(false);
8866 }
8867
8868 // if we're using an automatically calculated size and the existing
8869 // cache is already almost large enough don't resize
8870 if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
8871 // already large enough
8872 return 0;
8873 }
8874
8875 if (cacheSize == fCacheSize) {
8876 return 0;
8877 }
8878
8879 if (cacheSize == 0) {
8880 // delete existing cache
8881 pf->WaitFinishPrefetch();
8882 file->SetCacheRead(nullptr,this);
8883 delete pf;
8884 pf = nullptr;
8885 } else {
8886 // resize
8887 Int_t res = pf->SetBufferSize(cacheSize);
8888 if (res < 0) {
8889 return -1;
8890 }
8891 cacheSize = pf->GetBufferSize(); // update after potential clamp
8892 }
8893 } else {
8894 // no existing cache
8895 if (autocache) {
8896 if (fCacheUserSet) {
8897 // value was already set manually.
8898 if (fCacheSize == 0) return 0;
8899 // Expected a cache should exist; perhaps the user moved it
8900 // Do nothing more here.
8901 if (cacheSize) {
8902 Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
8903 }
8904 return -1;
8905 }
8906 }
8907 }
8908
8909 fCacheSize = cacheSize;
8910 if (cacheSize == 0 || pf) {
8911 return 0;
8912 }
8913
8914#ifdef R__USE_IMT
8916 pf = new TTreeCacheUnzip(this, cacheSize);
8917 else
8918#endif
8919 pf = new TTreeCache(this, cacheSize);
8920
8921 pf->SetAutoCreated(autocache);
8922
8923 return 0;
8924}
8925
8926////////////////////////////////////////////////////////////////////////////////
8927///interface to TTreeCache to set the cache entry range
8928///
8929/// Returns:
8930/// - 0 entry range set
8931/// - -1 on error
8934{
8935 if (!GetTree()) {
8936 if (LoadTree(0)<0) {
8937 Error("SetCacheEntryRange","Could not load a tree");
8938 return -1;
8939 }
8940 }
8941 if (GetTree()) {
8942 if (GetTree() != this) {
8943 return GetTree()->SetCacheEntryRange(first, last);
8944 }
8945 } else {
8946 Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
8947 return -1;
8948 }
8949
8950 TFile *f = GetCurrentFile();
8951 if (!f) {
8952 Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
8953 return -1;
8954 }
8955 TTreeCache *tc = GetReadCache(f,true);
8956 if (!tc) {
8957 Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
8958 return -1;
8959 }
8960 tc->SetEntryRange(first,last);
8961 return 0;
8962}
8963
8964////////////////////////////////////////////////////////////////////////////////
8965/// Interface to TTreeCache to set the number of entries for the learning phase
8970}
8971
8972////////////////////////////////////////////////////////////////////////////////
8973/// Enable/Disable circularity for this tree.
8974///
8975/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
8976/// per branch in memory.
8977/// Note that when this function is called (maxEntries>0) the Tree
8978/// must be empty or having only one basket per branch.
8979/// if maxEntries <= 0 the tree circularity is disabled.
8980///
8981/// #### NOTE 1:
8982/// Circular Trees are interesting in online real time environments
8983/// to store the results of the last maxEntries events.
8984/// #### NOTE 2:
8985/// Calling SetCircular with maxEntries <= 0 is necessary before
8986/// merging circular Trees that have been saved on files.
8987/// #### NOTE 3:
8988/// SetCircular with maxEntries <= 0 is automatically called
8989/// by TChain::Merge
8990/// #### NOTE 4:
8991/// A circular Tree can still be saved in a file. When read back,
8992/// it is still a circular Tree and can be filled again.
8995{
8996 if (maxEntries <= 0) {
8997 // Disable circularity.
8998 fMaxEntries = 1000000000;
8999 fMaxEntries *= 1000;
9001 //in case the Tree was originally created in gROOT, the branch
9002 //compression level was set to -1. If the Tree is now associated to
9003 //a file, reset the compression level to the file compression level
9004 if (fDirectory) {
9007 if (bfile) {
9008 compress = bfile->GetCompressionSettings();
9009 }
9011 for (Int_t i = 0; i < nb; i++) {
9013 branch->SetCompressionSettings(compress);
9014 }
9015 }
9016 } else {
9017 // Enable circularity.
9020 }
9021}
9022
9023////////////////////////////////////////////////////////////////////////////////
9024/// Set the debug level and the debug range.
9025///
9026/// For entries in the debug range, the functions TBranchElement::Fill
9027/// and TBranchElement::GetEntry will print the number of bytes filled
9028/// or read for each branch.
9030void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
9031{
9032 fDebug = level;
9033 fDebugMin = min;
9034 fDebugMax = max;
9035}
9036
9037////////////////////////////////////////////////////////////////////////////////
9038/// Update the default value for the branch's fEntryOffsetLen.
9039/// If updateExisting is true, also update all the existing branches.
9040/// If newdefault is less than 10, the new default value will be 10.
9043{
9044 if (newdefault < 10) {
9045 newdefault = 10;
9046 }
9048 if (updateExisting) {
9049 TIter next( GetListOfBranches() );
9050 TBranch *b;
9051 while ( ( b = (TBranch*)next() ) ) {
9052 b->SetEntryOffsetLen( newdefault, true );
9053 }
9054 if (fBranchRef) {
9056 }
9057 }
9058}
9059
9060////////////////////////////////////////////////////////////////////////////////
9061/// Change the tree's directory.
9062///
9063/// Remove reference to this tree from current directory and
9064/// add reference to new directory dir. The dir parameter can
9065/// be 0 in which case the tree does not belong to any directory.
9066///
9069{
9070 if (fDirectory == dir) {
9071 return;
9072 }
9073 if (fDirectory) {
9074 fDirectory->Remove(this);
9075
9076 // Delete or move the file cache if it points to this Tree
9077 TFile *file = fDirectory->GetFile();
9078 MoveReadCache(file,dir);
9079 }
9080 fDirectory = dir;
9081 if (fDirectory) {
9082 fDirectory->Append(this);
9083 }
9084 TFile* file = nullptr;
9085 if (fDirectory) {
9086 file = fDirectory->GetFile();
9087 }
9088 if (fBranchRef) {
9089 fBranchRef->SetFile(file);
9090 }
9091 TBranch* b = nullptr;
9092 TIter next(GetListOfBranches());
9093 while((b = (TBranch*) next())) {
9094 b->SetFile(file);
9095 }
9096}
9097
9098////////////////////////////////////////////////////////////////////////////////
9099/// Change number of entries in the tree.
9100///
9101/// If n >= 0, set number of entries in the tree = n.
9102///
9103/// If n < 0, set number of entries in the tree to match the
9104/// number of entries in each branch. (default for n is -1)
9105///
9106/// This function should be called only when one fills each branch
9107/// independently via TBranch::Fill without calling TTree::Fill.
9108/// Calling TTree::SetEntries() make sense only if the number of entries
9109/// in each branch is identical, a warning is issued otherwise.
9110/// The function returns the number of entries.
9111///
9114{
9115 // case 1 : force number of entries to n
9116 if (n >= 0) {
9117 fEntries = n;
9118 return n;
9119 }
9120
9121 // case 2; compute the number of entries from the number of entries in the branches
9122 TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
9124 Long64_t nMax = 0;
9125 TIter next(GetListOfBranches());
9126 while((b = (TBranch*) next())){
9127 Long64_t n2 = b->GetEntries();
9128 if (!bMin || n2 < nMin) {
9129 nMin = n2;
9130 bMin = b;
9131 }
9132 if (!bMax || n2 > nMax) {
9133 nMax = n2;
9134 bMax = b;
9135 }
9136 }
9137 if (bMin && nMin != nMax) {
9138 Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
9139 bMin->GetName(), nMin, bMax->GetName(), nMax);
9140 }
9141 fEntries = nMax;
9142 return fEntries;
9143}
9144
9145////////////////////////////////////////////////////////////////////////////////
9146/// Set an EntryList
9149{
9150 if (fEntryList) {
9151 //check if the previous entry list is owned by the tree
9153 delete fEntryList;
9154 }
9155 }
9156 fEventList = nullptr;
9157 if (!enlist) {
9158 fEntryList = nullptr;
9159 return;
9160 }
9162 fEntryList->SetTree(this);
9163
9164}
9165
9166////////////////////////////////////////////////////////////////////////////////
9167/// This function transfroms the given TEventList into a TEntryList
9168/// The new TEntryList is owned by the TTree and gets deleted when the tree
9169/// is deleted. This TEntryList can be returned by GetEntryList() function.
9172{
9174 if (fEntryList){
9176 TEntryList *tmp = fEntryList;
9177 fEntryList = nullptr; // Avoid problem with RecursiveRemove.
9178 delete tmp;
9179 } else {
9180 fEntryList = nullptr;
9181 }
9182 }
9183
9184 if (!evlist) {
9185 fEntryList = nullptr;
9186 fEventList = nullptr;
9187 return;
9188 }
9189
9191 char enlistname[100];
9192 snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
9193 fEntryList = new TEntryList(enlistname, evlist->GetTitle());
9194 fEntryList->SetDirectory(nullptr); // We own this.
9195 Int_t nsel = evlist->GetN();
9196 fEntryList->SetTree(this);
9198 for (Int_t i=0; i<nsel; i++){
9199 entry = evlist->GetEntry(i);
9201 }
9202 fEntryList->SetReapplyCut(evlist->GetReapplyCut());
9204}
9205
9206////////////////////////////////////////////////////////////////////////////////
9207/// Set number of entries to estimate variable limits.
9208/// If n is -1, the estimate is set to be the current maximum
9209/// for the tree (i.e. GetEntries() + 1)
9210/// If n is less than -1, the behavior is undefined.
9212void TTree::SetEstimate(Long64_t n /* = 1000000 */)
9213{
9214 if (n == 0) {
9215 n = 10000;
9216 } else if (n < 0) {
9217 n = fEntries - n;
9218 }
9219 fEstimate = n;
9220 GetPlayer();
9221 if (fPlayer) {
9223 }
9224}
9225
9226////////////////////////////////////////////////////////////////////////////////
9227/// Provide the end-user with the ability to enable/disable various experimental
9228/// IO features for this TTree.
9229///
9230/// Returns all the newly-set IO settings.
9233{
9234 // Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
9235 // error of their ways; this is just a safety check.
9237
9242
9244 return newSettings;
9245}
9246
9247////////////////////////////////////////////////////////////////////////////////
9248/// Set fFileNumber to number.
9249/// fFileNumber is used by TTree::Fill to set the file name
9250/// for a new file to be created when the current file exceeds fgTreeMaxSize.
9251/// (see TTree::ChangeFile)
9252/// if fFileNumber=10, the new file name will have a suffix "_11",
9253/// ie, fFileNumber is incremented before setting the file name
9255void TTree::SetFileNumber(Int_t number)
9256{
9257 if (fFileNumber < 0) {
9258 Warning("SetFileNumber", "file number must be positive. Set to 0");
9259 fFileNumber = 0;
9260 return;
9261 }
9262 fFileNumber = number;
9263}
9264
9265////////////////////////////////////////////////////////////////////////////////
9266/// Set all the branches in this TTree to be in decomposed object mode
9267/// (also known as MakeClass mode).
9268///
9269/// For MakeClass mode 0, the TTree expects the address where the data is stored
9270/// to be set by either the user or the TTree to the address of a full object
9271/// through the top level branch.
9272/// For MakeClass mode 1, this address is expected to point to a numerical type
9273/// or C-style array (variable or not) of numerical type, representing the
9274/// primitive data members.
9275/// The function's primary purpose is to allow the user to access the data
9276/// directly with numerical type variable rather than having to have the original
9277/// set of classes (or a reproduction thereof).
9278/// In other words, SetMakeClass sets the branch(es) into a
9279/// mode that allow its reading via a set of independant variables
9280/// (see the result of running TTree::MakeClass on your TTree) by changing the
9281/// interpretation of the address passed to SetAddress from being the beginning
9282/// of the object containing the data to being the exact location where the data
9283/// should be loaded. If you have the shared library corresponding to your object,
9284/// it is better if you do
9285/// `MyClass *objp = 0; tree->SetBranchAddress("toplevel",&objp);`, whereas
9286/// if you do not have the shared library but know your branch data type, e.g.
9287/// `Int_t* ptr = new Int_t[10];`, then:
9288/// `tree->SetMakeClass(1); tree->GetBranch("x")->SetAddress(ptr)` is the way to go.
9290void TTree::SetMakeClass(Int_t make)
9291{
9292 fMakeClass = make;
9293
9295 for (Int_t i = 0; i < nb; ++i) {
9297 branch->SetMakeClass(make);
9298 }
9299}
9300
9301////////////////////////////////////////////////////////////////////////////////
9302/// Set the maximum size in bytes of a Tree file (static function).
9303/// The default size is 100000000000LL, ie 100 Gigabytes.
9304///
9305/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
9306/// the function closes the current file and starts writing into
9307/// a new file with a name of the style "file_1.root" if the original
9308/// requested file name was "file.root".
9313}
9314
9315////////////////////////////////////////////////////////////////////////////////
9316/// Change the name of this tree.
9318void TTree::SetName(const char* name)
9319{
9320 if (gPad) {
9321 gPad->Modified();
9322 }
9323 // Trees are named objects in a THashList.
9324 // We must update hashlists if we change the name.
9325 TFile *file = nullptr;
9326 TTreeCache *pf = nullptr;
9327 if (fDirectory) {
9328 fDirectory->Remove(this);
9329 if ((file = GetCurrentFile())) {
9330 pf = GetReadCache(file);
9331 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9332 }
9333 }
9334 // This changes our hash value.
9335 fName = name;
9336 if (fDirectory) {
9337 fDirectory->Append(this);
9338 if (pf) {
9340 }
9341 }
9342}
9344void TTree::SetNotify(TObject *obj)
9345{
9346 if (obj && fNotify && dynamic_cast<TNotifyLinkBase *>(fNotify)) {
9347 auto *oldLink = static_cast<TNotifyLinkBase *>(fNotify);
9348 auto *newLink = dynamic_cast<TNotifyLinkBase *>(obj);
9349 if (!newLink) {
9350 Warning("TTree::SetNotify",
9351 "The tree or chain already has a fNotify registered and it is a TNotifyLink, while the new object is "
9352 "not a TNotifyLink. Setting fNotify to the new value will lead to an orphan linked list of "
9353 "TNotifyLinks and it is most likely not intended. If this is the intended goal, please call "
9354 "SetNotify(nullptr) first to silence this warning.");
9355 } else if (newLink->GetNext() != oldLink && oldLink->GetNext() != newLink) {
9356 // If newLink->GetNext() == oldLink then we are prepending the new head, as in TNotifyLink::PrependLink
9357 // If oldLink->GetNext() == newLink then we are removing the head of the list, as in TNotifyLink::RemoveLink
9358 // Otherwise newLink and oldLink are unrelated:
9359 Warning("TTree::SetNotify",
9360 "The tree or chain already has a TNotifyLink registered, and the new TNotifyLink `obj` does not link "
9361 "to it. Setting fNotify to the new value will lead to an orphan linked list of TNotifyLinks and it is "
9362 "most likely not intended. If this is the intended goal, please call SetNotify(nullptr) first to "
9363 "silence this warning.");
9364 }
9365 }
9366
9367 fNotify = obj;
9368}
9369
9370////////////////////////////////////////////////////////////////////////////////
9371/// Change the name and title of this tree.
9373void TTree::SetObject(const char* name, const char* title)
9374{
9375 if (gPad) {
9376 gPad->Modified();
9377 }
9378
9379 // Trees are named objects in a THashList.
9380 // We must update hashlists if we change the name
9381 TFile *file = nullptr;
9382 TTreeCache *pf = nullptr;
9383 if (fDirectory) {
9384 fDirectory->Remove(this);
9385 if ((file = GetCurrentFile())) {
9386 pf = GetReadCache(file);
9387 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9388 }
9389 }
9390 // This changes our hash value.
9391 fName = name;
9392 fTitle = title;
9393 if (fDirectory) {
9394 fDirectory->Append(this);
9395 if (pf) {
9397 }
9398 }
9399}
9400
9401////////////////////////////////////////////////////////////////////////////////
9402/// Enable or disable parallel unzipping of Tree buffers.
9405{
9406#ifdef R__USE_IMT
9407 if (GetTree() == nullptr) {
9409 if (!GetTree())
9410 return;
9411 }
9412 if (GetTree() != this) {
9413 GetTree()->SetParallelUnzip(opt, RelSize);
9414 return;
9415 }
9416 TFile* file = GetCurrentFile();
9417 if (!file)
9418 return;
9419
9420 TTreeCache* pf = GetReadCache(file);
9421 if (pf && !( opt ^ (nullptr != dynamic_cast<TTreeCacheUnzip*>(pf)))) {
9422 // done with opt and type are in agreement.
9423 return;
9424 }
9425 delete pf;
9426 auto cacheSize = GetCacheAutoSize(true);
9427 if (opt) {
9428 auto unzip = new TTreeCacheUnzip(this, cacheSize);
9429 unzip->SetUnzipBufferSize( Long64_t(cacheSize * RelSize) );
9430 } else {
9431 pf = new TTreeCache(this, cacheSize);
9432 }
9433#else
9434 (void)opt;
9435 (void)RelSize;
9436#endif
9437}
9438
9439////////////////////////////////////////////////////////////////////////////////
9440/// Set perf stats
9445}
9446
9447////////////////////////////////////////////////////////////////////////////////
9448/// The current TreeIndex is replaced by the new index.
9449/// Note that this function does not delete the previous index.
9450/// This gives the possibility to play with more than one index, e.g.,
9451/// ~~~ {.cpp}
9452/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
9453/// tree.SetTreeIndex(newIndex);
9454/// tree.Draw();
9455/// tree.SetTreeIndex(oldIndex);
9456/// tree.Draw(); etc
9457/// ~~~
9460{
9461 if (fTreeIndex) {
9462 fTreeIndex->SetTree(nullptr);
9463 }
9464 fTreeIndex = index;
9465}
9466
9467////////////////////////////////////////////////////////////////////////////////
9468/// Set tree weight.
9469///
9470/// The weight is used by TTree::Draw to automatically weight each
9471/// selected entry in the resulting histogram.
9472///
9473/// For example the equivalent of:
9474/// ~~~ {.cpp}
9475/// T.Draw("x", "w")
9476/// ~~~
9477/// is:
9478/// ~~~ {.cpp}
9479/// T.SetWeight(w);
9480/// T.Draw("x");
9481/// ~~~
9482/// This function is redefined by TChain::SetWeight. In case of a
9483/// TChain, an option "global" may be specified to set the same weight
9484/// for all trees in the TChain instead of the default behaviour
9485/// using the weights of each tree in the chain (see TChain::SetWeight).
9488{
9489 fWeight = w;
9490}
9491
9492////////////////////////////////////////////////////////////////////////////////
9493/// Print values of all active leaves for entry.
9494///
9495/// - if entry==-1, print current entry (default)
9496/// - if a leaf is an array, a maximum of lenmax elements is printed.
9499{
9500 if (entry != -1) {
9502 if (ret == -2) {
9503 Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
9504 return;
9505 } else if (ret == -1) {
9506 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9507 return;
9508 }
9509 ret = GetEntry(entry);
9510 if (ret == -1) {
9511 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9512 return;
9513 } else if (ret == 0) {
9514 Error("Show()", "Cannot read entry %lld (no data read)", entry);
9515 return;
9516 }
9517 }
9518 printf("======> EVENT:%lld\n", fReadEntry);
9520 Int_t nleaves = leaves->GetEntriesFast();
9521 Int_t ltype;
9522 for (Int_t i = 0; i < nleaves; i++) {
9523 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
9524 TBranch* branch = leaf->GetBranch();
9525 if (branch->TestBit(kDoNotProcess)) {
9526 continue;
9527 }
9528 Int_t len = leaf->GetLen();
9529 if (len <= 0) {
9530 continue;
9531 }
9533 if (leaf->IsA() == TLeafElement::Class()) {
9534 leaf->PrintValue(lenmax);
9535 continue;
9536 }
9537 if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
9538 continue;
9539 }
9540 ltype = 10;
9541 if (leaf->IsA() == TLeafF::Class()) {
9542 ltype = 5;
9543 }
9544 if (leaf->IsA() == TLeafD::Class()) {
9545 ltype = 5;
9546 }
9547 if (leaf->IsA() == TLeafC::Class()) {
9548 len = 1;
9549 ltype = 5;
9550 };
9551 printf(" %-15s = ", leaf->GetName());
9552 for (Int_t l = 0; l < len; l++) {
9553 leaf->PrintValue(l);
9554 if (l == (len - 1)) {
9555 printf("\n");
9556 continue;
9557 }
9558 printf(", ");
9559 if ((l % ltype) == 0) {
9560 printf("\n ");
9561 }
9562 }
9563 }
9564}
9565
9566////////////////////////////////////////////////////////////////////////////////
9567/// Start the TTreeViewer on this tree.
9568///
9569/// - ww is the width of the canvas in pixels
9570/// - wh is the height of the canvas in pixels
9572void TTree::StartViewer()
9573{
9574 GetPlayer();
9575 if (fPlayer) {
9576 fPlayer->StartViewer(600, 400);
9577 }
9578}
9579
9580////////////////////////////////////////////////////////////////////////////////
9581/// Stop the cache learning phase
9582///
9583/// Returns:
9584/// - 0 learning phase stopped or not active
9585/// - -1 on error
9588{
9589 if (!GetTree()) {
9590 if (LoadTree(0)<0) {
9591 Error("StopCacheLearningPhase","Could not load a tree");
9592 return -1;
9593 }
9594 }
9595 if (GetTree()) {
9596 if (GetTree() != this) {
9597 return GetTree()->StopCacheLearningPhase();
9598 }
9599 } else {
9600 Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
9601 return -1;
9602 }
9603
9604 TFile *f = GetCurrentFile();
9605 if (!f) {
9606 Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
9607 return -1;
9608 }
9609 TTreeCache *tc = GetReadCache(f,true);
9610 if (!tc) {
9611 Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
9612 return -1;
9613 }
9614 tc->StopLearningPhase();
9615 return 0;
9616}
9617
9618////////////////////////////////////////////////////////////////////////////////
9619/// Set the fTree member for all branches and sub branches.
9622{
9623 Int_t nb = branches.GetEntriesFast();
9624 for (Int_t i = 0; i < nb; ++i) {
9625 TBranch* br = (TBranch*) branches.UncheckedAt(i);
9626 br->SetTree(tree);
9627
9628 Int_t writeBasket = br->GetWriteBasket();
9629 for (Int_t j = writeBasket; j >= 0; --j) {
9630 TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
9631 if (bk) {
9632 tree->IncrementTotalBuffers(bk->GetBufferSize());
9633 }
9634 }
9635
9636 tree->RegisterBranchFullName({std::string{br->GetFullName()}, br});
9637
9638 ROOT::Internal::TreeUtils::TBranch__SetTree(tree, *br->GetListOfBranches());
9639 }
9640}
9641
9642////////////////////////////////////////////////////////////////////////////////
9643/// Set the fTree member for all friend elements.
9646{
9647 if (frlist) {
9648 TObjLink *lnk = frlist->FirstLink();
9649 while (lnk) {
9650 TFriendElement *elem = (TFriendElement*)lnk->GetObject();
9651 elem->fParentTree = tree;
9652 lnk = lnk->Next();
9653 }
9654 }
9655}
9656
9657////////////////////////////////////////////////////////////////////////////////
9658/// Stream a class object.
9661{
9662 if (b.IsReading()) {
9663 UInt_t R__s, R__c;
9664 if (fDirectory) {
9665 fDirectory->Remove(this);
9666 //delete the file cache if it points to this Tree
9667 TFile *file = fDirectory->GetFile();
9668 MoveReadCache(file,nullptr);
9669 }
9670 fDirectory = nullptr;
9671 fCacheDoAutoInit = true;
9672 fCacheUserSet = false;
9673 Version_t R__v = b.ReadVersion(&R__s, &R__c);
9674 if (R__v > 4) {
9675 b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
9676
9677 fBranches.SetOwner(true); // True needed only for R__v < 19 and most R__v == 19
9678
9679 if (fBranchRef) fBranchRef->SetTree(this);
9682
9683 if (fTreeIndex) {
9684 fTreeIndex->SetTree(this);
9685 }
9686 if (fIndex.fN) {
9687 Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
9688 fIndex.Set(0);
9689 fIndexValues.Set(0);
9690 }
9691 if (fEstimate <= 10000) {
9692 fEstimate = 1000000;
9693 }
9694
9695 if (fNClusterRange) {
9696 // The I/O allocated just enough memory to hold the
9697 // current set of ranges.
9699 }
9700
9701 // Throughs calls to `GetCacheAutoSize` or `EnableCache` (for example
9702 // by TTreePlayer::Process, the cache size will be automatically
9703 // determined unless the user explicitly call `SetCacheSize`
9704 fCacheSize = 0;
9705 fCacheUserSet = false;
9706
9708 return;
9709 }
9710 //====process old versions before automatic schema evolution
9711 Stat_t djunk;
9712 Int_t ijunk;
9717 b >> fScanField;
9720 b >> djunk; fEntries = (Long64_t)djunk;
9725 if (fEstimate <= 10000) fEstimate = 1000000;
9727 if (fBranchRef) fBranchRef->SetTree(this);
9731 if (R__v > 1) fIndexValues.Streamer(b);
9732 if (R__v > 2) fIndex.Streamer(b);
9733 if (R__v > 3) {
9735 OldInfoList.Streamer(b);
9736 OldInfoList.Delete();
9737 }
9738 fNClusterRange = 0;
9741 b.CheckByteCount(R__s, R__c, TTree::IsA());
9742 //====end of old versions
9743 } else {
9744 if (fBranchRef) {
9745 fBranchRef->Clear();
9746 }
9748 if (table) TRefTable::SetRefTable(nullptr);
9749
9750 b.WriteClassBuffer(TTree::Class(), this);
9751
9752 if (table) TRefTable::SetRefTable(table);
9753 }
9754}
9755
9756////////////////////////////////////////////////////////////////////////////////
9757/// Unbinned fit of one or more variable(s) from a tree.
9758///
9759/// funcname is a TF1 function.
9760///
9761/// \note see TTree::Draw for explanations of the other parameters.
9762///
9763/// Fit the variable varexp using the function funcname using the
9764/// selection cuts given by selection.
9765///
9766/// The list of fit options is given in parameter option.
9767///
9768/// - option = "Q" Quiet mode (minimum printing)
9769/// - option = "V" Verbose mode (default is between Q and V)
9770/// - option = "E" Perform better Errors estimation using Minos technique
9771/// - option = "M" More. Improve fit results
9772///
9773/// You can specify boundary limits for some or all parameters via
9774/// ~~~ {.cpp}
9775/// func->SetParLimits(p_number, parmin, parmax);
9776/// ~~~
9777/// if parmin>=parmax, the parameter is fixed
9778///
9779/// Note that you are not forced to fix the limits for all parameters.
9780/// For example, if you fit a function with 6 parameters, you can do:
9781/// ~~~ {.cpp}
9782/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
9783/// func->SetParLimits(4,-10,-4);
9784/// func->SetParLimits(5, 1,1);
9785/// ~~~
9786/// With this setup:
9787///
9788/// - Parameters 0->3 can vary freely
9789/// - Parameter 4 has boundaries [-10,-4] with initial value -8
9790/// - Parameter 5 is fixed to 100.
9791///
9792/// For the fit to be meaningful, the function must be self-normalized.
9793///
9794/// i.e. It must have the same integral regardless of the parameter
9795/// settings. Otherwise the fit will effectively just maximize the
9796/// area.
9797///
9798/// It is mandatory to have a normalization variable
9799/// which is fixed for the fit. e.g.
9800/// ~~~ {.cpp}
9801/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
9802/// f1->SetParameters(1, 3.1, 0.01);
9803/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
9804/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
9805/// ~~~
9806/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
9807///
9808/// Return status:
9809///
9810/// - The function return the status of the fit in the following form
9811/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
9812/// - The fitResult is 0 is the fit is OK.
9813/// - The fitResult is negative in case of an error not connected with the fit.
9814/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
9815/// - If the number of selected entries is null the function returns -1
9818{
9819 GetPlayer();
9820 if (fPlayer) {
9822 }
9823 return -1;
9824}
9825
9826////////////////////////////////////////////////////////////////////////////////
9827/// Replace current attributes by current style.
9850}
9851
9852////////////////////////////////////////////////////////////////////////////////
9853/// Write this object to the current directory. For more see TObject::Write
9854/// If option & kFlushBasket, call FlushBasket before writing the tree.
9856Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
9857{
9860 return 0;
9862}
9863
9864////////////////////////////////////////////////////////////////////////////////
9865/// Write this object to the current directory. For more see TObject::Write
9866/// If option & kFlushBasket, call FlushBasket before writing the tree.
9869{
9870 return ((const TTree*)this)->Write(name, option, bufsize);
9871}
9872
9873////////////////////////////////////////////////////////////////////////////////
9874/// \class TTreeFriendLeafIter
9875///
9876/// Iterator on all the leaves in a TTree and its friend
9877
9879
9880////////////////////////////////////////////////////////////////////////////////
9881/// Create a new iterator. By default the iteration direction
9882/// is kIterForward. To go backward use kIterBackward.
9885: fTree(const_cast<TTree*>(tree))
9886, fLeafIter(nullptr)
9887, fTreeIter(nullptr)
9888, fDirection(dir)
9889{
9890}
9891
9892////////////////////////////////////////////////////////////////////////////////
9893/// Copy constructor. Does NOT copy the 'cursor' location!
9896: TIterator(iter)
9897, fTree(iter.fTree)
9898, fLeafIter(nullptr)
9899, fTreeIter(nullptr)
9900, fDirection(iter.fDirection)
9901{
9902}
9903
9904////////////////////////////////////////////////////////////////////////////////
9905/// Overridden assignment operator. Does NOT copy the 'cursor' location!
9908{
9909 if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
9911 fDirection = rhs1.fDirection;
9912 }
9913 return *this;
9914}
9915
9916////////////////////////////////////////////////////////////////////////////////
9917/// Overridden assignment operator. Does NOT copy the 'cursor' location!
9920{
9921 if (this != &rhs) {
9922 fDirection = rhs.fDirection;
9923 }
9924 return *this;
9925}
9926
9927////////////////////////////////////////////////////////////////////////////////
9928/// Go the next friend element
9931{
9932 if (!fTree) return nullptr;
9933
9934 TObject * next;
9935 TTree * nextTree;
9936
9937 if (!fLeafIter) {
9938 TObjArray *list = fTree->GetListOfLeaves();
9939 if (!list) return nullptr; // Can happen with an empty chain.
9940 fLeafIter = list->MakeIterator(fDirection);
9941 if (!fLeafIter) return nullptr;
9942 }
9943
9944 next = fLeafIter->Next();
9945 if (!next) {
9946 if (!fTreeIter) {
9948 if (!list) return next;
9949 fTreeIter = list->MakeIterator(fDirection);
9950 if (!fTreeIter) return nullptr;
9951 }
9953 ///nextTree = (TTree*)fTreeIter->Next();
9954 if (nextFriend) {
9955 nextTree = const_cast<TTree*>(nextFriend->GetTree());
9956 if (!nextTree) return Next();
9958 fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
9959 if (!fLeafIter) return nullptr;
9960 next = fLeafIter->Next();
9961 }
9962 }
9963 return next;
9964}
9965
9966////////////////////////////////////////////////////////////////////////////////
9967/// Returns the object option stored in the list.
9970{
9971 if (fLeafIter) return fLeafIter->GetOption();
9972 return "";
9973}
#define R__unlikely(expr)
Definition RConfig.hxx:599
#define SafeDelete(p)
Definition RConfig.hxx:538
#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:622
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:414
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:9644
bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
Definition TTree.cxx:1234
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:2425
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2992
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:5118
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:5540
void BuildRealData(void *pointer=nullptr, Bool_t isTransient=kFALSE)
Build a full list of persistent data members.
Definition TClass.cxx:2137
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:3764
Bool_t IsTObject() const
Return kTRUE is the class inherits from TObject.
Definition TClass.cxx:6081
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:4727
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:3003
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:3074
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:731
TTree * fTree
tree being iterated
Definition TTree.h:734
TIterator & operator=(const TIterator &rhs) override
Overridden assignment operator. Does NOT copy the 'cursor' location!
Definition TTree.cxx:9906
TObject * Next() override
Go the next friend element.
Definition TTree.cxx:9929
TIterator * fLeafIter
current leaf sub-iterator.
Definition TTree.h:735
Option_t * GetOption() const override
Returns the object option stored in the list.
Definition TTree.cxx:9968
TIterator * fTreeIter
current tree sub-iterator.
Definition TTree.h:736
bool fDirection
iteration direction
Definition TTree.h:737
static TClass * Class()
Helper class to iterate over cluster of baskets.
Definition TTree.h:282
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:319
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:199
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:203
TTree * fTree
Definition TTree.h:202
~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:84
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:141
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:8635
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:5403
TList * fFriends
pointer to list of friend elements
Definition TTree.h:135
bool fIMTEnabled
! true if implicit multi-threading is enabled for this tree
Definition TTree.h:147
virtual bool GetBranchStatus(const char *branchname) const
Return status of branch with name branchname.
Definition TTree.cxx:5388
UInt_t fFriendLockStatus
! Record which method is locking the friend recursion
Definition TTree.h:142
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:6108
Long64_t fTotBytes
Total number of bytes in all branches before compression.
Definition TTree.h:91
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:101
virtual void Show(Long64_t entry=-1, Int_t lenmax=20)
Print values of all active leaves for entry.
Definition TTree.cxx:9497
TEventList * fEventList
! Pointer to event selection list (if one)
Definition TTree.h:130
virtual Long64_t GetAutoSave() const
Definition TTree.h:463
virtual Int_t StopCacheLearningPhase()
Stop the cache learning phase.
Definition TTree.cxx:9586
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:5648
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:149
virtual void SetCircular(Long64_t maxEntries)
Enable/Disable circularity for this tree.
Definition TTree.cxx:8993
Long64_t fSavedBytes
Number of autosaved bytes.
Definition TTree.h:93
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:8398
virtual TClusterIterator GetClusterIterator(Long64_t firstentry)
Return an iterator over the cluster of baskets starting at firstentry.
Definition TTree.cxx:5475
virtual void ResetBranchAddress(TBranch *)
Tell a branch to set its address to zero.
Definition TTree.cxx:8152
bool fCacheUserSet
! true if the cache setting was explicitly given by user
Definition TTree.h:146
char GetNewlineValue(std::istream &inputStream)
Determine which newline this file is using.
Definition TTree.cxx:7675
TIOFeatures fIOFeatures
IO features to define for newly-written baskets and branches.
Definition TTree.h:119
virtual Long64_t GetEntryNumberWithIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5920
Long64_t fDebugMin
! First entry number to debug
Definition TTree.h:117
virtual Long64_t SetEntries(Long64_t n=-1)
Change number of entries in the tree.
Definition TTree.cxx:9112
virtual TObjArray * GetListOfLeaves()
Definition TTree.h:544
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:5415
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:5487
TList * fAliases
List of aliases for expressions based on the tree branches.
Definition TTree.h:129
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:108
void Streamer(TBuffer &) override
Stream a class object.
Definition TTree.cxx:9659
std::atomic< Long64_t > fIMTZipBytes
! Zip bytes for the IMT flush baskets.
Definition TTree.h:166
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:7968
TVirtualTreePlayer * GetPlayer()
Load the TTreePlayer (if not already done).
Definition TTree.cxx:6315
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:6778
virtual Long64_t ReadStream(std::istream &inputStream, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from an input stream.
Definition TTree.cxx:7702
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:9029
Int_t fScanField
Number of runs before prompting in Scan.
Definition TTree.h:97
void Draw(Option_t *opt) override
Default Draw method for all objects.
Definition TTree.h:446
virtual TTree * GetFriend(const char *) const
Return a pointer to the TTree friend whose name or alias is friendname.
Definition TTree.cxx:5985
virtual void SetNotify(TObject *obj)
Sets the address of the object to be notified when the tree is loaded.
Definition TTree.cxx:9343
virtual Double_t GetMaximum(const char *columname)
Return maximum of column with name columname.
Definition TTree.cxx:6245
virtual Long64_t GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5900
static void SetMaxTreeSize(Long64_t maxsize=100000000000LL)
Set the maximum size in bytes of a Tree file (static function).
Definition TTree.cxx:9309
void Print(Option_t *option="") const override
Print a summary of the tree contents.
Definition TTree.cxx:7305
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:9816
Int_t fNClusterRange
Number of Cluster range in addition to the one defined by 'AutoFlush'.
Definition TTree.h:100
virtual void PrintCacheStats(Option_t *option="") const
Print statistics about the TreeCache for this tree.
Definition TTree.cxx:7457
TVirtualTreePlayer * fPlayer
! Pointer to current Tree player
Definition TTree.h:139
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:6092
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:9289
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:7098
TObjArray fBranches
List of Branches.
Definition TTree.h:127
TDirectory * GetDirectory() const
Definition TTree.h:477
bool fCacheDoAutoInit
! true if cache auto creation or resize check is needed
Definition TTree.h:144
TTreeCache * GetReadCache(TFile *file) const
Find and return the TTreeCache registered with the file and which may contain branches for us.
Definition TTree.cxx:6328
Long64_t fEntries
Number of entries.
Definition TTree.h:89
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:5864
virtual void SetWeight(Double_t w=1, Option_t *option="")
Set tree weight.
Definition TTree.cxx:9486
void InitializeBranchLists(bool checkLeafCount)
Divides the top-level branches into two vectors: (i) branches to be processed sequentially and (ii) b...
Definition TTree.cxx:5791
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr=nullptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8486
Long64_t * fClusterSize
[fNClusterRange] Number of entries in each cluster for a given range.
Definition TTree.h:109
Long64_t fFlushedBytes
Number of auto-flushed bytes.
Definition TTree.h:94
virtual void SetPerfStats(TVirtualPerfStats *perf)
Set perf stats.
Definition TTree.cxx:9441
std::atomic< Long64_t > fIMTTotBytes
! Total bytes for the IMT flush baskets
Definition TTree.h:165
virtual void SetCacheLearnEntries(Int_t n=10)
Interface to TTreeCache to set the number of entries for the learning phase.
Definition TTree.cxx:8966
TEntryList * fEntryList
! Pointer to event selection list (if one)
Definition TTree.h:131
@ kSplitCollectionOfPointers
Definition TTree.h:278
virtual TVirtualIndex * GetTreeIndex() const
Definition TTree.h:573
TList * fExternalFriends
! List of TFriendsElement pointing to us and need to be notified of LoadTree. Content not owned.
Definition TTree.h:136
virtual Long64_t Merge(TCollection *list, Option_t *option="")
Merge the trees in the TList into this tree.
Definition TTree.cxx:6912
virtual void SetMaxVirtualSize(Long64_t size=0)
Definition TTree.h:680
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:8443
Long64_t fMaxEntryLoop
Maximum number of entries to process.
Definition TTree.h:103
virtual void SetParallelUnzip(bool opt=true, Float_t RelSize=-1)
Enable or disable parallel unzipping of Tree buffers.
Definition TTree.cxx:9403
virtual void SetDirectory(TDirectory *dir)
Change the tree's directory.
Definition TTree.cxx:9067
void SortBranchesByTime()
Sorts top-level branches by the last average task time recorded per branch.
Definition TTree.cxx:5844
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:465
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:7537
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:9170
void MoveReadCache(TFile *src, TDirectory *dir)
Move a cache from a file to the current file in dir.
Definition TTree.cxx:7069
Long64_t fAutoFlush
Auto-flush tree when fAutoFlush entries written or -fAutoFlush (compressed) bytes produced.
Definition TTree.h:106
Int_t fUpdate
Update frequency for EntryLoop.
Definition TTree.h:98
virtual void ResetAfterMerge(TFileMergeInfo *)
Resets the state of this TTree after a merge (keep the customization but forget the data).
Definition TTree.cxx:8121
virtual Long64_t GetEntries() const
Definition TTree.h:478
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition TTree.cxx:9211
Int_t fTimerInterval
Timer interval in milliseconds.
Definition TTree.h:96
Int_t fDebug
! Debug level
Definition TTree.h:116
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:8812
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:5875
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:121
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:6205
virtual Long64_t GetZipBytes() const
Definition TTree.h:600
TObjArray fLeaves
Direct pointers to individual branch leaves.
Definition TTree.h:128
virtual void Reset(Option_t *option="")
Reset baskets, buffers and entries count in all branches and leaves.
Definition TTree.cxx:8090
virtual void KeepCircular()
Keep a maximum of fMaxEntries in memory.
Definition TTree.cxx:6425
virtual void SetDefaultEntryOffsetLen(Int_t newdefault, bool updateExisting=false)
Update the default value for the branch's fEntryOffsetLen.
Definition TTree.cxx:9041
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:104
virtual Long64_t GetTotBytes() const
Definition TTree.h:571
virtual Int_t MakeSelector(const char *selector=nullptr, Option_t *option="")
Generate skeleton selector class for this tree.
Definition TTree.cxx:6832
virtual void SetObject(const char *name, const char *title)
Change the name and title of this tree.
Definition TTree.cxx:9372
TVirtualPerfStats * fPerfStats
! pointer to the current perf stats object
Definition TTree.h:137
Double_t fWeight
Tree weight (see TTree::SetWeight)
Definition TTree.h:95
std::vector< TBranch * > fSeqBranches
! Branches to be processed sequentially when IMT is on
Definition TTree.h:150
Long64_t fDebugMax
! Last entry number to debug
Definition TTree.h:118
Int_t fDefaultEntryOffsetLen
Initial Length of fEntryOffset table in the basket buffers.
Definition TTree.h:99
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:105
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:365
std::atomic< UInt_t > fAllocationCount
indicates basket should be resized to exact memory usage, but causes significant
Definition TTree.h:157
virtual Int_t GetEntryWithIndex(Int_t major, Int_t minor=0)
Read entry corresponding to major and minor number.
Definition TTree.cxx:5937
static TTree * MergeTrees(TList *list, Option_t *option="")
Static function merging the trees in the TList into a new tree.
Definition TTree.cxx:6863
bool MemoryFull(Int_t nbytes)
Check if adding nbytes to memory we are still below MaxVirtualsize.
Definition TTree.cxx:6847
virtual Long64_t GetReadEntry() const
Definition TTree.h:564
virtual TObjArray * GetListOfBranches()
Definition TTree.h:543
Long64_t fZipBytes
Total number of bytes in all branches after compression.
Definition TTree.h:92
virtual TTree * GetTree() const
Definition TTree.h:572
TBuffer * fTransientBuffer
! Pointer to the current transient buffer.
Definition TTree.h:143
virtual void SetEntryList(TEntryList *list, Option_t *opt="")
Set an EntryList.
Definition TTree.cxx:9147
bool Notify() override
Function called when loading a new class library.
Definition TTree.cxx:7119
virtual void AddZipBytes(Int_t zip)
Definition TTree.h:344
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition TTree.cxx:6483
virtual Long64_t ReadFile(const char *filename, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from filename.
Definition TTree.cxx:7651
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:9231
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:138
virtual Double_t GetMinimum(const char *columname)
Return minimum of column with name columname.
Definition TTree.cxx:6285
virtual void RemoveFriend(TTree *)
Remove a friend from the list of friends.
Definition TTree.cxx:8064
virtual Long64_t GetEntriesFast() const
Return a number greater or equal to the total number of entries in the dataset.
Definition TTree.h:520
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:6366
Long64_t fChainOffset
! Offset of 1st entry of this Tree in a TChain
Definition TTree.h:111
@ kOnlyFlushAtCluster
If set, the branch's buffers will grow until an event cluster boundary is hit, guaranteeing a basket ...
Definition TTree.h:268
@ kEntriesReshuffled
If set, signals that this TTree is the output of the processing of another TTree, and the entries are...
Definition TTree.h:273
@ kCircular
Definition TTree.h:264
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:5520
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:7600
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:8459
static void SetBranchStyle(Int_t style=1)
Set the current branch style.
Definition TTree.cxx:8766
~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:6382
TClass * IsA() const override
Definition TTree.h:720
Long64_t fEstimate
Number of entries to estimate histogram limits.
Definition TTree.h:107
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:6567
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:9867
TVirtualIndex * fTreeIndex
Pointer to the tree Index (if any)
Definition TTree.h:134
void UseCurrentStyle() override
Replace current attributes by current style.
Definition TTree.cxx:9828
TObject * fNotify
Object to be notified when loading a Tree.
Definition TTree.h:125
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:110
TList * fClones
! List of cloned trees which share our addresses
Definition TTree.h:140
std::atomic< Long64_t > fTotalBuffers
! Total number of bytes in branch buffers
Definition TTree.h:113
static TClass * Class()
@ kFindBranch
Definition TTree.h:223
@ kResetBranchAddresses
Definition TTree.h:236
@ kFindLeaf
Definition TTree.h:224
@ kGetEntryWithIndex
Definition TTree.h:228
@ kPrint
Definition TTree.h:233
@ kGetFriend
Definition TTree.h:229
@ kGetBranch
Definition TTree.h:226
@ kSetBranchStatus
Definition TTree.h:235
@ kLoadTree
Definition TTree.h:232
@ kGetEntry
Definition TTree.h:227
@ kGetLeaf
Definition TTree.h:231
@ kRemoveFriend
Definition TTree.h:234
@ kGetFriendAlias
Definition TTree.h:230
@ kGetAlias
Definition TTree.h:225
virtual void SetTreeIndex(TVirtualIndex *index)
The current TreeIndex is replaced by the new index.
Definition TTree.cxx:9458
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:7143
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:7585
virtual Int_t SetCacheEntryRange(Long64_t first, Long64_t last)
interface to TTreeCache to set the cache entry range
Definition TTree.cxx:8932
static Long64_t GetMaxTreeSize()
Static function which returns the tree file size limit in bytes.
Definition TTree.cxx:6275
bool fCacheDoClusterPrefetch
! true if cache is prefetching whole clusters
Definition TTree.h:145
Int_t SetBranchAddressImp(TBranch *branch, void *addr, TBranch **ptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8546
virtual bool SetAlias(const char *aliasName, const char *aliasFormula)
Set a tree variable alias.
Definition TTree.cxx:8242
virtual void CopyAddresses(TTree *, bool undo=false)
Set branch addresses of passed tree equal to ours.
Definition TTree.cxx:3306
virtual Int_t BuildIndex(const char *majorname, const char *minorname="0", bool long64major=false, bool long64minor=false)
Build a Tree Index (default is TTreeIndex).
Definition TTree.cxx:2634
Long64_t fMaxEntries
Maximum number of entries in case of circular buffers.
Definition TTree.h:102
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:545
virtual void Refresh()
Refresh contents of this tree and its branches from the current status on disk.
Definition TTree.cxx:8003
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:8297
static Long64_t fgMaxTreeSize
Maximum size of a file containing a Tree.
Definition TTree.h:160
Long64_t fReadEntry
! Number of the entry being processed
Definition TTree.h:112
TArrayD fIndexValues
Sorted index values.
Definition TTree.h:132
void MarkEventCluster()
Mark the previous event as being at the end of the event cluster.
Definition TTree.cxx:8359
UInt_t fNEntriesSinceSorting
! Number of entries processed since the last re-sorting of branches
Definition TTree.h:148
virtual void SetFileNumber(Int_t number=0)
Set fFileNumber to number.
Definition TTree.cxx:9254
virtual TLeaf * FindLeaf(const char *name)
Find leaf..
Definition TTree.cxx:4921
virtual void StartViewer()
Start the TTreeViewer on this tree.
Definition TTree.cxx:9571
Int_t GetMakeClass() const
Definition TTree.h:550
virtual Int_t MakeCode(const char *filename=nullptr)
Generate a skeleton function for this tree.
Definition TTree.cxx:6650
bool fIMTFlush
! True if we are doing a multithreaded flush.
Definition TTree.h:164
TDirectory * fDirectory
! Pointer to directory holding this tree
Definition TTree.h:126
@ kNeedEnableDecomposedObj
Definition TTree.h:256
@ kClassMismatch
Definition TTree.h:249
@ kVoidPtr
Definition TTree.h:254
@ kMatchConversionCollection
Definition TTree.h:252
@ kMissingCompiledCollectionProxy
Definition TTree.h:247
@ kMismatch
Definition TTree.h:248
@ kMatchConversion
Definition TTree.h:251
@ kInternalError
Definition TTree.h:246
@ kMatch
Definition TTree.h:250
@ kMissingBranch
Definition TTree.h:245
@ kMakeClass
Definition TTree.h:253
static Int_t fgBranchStyle
Old/New branch style.
Definition TTree.h:159
virtual void ResetBranchAddresses()
Tell all of our branches to drop their current objects and allocate new ones.
Definition TTree.cxx:8162
Int_t fNfill
! Local for EntryLoop
Definition TTree.h:115
void SetName(const char *name) override
Change the name of this tree.
Definition TTree.cxx:9317
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:8044
TArrayI fIndex
Index of sorted values.
Definition TTree.h:133
virtual Int_t SetCacheSize(Long64_t cachesize=-1)
Set maximum size of the file cache .
Definition TTree.cxx:8784
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:6084
virtual Int_t MakeClass(const char *classname=nullptr, Option_t *option="")
Generate a skeleton analysis class for this tree.
Definition TTree.cxx:6617
virtual const char * GetFriendAlias(TTree *) const
If the 'tree' is a friend, this method returns its alias name.
Definition TTree.cxx:6042
virtual void RemoveExternalFriend(TFriendElement *)
Removes external friend.
Definition TTree.cxx:8055
Int_t fPacketSize
! Number of entries in one packet for parallel root
Definition TTree.h:114
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:8200
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:343
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:120
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:6461
static constexpr Long64_t kMaxEntries
Definition TTree.h:241
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:7286
std::unordered_map< std::string, TBranch * > fNamesToBranches
! maps names to their branches, useful when retrieving branches by name
Definition TTree.h:169
virtual Long64_t GetAutoFlush() const
Definition TTree.h:462
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 TVirtualIndex * BuildIndex(const TTree *T, const char *majorname, const char *minorname, bool long64major=false, bool long64minor=false)=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 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
void TBranch__SetTree(TTree *tree, TObjArray &branches)
Set the fTree member for all branches and sub branches.
Definition TTree.cxx:9620
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:595
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:403
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