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 TTree
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 TClonesArray](\ref addingacolumnoftclonesarray)
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 integer (`Char_t`); Mostly signed, might be unsigned in special platforms or depending on compiler flags, thus do not use std::int8_t as underlying variable since they are not equivalent; 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 24 bit (or 32) floating point with truncated mantissa (`Float16_t`, stored as 3 bytes by default or as fixed-point arithmetic 4 bytes Int_t if range is customized; occupies 4 bytes in memory): By default, in disk, only 21 bits are used: 1 for the sign, 8 for the exponent and 12 for the mantissa. Can be customized with suffix `[min,max(,nbits)] `where `nbits` is for the mantissa.
104 - `D` : a 64 bit floating point (`Double_t`)
105 - `d` : a 32 (or 24) bit floating point with truncated mantissa (`Double32_t`, stored as a 4 bytes Float_t by default or as 3 bytes if range is customized; occupies 8 bytes in memory): By default, in disk, 1 bit is used for the sign, 8 for the exponent and 23 for the mantissa. Can be customized to 3 bytes (24 bits) with suffix `[min,max(,nbits)]` where `nbits` is 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 See TStreamerElement::GetRange for further details.
138
139 Examples of writing/reading plain C arrays with fixed or variable length into/from TTrees:
140
141~~~ {.cpp}
142 TTree *t = new TTree("t", "t");
143 int n;
144 Double32_t arr[64];
145 // Double32_t* arr = new Double32_t[64]; // equivalent, later just remember delete[]
146 t->Branch("n", &n);
147 t->Branch("arr", arr, "arr[n]/d[0,1,32]");
148 t->Branch("arr_def", arr, "arr_def[n]/d");
149 t->Branch("arr_fix", arr, "arr_fix[64]/d[0,1,32]");
150 t->Branch("arr_fix_def", arr, "arr_fix_def[64]/d");
151 t->Branch("single", arr, "single/d[0,1,32]");
152 t->Branch("single_def", arr, "single_def/d");
153 for (int j = 0; j < 64; ++j) {
154 arr[j] = 0.01 * j;
155 }
156 n = 3;
157 t->Fill();
158 // Reading now:
159 const auto nEntries = t->GetEntries();
160 t->Scan();
161 for (auto name : {"arr", "arr_def", "arr_fix", "arr_fix_def", "single", "single_def"}) {
162 t->ResetBranchAddresses();
163 t->SetBranchAddress("n", &n);
164 t->SetBranchAddress(name, arr);
165 for (Long64_t i = 0; i < nEntries; ++i) {
166 t->GetEntry(i);
167 // Work with arr
168 }
169 }
170~~~
171
172\anchor addingacolumnofstl
173## Adding a column holding STL collection instances (e.g. std::vector or std::list)
174
175~~~ {.cpp}
176 auto branch = tree.Branch( branchname, STLcollection, bufsize, splitlevel);
177~~~
178`STLcollection` is the address of a pointer to a container of the standard
179library such as `std::vector`, `std::list`, containing pointers, fundamental types
180or objects.
181If the splitlevel is a value bigger than 100 (`TTree::kSplitCollectionOfPointers`)
182then the collection will be written in split mode, i.e. transparently storing
183individual data members as arrays, therewith potentially increasing compression ratio.
184
185### Note
186In case of dynamic structures changing with each entry, see e.g.
187~~~ {.cpp}
188 branch->SetAddress(void *address)
189~~~
190one must redefine the branch address before filling the branch
191again. This is done via the `TBranch::SetAddress` member function.
192
193\anchor addingacolumnofobjs
194## Add a column holding objects (or a TObjArray)
195
196~~~ {.cpp}
197 MyClass object;
198 auto branch = tree.Branch(branchname, &object, bufsize, splitlevel)
199~~~
200Note: The 2nd parameter must be the address of a valid object.
201 The object must not be destroyed (i.e. be deleted) until the TTree
202 is deleted or TTree::ResetBranchAddress is called.
203
204- if splitlevel=0, the object is serialized in the branch buffer.
205- if splitlevel=1 (default), this branch will automatically be split
206 into subbranches, with one subbranch for each data member or object
207 of the object itself. In case the object member is a TClonesArray,
208 the mechanism described in case C is applied to this array.
209- if splitlevel=2 ,this branch will automatically be split
210 into subbranches, with one subbranch for each data member or object
211 of the object itself. In case the object member is a TClonesArray,
212 it is processed as a TObject*, only one branch.
213
214Another available syntax is the following:
215
216~~~ {.cpp}
217 auto branch_a = tree.Branch(branchname, &p_object, bufsize, splitlevel)
218 auto branch_b = tree.Branch(branchname, className, &p_object, bufsize, splitlevel)
219~~~
220- `p_object` is a pointer to an object.
221- If `className` is not specified, the `Branch` method uses the type of `p_object`
222 to determine the type of the object.
223- If `className` is used to specify explicitly the object type, the `className`
224 must be of a type related to the one pointed to by the pointer. It should be
225 either a parent or derived class.
226
227Note: The pointer whose address is passed to `TTree::Branch` must not
228 be destroyed (i.e. go out of scope) until the TTree is deleted or
229 TTree::ResetBranchAddress is called.
230
231Note: The pointer `p_object` can be initialized before calling `TTree::Branch`
232~~~ {.cpp}
233 auto p_object = new MyDataClass;
234 tree.Branch(branchname, &p_object);
235~~~
236or not
237~~~ {.cpp}
238 MyDataClass* p_object = nullptr;
239 tree.Branch(branchname, &p_object);
240~~~
241In either case, the ownership of the object is not taken over by the `TTree`.
242Even though in the first case an object is be allocated by `TTree::Branch`,
243the object will <b>not</b> be deleted when the `TTree` is deleted.
244
245\anchor addingacolumnoftclonesarray
246## Add a column holding TClonesArray instances
247
248*The usage of `TClonesArray` should be abandoned in favour of `std::vector`,
249for which `TTree` has been heavily optimised, as well as `RNTuple`.*
250
251~~~ {.cpp}
252 // clonesarray is the address of a pointer to a TClonesArray.
253 auto branch = tree.Branch(branchname, clonesarray, bufsize, splitlevel)
254~~~
255The TClonesArray is a direct access list of objects of the same class.
256For example, if the TClonesArray is an array of TTrack objects,
257this function will create one subbranch for each data member of
258the object TTrack.
259
260\anchor fillthetree
261## Fill the Tree
262
263A TTree instance is filled with the invocation of the TTree::Fill method:
264~~~ {.cpp}
265 tree.Fill()
266~~~
267Upon its invocation, a loop on all defined branches takes place that for each branch invokes
268the TBranch::Fill method.
269
270\anchor addcoltoexistingtree
271## Add a column to an already existing Tree
272
273You may want to add a branch to an existing tree. For example,
274if one variable in the tree was computed with a certain algorithm,
275you may want to try another algorithm and compare the results.
276One solution is to add a new branch, fill it, and save the tree.
277The code below adds a simple branch to an existing tree.
278Note the `kOverwrite` option in the `Write` method: it overwrites the
279existing tree. If it is not specified, two copies of the tree headers
280are saved.
281~~~ {.cpp}
282 void addBranchToTree() {
283 TFile f("tree.root", "update");
284
285 Float_t new_v;
286 auto mytree = f->Get<TTree>("mytree");
287 auto newBranch = mytree->Branch("new_v", &new_v, "new_v/F");
288
289 auto nentries = mytree->GetEntries(); // read the number of entries in the mytree
290
291 for (Long64_t i = 0; i < nentries; i++) {
292 new_v = gRandom->Gaus(0, 1);
293 newBranch->Fill();
294 }
295
296 mytree->Write("", TObject::kOverwrite); // save only the new version of the tree
297 }
298~~~
299It is not always possible to add branches to existing datasets stored in TFiles: for example,
300these files might not be writeable, just readable. In addition, modifying in place a TTree
301causes a new TTree instance to be written and the previous one to be deleted.
302For this reasons, ROOT offers the concept of friends for TTree and TChain.
303
304\anchor fullexample
305## A Complete Example
306
307~~~ {.cpp}
308// A simple example creating a tree
309// Compile it with: `g++ myTreeExample.cpp -o myTreeExample `root-config --cflags --libs`
310
311#include "TFile.h"
312#include "TH1D.h"
313#include "TRandom3.h"
314#include "TTree.h"
315
316int main()
317{
318 // Create a new ROOT binary machine independent file.
319 // Note that this file may contain any kind of ROOT objects, histograms,trees
320 // pictures, graphics objects, detector geometries, tracks, events, etc..
321 TFile hfile("htree.root", "RECREATE", "Demo ROOT file with trees");
322
323 // Define a histogram and some simple structures
324 TH1D hpx("hpx", "This is the px distribution", 100, -4, 4);
325
326 typedef struct {
327 Float_t x, y, z;
328 } Point;
329
330 typedef struct {
331 Int_t ntrack, nseg, nvertex;
332 UInt_t flag;
333 Float_t temperature;
334 } Event;
335 Point point;
336 Event event;
337
338 // Create a ROOT Tree
339 TTree tree("T", "An example of ROOT tree with a few branches");
340 tree.Branch("point", &point, "x:y:z");
341 tree.Branch("event", &event, "ntrack/I:nseg:nvertex:flag/i:temperature/F");
342 tree.Branch("hpx", &hpx);
343
344 float px, py;
345
346 TRandom3 myGenerator;
347
348 // Here we start a loop on 1000 events
349 for (Int_t i = 0; i < 1000; i++) {
350 myGenerator.Rannor(px, py);
351 const auto random = myGenerator.Rndm(1);
352
353 // Fill histogram
354 hpx.Fill(px);
355
356 // Fill structures
357 point.x = 10 * (random - 1);
358 point.y = 5 * random;
359 point.z = 20 * random;
360 event.ntrack = int(100 * random);
361 event.nseg = int(2 * event.ntrack);
362 event.nvertex = 1;
363 event.flag = int(random + 0.5);
364 event.temperature = 20 + random;
365
366 // Fill the tree. For each event, save the 2 structures and object.
367 // In this simple example, the objects hpx, hprof and hpxpy are only slightly
368 // different from event to event. We expect a big compression factor!
369 tree.Fill();
370 }
371
372 // Save all objects in this file
373 hfile.Write();
374
375 // Close the file. Note that this is automatically done when you leave
376 // the application upon file destruction.
377 hfile.Close();
378
379 return 0;
380}
381~~~
382## TTree Diagram
383
384The following diagram shows the organisation of the federation of classes related to TTree.
385
386Begin_Macro
387../../../tutorials/legacy/tree/tree.C
388End_Macro
389*/
390
391#include <ROOT/RConfig.hxx>
392#include "TTree.h"
393
394#include "ROOT/TIOFeatures.hxx"
395#include "TArrayC.h"
396#include "TBufferFile.h"
397#include "TBaseClass.h"
398#include "TBasket.h"
399#include "TBranchClones.h"
400#include "TBranchElement.h"
401#include "TBranchObject.h"
402#include "TBranchRef.h"
403#include "TBrowser.h"
404#include "TClass.h"
405#include "TClassEdit.h"
406#include "TClonesArray.h"
407#include "TCut.h"
408#include "TDataMember.h"
409#include "TDataType.h"
410#include "TDirectory.h"
411#include "TError.h"
412#include "TEntryList.h"
413#include "TEnv.h"
414#include "TEventList.h"
415#include "TFile.h"
416#include "TFolder.h"
417#include "TFriendElement.h"
418#include "TInterpreter.h"
419#include "TLeaf.h"
420#include "TLeafB.h"
421#include "TLeafC.h"
422#include "TLeafD.h"
423#include "TLeafElement.h"
424#include "TLeafF.h"
425#include "TLeafI.h"
426#include "TLeafL.h"
427#include "TLeafObject.h"
428#include "TLeafS.h"
429#include "TList.h"
430#include "TMath.h"
431#include "TMemFile.h"
432#include "TROOT.h"
433#include "TRealData.h"
434#include "TRegexp.h"
435#include "TRefTable.h"
436#include "TStreamerElement.h"
437#include "TStreamerInfo.h"
438#include "TStyle.h"
439#include "TSystem.h"
440#include "TTreeCloner.h"
441#include "TTreeCache.h"
442#include "TTreeCacheUnzip.h"
445#include "TVirtualIndex.h"
446#include "TVirtualPerfStats.h"
447#include "TVirtualPad.h"
448#include "TBranchSTL.h"
449#include "TSchemaRuleSet.h"
450#include "TFileMergeInfo.h"
451#include "ROOT/StringConv.hxx"
452#include "TVirtualMutex.h"
453#include "strlcpy.h"
454#include "snprintf.h"
455
456#include "TBranchIMTHelper.h"
457#include "TNotifyLink.h"
458
459#include <chrono>
460#include <cstddef>
461#include <iostream>
462#include <fstream>
463#include <sstream>
464#include <string>
465#include <cstdio>
466#include <climits>
467#include <algorithm>
468#include <set>
469
470#ifdef R__USE_IMT
472#include <thread>
473#endif
475constexpr Int_t kNEntriesResort = 100;
477
478Int_t TTree::fgBranchStyle = 1; // Use new TBranch style with TBranchElement.
479Long64_t TTree::fgMaxTreeSize = 100000000000LL;
480
481
482////////////////////////////////////////////////////////////////////////////////
483////////////////////////////////////////////////////////////////////////////////
484////////////////////////////////////////////////////////////////////////////////
487{
488 // Return the leaflist 'char' for a given datatype.
489
490 switch(datatype) {
491 case kChar_t: return 'B';
492 case kUChar_t: return 'b';
493 case kBool_t: return 'O';
494 case kShort_t: return 'S';
495 case kUShort_t: return 's';
496 case kCounter:
497 case kInt_t: return 'I';
498 case kUInt_t: return 'i';
499 case kDouble_t: return 'D';
500 case kDouble32_t: return 'd';
501 case kFloat_t: return 'F';
502 case kFloat16_t: return 'f';
503 case kLong_t: return 'G';
504 case kULong_t: return 'g';
505 case kchar: return 0; // unsupported
506 case kLong64_t: return 'L';
507 case kULong64_t: return 'l';
508
509 case kCharStar: return 'C';
510 case kBits: return 0; //unsupported
511
512 case kOther_t:
513 case kNoType_t:
514 default:
515 return 0;
516 }
517 return 0;
518}
519
520////////////////////////////////////////////////////////////////////////////////
521/// \class TTree::TFriendLock
522/// Helper class to prevent infinite recursion in the usage of TTree Friends.
523
524////////////////////////////////////////////////////////////////////////////////
525/// Record in tree that it has been used while recursively looks through the friends.
528: fTree(tree)
529{
530 // We could also add some code to acquire an actual
531 // lock to prevent multi-thread issues
533 if (fTree) {
536 } else {
537 fPrevious = false;
538 }
539}
540
541////////////////////////////////////////////////////////////////////////////////
542/// Copy constructor.
545 fTree(tfl.fTree),
546 fMethodBit(tfl.fMethodBit),
547 fPrevious(tfl.fPrevious)
548{
549}
550
551////////////////////////////////////////////////////////////////////////////////
552/// Assignment operator.
555{
556 if(this!=&tfl) {
557 fTree=tfl.fTree;
558 fMethodBit=tfl.fMethodBit;
559 fPrevious=tfl.fPrevious;
560 }
561 return *this;
562}
563
564////////////////////////////////////////////////////////////////////////////////
565/// Restore the state of tree the same as before we set the lock.
568{
569 if (fTree) {
570 if (!fPrevious) {
571 fTree->fFriendLockStatus &= ~(fMethodBit & kBitMask);
572 }
573 }
574}
575
576////////////////////////////////////////////////////////////////////////////////
577/// \class TTree::TClusterIterator
578/// Helper class to iterate over cluster of baskets.
579/// \note In contrast to class TListIter, looping here must NOT be done using
580/// `while (iter())` or `while (iter.Next())` that would lead to an infinite loop, but rather using
581/// `while( (auto clusterStart = iter()) < tree->GetEntries() )`.
582/// \see TTree::GetClusterIterator
583
584////////////////////////////////////////////////////////////////////////////////
585/// Regular constructor.
586/// TTree is not set as const, since we might modify if it is a TChain.
588TTree::TClusterIterator::TClusterIterator(TTree *tree, Long64_t firstEntry) : fTree(tree), fClusterRange(0), fStartEntry(0), fNextEntry(0), fEstimatedSize(-1)
589{
590 if (fTree->fNClusterRange) {
591 // Find the correct cluster range.
592 //
593 // Since fClusterRangeEnd contains the inclusive upper end of the range, we need to search for the
594 // range that was containing the previous entry and add 1 (because BinarySearch consider the values
595 // to be the inclusive start of the bucket).
597
600 if (fClusterRange == 0) {
601 pedestal = 0;
603 } else {
606 }
610 } else {
612 }
613 if (autoflush <= 0) {
615 }
617 } else if ( fTree->GetAutoFlush() <= 0 ) {
618 // Case of old files before November 9 2009 *or* small tree where AutoFlush was never set.
620 } else {
622 }
623 fNextEntry = fStartEntry; // Position correctly for the first call to Next()
624}
625
626////////////////////////////////////////////////////////////////////////////////
627/// Estimate the cluster size.
628///
629/// In almost all cases, this quickly returns the size of the auto-flush
630/// in the TTree.
631///
632/// However, in the case where the cluster size was not fixed (old files and
633/// case where autoflush was explicitly set to zero), we need estimate
634/// a cluster size in relation to the size of the cache.
635///
636/// After this value is calculated once for the TClusterIterator, it is
637/// cached and reused in future calls.
640{
641 auto autoFlush = fTree->GetAutoFlush();
642 if (autoFlush > 0) return autoFlush;
643 if (fEstimatedSize > 0) return fEstimatedSize;
644
645 Long64_t zipBytes = fTree->GetZipBytes();
646 if (zipBytes == 0) {
647 fEstimatedSize = fTree->GetEntries() - 1;
648 if (fEstimatedSize <= 0)
649 fEstimatedSize = 1;
650 } else {
652 Long64_t cacheSize = fTree->GetCacheSize();
653 if (cacheSize == 0) {
654 // Humm ... let's double check on the file.
655 TFile *file = fTree->GetCurrentFile();
656 if (file) {
657 TFileCacheRead *cache = fTree->GetReadCache(file);
658 if (cache) {
659 cacheSize = cache->GetBufferSize();
660 }
661 }
662 }
663 // If neither file nor tree has a cache, use the current default.
664 if (cacheSize <= 0) {
665 cacheSize = 30000000;
666 }
667 clusterEstimate = fTree->GetEntries() * cacheSize / zipBytes;
668 // If there are no entries, then just default to 1.
669 fEstimatedSize = clusterEstimate ? clusterEstimate : 1;
670 }
671 return fEstimatedSize;
672}
673
674////////////////////////////////////////////////////////////////////////////////
675/// Move on to the next cluster and return the starting entry
676/// of this next cluster
679{
680 fStartEntry = fNextEntry;
681 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
682 if (fClusterRange == fTree->fNClusterRange) {
683 // We are looking at a range which size
684 // is defined by AutoFlush itself and goes to the GetEntries.
685 fNextEntry += GetEstimatedClusterSize();
686 } else {
687 if (fStartEntry > fTree->fClusterRangeEnd[fClusterRange]) {
688 ++fClusterRange;
689 }
690 if (fClusterRange == fTree->fNClusterRange) {
691 // We are looking at the last range which size
692 // is defined by AutoFlush itself and goes to the GetEntries.
693 fNextEntry += GetEstimatedClusterSize();
694 } else {
695 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
696 if (clusterSize == 0) {
697 clusterSize = GetEstimatedClusterSize();
698 }
699 fNextEntry += clusterSize;
700 if (fNextEntry > fTree->fClusterRangeEnd[fClusterRange]) {
701 // The last cluster of the range was a partial cluster,
702 // so the next cluster starts at the beginning of the
703 // next range.
704 fNextEntry = fTree->fClusterRangeEnd[fClusterRange] + 1;
705 }
706 }
707 }
708 } else {
709 // Case of old files before November 9 2009
710 fNextEntry = fStartEntry + GetEstimatedClusterSize();
711 }
712 if (fNextEntry > fTree->GetEntries()) {
713 fNextEntry = fTree->GetEntries();
714 }
715 return fStartEntry;
716}
717
718////////////////////////////////////////////////////////////////////////////////
719/// Move on to the previous cluster and return the starting entry
720/// of this previous cluster
723{
724 fNextEntry = fStartEntry;
725 if (fTree->fNClusterRange || fTree->GetAutoFlush() > 0) {
726 if (fClusterRange == 0 || fTree->fNClusterRange == 0) {
727 // We are looking at a range which size
728 // is defined by AutoFlush itself.
729 fStartEntry -= GetEstimatedClusterSize();
730 } else {
731 if (fNextEntry <= fTree->fClusterRangeEnd[fClusterRange]) {
732 --fClusterRange;
733 }
734 if (fClusterRange == 0) {
735 // We are looking at the first range.
736 fStartEntry = 0;
737 } else {
738 Long64_t clusterSize = fTree->fClusterSize[fClusterRange];
739 if (clusterSize == 0) {
740 clusterSize = GetEstimatedClusterSize();
741 }
742 fStartEntry -= clusterSize;
743 }
744 }
745 } else {
746 // Case of old files before November 9 2009 or trees that never auto-flushed.
747 fStartEntry = fNextEntry - GetEstimatedClusterSize();
748 }
749 if (fStartEntry < 0) {
750 fStartEntry = 0;
751 }
752 return fStartEntry;
753}
754
755////////////////////////////////////////////////////////////////////////////////
756////////////////////////////////////////////////////////////////////////////////
757////////////////////////////////////////////////////////////////////////////////
758
759////////////////////////////////////////////////////////////////////////////////
760/// Default constructor and I/O constructor.
761///
762/// Note: We do *not* insert ourself into the current directory.
763///
766: TNamed()
767, TAttLine()
768, TAttFill()
769, TAttMarker()
770, fEntries(0)
771, fTotBytes(0)
772, fZipBytes(0)
773, fSavedBytes(0)
774, fFlushedBytes(0)
775, fWeight(1)
777, fScanField(25)
778, fUpdate(0)
782, fMaxEntries(0)
783, fMaxEntryLoop(0)
785, fAutoSave( -300000000)
786, fAutoFlush(-30000000)
787, fEstimate(1000000)
788, fClusterRangeEnd(nullptr)
789, fClusterSize(nullptr)
790, fCacheSize(0)
791, fChainOffset(0)
792, fReadEntry(-1)
793, fTotalBuffers(0)
794, fPacketSize(100)
795, fNfill(0)
796, fDebug(0)
797, fDebugMin(0)
798, fDebugMax(9999999)
799, fMakeClass(0)
800, fFileNumber(0)
801, fNotify(nullptr)
802, fDirectory(nullptr)
803, fBranches()
804, fLeaves()
805, fAliases(nullptr)
806, fEventList(nullptr)
807, fEntryList(nullptr)
808, fIndexValues()
809, fIndex()
810, fTreeIndex(nullptr)
811, fFriends(nullptr)
812, fExternalFriends(nullptr)
813, fPerfStats(nullptr)
814, fUserInfo(nullptr)
815, fPlayer(nullptr)
816, fClones(nullptr)
817, fBranchRef(nullptr)
819, fTransientBuffer(nullptr)
823, fIMTEnabled(ROOT::IsImplicitMTEnabled())
825{
826 fMaxEntries = 1000000000;
827 fMaxEntries *= 1000;
828
829 fMaxEntryLoop = 1000000000;
830 fMaxEntryLoop *= 1000;
831
832 fBranches.SetOwner(true);
833}
834
835////////////////////////////////////////////////////////////////////////////////
836/// Normal tree constructor.
837///
838/// The tree is created in the current directory.
839/// Use the various functions Branch below to add branches to this tree.
840///
841/// If the first character of title is a "/", the function assumes a folder name.
842/// In this case, it creates automatically branches following the folder hierarchy.
843/// splitlevel may be used in this case to control the split level.
845TTree::TTree(const char* name, const char* title, Int_t splitlevel /* = 99 */,
846 TDirectory* dir /* = gDirectory*/)
847: TNamed(name, title)
848, TAttLine()
849, TAttFill()
850, TAttMarker()
851, fEntries(0)
852, fTotBytes(0)
853, fZipBytes(0)
854, fSavedBytes(0)
855, fFlushedBytes(0)
856, fWeight(1)
857, fTimerInterval(0)
858, fScanField(25)
859, fUpdate(0)
860, fDefaultEntryOffsetLen(1000)
861, fNClusterRange(0)
862, fMaxClusterRange(0)
863, fMaxEntries(0)
864, fMaxEntryLoop(0)
865, fMaxVirtualSize(0)
866, fAutoSave( -300000000)
867, fAutoFlush(-30000000)
868, fEstimate(1000000)
869, fClusterRangeEnd(nullptr)
870, fClusterSize(nullptr)
871, fCacheSize(0)
872, fChainOffset(0)
873, fReadEntry(-1)
874, fTotalBuffers(0)
875, fPacketSize(100)
876, fNfill(0)
877, fDebug(0)
878, fDebugMin(0)
879, fDebugMax(9999999)
880, fMakeClass(0)
881, fFileNumber(0)
882, fNotify(nullptr)
883, fDirectory(dir)
884, fBranches()
885, fLeaves()
886, fAliases(nullptr)
887, fEventList(nullptr)
888, fEntryList(nullptr)
889, fIndexValues()
890, fIndex()
891, fTreeIndex(nullptr)
892, fFriends(nullptr)
893, fExternalFriends(nullptr)
894, fPerfStats(nullptr)
895, fUserInfo(nullptr)
896, fPlayer(nullptr)
897, fClones(nullptr)
898, fBranchRef(nullptr)
899, fFriendLockStatus(0)
900, fTransientBuffer(nullptr)
901, fCacheDoAutoInit(true)
902, fCacheDoClusterPrefetch(false)
903, fCacheUserSet(false)
904, fIMTEnabled(ROOT::IsImplicitMTEnabled())
905, fNEntriesSinceSorting(0)
906{
907 // TAttLine state.
911
912 // TAttFill state.
915
916 // TAttMarkerState.
920
921 fMaxEntries = 1000000000;
922 fMaxEntries *= 1000;
923
924 fMaxEntryLoop = 1000000000;
925 fMaxEntryLoop *= 1000;
926
927 // Insert ourself into the current directory.
928 // FIXME: This is very annoying behaviour, we should
929 // be able to choose to not do this like we
930 // can with a histogram.
931 if (fDirectory) fDirectory->Append(this);
932
933 fBranches.SetOwner(true);
934
935 // If title starts with "/" and is a valid folder name, a superbranch
936 // is created.
937 // FIXME: Why?
938 if (strlen(title) > 2) {
939 if (title[0] == '/') {
940 Branch(title+1,32000,splitlevel);
941 }
942 }
943}
944
945////////////////////////////////////////////////////////////////////////////////
946/// Destructor.
949{
950 if (auto link = dynamic_cast<TNotifyLinkBase*>(fNotify)) {
951 link->Clear();
952 }
953 if (fAllocationCount && (gDebug > 0)) {
954 Info("TTree::~TTree", "For tree %s, allocation count is %u.", GetName(), fAllocationCount.load());
955#ifdef R__TRACK_BASKET_ALLOC_TIME
956 Info("TTree::~TTree", "For tree %s, allocation time is %lluus.", GetName(), fAllocationTime.load());
957#endif
958 }
959
960 if (fDirectory) {
961 // We are in a directory, which may possibly be a file.
962 if (fDirectory->GetList()) {
963 // Remove us from the directory listing.
964 fDirectory->Remove(this);
965 }
966 //delete the file cache if it points to this Tree
967 TFile *file = fDirectory->GetFile();
968 MoveReadCache(file,nullptr);
969 }
970
971 // Remove the TTree from any list (linked to to the list of Cleanups) to avoid the unnecessary call to
972 // this RecursiveRemove while we delete our content.
974 ResetBit(kMustCleanup); // Don't redo it.
975
976 // We don't own the leaves in fLeaves, the branches do.
977 fLeaves.Clear();
978 // I'm ready to destroy any objects allocated by
979 // SetAddress() by my branches. If I have clones,
980 // tell them to zero their pointers to this shared
981 // memory.
982 if (fClones && fClones->GetEntries()) {
983 // I have clones.
984 // I am about to delete the objects created by
985 // SetAddress() which we are sharing, so tell
986 // the clones to release their pointers to them.
987 for (TObjLink* lnk = fClones->FirstLink(); lnk; lnk = lnk->Next()) {
988 TTree* clone = (TTree*) lnk->GetObject();
989 // clone->ResetBranchAddresses();
990
991 // Reset only the branch we have set the address of.
992 CopyAddresses(clone,true);
993 }
994 }
995 // Get rid of our branches, note that this will also release
996 // any memory allocated by TBranchElement::SetAddress().
998
999 // The TBranch destructor is using fDirectory to detect whether it
1000 // owns the TFile that contains its data (See TBranch::~TBranch)
1001 fDirectory = nullptr;
1002
1003 // FIXME: We must consider what to do with the reset of these if we are a clone.
1004 delete fPlayer;
1005 fPlayer = nullptr;
1006 if (fExternalFriends) {
1007 using namespace ROOT::Detail;
1009 fetree->Reset();
1010 fExternalFriends->Clear("nodelete");
1012 }
1013 if (fFriends) {
1014 fFriends->Delete();
1015 delete fFriends;
1016 fFriends = nullptr;
1017 }
1018 if (fAliases) {
1019 fAliases->Delete();
1020 delete fAliases;
1021 fAliases = nullptr;
1022 }
1023 if (fUserInfo) {
1024 fUserInfo->Delete();
1025 delete fUserInfo;
1026 fUserInfo = nullptr;
1027 }
1028 if (fClones) {
1029 // Clone trees should no longer be removed from fClones when they are deleted.
1030 {
1032 gROOT->GetListOfCleanups()->Remove(fClones);
1033 }
1034 // Note: fClones does not own its content.
1035 delete fClones;
1036 fClones = nullptr;
1037 }
1038 if (fEntryList) {
1039 if (fEntryList->TestBit(kCanDelete) && fEntryList->GetDirectory()==nullptr) {
1040 // Delete the entry list if it is marked to be deleted and it is not also
1041 // owned by a directory. (Otherwise we would need to make sure that a
1042 // TDirectoryFile that has a TTree in it does a 'slow' TList::Delete.
1043 delete fEntryList;
1044 fEntryList=nullptr;
1045 }
1046 }
1047 delete fTreeIndex;
1048 fTreeIndex = nullptr;
1049 delete fBranchRef;
1050 fBranchRef = nullptr;
1051 delete [] fClusterRangeEnd;
1052 fClusterRangeEnd = nullptr;
1053 delete [] fClusterSize;
1054 fClusterSize = nullptr;
1055
1056 if (fTransientBuffer) {
1057 delete fTransientBuffer;
1058 fTransientBuffer = nullptr;
1059 }
1060}
1061
1062////////////////////////////////////////////////////////////////////////////////
1063/// Returns the transient buffer currently used by this TTree for reading/writing baskets.
1075}
1076
1077////////////////////////////////////////////////////////////////////////////////
1078/// Add branch with name bname to the Tree cache.
1079/// If bname="*" all branches are added to the cache.
1080/// if subbranches is true all the branches of the subbranches are
1081/// also put to the cache.
1082///
1083/// Returns:
1084/// - 0 branch added or already included
1085/// - -1 on error
1087Int_t TTree::AddBranchToCache(const char*bname, bool subbranches)
1088{
1089 if (!GetTree()) {
1090 if (LoadTree(0)<0) {
1091 Error("AddBranchToCache","Could not load a tree");
1092 return -1;
1093 }
1094 }
1095 if (GetTree()) {
1096 if (GetTree() != this) {
1097 return GetTree()->AddBranchToCache(bname, subbranches);
1098 }
1099 } else {
1100 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1101 return -1;
1102 }
1103
1104 TFile *f = GetCurrentFile();
1105 if (!f) {
1106 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1107 return -1;
1108 }
1109 TTreeCache *tc = GetReadCache(f,true);
1110 if (!tc) {
1111 Error("AddBranchToCache", "No cache is available, branch not added");
1112 return -1;
1113 }
1114 return tc->AddBranch(bname,subbranches);
1115}
1116
1117////////////////////////////////////////////////////////////////////////////////
1118/// Add branch b to the Tree cache.
1119/// if subbranches is true all the branches of the subbranches are
1120/// also put to the cache.
1121///
1122/// Returns:
1123/// - 0 branch added or already included
1124/// - -1 on error
1127{
1128 if (!GetTree()) {
1129 if (LoadTree(0)<0) {
1130 Error("AddBranchToCache","Could not load a tree");
1131 return -1;
1132 }
1133 }
1134 if (GetTree()) {
1135 if (GetTree() != this) {
1136 Int_t res = GetTree()->AddBranchToCache(b, subbranches);
1137 if (res<0) {
1138 Error("AddBranchToCache", "Error adding branch");
1139 }
1140 return res;
1141 }
1142 } else {
1143 Error("AddBranchToCache", "No tree is available. Branch was not added to the cache");
1144 return -1;
1145 }
1146
1147 TFile *f = GetCurrentFile();
1148 if (!f) {
1149 Error("AddBranchToCache", "No file is available. Branch was not added to the cache");
1150 return -1;
1151 }
1152 TTreeCache *tc = GetReadCache(f,true);
1153 if (!tc) {
1154 Error("AddBranchToCache", "No cache is available, branch not added");
1155 return -1;
1156 }
1157 return tc->AddBranch(b,subbranches);
1158}
1159
1160////////////////////////////////////////////////////////////////////////////////
1161/// Remove the branch with name 'bname' from the Tree cache.
1162/// If bname="*" all branches are removed from the cache.
1163/// if subbranches is true all the branches of the subbranches are
1164/// also removed from the cache.
1165///
1166/// Returns:
1167/// - 0 branch dropped or not in cache
1168/// - -1 on error
1170Int_t TTree::DropBranchFromCache(const char*bname, bool subbranches)
1171{
1172 if (!GetTree()) {
1173 if (LoadTree(0)<0) {
1174 Error("DropBranchFromCache","Could not load a tree");
1175 return -1;
1176 }
1177 }
1178 if (GetTree()) {
1179 if (GetTree() != this) {
1180 return GetTree()->DropBranchFromCache(bname, subbranches);
1181 }
1182 } else {
1183 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1184 return -1;
1185 }
1186
1187 TFile *f = GetCurrentFile();
1188 if (!f) {
1189 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1190 return -1;
1191 }
1192 TTreeCache *tc = GetReadCache(f,true);
1193 if (!tc) {
1194 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1195 return -1;
1196 }
1197 return tc->DropBranch(bname,subbranches);
1198}
1199
1200////////////////////////////////////////////////////////////////////////////////
1201/// Remove the branch b from the Tree cache.
1202/// if subbranches is true all the branches of the subbranches are
1203/// also removed from the cache.
1204///
1205/// Returns:
1206/// - 0 branch dropped or not in cache
1207/// - -1 on error
1210{
1211 if (!GetTree()) {
1212 if (LoadTree(0)<0) {
1213 Error("DropBranchFromCache","Could not load a tree");
1214 return -1;
1215 }
1216 }
1217 if (GetTree()) {
1218 if (GetTree() != this) {
1219 Int_t res = GetTree()->DropBranchFromCache(b, subbranches);
1220 if (res<0) {
1221 Error("DropBranchFromCache", "Error dropping branch");
1222 }
1223 return res;
1224 }
1225 } else {
1226 Error("DropBranchFromCache", "No tree is available. Branch was not dropped from the cache");
1227 return -1;
1228 }
1229
1230 TFile *f = GetCurrentFile();
1231 if (!f) {
1232 Error("DropBranchFromCache", "No file is available. Branch was not dropped from the cache");
1233 return -1;
1234 }
1235 TTreeCache *tc = GetReadCache(f,true);
1236 if (!tc) {
1237 Error("DropBranchFromCache", "No cache is available, branch not dropped");
1238 return -1;
1239 }
1240 return tc->DropBranch(b,subbranches);
1241}
1242
1243////////////////////////////////////////////////////////////////////////////////
1244/// Add a cloned tree to our list of trees to be notified whenever we change
1245/// our branch addresses or when we are deleted.
1247void TTree::AddClone(TTree* clone)
1248{
1249 if (!fClones) {
1250 fClones = new TList();
1251 fClones->SetOwner(false);
1252 // So that the clones are automatically removed from the list when
1253 // they are deleted.
1254 {
1256 gROOT->GetListOfCleanups()->Add(fClones);
1257 }
1258 }
1259 if (!fClones->FindObject(clone)) {
1260 fClones->Add(clone);
1261 }
1262}
1263
1264// Check whether mainTree and friendTree can be friends w.r.t. the kEntriesReshuffled bit.
1265// In particular, if any has the bit set, then friendTree must have a TTreeIndex and the
1266// branches used for indexing must be present in mainTree.
1267// Return true if the trees can be friends, false otherwise.
1269{
1272 const auto friendHasValidIndex = [&] {
1273 auto idx = friendTree.GetTreeIndex();
1274 return idx ? idx->IsValidFor(&mainTree) : false;
1275 }();
1276
1278 const auto reshuffledTreeName = isMainReshuffled ? mainTree.GetName() : friendTree.GetName();
1279 const auto msg =
1280 "Tree '%s' has the kEntriesReshuffled bit set and cannot have friends nor can be added as a friend unless the "
1281 "main tree has a TTreeIndex on the friend tree '%s'. You can also unset the bit manually if you know what you "
1282 "are doing; note that you risk associating wrong TTree entries of the friend with those of the main TTree!";
1283 Error("AddFriend", msg, reshuffledTreeName, friendTree.GetName());
1284 return false;
1285 }
1286 return true;
1287}
1288
1289////////////////////////////////////////////////////////////////////////////////
1290/// Add a TFriendElement to the list of friends.
1291///
1292/// This function:
1293/// - opens a file if filename is specified
1294/// - reads a Tree with name treename from the file (current directory)
1295/// - adds the Tree to the list of friends
1296/// see other AddFriend functions
1297///
1298/// A TFriendElement TF describes a TTree object TF in a file.
1299/// When a TFriendElement TF is added to the list of friends of an
1300/// existing TTree T, any variable from TF can be referenced in a query
1301/// to T.
1302///
1303/// A tree keeps a list of friends. In the context of a tree (or a chain),
1304/// friendship means unrestricted access to the friends data. In this way
1305/// it is much like adding another branch to the tree without taking the risk
1306/// of damaging it. To add a friend to the list, you can use the TTree::AddFriend
1307/// method. The tree in the diagram below has two friends (friend_tree1 and
1308/// friend_tree2) and now has access to the variables a,b,c,i,j,k,l and m.
1309///
1310/// \image html ttree_friend1.png
1311///
1312/// The AddFriend method has two parameters, the first is the tree name and the
1313/// second is the name of the ROOT file where the friend tree is saved.
1314/// AddFriend automatically opens the friend file. If no file name is given,
1315/// the tree called ft1 is assumed to be in the same file as the original tree.
1316///
1317/// tree.AddFriend("ft1","friendfile1.root");
1318/// If the friend tree has the same name as the original tree, you can give it
1319/// an alias in the context of the friendship:
1320///
1321/// tree.AddFriend("tree1 = tree","friendfile1.root");
1322/// Once the tree has friends, we can use TTree::Draw as if the friend's
1323/// variables were in the original tree. To specify which tree to use in
1324/// the Draw method, use the syntax:
1325/// ~~~ {.cpp}
1326/// <treeName>.<branchname>.<varname>
1327/// ~~~
1328/// If the variablename is enough to uniquely identify the variable, you can
1329/// leave out the tree and/or branch name.
1330/// For example, these commands generate a 3-d scatter plot of variable "var"
1331/// in the TTree tree versus variable v1 in TTree ft1 versus variable v2 in
1332/// TTree ft2.
1333/// ~~~ {.cpp}
1334/// tree.AddFriend("ft1","friendfile1.root");
1335/// tree.AddFriend("ft2","friendfile2.root");
1336/// tree.Draw("var:ft1.v1:ft2.v2");
1337/// ~~~
1338/// \image html ttree_friend2.png
1339///
1340/// The picture illustrates the access of the tree and its friends with a
1341/// Draw command.
1342/// When AddFriend is called, the ROOT file is automatically opened and the
1343/// friend tree (ft1) is read into memory. The new friend (ft1) is added to
1344/// the list of friends of tree.
1345/// The number of entries in the friend must be equal or greater to the number
1346/// of entries of the original tree. If the friend tree has fewer entries a
1347/// warning is given and the missing entries are not included in the histogram.
1348/// To retrieve the list of friends from a tree use TTree::GetListOfFriends.
1349/// When the tree is written to file (TTree::Write), the friends list is saved
1350/// with it. And when the tree is retrieved, the trees on the friends list are
1351/// also retrieved and the friendship restored.
1352/// When a tree is deleted, the elements of the friend list are also deleted.
1353/// It is possible to declare a friend tree that has the same internal
1354/// structure (same branches and leaves) as the original tree, and compare the
1355/// same values by specifying the tree.
1356/// ~~~ {.cpp}
1357/// tree.Draw("var:ft1.var:ft2.var")
1358/// ~~~
1360TFriendElement *TTree::AddFriend(const char *treename, const char *filename)
1361{
1362 if (!fFriends) {
1363 fFriends = new TList();
1364 }
1366
1367 TTree *t = fe->GetTree();
1368 bool canAddFriend = true;
1369 if (t) {
1370 canAddFriend = CheckReshuffling(*this, *t);
1371 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1372 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent Tree: %lld", treename,
1374 }
1375 } else {
1376 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, filename);
1377 canAddFriend = false;
1378 }
1379
1380 if (canAddFriend)
1381 fFriends->Add(fe);
1382 return fe;
1383}
1384
1385////////////////////////////////////////////////////////////////////////////////
1386/// Add a TFriendElement to the list of friends.
1387///
1388/// The TFile is managed by the user (e.g. the user must delete the file).
1389/// For complete description see AddFriend(const char *, const char *).
1390/// This function:
1391/// - reads a Tree with name treename from the file
1392/// - adds the Tree to the list of friends
1394TFriendElement *TTree::AddFriend(const char *treename, TFile *file)
1395{
1396 if (!fFriends) {
1397 fFriends = new TList();
1398 }
1399 TFriendElement *fe = new TFriendElement(this, treename, file);
1400 R__ASSERT(fe);
1401 TTree *t = fe->GetTree();
1402 bool canAddFriend = true;
1403 if (t) {
1404 canAddFriend = CheckReshuffling(*this, *t);
1405 if (!t->GetTreeIndex() && (t->GetEntries() < fEntries)) {
1406 Warning("AddFriend", "FriendElement %s in file %s has less entries %lld than its parent tree: %lld", treename,
1407 file->GetName(), t->GetEntries(), fEntries);
1408 }
1409 } else {
1410 Error("AddFriend", "Cannot find tree '%s' in file '%s', friend not added", treename, file->GetName());
1411 canAddFriend = false;
1412 }
1413
1414 if (canAddFriend)
1415 fFriends->Add(fe);
1416 return fe;
1417}
1418
1419////////////////////////////////////////////////////////////////////////////////
1420/// Add a TFriendElement to the list of friends.
1421///
1422/// The TTree is managed by the user (e.g., the user must delete the file).
1423/// For a complete description see AddFriend(const char *, const char *).
1425TFriendElement *TTree::AddFriend(TTree *tree, const char *alias, bool warn)
1426{
1427 if (!tree) {
1428 return nullptr;
1429 }
1430 if (!fFriends) {
1431 fFriends = new TList();
1432 }
1433 TFriendElement *fe = new TFriendElement(this, tree, alias);
1434 R__ASSERT(fe); // this assert is for historical reasons. Don't remove it unless you understand all the consequences.
1435 TTree *t = fe->GetTree();
1436 if (warn && (t->GetEntries() < fEntries)) {
1437 Warning("AddFriend", "FriendElement '%s' in file '%s' has less entries %lld than its parent tree: %lld",
1438 tree->GetName(), fe->GetFile() ? fe->GetFile()->GetName() : "(memory resident)", t->GetEntries(),
1439 fEntries);
1440 }
1441 if (CheckReshuffling(*this, *t))
1442 fFriends->Add(fe);
1443 else
1444 tree->RemoveExternalFriend(fe);
1445 return fe;
1446}
1447
1448////////////////////////////////////////////////////////////////////////////////
1449/// AutoSave tree header every fAutoSave bytes.
1450///
1451/// When large Trees are produced, it is safe to activate the AutoSave
1452/// procedure. Some branches may have buffers holding many entries.
1453/// If fAutoSave is negative, AutoSave is automatically called by
1454/// TTree::Fill when the number of bytes generated since the previous
1455/// AutoSave is greater than -fAutoSave bytes.
1456/// If fAutoSave is positive, AutoSave is automatically called by
1457/// TTree::Fill every N entries.
1458/// This function may also be invoked by the user.
1459/// Each AutoSave generates a new key on the file.
1460/// Once the key with the tree header has been written, the previous cycle
1461/// (if any) is deleted.
1462///
1463/// Note that calling TTree::AutoSave too frequently (or similarly calling
1464/// TTree::SetAutoSave with a small value) is an expensive operation.
1465/// You should make tests for your own application to find a compromise
1466/// between speed and the quantity of information you may loose in case of
1467/// a job crash.
1468///
1469/// In case your program crashes before closing the file holding this tree,
1470/// the file will be automatically recovered when you will connect the file
1471/// in UPDATE mode.
1472/// The Tree will be recovered at the status corresponding to the last AutoSave.
1473///
1474/// if option contains "SaveSelf", gDirectory->SaveSelf() is called.
1475/// This allows another process to analyze the Tree while the Tree is being filled.
1476///
1477/// if option contains "FlushBaskets", TTree::FlushBaskets is called and all
1478/// the current basket are closed-out and written to disk individually.
1479///
1480/// By default the previous header is deleted after having written the new header.
1481/// if option contains "Overwrite", the previous Tree header is deleted
1482/// before written the new header. This option is slightly faster, but
1483/// the default option is safer in case of a problem (disk quota exceeded)
1484/// when writing the new header.
1485///
1486/// The function returns the number of bytes written to the file.
1487/// if the number of bytes is null, an error has occurred while writing
1488/// the header to the file.
1489///
1490/// ## How to write a Tree in one process and view it from another process
1491///
1492/// The following two scripts illustrate how to do this.
1493/// The script treew.C is executed by process1, treer.C by process2
1494///
1495/// script treew.C:
1496/// ~~~ {.cpp}
1497/// void treew() {
1498/// TFile f("test.root","recreate");
1499/// TNtuple *ntuple = new TNtuple("ntuple","Demo","px:py:pz:random:i");
1500/// Float_t px, py, pz;
1501/// for ( Int_t i=0; i<10000000; i++) {
1502/// gRandom->Rannor(px,py);
1503/// pz = px*px + py*py;
1504/// Float_t random = gRandom->Rndm(1);
1505/// ntuple->Fill(px,py,pz,random,i);
1506/// if (i%1000 == 1) ntuple->AutoSave("SaveSelf");
1507/// }
1508/// }
1509/// ~~~
1510/// script treer.C:
1511/// ~~~ {.cpp}
1512/// void treer() {
1513/// TFile f("test.root");
1514/// TTree *ntuple = (TTree*)f.Get("ntuple");
1515/// TCanvas c1;
1516/// Int_t first = 0;
1517/// while(1) {
1518/// if (first == 0) ntuple->Draw("px>>hpx", "","",10000000,first);
1519/// else ntuple->Draw("px>>+hpx","","",10000000,first);
1520/// first = (Int_t)ntuple->GetEntries();
1521/// c1.Update();
1522/// gSystem->Sleep(1000); //sleep 1 second
1523/// ntuple->Refresh();
1524/// }
1525/// }
1526/// ~~~
1529{
1530 if (!fDirectory || fDirectory == gROOT || !fDirectory->IsWritable()) return 0;
1531 if (gDebug > 0) {
1532 Info("AutoSave", "Tree:%s after %lld bytes written\n",GetName(),GetTotBytes());
1533 }
1534 TString opt = option;
1535 opt.ToLower();
1536
1537 if (opt.Contains("flushbaskets")) {
1538 if (gDebug > 0) Info("AutoSave", "calling FlushBaskets \n");
1540 }
1541
1543
1544 TKey *key = (TKey*)fDirectory->GetListOfKeys()->FindObject(GetName());
1546 if (opt.Contains("overwrite")) {
1547 nbytes = fDirectory->WriteTObject(this,"","overwrite");
1548 } else {
1549 nbytes = fDirectory->WriteTObject(this); //nbytes will be 0 if Write failed (disk space exceeded)
1550 if (nbytes && key && strcmp(ClassName(), key->GetClassName()) == 0) {
1551 key->Delete();
1552 delete key;
1553 }
1554 }
1555 // save StreamerInfo
1556 TFile *file = fDirectory->GetFile();
1557 if (file) file->WriteStreamerInfo();
1558
1559 if (opt.Contains("saveself")) {
1561 //the following line is required in case GetUserInfo contains a user class
1562 //for which the StreamerInfo must be written. One could probably be a bit faster (Rene)
1563 if (file) file->WriteHeader();
1564 }
1565
1566 return nbytes;
1567}
1568
1569namespace {
1570 // This error message is repeated several times in the code. We write it once.
1571 const char* writeStlWithoutProxyMsg = "The class requested (%s) for the branch \"%s\""
1572 " is an instance of an stl collection and does not have a compiled CollectionProxy."
1573 " Please generate the dictionary for this collection (%s) to avoid to write corrupted data.";
1574}
1575
1576////////////////////////////////////////////////////////////////////////////////
1577/// Same as TTree::Branch() with added check that addobj matches className.
1578///
1579/// \see TTree::Branch()
1580///
1582TBranch* TTree::BranchImp(const char* branchname, const char* classname, TClass* ptrClass, void* addobj, Int_t bufsize, Int_t splitlevel)
1583{
1584 TClass* claim = TClass::GetClass(classname);
1585 if (!ptrClass) {
1586 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1588 claim->GetName(), branchname, claim->GetName());
1589 return nullptr;
1590 }
1591 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1592 }
1593 TClass* actualClass = nullptr;
1594 void** addr = (void**) addobj;
1595 if (addr) {
1596 actualClass = ptrClass->GetActualClass(*addr);
1597 }
1598 if (ptrClass && claim) {
1599 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1600 // Note we currently do not warn in case of splicing or over-expectation).
1601 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1602 // The type is the same according to the C++ type_info, we must be in the case of
1603 // a template of Double32_t. This is actually a correct case.
1604 } else {
1605 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the pointer passed (%s)",
1606 claim->GetName(), branchname, ptrClass->GetName());
1607 }
1608 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1609 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1610 // The type is the same according to the C++ type_info, we must be in the case of
1611 // a template of Double32_t. This is actually a correct case.
1612 } else {
1613 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1614 actualClass->GetName(), branchname, claim->GetName());
1615 }
1616 }
1617 }
1618 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1620 claim->GetName(), branchname, claim->GetName());
1621 return nullptr;
1622 }
1623 return Branch(branchname, classname, (void*) addobj, bufsize, splitlevel);
1624}
1625
1626////////////////////////////////////////////////////////////////////////////////
1627/// Same as TTree::Branch but automatic detection of the class name.
1628/// \see TTree::Branch
1631{
1632 if (!ptrClass) {
1633 Error("Branch", "The pointer specified for %s is not of a class known to ROOT", branchname);
1634 return nullptr;
1635 }
1636 TClass* actualClass = nullptr;
1637 void** addr = (void**) addobj;
1638 if (addr && *addr) {
1639 actualClass = ptrClass->GetActualClass(*addr);
1640 if (!actualClass) {
1641 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",
1642 branchname, ptrClass->GetName());
1644 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1645 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());
1646 return nullptr;
1647 }
1648 } else {
1650 }
1651 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1653 actualClass->GetName(), branchname, actualClass->GetName());
1654 return nullptr;
1655 }
1656 return Branch(branchname, actualClass->GetName(), (void*) addobj, bufsize, splitlevel);
1657}
1658
1659////////////////////////////////////////////////////////////////////////////////
1660/// Same as TTree::Branch but automatic detection of the class name.
1661/// \see TTree::Branch
1663TBranch* TTree::BranchImpRef(const char* branchname, const char *classname, TClass* ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel)
1664{
1665 TClass* claim = TClass::GetClass(classname);
1666 if (!ptrClass) {
1667 if (claim && claim->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(claim->GetCollectionProxy())) {
1669 claim->GetName(), branchname, claim->GetName());
1670 return nullptr;
1671 } else if (claim == nullptr) {
1672 Error("Branch", "The pointer specified for %s is not of a class known to ROOT and %s is not a known class", branchname, classname);
1673 return nullptr;
1674 }
1675 ptrClass = claim;
1676 }
1677 TClass* actualClass = nullptr;
1678 if (!addobj) {
1679 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1680 return nullptr;
1681 }
1682 actualClass = ptrClass->GetActualClass(addobj);
1683 if (ptrClass && claim) {
1684 if (!(claim->InheritsFrom(ptrClass) || ptrClass->InheritsFrom(claim))) {
1685 // Note we currently do not warn in case of splicing or over-expectation).
1686 if (claim->IsLoaded() && ptrClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), ptrClass->GetTypeInfo()->name() ) == 0) {
1687 // The type is the same according to the C++ type_info, we must be in the case of
1688 // a template of Double32_t. This is actually a correct case.
1689 } else {
1690 Error("Branch", "The class requested (%s) for \"%s\" is different from the type of the object passed (%s)",
1691 claim->GetName(), branchname, ptrClass->GetName());
1692 }
1693 } else if (actualClass && (claim != actualClass) && !actualClass->InheritsFrom(claim)) {
1694 if (claim->IsLoaded() && actualClass->IsLoaded() && strcmp( claim->GetTypeInfo()->name(), actualClass->GetTypeInfo()->name() ) == 0) {
1695 // The type is the same according to the C++ type_info, we must be in the case of
1696 // a template of Double32_t. This is actually a correct case.
1697 } else {
1698 Error("Branch", "The actual class (%s) of the object provided for the definition of the branch \"%s\" does not inherit from %s",
1699 actualClass->GetName(), branchname, claim->GetName());
1700 }
1701 }
1702 }
1703 if (!actualClass) {
1704 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",
1705 branchname, ptrClass->GetName());
1707 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1708 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());
1709 return nullptr;
1710 }
1711 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1713 actualClass->GetName(), branchname, actualClass->GetName());
1714 return nullptr;
1715 }
1716 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, false, bufsize, splitlevel);
1717}
1718
1719////////////////////////////////////////////////////////////////////////////////
1720/// Same as TTree::Branch but automatic detection of the class name.
1721/// \see TTree::Branch
1724{
1725 if (!ptrClass) {
1726 if (datatype == kOther_t || datatype == kNoType_t) {
1727 Error("Branch", "The pointer specified for %s is not of a class or type known to ROOT", branchname);
1728 } else {
1730 return Branch(branchname,addobj,varname.Data(),bufsize);
1731 }
1732 return nullptr;
1733 }
1734 TClass* actualClass = nullptr;
1735 if (!addobj) {
1736 Error("Branch", "Reference interface requires a valid object (for branch: %s)!", branchname);
1737 return nullptr;
1738 }
1739 actualClass = ptrClass->GetActualClass(addobj);
1740 if (!actualClass) {
1741 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",
1742 branchname, ptrClass->GetName());
1744 } else if ((ptrClass != actualClass) && !actualClass->InheritsFrom(ptrClass)) {
1745 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());
1746 return nullptr;
1747 }
1748 if (actualClass && actualClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(actualClass->GetCollectionProxy())) {
1750 actualClass->GetName(), branchname, actualClass->GetName());
1751 return nullptr;
1752 }
1753 return BronchExec(branchname, actualClass->GetName(), (void*) addobj, false, bufsize, splitlevel);
1754}
1755
1756////////////////////////////////////////////////////////////////////////////////
1757// Wrapper to turn Branch call with an std::array into the relevant leaf list
1758// call
1759TBranch *TTree::BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize,
1760 Int_t /* splitlevel */)
1761{
1762 if (datatype == kOther_t || datatype == kNoType_t) {
1763 Error("Branch",
1764 "The inner type of the std::array passed specified for %s is not of a class or type known to ROOT",
1765 branchname);
1766 } else {
1768 varname.Form("%s[%d]/%c", branchname, (int)N, DataTypeToChar(datatype));
1769 return Branch(branchname, addobj, varname.Data(), bufsize);
1770 }
1771 return nullptr;
1772}
1773
1774////////////////////////////////////////////////////////////////////////////////
1775/// Deprecated function. Use next function instead.
1777Int_t TTree::Branch(TList* li, Int_t bufsize /* = 32000 */ , Int_t splitlevel /* = 99 */)
1778{
1779 return Branch((TCollection*) li, bufsize, splitlevel);
1780}
1781
1782////////////////////////////////////////////////////////////////////////////////
1783/// Create one branch for each element in the collection.
1784///
1785/// Each entry in the collection becomes a top level branch if the
1786/// corresponding class is not a collection. If it is a collection, the entry
1787/// in the collection becomes in turn top level branches, etc.
1788/// The splitlevel is decreased by 1 every time a new collection is found.
1789/// For example if list is a TObjArray*
1790/// - if splitlevel = 1, one top level branch is created for each element
1791/// of the TObjArray.
1792/// - if splitlevel = 2, one top level branch is created for each array element.
1793/// if, in turn, one of the array elements is a TCollection, one top level
1794/// branch will be created for each element of this collection.
1795///
1796/// In case a collection element is a TClonesArray, the special Tree constructor
1797/// for TClonesArray is called.
1798/// The collection itself cannot be a TClonesArray.
1799///
1800/// The function returns the total number of branches created.
1801///
1802/// If name is given, all branch names will be prefixed with name_.
1803///
1804/// IMPORTANT NOTE1: This function should not be called with splitlevel < 1.
1805///
1806/// IMPORTANT NOTE2: The branches created by this function will have names
1807/// corresponding to the collection or object names. It is important
1808/// to give names to collections to avoid misleading branch names or
1809/// identical branch names. By default collections have a name equal to
1810/// the corresponding class name, e.g. the default name for a TList is "TList".
1811///
1812/// And in general, in case two or more master branches contain subbranches
1813/// with identical names, one must add a "." (dot) character at the end
1814/// of the master branch name. This will force the name of the subbranches
1815/// to be of the form `master.subbranch` instead of simply `subbranch`.
1816/// This situation happens when the top level object
1817/// has two or more members referencing the same class.
1818/// Without the dot, the prefix will not be there and that might cause ambiguities.
1819/// For example, if a Tree has two branches B1 and B2 corresponding
1820/// to objects of the same class MyClass, one can do:
1821/// ~~~ {.cpp}
1822/// tree.Branch("B1.","MyClass",&b1,8000,1);
1823/// tree.Branch("B2.","MyClass",&b2,8000,1);
1824/// ~~~
1825/// if MyClass has 3 members a,b,c, the two instructions above will generate
1826/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
1827/// In other words, the trailing dot of the branch name is semantically relevant
1828/// and recommended.
1829///
1830/// Example:
1831/// ~~~ {.cpp}
1832/// {
1833/// TTree T("T","test list");
1834/// TList *list = new TList();
1835///
1836/// TObjArray *a1 = new TObjArray();
1837/// a1->SetName("a1");
1838/// list->Add(a1);
1839/// TH1F *ha1a = new TH1F("ha1a","ha1",100,0,1);
1840/// TH1F *ha1b = new TH1F("ha1b","ha1",100,0,1);
1841/// a1->Add(ha1a);
1842/// a1->Add(ha1b);
1843/// TObjArray *b1 = new TObjArray();
1844/// b1->SetName("b1");
1845/// list->Add(b1);
1846/// TH1F *hb1a = new TH1F("hb1a","hb1",100,0,1);
1847/// TH1F *hb1b = new TH1F("hb1b","hb1",100,0,1);
1848/// b1->Add(hb1a);
1849/// b1->Add(hb1b);
1850///
1851/// TObjArray *a2 = new TObjArray();
1852/// a2->SetName("a2");
1853/// list->Add(a2);
1854/// TH1S *ha2a = new TH1S("ha2a","ha2",100,0,1);
1855/// TH1S *ha2b = new TH1S("ha2b","ha2",100,0,1);
1856/// a2->Add(ha2a);
1857/// a2->Add(ha2b);
1858///
1859/// T.Branch(list,16000,2);
1860/// T.Print();
1861/// }
1862/// ~~~
1864Int_t TTree::Branch(TCollection* li, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */, const char* name /* = "" */)
1865{
1866
1867 if (!li) {
1868 return 0;
1869 }
1870 TObject* obj = nullptr;
1871 Int_t nbranches = GetListOfBranches()->GetEntries();
1872 if (li->InheritsFrom(TClonesArray::Class())) {
1873 Error("Branch", "Cannot call this constructor for a TClonesArray");
1874 return 0;
1875 }
1876 Int_t nch = strlen(name);
1878 TIter next(li);
1879 while ((obj = next())) {
1881 TCollection* col = (TCollection*) obj;
1882 if (nch) {
1883 branchname.Form("%s_%s_", name, col->GetName());
1884 } else {
1885 branchname.Form("%s_", col->GetName());
1886 }
1887 Branch(col, bufsize, splitlevel - 1, branchname);
1888 } else {
1889 if (nch && (name[nch-1] == '_')) {
1890 branchname.Form("%s%s", name, obj->GetName());
1891 } else {
1892 if (nch) {
1893 branchname.Form("%s_%s", name, obj->GetName());
1894 } else {
1895 branchname.Form("%s", obj->GetName());
1896 }
1897 }
1898 if (splitlevel > 99) {
1899 branchname += ".";
1900 }
1901 Bronch(branchname, obj->ClassName(), li->GetObjectRef(obj), bufsize, splitlevel - 1);
1902 }
1903 }
1904 return GetListOfBranches()->GetEntries() - nbranches;
1905}
1906
1907////////////////////////////////////////////////////////////////////////////////
1908/// Create one branch for each element in the folder.
1909/// Returns the total number of branches created.
1911Int_t TTree::Branch(const char* foldername, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
1912{
1913 TObject* ob = gROOT->FindObjectAny(foldername);
1914 if (!ob) {
1915 return 0;
1916 }
1917 if (ob->IsA() != TFolder::Class()) {
1918 return 0;
1919 }
1920 Int_t nbranches = GetListOfBranches()->GetEntries();
1921 TFolder* folder = (TFolder*) ob;
1922 TIter next(folder->GetListOfFolders());
1923 TObject* obj = nullptr;
1924 char* curname = new char[1000];
1925 char occur[20];
1926 while ((obj = next())) {
1927 snprintf(curname,1000, "%s/%s", foldername, obj->GetName());
1928 if (obj->IsA() == TFolder::Class()) {
1930 } else {
1931 void* add = (void*) folder->GetListOfFolders()->GetObjectRef(obj);
1932 for (Int_t i = 0; i < 1000; ++i) {
1933 if (curname[i] == 0) {
1934 break;
1935 }
1936 if (curname[i] == '/') {
1937 curname[i] = '.';
1938 }
1939 }
1940 Int_t noccur = folder->Occurence(obj);
1941 if (noccur > 0) {
1942 snprintf(occur,20, "_%d", noccur);
1943 strlcat(curname, occur,1000);
1944 }
1946 if (br) br->SetBranchFolder();
1947 }
1948 }
1949 delete[] curname;
1950 return GetListOfBranches()->GetEntries() - nbranches;
1951}
1952
1953////////////////////////////////////////////////////////////////////////////////
1954/// Create a new TTree Branch.
1955///
1956/// This Branch constructor is provided to support non-objects in
1957/// a Tree. The variables described in leaflist may be simple
1958/// variables or structures. // See the two following
1959/// constructors for writing objects in a Tree.
1960///
1961/// By default the branch buffers are stored in the same file as the Tree.
1962/// use TBranch::SetFile to specify a different file
1963///
1964/// * address is the address of the first item of a structure.
1965/// * leaflist is the concatenation of all the variable names and types
1966/// separated by a colon character :
1967/// The variable name and the variable type are separated by a slash (/).
1968/// The variable type may be 0,1 or 2 characters. If no type is given,
1969/// the type of the variable is assumed to be the same as the previous
1970/// variable. If the first variable does not have a type, it is assumed
1971/// of type `F` by default. The list of currently supported types is given below:
1972/// - `C` : a character string terminated by the 0 character
1973/// - `B` : an 8 bit integer (`Char_t`); Mostly signed, might be unsigned in special platforms or depending on compiler flags, thus do not use std::int8_t as underlying variable since they are not equivalent; Treated as a character when in an array.
1974/// - `b` : an 8 bit unsigned integer (`UChar_t`)
1975/// - `S` : a 16 bit signed integer (`Short_t`)
1976/// - `s` : a 16 bit unsigned integer (`UShort_t`)
1977/// - `I` : a 32 bit signed integer (`Int_t`)
1978/// - `i` : a 32 bit unsigned integer (`UInt_t`)
1979/// - `F` : a 32 bit floating point (`Float_t`)
1980/// - `f` : a 24 bit floating point with truncated mantissa (`Float16_t`)
1981/// - `D` : a 64 bit floating point (`Double_t`)
1982/// - `d` : a 24 bit truncated floating point (`Double32_t`)
1983/// - `L` : a 64 bit signed integer (`Long64_t`)
1984/// - `l` : a 64 bit unsigned integer (`ULong64_t`)
1985/// - `G` : a long signed integer, stored as 64 bit (`Long_t`)
1986/// - `g` : a long unsigned integer, stored as 64 bit (`ULong_t`)
1987/// - `O` : [the letter `o`, not a zero] a boolean (`bool`)
1988///
1989/// Arrays of values are supported with the following syntax:
1990/// - If leaf name has the form var[nelem], where nelem is alphanumeric, then
1991/// if nelem is a leaf name, it is used as the variable size of the array,
1992/// otherwise return 0.
1993/// The leaf referred to by nelem **MUST** be an int (/I),
1994/// - If leaf name has the form var[nelem], where nelem is a non-negative integer, then
1995/// it is used as the fixed size of the array.
1996/// - If leaf name has the form of a multi-dimensional array (e.g. var[nelem][nelem2])
1997/// where nelem and nelem2 are non-negative integer) then
1998/// it is used as a 2 dimensional array of fixed size.
1999/// - In case of the truncated floating point types (Float16_t and Double32_t) you can
2000/// furthermore specify the range in the style [xmin,xmax] or [xmin,xmax,nbits] after
2001/// the type character. See `TStreamerElement::GetRange()` for further information.
2002///
2003/// Any of other form is not supported.
2004///
2005/// Note that the TTree will assume that all the item are contiguous in memory.
2006/// On some platform, this is not always true of the member of a struct or a class,
2007/// due to padding and alignment. Sorting your data member in order of decreasing
2008/// sizeof usually leads to their being contiguous in memory.
2009///
2010/// * bufsize is the buffer size in bytes for this branch
2011/// The default value is 32000 bytes and should be ok for most cases.
2012/// You can specify a larger value (e.g. 256000) if your Tree is not split
2013/// and each entry is large (Megabytes)
2014/// A small value for bufsize is optimum if you intend to access
2015/// the entries in the Tree randomly and your Tree is in split mode.
2017TBranch* TTree::Branch(const char* name, void* address, const char* leaflist, Int_t bufsize /* = 32000 */)
2018{
2019 TBranch* branch = new TBranch(this, name, address, leaflist, bufsize);
2020 if (branch->IsZombie()) {
2021 delete branch;
2022 branch = nullptr;
2023 return nullptr;
2024 }
2026 return branch;
2027}
2028
2029////////////////////////////////////////////////////////////////////////////////
2030/// Create a new branch with the object of class classname at address addobj.
2031///
2032/// WARNING:
2033///
2034/// Starting with Root version 3.01, the Branch function uses the new style
2035/// branches (TBranchElement). To get the old behaviour, you can:
2036/// - call BranchOld or
2037/// - call TTree::SetBranchStyle(0)
2038///
2039/// Note that with the new style, classname does not need to derive from TObject.
2040/// It must derived from TObject if the branch style has been set to 0 (old)
2041///
2042/// Note: See the comments in TBranchElement::SetAddress() for a more
2043/// detailed discussion of the meaning of the addobj parameter in
2044/// the case of new-style branches.
2045///
2046/// Use splitlevel < 0 instead of splitlevel=0 when the class
2047/// has a custom Streamer
2048///
2049/// Note: if the split level is set to the default (99), TTree::Branch will
2050/// not issue a warning if the class can not be split.
2052TBranch* TTree::Branch(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2053{
2054 if (fgBranchStyle == 1) {
2055 return Bronch(name, classname, addobj, bufsize, splitlevel);
2056 } else {
2057 if (splitlevel < 0) {
2058 splitlevel = 0;
2059 }
2060 return BranchOld(name, classname, addobj, bufsize, splitlevel);
2061 }
2062}
2063
2064////////////////////////////////////////////////////////////////////////////////
2065/// Create a new TTree BranchObject.
2066///
2067/// Build a TBranchObject for an object of class classname.
2068/// addobj is the address of a pointer to an object of class classname.
2069/// IMPORTANT: classname must derive from TObject.
2070/// The class dictionary must be available (ClassDef in class header).
2071///
2072/// This option requires access to the library where the corresponding class
2073/// is defined. Accessing one single data member in the object implies
2074/// reading the full object.
2075/// See the next Branch constructor for a more efficient storage
2076/// in case the entry consists of arrays of identical objects.
2077///
2078/// By default the branch buffers are stored in the same file as the Tree.
2079/// use TBranch::SetFile to specify a different file
2080///
2081/// IMPORTANT NOTE about branch names:
2082///
2083/// And in general, in case two or more master branches contain subbranches
2084/// with identical names, one must add a "." (dot) character at the end
2085/// of the master branch name. This will force the name of the subbranches
2086/// to be of the form `master.subbranch` instead of simply `subbranch`.
2087/// This situation happens when the top level object
2088/// has two or more members referencing the same class.
2089/// For example, if a Tree has two branches B1 and B2 corresponding
2090/// to objects of the same class MyClass, one can do:
2091/// ~~~ {.cpp}
2092/// tree.Branch("B1.","MyClass",&b1,8000,1);
2093/// tree.Branch("B2.","MyClass",&b2,8000,1);
2094/// ~~~
2095/// if MyClass has 3 members a,b,c, the two instructions above will generate
2096/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2097///
2098/// bufsize is the buffer size in bytes for this branch
2099/// The default value is 32000 bytes and should be ok for most cases.
2100/// You can specify a larger value (e.g. 256000) if your Tree is not split
2101/// and each entry is large (Megabytes)
2102/// A small value for bufsize is optimum if you intend to access
2103/// the entries in the Tree randomly and your Tree is in split mode.
2105TBranch* TTree::BranchOld(const char* name, const char* classname, void* addobj, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 1 */)
2106{
2107 TClass* cl = TClass::GetClass(classname);
2108 if (!cl) {
2109 Error("BranchOld", "Cannot find class: '%s'", classname);
2110 return nullptr;
2111 }
2112 if (!cl->IsTObject()) {
2113 if (fgBranchStyle == 0) {
2114 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2115 "\tfgBranchStyle is set to zero requesting by default to use BranchOld.\n"
2116 "\tIf this is intentional use Bronch instead of Branch or BranchOld.", classname);
2117 } else {
2118 Fatal("BranchOld", "The requested class ('%s') does not inherit from TObject.\n"
2119 "\tYou can not use BranchOld to store objects of this type.",classname);
2120 }
2121 return nullptr;
2122 }
2123 TBranch* branch = new TBranchObject(this, name, classname, addobj, bufsize, splitlevel);
2125 if (!splitlevel) {
2126 return branch;
2127 }
2128 // We are going to fully split the class now.
2129 TObjArray* blist = branch->GetListOfBranches();
2130 const char* rdname = nullptr;
2131 const char* dname = nullptr;
2133 char** apointer = (char**) addobj;
2134 TObject* obj = (TObject*) *apointer;
2135 bool delobj = false;
2136 if (!obj) {
2137 obj = (TObject*) cl->New();
2138 delobj = true;
2139 }
2140 // Build the StreamerInfo if first time for the class.
2141 BuildStreamerInfo(cl, obj);
2142 // Loop on all public data members of the class and its base classes.
2144 Int_t isDot = 0;
2145 if (name[lenName-1] == '.') {
2146 isDot = 1;
2147 }
2148 TBranch* branch1 = nullptr;
2149 TRealData* rd = nullptr;
2150 TRealData* rdi = nullptr;
2152 TIter next(cl->GetListOfRealData());
2153 // Note: This loop results in a full split because the
2154 // real data list includes all data members of
2155 // data members.
2156 while ((rd = (TRealData*) next())) {
2157 if (rd->TestBit(TRealData::kTransient)) continue;
2158
2159 // Loop over all data members creating branches for each one.
2160 TDataMember* dm = rd->GetDataMember();
2161 if (!dm->IsPersistent()) {
2162 // Do not process members with an "!" as the first character in the comment field.
2163 continue;
2164 }
2165 if (rd->IsObject()) {
2166 // We skip data members of class type.
2167 // But we do build their real data, their
2168 // streamer info, and write their streamer
2169 // info to the current directory's file.
2170 // Oh yes, and we also do this for all of
2171 // their base classes.
2173 if (clm) {
2174 BuildStreamerInfo(clm, (char*) obj + rd->GetThisOffset());
2175 }
2176 continue;
2177 }
2178 rdname = rd->GetName();
2179 dname = dm->GetName();
2180 if (cl->CanIgnoreTObjectStreamer()) {
2181 // Skip the TObject base class data members.
2182 // FIXME: This prevents a user from ever
2183 // using these names themself!
2184 if (!strcmp(dname, "fBits")) {
2185 continue;
2186 }
2187 if (!strcmp(dname, "fUniqueID")) {
2188 continue;
2189 }
2190 }
2191 TDataType* dtype = dm->GetDataType();
2192 Int_t code = 0;
2193 if (dtype) {
2194 code = dm->GetDataType()->GetType();
2195 }
2196 // Encode branch name. Use real data member name
2198 if (isDot) {
2199 if (dm->IsaPointer()) {
2200 // FIXME: This is wrong! The asterisk is not usually in the front!
2201 branchname.Form("%s%s", name, &rdname[1]);
2202 } else {
2203 branchname.Form("%s%s", name, &rdname[0]);
2204 }
2205 }
2206 // FIXME: Change this to a string stream.
2208 Int_t offset = rd->GetThisOffset();
2209 char* pointer = ((char*) obj) + offset;
2210 if (dm->IsaPointer()) {
2211 // We have a pointer to an object or a pointer to an array of basic types.
2212 TClass* clobj = nullptr;
2213 if (!dm->IsBasic()) {
2215 }
2216 if (clobj && clobj->InheritsFrom(TClonesArray::Class())) {
2217 // We have a pointer to a clones array.
2218 char* cpointer = (char*) pointer;
2219 char** ppointer = (char**) cpointer;
2221 if (splitlevel != 2) {
2222 if (isDot) {
2224 } else {
2225 // FIXME: This is wrong! The asterisk is not usually in the front!
2226 branch1 = new TBranchClones(branch,&branchname.Data()[1], pointer, bufsize);
2227 }
2228 blist->Add(branch1);
2229 } else {
2230 if (isDot) {
2231 branch1 = new TBranchObject(branch, branchname, li->ClassName(), pointer, bufsize);
2232 } else {
2233 // FIXME: This is wrong! The asterisk is not usually in the front!
2234 branch1 = new TBranchObject(branch, &branchname.Data()[1], li->ClassName(), pointer, bufsize);
2235 }
2236 blist->Add(branch1);
2237 }
2238 } else if (clobj) {
2239 // We have a pointer to an object.
2240 //
2241 // It must be a TObject object.
2242 if (!clobj->IsTObject()) {
2243 continue;
2244 }
2245 branch1 = new TBranchObject(branch, dname, clobj->GetName(), pointer, bufsize, 0);
2246 if (isDot) {
2247 branch1->SetName(branchname);
2248 } else {
2249 // FIXME: This is wrong! The asterisk is not usually in the front!
2250 // Do not use the first character (*).
2251 branch1->SetName(&branchname.Data()[1]);
2252 }
2253 blist->Add(branch1);
2254 } else {
2255 // We have a pointer to an array of basic types.
2256 //
2257 // Check the comments in the text of the code for an index specification.
2258 const char* index = dm->GetArrayIndex();
2259 if (index[0]) {
2260 // We are a pointer to a varying length array of basic types.
2261 //check that index is a valid data member name
2262 //if member is part of an object (e.g. fA and index=fN)
2263 //index must be changed from fN to fA.fN
2264 TString aindex (rd->GetName());
2265 Ssiz_t rdot = aindex.Last('.');
2266 if (rdot>=0) {
2267 aindex.Remove(rdot+1);
2268 aindex.Append(index);
2269 }
2270 nexti.Reset();
2271 while ((rdi = (TRealData*) nexti())) {
2272 if (rdi->TestBit(TRealData::kTransient)) continue;
2273
2274 if (!strcmp(rdi->GetName(), index)) {
2275 break;
2276 }
2277 if (!strcmp(rdi->GetName(), aindex)) {
2278 index = rdi->GetName();
2279 break;
2280 }
2281 }
2282
2283 char vcode = DataTypeToChar((EDataType)code);
2284 // Note that we differentiate between strings and
2285 // char array by the fact that there is NO specified
2286 // size for a string (see next if (code == 1)
2287
2288 if (vcode) {
2289 leaflist.Form("%s[%s]/%c", &rdname[0], index, vcode);
2290 } else {
2291 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2292 leaflist = "";
2293 }
2294 } else {
2295 // We are possibly a character string.
2296 if (code == 1) {
2297 // We are a character string.
2298 leaflist.Form("%s/%s", dname, "C");
2299 } else {
2300 // Invalid array specification.
2301 // FIXME: We need an error message here.
2302 continue;
2303 }
2304 }
2305 // There are '*' in both the branchname and leaflist, remove them.
2306 TString bname( branchname );
2307 bname.ReplaceAll("*","");
2308 leaflist.ReplaceAll("*","");
2309 // Add the branch to the tree and indicate that the address
2310 // is that of a pointer to be dereferenced before using.
2311 branch1 = new TBranch(branch, bname, *((void**) pointer), leaflist, bufsize);
2312 TLeaf* leaf = (TLeaf*) branch1->GetListOfLeaves()->At(0);
2314 leaf->SetAddress((void**) pointer);
2315 blist->Add(branch1);
2316 }
2317 } else if (dm->IsBasic()) {
2318 // We have a basic type.
2319
2320 char vcode = DataTypeToChar((EDataType)code);
2321 if (vcode) {
2322 leaflist.Form("%s/%c", rdname, vcode);
2323 } else {
2324 Error("BranchOld", "Cannot create branch for rdname: %s code: %d", branchname.Data(), code);
2325 leaflist = "";
2326 }
2327 branch1 = new TBranch(branch, branchname, pointer, leaflist, bufsize);
2328 branch1->SetTitle(rdname);
2329 blist->Add(branch1);
2330 } else {
2331 // We have a class type.
2332 // Note: This cannot happen due to the rd->IsObject() test above.
2333 // FIXME: Put an error message here just in case.
2334 }
2335 if (branch1) {
2336 branch1->SetOffset(offset);
2337 } else {
2338 Warning("BranchOld", "Cannot process member: '%s'", rdname);
2339 }
2340 }
2341 if (delobj) {
2342 delete obj;
2343 obj = nullptr;
2344 }
2345 return branch;
2346}
2347
2348////////////////////////////////////////////////////////////////////////////////
2349/// Build the optional branch supporting the TRefTable.
2350/// This branch will keep all the information to find the branches
2351/// containing referenced objects.
2352///
2353/// At each Tree::Fill, the branch numbers containing the
2354/// referenced objects are saved to the TBranchRef basket.
2355/// When the Tree header is saved (via TTree::Write), the branch
2356/// is saved keeping the information with the pointers to the branches
2357/// having referenced objects.
2360{
2361 if (!fBranchRef) {
2362 fBranchRef = new TBranchRef(this);
2363 }
2364 return fBranchRef;
2365}
2366
2367////////////////////////////////////////////////////////////////////////////////
2368/// Create a new TTree BranchElement.
2369///
2370/// ## WARNING about this new function
2371///
2372/// This function is designed to replace the internal
2373/// implementation of the old TTree::Branch (whose implementation
2374/// has been moved to BranchOld).
2375///
2376/// NOTE: The 'Bronch' method supports only one possible calls
2377/// signature (where the object type has to be specified
2378/// explicitly and the address must be the address of a pointer).
2379/// For more flexibility use 'Branch'. Use Bronch only in (rare)
2380/// cases (likely to be legacy cases) where both the new and old
2381/// implementation of Branch needs to be used at the same time.
2382///
2383/// This function is far more powerful than the old Branch
2384/// function. It supports the full C++, including STL and has
2385/// the same behaviour in split or non-split mode. classname does
2386/// not have to derive from TObject. The function is based on
2387/// the new TStreamerInfo.
2388///
2389/// Build a TBranchElement for an object of class classname.
2390///
2391/// addr is the address of a pointer to an object of class
2392/// classname. The class dictionary must be available (ClassDef
2393/// in class header).
2394///
2395/// Note: See the comments in TBranchElement::SetAddress() for a more
2396/// detailed discussion of the meaning of the addr parameter.
2397///
2398/// This option requires access to the library where the
2399/// corresponding class is defined. Accessing one single data
2400/// member in the object implies reading the full object.
2401///
2402/// By default the branch buffers are stored in the same file as the Tree.
2403/// use TBranch::SetFile to specify a different file
2404///
2405/// IMPORTANT NOTE about branch names:
2406///
2407/// And in general, in case two or more master branches contain subbranches
2408/// with identical names, one must add a "." (dot) character at the end
2409/// of the master branch name. This will force the name of the subbranches
2410/// to be of the form `master.subbranch` instead of simply `subbranch`.
2411/// This situation happens when the top level object
2412/// has two or more members referencing the same class.
2413/// For example, if a Tree has two branches B1 and B2 corresponding
2414/// to objects of the same class MyClass, one can do:
2415/// ~~~ {.cpp}
2416/// tree.Branch("B1.","MyClass",&b1,8000,1);
2417/// tree.Branch("B2.","MyClass",&b2,8000,1);
2418/// ~~~
2419/// if MyClass has 3 members a,b,c, the two instructions above will generate
2420/// subbranches called B1.a, B1.b ,B1.c, B2.a, B2.b, B2.c
2421///
2422/// bufsize is the buffer size in bytes for this branch
2423/// The default value is 32000 bytes and should be ok for most cases.
2424/// You can specify a larger value (e.g. 256000) if your Tree is not split
2425/// and each entry is large (Megabytes)
2426/// A small value for bufsize is optimum if you intend to access
2427/// the entries in the Tree randomly and your Tree is in split mode.
2428///
2429/// Use splitlevel < 0 instead of splitlevel=0 when the class
2430/// has a custom Streamer
2431///
2432/// Note: if the split level is set to the default (99), TTree::Branch will
2433/// not issue a warning if the class can not be split.
2435TBranch* TTree::Bronch(const char* name, const char* classname, void* addr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2436{
2437 return BronchExec(name, classname, addr, true, bufsize, splitlevel);
2438}
2439
2440////////////////////////////////////////////////////////////////////////////////
2441/// Helper function implementing TTree::Bronch and TTree::Branch(const char *name, T &obj);
2443TBranch* TTree::BronchExec(const char* name, const char* classname, void* addr, bool isptrptr, Int_t bufsize /* = 32000 */, Int_t splitlevel /* = 99 */)
2444{
2445 TClass* cl = TClass::GetClass(classname);
2446 if (!cl) {
2447 Error("Bronch", "Cannot find class:%s", classname);
2448 return nullptr;
2449 }
2450
2451 //if splitlevel <= 0 and class has a custom Streamer, we must create
2452 //a TBranchObject. We cannot assume that TClass::ReadBuffer is consistent
2453 //with the custom Streamer. The penalty is that one cannot process
2454 //this Tree without the class library containing the class.
2455
2456 char* objptr = nullptr;
2457 if (!isptrptr) {
2458 objptr = (char*)addr;
2459 } else if (addr) {
2460 objptr = *((char**) addr);
2461 }
2462
2463 if (cl == TClonesArray::Class()) {
2465 if (!clones) {
2466 Error("Bronch", "Pointer to TClonesArray is null");
2467 return nullptr;
2468 }
2469 if (!clones->GetClass()) {
2470 Error("Bronch", "TClonesArray with no class defined in branch: %s", name);
2471 return nullptr;
2472 }
2473 if (!clones->GetClass()->HasDataMemberInfo()) {
2474 Error("Bronch", "TClonesArray with no dictionary defined in branch: %s", name);
2475 return nullptr;
2476 }
2477 bool hasCustomStreamer = clones->GetClass()->HasCustomStreamerMember();
2478 if (splitlevel > 0) {
2480 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", clones->GetClass()->GetName());
2481 } else {
2482 if (hasCustomStreamer) clones->BypassStreamer(false);
2483 TBranchObject *branch = new TBranchObject(this,name,classname,addr,bufsize,0,/*compress=*/ -1,isptrptr);
2485 return branch;
2486 }
2487 }
2488
2489 if (cl->GetCollectionProxy()) {
2491 //if (!collProxy) {
2492 // Error("Bronch", "%s is missing its CollectionProxy (for branch %s)", classname, name);
2493 //}
2494 TClass* inklass = collProxy->GetValueClass();
2495 if (!inklass && (collProxy->GetType() == 0)) {
2496 Error("Bronch", "%s with no class defined in branch: %s", classname, name);
2497 return nullptr;
2498 }
2499 if ((splitlevel > 0) && inklass && (inklass->GetCollectionProxy() == nullptr)) {
2501 if ((stl != ROOT::kSTLmap) && (stl != ROOT::kSTLmultimap)) {
2502 if (!inklass->HasDataMemberInfo()) {
2503 Error("Bronch", "Container with no dictionary defined in branch: %s", name);
2504 return nullptr;
2505 }
2506 if (inklass->HasCustomStreamerMember()) {
2507 Warning("Bronch", "Using split mode on a class: %s with a custom Streamer", inklass->GetName());
2508 }
2509 }
2510 }
2511 //-------------------------------------------------------------------------
2512 // If the splitting switch is enabled, the split level is big enough and
2513 // the collection contains pointers we can split it
2514 //////////////////////////////////////////////////////////////////////////
2515
2516 TBranch *branch;
2517 if( splitlevel > kSplitCollectionOfPointers && collProxy->HasPointers() )
2519 else
2522 if (isptrptr) {
2523 branch->SetAddress(addr);
2524 } else {
2525 branch->SetObject(addr);
2526 }
2527 return branch;
2528 }
2529
2530 bool hasCustomStreamer = false;
2531 if (!cl->HasDataMemberInfo() && !cl->GetCollectionProxy()) {
2532 Error("Bronch", "Cannot find dictionary for class: %s", classname);
2533 return nullptr;
2534 }
2535
2536 if (!cl->GetCollectionProxy() && cl->HasCustomStreamerMember()) {
2537 // Not an STL container and the linkdef file had a "-" after the class name.
2538 hasCustomStreamer = true;
2539 }
2540
2541 if (splitlevel < 0 || ((splitlevel == 0) && hasCustomStreamer && cl->IsTObject())) {
2544 return branch;
2545 }
2546
2547 if (cl == TClonesArray::Class()) {
2548 // Special case of TClonesArray.
2549 // No dummy object is created.
2550 // The streamer info is not rebuilt unoptimized.
2551 // No dummy top-level branch is created.
2552 // No splitting is attempted.
2555 if (isptrptr) {
2556 branch->SetAddress(addr);
2557 } else {
2558 branch->SetObject(addr);
2559 }
2560 return branch;
2561 }
2562
2563 //
2564 // If we are not given an object to use as an i/o buffer
2565 // then create a temporary one which we will delete just
2566 // before returning.
2567 //
2568
2569 bool delobj = false;
2570
2571 if (!objptr) {
2572 objptr = (char*) cl->New();
2573 delobj = true;
2574 }
2575
2576 //
2577 // Avoid splitting unsplittable classes.
2578 //
2579
2580 if ((splitlevel > 0) && !cl->CanSplit()) {
2581 if (splitlevel != 99) {
2582 Warning("Bronch", "%s cannot be split, resetting splitlevel to 0", cl->GetName());
2583 }
2584 splitlevel = 0;
2585 }
2586
2587 //
2588 // Make sure the streamer info is built and fetch it.
2589 //
2590 // If we are splitting, then make sure the streamer info
2591 // is built unoptimized (data members are not combined).
2592 //
2593
2595 if (!sinfo) {
2596 Error("Bronch", "Cannot build the StreamerInfo for class: %s", cl->GetName());
2597 return nullptr;
2598 }
2599
2600 //
2601 // Create a dummy top level branch object.
2602 //
2603
2604 Int_t id = -1;
2605 if (splitlevel > 0) {
2606 id = -2;
2607 }
2610
2611 //
2612 // Do splitting, if requested.
2613 //
2614
2616 branch->Unroll(name, cl, sinfo, objptr, bufsize, splitlevel);
2617 }
2618
2619 //
2620 // Setup our offsets into the user's i/o buffer.
2621 //
2622
2623 if (isptrptr) {
2624 branch->SetAddress(addr);
2625 } else {
2626 branch->SetObject(addr);
2627 }
2628
2629 if (delobj) {
2630 cl->Destructor(objptr);
2631 objptr = nullptr;
2632 }
2633
2634 return branch;
2635}
2636
2637////////////////////////////////////////////////////////////////////////////////
2638/// Browse content of the TTree.
2641{
2643 if (fUserInfo) {
2644 if (strcmp("TList",fUserInfo->GetName())==0) {
2645 fUserInfo->SetName("UserInfo");
2646 b->Add(fUserInfo);
2647 fUserInfo->SetName("TList");
2648 } else {
2649 b->Add(fUserInfo);
2650 }
2651 }
2652}
2653
2654////////////////////////////////////////////////////////////////////////////////
2655/// Build a Tree Index (default is TTreeIndex).
2656/// See a description of the parameters and functionality in
2657/// TTreeIndex::TTreeIndex().
2658///
2659/// The return value is the number of entries in the Index (< 0 indicates failure).
2660///
2661/// A TTreeIndex object pointed by fTreeIndex is created.
2662/// This object will be automatically deleted by the TTree destructor.
2663/// If an index is already existing, this is replaced by the new one without being
2664/// deleted. This behaviour prevents the deletion of a previously external index
2665/// assigned to the TTree via the TTree::SetTreeIndex() method.
2666/// \see TTree::SetTreeIndex()
2668Int_t TTree::BuildIndex(const char* majorname, const char* minorname /* = "0" */, bool long64major, bool long64minor)
2669{
2671 if (fTreeIndex->IsZombie()) {
2672 delete fTreeIndex;
2673 fTreeIndex = nullptr;
2674 return 0;
2675 }
2676 return fTreeIndex->GetN();
2677}
2678
2679////////////////////////////////////////////////////////////////////////////////
2680/// Build StreamerInfo for class cl.
2681/// pointer is an optional argument that may contain a pointer to an object of cl.
2683TStreamerInfo* TTree::BuildStreamerInfo(TClass* cl, void* pointer /* = 0 */, bool canOptimize /* = true */ )
2684{
2685 if (!cl) {
2686 return nullptr;
2687 }
2688 cl->BuildRealData(pointer);
2690
2691 // Create StreamerInfo for all base classes.
2692 TBaseClass* base = nullptr;
2693 TIter nextb(cl->GetListOfBases());
2694 while((base = (TBaseClass*) nextb())) {
2695 if (base->IsSTLContainer()) {
2696 continue;
2697 }
2698 TClass* clm = TClass::GetClass(base->GetName());
2700 }
2701 if (sinfo && fDirectory) {
2702 sinfo->ForceWriteInfo(fDirectory->GetFile());
2703 }
2704 return sinfo;
2705}
2706
2707////////////////////////////////////////////////////////////////////////////////
2708/// Enable the TTreeCache unless explicitly disabled for this TTree by
2709/// a prior call to `SetCacheSize(0)`.
2710/// If the environment variable `ROOT_TTREECACHE_SIZE` or the rootrc config
2711/// `TTreeCache.Size` has been set to zero, this call will over-ride them with
2712/// a value of 1.0 (i.e. use a cache size to hold 1 cluster)
2713///
2714/// Return true if there is a cache attached to the `TTree` (either pre-exisiting
2715/// or created as part of this call)
2716bool TTree::EnableCache()
2717{
2718 TFile* file = GetCurrentFile();
2719 if (!file)
2720 return false;
2721 // Check for an existing cache
2722 TTreeCache* pf = GetReadCache(file);
2723 if (pf)
2724 return true;
2725 if (fCacheUserSet && fCacheSize == 0)
2726 return false;
2727 return (0 == SetCacheSizeAux(true, -1));
2728}
2729
2730////////////////////////////////////////////////////////////////////////////////
2731/// Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
2732/// Create a new file. If the original file is named "myfile.root",
2733/// subsequent files are named "myfile_1.root", "myfile_2.root", etc.
2734///
2735/// Returns a pointer to the new file.
2736///
2737/// Currently, the automatic change of file is restricted
2738/// to the case where the tree is in the top level directory.
2739/// The file should not contain sub-directories.
2740///
2741/// Before switching to a new file, the tree header is written
2742/// to the current file, then the current file is closed.
2743///
2744/// To process the multiple files created by ChangeFile, one must use
2745/// a TChain.
2746///
2747/// The new file name has a suffix "_N" where N is equal to fFileNumber+1.
2748/// By default a Root session starts with fFileNumber=0. One can set
2749/// fFileNumber to a different value via TTree::SetFileNumber.
2750/// In case a file named "_N" already exists, the function will try
2751/// a file named "__N", then "___N", etc.
2752///
2753/// fgMaxTreeSize can be set via the static function TTree::SetMaxTreeSize.
2754/// The default value of fgMaxTreeSize is 100 Gigabytes.
2755///
2756/// If the current file contains other objects like TH1 and TTree,
2757/// these objects are automatically moved to the new file.
2758///
2759/// \warning Be careful when writing the final Tree header to the file!
2760/// Don't do:
2761/// ~~~ {.cpp}
2762/// TFile *file = new TFile("myfile.root","recreate");
2763/// TTree *T = new TTree("T","title");
2764/// T->Fill(); // Loop
2765/// file->Write();
2766/// file->Close();
2767/// ~~~
2768/// \warning but do the following:
2769/// ~~~ {.cpp}
2770/// TFile *file = new TFile("myfile.root","recreate");
2771/// TTree *T = new TTree("T","title");
2772/// T->Fill(); // Loop
2773/// file = T->GetCurrentFile(); // To get the pointer to the current file
2774/// file->Write();
2775/// file->Close();
2776/// ~~~
2777///
2778/// \note This method is never called if the input file is a `TMemFile` or derivate.
2781{
2782 // Changing file clashes with the design of TMemFile and derivates, see #6523,
2783 // as well as with TFileMerger operations, see #6640.
2784 if ((dynamic_cast<TMemFile *>(file)) || file->TestBit(TFile::kCancelTTreeChangeRequest))
2785 return file;
2786 file->cd();
2787 Write();
2788 Reset();
2789 constexpr auto kBufSize = 2000;
2790 char* fname = new char[kBufSize];
2791 ++fFileNumber;
2792 char uscore[10];
2793 for (Int_t i = 0; i < 10; ++i) {
2794 uscore[i] = 0;
2795 }
2796 Int_t nus = 0;
2797 // Try to find a suitable file name that does not already exist.
2798 while (nus < 10) {
2799 uscore[nus] = '_';
2800 fname[0] = 0;
2801 strlcpy(fname, file->GetName(), kBufSize);
2802
2803 if (fFileNumber > 1) {
2804 char* cunder = strrchr(fname, '_');
2805 if (cunder) {
2807 const char* cdot = strrchr(file->GetName(), '.');
2808 if (cdot) {
2810 }
2811 } else {
2812 char fcount[21];
2813 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2815 }
2816 } else {
2817 char* cdot = strrchr(fname, '.');
2818 if (cdot) {
2820 strlcat(fname, strrchr(file->GetName(), '.'), kBufSize);
2821 } else {
2822 char fcount[21];
2823 snprintf(fcount,21, "%s%d", uscore, fFileNumber);
2825 }
2826 }
2828 break;
2829 }
2830 ++nus;
2831 Warning("ChangeFile", "file %s already exists, trying with %d underscores", fname, nus + 1);
2832 }
2834 TFile* newfile = TFile::Open(fname, "recreate", "chain files", compress);
2835 if (newfile == nullptr) {
2836 Error("Fill","Failed to open new file %s, continuing as a memory tree.",fname);
2837 } else {
2838 Printf("Fill: Switching to new file: %s", fname);
2839 }
2840 // The current directory may contain histograms and trees.
2841 // These objects must be moved to the new file.
2842 TBranch* branch = nullptr;
2843 TObject* obj = nullptr;
2844 while ((obj = file->GetList()->First())) {
2845 file->Remove(obj);
2846 // Histogram: just change the directory.
2847 if (obj->InheritsFrom("TH1")) {
2848 gROOT->ProcessLine(TString::Format("((%s*)0x%zx)->SetDirectory((TDirectory*)0x%zx);", obj->ClassName(), (size_t) obj, (size_t) newfile));
2849 continue;
2850 }
2851 // Tree: must save all trees in the old file, reset them.
2852 if (obj->InheritsFrom(TTree::Class())) {
2853 TTree* t = (TTree*) obj;
2854 if (t != this) {
2855 t->AutoSave();
2856 t->Reset();
2858 }
2861 while ((branch = (TBranch*)nextb())) {
2862 branch->SetFile(newfile);
2863 }
2864 if (t->GetBranchRef()) {
2865 t->GetBranchRef()->SetFile(newfile);
2866 }
2867 continue;
2868 }
2869 // Not a TH1 or a TTree, move object to new file.
2870 if (newfile) newfile->Append(obj);
2871 file->Remove(obj);
2872 }
2873 file->TObject::Delete();
2874 file = nullptr;
2875 delete[] fname;
2876 fname = nullptr;
2877 return newfile;
2878}
2879
2880////////////////////////////////////////////////////////////////////////////////
2881/// Check whether or not the address described by the last 3 parameters
2882/// matches the content of the branch. If a Data Model Evolution conversion
2883/// is involved, reset the fInfo of the branch.
2884/// The return values are:
2885//
2886/// - kMissingBranch (-5) : Missing branch
2887/// - kInternalError (-4) : Internal error (could not find the type corresponding to a data type number)
2888/// - kMissingCompiledCollectionProxy (-3) : Missing compiled collection proxy for a compiled collection
2889/// - kMismatch (-2) : Non-Class Pointer type given does not match the type expected by the branch
2890/// - kClassMismatch (-1) : Class Pointer type given does not match the type expected by the branch
2891/// - kMatch (0) : perfect match
2892/// - kMatchConversion (1) : match with (I/O) conversion
2893/// - kMatchConversionCollection (2) : match with (I/O) conversion of the content of a collection
2894/// - kMakeClass (3) : MakeClass mode so we can not check.
2895/// - kVoidPtr (4) : void* passed so no check was made.
2896/// - kNoCheck (5) : Underlying TBranch not yet available so no check was made.
2897/// In addition this can be multiplexed with the two bits:
2898/// - kNeedEnableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to be in Decomposed Object (aka MakeClass) mode.
2899/// - kNeedDisableDecomposedObj : in order for the address (type) to be 'usable' the branch needs to not be in Decomposed Object (aka MakeClass) mode.
2900/// This bits can be masked out by using kDecomposedObjMask
2903{
2904 if (GetMakeClass()) {
2905 // If we are in MakeClass mode so we do not really use classes.
2906 return kMakeClass;
2907 }
2908
2909 // Let's determine what we need!
2910 TClass* expectedClass = nullptr;
2912 if (0 != branch->GetExpectedType(expectedClass,expectedType) ) {
2913 // Something went wrong, the warning message has already been issued.
2914 return kInternalError;
2915 }
2916 bool isBranchElement = branch->InheritsFrom( TBranchElement::Class() );
2917 if (expectedClass && datatype == kOther_t && ptrClass == nullptr) {
2918 if (isBranchElement) {
2920 bEl->SetTargetClass( expectedClass->GetName() );
2921 }
2922 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
2923 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2924 "The class expected (%s) refers to an stl collection and do not have a compiled CollectionProxy. "
2925 "Please generate the dictionary for this class (%s)",
2926 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2928 }
2929 if (!expectedClass->IsLoaded()) {
2930 // The originally expected class does not have a dictionary, it is then plausible that the pointer being passed is the right type
2931 // (we really don't know). So let's express that.
2932 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2933 "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."
2934 "Please generate the dictionary for this class (%s)",
2935 branch->GetName(), expectedClass->GetName(), expectedClass->GetName());
2936 } else {
2937 Error("SetBranchAddress", "Unable to determine the type given for the address for \"%s\". "
2938 "This is probably due to a missing dictionary, the original data class for this branch is %s.", branch->GetName(), expectedClass->GetName());
2939 }
2940 return kClassMismatch;
2941 }
2942 if (expectedClass && ptrClass && (branch->GetMother() == branch)) {
2943 // Top Level branch
2944 if (!isptr) {
2945 Error("SetBranchAddress", "The address for \"%s\" should be the address of a pointer!", branch->GetName());
2946 }
2947 }
2948 if (expectedType == kFloat16_t) {
2950 }
2951 if (expectedType == kDouble32_t) {
2953 }
2954 if (datatype == kFloat16_t) {
2956 }
2957 if (datatype == kDouble32_t) {
2959 }
2960
2961 /////////////////////////////////////////////////////////////////////////////
2962 // Deal with the class renaming
2963 /////////////////////////////////////////////////////////////////////////////
2964
2965 if( expectedClass && ptrClass &&
2968 ptrClass->GetSchemaRules() &&
2969 ptrClass->GetSchemaRules()->HasRuleWithSourceClass( expectedClass->GetName() ) ) {
2971
2972 if ( ptrClass->GetCollectionProxy() && expectedClass->GetCollectionProxy() ) {
2973 if (gDebug > 7)
2974 Info("SetBranchAddress", "Matching STL collection (at least according to the SchemaRuleSet when "
2975 "reading a %s into a %s",expectedClass->GetName(),ptrClass->GetName());
2976
2977 bEl->SetTargetClass( ptrClass->GetName() );
2978 return kMatchConversion;
2979
2980 } else if ( !ptrClass->GetConversionStreamerInfo( expectedClass, bEl->GetClassVersion() ) &&
2981 !ptrClass->FindConversionStreamerInfo( expectedClass, bEl->GetCheckSum() ) ) {
2982 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());
2983
2984 bEl->SetTargetClass( expectedClass->GetName() );
2985 return kClassMismatch;
2986 }
2987 else {
2988
2989 bEl->SetTargetClass( ptrClass->GetName() );
2990 return kMatchConversion;
2991 }
2992
2993 } else if (expectedClass && ptrClass && !expectedClass->InheritsFrom(ptrClass)) {
2994
2995 if (expectedClass->GetCollectionProxy() && ptrClass->GetCollectionProxy() &&
2997 expectedClass->GetCollectionProxy()->GetValueClass() &&
2998 ptrClass->GetCollectionProxy()->GetValueClass() )
2999 {
3000 // In case of collection, we know how to convert them, if we know how to convert their content.
3001 // NOTE: we need to extend this to std::pair ...
3002
3003 TClass *onfileValueClass = expectedClass->GetCollectionProxy()->GetValueClass();
3004 TClass *inmemValueClass = ptrClass->GetCollectionProxy()->GetValueClass();
3005
3006 if (inmemValueClass->GetSchemaRules() &&
3007 inmemValueClass->GetSchemaRules()->HasRuleWithSourceClass(onfileValueClass->GetName() ) )
3008 {
3010 bEl->SetTargetClass( ptrClass->GetName() );
3012 }
3013 }
3014
3015 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());
3016 if (isBranchElement) {
3018 bEl->SetTargetClass( expectedClass->GetName() );
3019 }
3020 return kClassMismatch;
3021
3022 } else if ((expectedType != kOther_t) && (datatype != kOther_t) && (expectedType != kNoType_t) && (datatype != kNoType_t) && (expectedType != datatype)) {
3023 if (datatype != kChar_t) {
3024 // For backward compatibility we assume that (char*) was just a cast and/or a generic address
3025 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" (%d) by the branch: %s",
3027 return kMismatch;
3028 }
3029 } else if ((expectedClass && (datatype != kOther_t && datatype != kNoType_t && datatype != kInt_t)) ||
3031 // Sometime a null pointer can look an int, avoid complaining in that case.
3032 if (expectedClass) {
3033 Error("SetBranchAddress", "The pointer type given \"%s\" (%d) does not correspond to the type needed \"%s\" by the branch: %s",
3034 TDataType::GetTypeName(datatype), datatype, expectedClass->GetName(), branch->GetName());
3035 if (isBranchElement) {
3037 bEl->SetTargetClass( expectedClass->GetName() );
3038 }
3039 } else {
3040 // 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
3041 // a struct).
3042 bool found = false;
3043 if (ptrClass->IsLoaded()) {
3044 TIter next(ptrClass->GetListOfRealData());
3045 TRealData *rdm;
3046 while ((rdm = (TRealData*)next())) {
3047 if (rdm->GetThisOffset() == 0) {
3048 TDataType *dmtype = rdm->GetDataMember()->GetDataType();
3049 if (dmtype) {
3050 EDataType etype = (EDataType)dmtype->GetType();
3051 if (etype == expectedType) {
3052 found = true;
3053 }
3054 }
3055 break;
3056 }
3057 }
3058 } else {
3059 TIter next(ptrClass->GetListOfDataMembers());
3060 TDataMember *dm;
3061 while ((dm = (TDataMember*)next())) {
3062 if (dm->GetOffset() == 0) {
3063 TDataType *dmtype = dm->GetDataType();
3064 if (dmtype) {
3065 EDataType etype = (EDataType)dmtype->GetType();
3066 if (etype == expectedType) {
3067 found = true;
3068 }
3069 }
3070 break;
3071 }
3072 }
3073 }
3074 if (found) {
3075 // let's check the size.
3076 TLeaf *last = (TLeaf*)branch->GetListOfLeaves()->Last();
3077 long len = last->GetOffset() + last->GetLenType() * last->GetLen();
3078 if (len <= ptrClass->Size()) {
3079 return kMatch;
3080 }
3081 }
3082 Error("SetBranchAddress", "The pointer type given \"%s\" does not correspond to the type needed \"%s\" (%d) by the branch: %s",
3084 }
3085 return kMismatch;
3086 }
3087 if (expectedClass && expectedClass->GetCollectionProxy() && dynamic_cast<TEmulatedCollectionProxy*>(expectedClass->GetCollectionProxy())) {
3088 Error("SetBranchAddress", writeStlWithoutProxyMsg,
3089 expectedClass->GetName(), branch->GetName(), expectedClass->GetName());
3090 if (isBranchElement) {
3092 bEl->SetTargetClass( expectedClass->GetName() );
3093 }
3095 }
3096 if (isBranchElement) {
3097 if (expectedClass) {
3099 bEl->SetTargetClass( expectedClass->GetName() );
3100 } else if (expectedType != kNoType_t && expectedType != kOther_t) {
3102 }
3103 }
3104 return kMatch;
3105}
3106
3107////////////////////////////////////////////////////////////////////////////////
3108/// Create a clone of this tree and copy nentries.
3109///
3110/// By default copy all entries.
3111/// The compression level of the cloned tree is set to the destination
3112/// file's compression level.
3113///
3114/// NOTE: Only active branches are copied. See TTree::SetBranchStatus for more
3115/// information and usage regarding the (de)activation of branches. More
3116/// examples are provided in the tutorials listed below.
3117///
3118/// NOTE: If the TTree is a TChain, the structure of the first TTree
3119/// is used for the copy.
3120///
3121/// IMPORTANT: The cloned tree stays connected with this tree until
3122/// this tree is deleted. In particular, any changes in
3123/// branch addresses in this tree are forwarded to the
3124/// clone trees, unless a branch in a clone tree has had
3125/// its address changed, in which case that change stays in
3126/// effect. When this tree is deleted, all the addresses of
3127/// the cloned tree are reset to their default values.
3128///
3129/// If 'option' contains the word 'fast' and nentries is -1, the
3130/// cloning will be done without unzipping or unstreaming the baskets
3131/// (i.e., a direct copy of the raw bytes on disk).
3132///
3133/// When 'fast' is specified, 'option' can also contain a sorting
3134/// order for the baskets in the output file.
3135///
3136/// There are currently 3 supported sorting order:
3137///
3138/// - SortBasketsByOffset (the default)
3139/// - SortBasketsByBranch
3140/// - SortBasketsByEntry
3141///
3142/// When using SortBasketsByOffset the baskets are written in the
3143/// output file in the same order as in the original file (i.e. the
3144/// baskets are sorted by their offset in the original file; Usually
3145/// this also means that the baskets are sorted by the index/number of
3146/// the _last_ entry they contain)
3147///
3148/// When using SortBasketsByBranch all the baskets of each individual
3149/// branches are stored contiguously. This tends to optimize reading
3150/// speed when reading a small number (1->5) of branches, since all
3151/// their baskets will be clustered together instead of being spread
3152/// across the file. However it might decrease the performance when
3153/// reading more branches (or the full entry).
3154///
3155/// When using SortBasketsByEntry the baskets with the lowest starting
3156/// entry are written first. (i.e. the baskets are sorted by the
3157/// index/number of the first entry they contain). This means that on
3158/// the file the baskets will be in the order in which they will be
3159/// needed when reading the whole tree sequentially.
3160///
3161/// For examples of CloneTree, see tutorials:
3162///
3163/// - copytree.C:
3164/// A macro to copy a subset of a TTree to a new TTree.
3165/// The input file has been generated by the program in
3166/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3167///
3168/// - copytree2.C:
3169/// A macro to copy a subset of a TTree to a new TTree.
3170/// One branch of the new Tree is written to a separate file.
3171/// The input file has been generated by the program in
3172/// $ROOTSYS/test/Event with: Event 1000 1 1 1
3174TTree* TTree::CloneTree(Long64_t nentries /* = -1 */, Option_t* option /* = "" */)
3175{
3176 // Options
3177 bool fastClone = false;
3178
3179 TString opt = option;
3180 opt.ToLower();
3181 if (opt.Contains("fast")) {
3182 fastClone = true;
3183 }
3184
3185 // If we are a chain, switch to the first tree.
3186 if (fEntries > 0) {
3187 const auto res = LoadTree(0);
3188 if (res < -2 || res == -1) {
3189 // -1 is not accepted, it happens when no trees were defined
3190 // -2 is the only acceptable error, when the chain has zero entries, but tree(s) were defined
3191 // Other errors (-3, ...) are not accepted
3192 Error("CloneTree", "returning nullptr since LoadTree failed with code %lld.", res);
3193 return nullptr;
3194 }
3195 }
3196
3197 // Note: For a tree we get the this pointer, for
3198 // a chain we get the chain's current tree.
3199 TTree* thistree = GetTree();
3200
3201 // We will use this to override the IO features on the cloned branches.
3203 ;
3204
3205 // Note: For a chain, the returned clone will be
3206 // a clone of the chain's first tree.
3207 TTree* newtree = (TTree*) thistree->Clone();
3208 if (!newtree) {
3209 return nullptr;
3210 }
3211
3212 // The clone should not delete any objects allocated by SetAddress().
3213 TObjArray* branches = newtree->GetListOfBranches();
3214 Int_t nb = branches->GetEntriesFast();
3215 for (Int_t i = 0; i < nb; ++i) {
3216 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3217 if (br->InheritsFrom(TBranchElement::Class())) {
3218 ((TBranchElement*) br)->ResetDeleteObject();
3219 }
3220 }
3221
3222 // Add the new tree to the list of clones so that
3223 // we can later inform it of changes to branch addresses.
3224 thistree->AddClone(newtree);
3225 if (thistree != this) {
3226 // In case this object is a TChain, add the clone
3227 // also to the TChain's list of clones.
3229 }
3230
3231 newtree->Reset();
3232
3233 TDirectory* ndir = newtree->GetDirectory();
3234 TFile* nfile = nullptr;
3235 if (ndir) {
3236 nfile = ndir->GetFile();
3237 }
3238 Int_t newcomp = -1;
3239 if (nfile) {
3240 newcomp = nfile->GetCompressionSettings();
3241 }
3242
3243 //
3244 // Delete non-active branches from the clone.
3245 //
3246 // Note: If we are a chain, this does nothing
3247 // since chains have no leaves.
3248 TObjArray* leaves = newtree->GetListOfLeaves();
3249 Int_t nleaves = leaves->GetEntriesFast();
3250 for (Int_t lndx = 0; lndx < nleaves; ++lndx) {
3251 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(lndx);
3252 if (!leaf) {
3253 continue;
3254 }
3255 TBranch* branch = leaf->GetBranch();
3256 if (branch && (newcomp > -1)) {
3257 branch->SetCompressionSettings(newcomp);
3258 }
3259 if (branch) branch->SetIOFeatures(features);
3260 if (!branch || !branch->TestBit(kDoNotProcess)) {
3261 continue;
3262 }
3263 // size might change at each iteration of the loop over the leaves.
3264 nb = branches->GetEntriesFast();
3265 for (Long64_t i = 0; i < nb; ++i) {
3266 TBranch* br = (TBranch*) branches->UncheckedAt(i);
3267 if (br == branch) {
3268 branches->RemoveAt(i);
3269 delete br;
3270 br = nullptr;
3271 branches->Compress();
3272 break;
3273 }
3274 TObjArray* lb = br->GetListOfBranches();
3275 Int_t nb1 = lb->GetEntriesFast();
3276 for (Int_t j = 0; j < nb1; ++j) {
3277 TBranch* b1 = (TBranch*) lb->UncheckedAt(j);
3278 if (!b1) {
3279 continue;
3280 }
3281 if (b1 == branch) {
3282 lb->RemoveAt(j);
3283 delete b1;
3284 b1 = nullptr;
3285 lb->Compress();
3286 break;
3287 }
3289 Int_t nb2 = lb1->GetEntriesFast();
3290 for (Int_t k = 0; k < nb2; ++k) {
3291 TBranch* b2 = (TBranch*) lb1->UncheckedAt(k);
3292 if (!b2) {
3293 continue;
3294 }
3295 if (b2 == branch) {
3296 lb1->RemoveAt(k);
3297 delete b2;
3298 b2 = nullptr;
3299 lb1->Compress();
3300 break;
3301 }
3302 }
3303 }
3304 }
3305 }
3306 leaves->Compress();
3307
3308 // Copy MakeClass status.
3309 newtree->SetMakeClass(fMakeClass);
3310
3311 // Copy branch addresses.
3313
3314 //
3315 // Copy entries if requested.
3316 //
3317
3318 if (nentries != 0) {
3319 if (fastClone && (nentries < 0)) {
3320 if ( newtree->CopyEntries( this, -1, option, false ) < 0 ) {
3321 // There was a problem!
3322 Error("CloneTTree", "TTree has not been cloned\n");
3323 delete newtree;
3324 newtree = nullptr;
3325 return nullptr;
3326 }
3327 } else {
3328 newtree->CopyEntries( this, nentries, option, false );
3329 }
3330 }
3331
3332 return newtree;
3333}
3334
3335////////////////////////////////////////////////////////////////////////////////
3336/// Set branch addresses of passed tree equal to ours.
3337/// If undo is true, reset the branch addresses instead of copying them.
3338/// This ensures 'separation' of a cloned tree from its original.
3340void TTree::CopyAddresses(TTree* tree, bool undo)
3341{
3342 // Copy branch addresses starting from branches.
3344 Int_t nbranches = branches->GetEntriesFast();
3345 for (Int_t i = 0; i < nbranches; ++i) {
3346 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
3347 if (branch->TestBit(kDoNotProcess)) {
3348 continue;
3349 }
3350 if (undo) {
3351 TBranch* br = tree->GetBranch(branch->GetName());
3352 tree->ResetBranchAddress(br);
3353 } else {
3354 char* addr = branch->GetAddress();
3355 if (!addr) {
3356 if (branch->IsA() == TBranch::Class()) {
3357 // If the branch was created using a leaflist, the branch itself may not have
3358 // an address but the leaf might already.
3359 TLeaf *firstleaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
3360 if (!firstleaf || firstleaf->GetValuePointer()) {
3361 // Either there is no leaf (and thus no point in copying the address)
3362 // or the leaf has an address but we can not copy it via the branche
3363 // this will be copied via the next loop (over the leaf).
3364 continue;
3365 }
3366 }
3367 // Note: This may cause an object to be allocated.
3368 branch->SetAddress(nullptr);
3369 addr = branch->GetAddress();
3370 }
3371 TBranch* br = tree->GetBranch(branch->GetFullName());
3372 if (br) {
3373 if (br->GetMakeClass() != branch->GetMakeClass())
3374 br->SetMakeClass(branch->GetMakeClass());
3375 br->SetAddress(addr);
3376 // The copy does not own any object allocated by SetAddress().
3377 if (br->InheritsFrom(TBranchElement::Class())) {
3378 ((TBranchElement*) br)->ResetDeleteObject();
3379 }
3380 } else {
3381 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3382 }
3383 }
3384 }
3385
3386 // Copy branch addresses starting from leaves.
3388 Int_t ntleaves = tleaves->GetEntriesFast();
3389 std::set<TLeaf*> updatedLeafCount;
3390 for (Int_t i = 0; i < ntleaves; ++i) {
3391 TLeaf* tleaf = (TLeaf*) tleaves->UncheckedAt(i);
3392 TBranch* tbranch = tleaf->GetBranch();
3393 TBranch* branch = GetBranch(tbranch->GetName());
3394 if (!branch) {
3395 continue;
3396 }
3397 TLeaf* leaf = branch->GetLeaf(tleaf->GetName());
3398 if (!leaf) {
3399 continue;
3400 }
3401 if (branch->TestBit(kDoNotProcess)) {
3402 continue;
3403 }
3404 if (undo) {
3405 // Now we know whether the address has been transferred
3407 } else {
3408 TBranchElement *mother = dynamic_cast<TBranchElement*>(leaf->GetBranch()->GetMother());
3409 bool needAddressReset = false;
3410 if (leaf->GetLeafCount() && (leaf->TestBit(TLeaf::kNewValue) || !leaf->GetValuePointer() || (mother && mother->IsObjectOwner())) && tleaf->GetLeafCount())
3411 {
3412 // If it is an array and it was allocated by the leaf itself,
3413 // let's make sure it is large enough for the incoming data.
3414 if (leaf->GetLeafCount()->GetMaximum() < tleaf->GetLeafCount()->GetMaximum()) {
3415 leaf->GetLeafCount()->IncludeRange( tleaf->GetLeafCount() );
3416 updatedLeafCount.insert(leaf->GetLeafCount());
3417 needAddressReset = true;
3418 } else {
3419 needAddressReset = (updatedLeafCount.find(leaf->GetLeafCount()) != updatedLeafCount.end());
3420 }
3421 }
3422 if (needAddressReset && leaf->GetValuePointer()) {
3423 if (leaf->IsA() == TLeafElement::Class() && mother)
3424 mother->ResetAddress();
3425 else
3426 leaf->SetAddress(nullptr);
3427 }
3428 if (!branch->GetAddress() && !leaf->GetValuePointer()) {
3429 // We should attempts to set the address of the branch.
3430 // something like:
3431 //(TBranchElement*)branch->GetMother()->SetAddress(0)
3432 //plus a few more subtleties (see TBranchElement::GetEntry).
3433 //but for now we go the simplest route:
3434 //
3435 // Note: This may result in the allocation of an object.
3436 branch->SetupAddresses();
3437 }
3438 if (branch->GetAddress()) {
3439 tree->SetBranchAddress(branch->GetName(), (void*) branch->GetAddress());
3440 TBranch* br = tree->GetBranch(branch->GetName());
3441 if (br) {
3442 if (br->IsA() != branch->IsA()) {
3443 Error(
3444 "CopyAddresses",
3445 "Branch kind mismatch between input tree '%s' and output tree '%s' for branch '%s': '%s' vs '%s'",
3446 tree->GetName(), br->GetTree()->GetName(), br->GetName(), branch->IsA()->GetName(),
3447 br->IsA()->GetName());
3448 }
3449 // The copy does not own any object allocated by SetAddress().
3450 // FIXME: We do too much here, br may not be a top-level branch.
3451 if (br->InheritsFrom(TBranchElement::Class())) {
3452 ((TBranchElement*) br)->ResetDeleteObject();
3453 }
3454 } else {
3455 Warning("CopyAddresses", "Could not find branch named '%s' in tree named '%s'", branch->GetName(), tree->GetName());
3456 }
3457 } else {
3458 tleaf->SetAddress(leaf->GetValuePointer());
3459 }
3460 }
3461 }
3462
3463 if (undo &&
3464 ( tree->IsA()->InheritsFrom("TNtuple") || tree->IsA()->InheritsFrom("TNtupleD") )
3465 ) {
3466 tree->ResetBranchAddresses();
3467 }
3468}
3469
3470namespace {
3471
3472 enum EOnIndexError { kDrop, kKeep, kBuild };
3473
3474 bool R__HandleIndex(EOnIndexError onIndexError, TTree *newtree, TTree *oldtree)
3475 {
3476 // Return true if we should continue to handle indices, false otherwise.
3477
3478 bool withIndex = true;
3479
3480 if ( newtree->GetTreeIndex() ) {
3481 if ( oldtree->GetTree()->GetTreeIndex() == nullptr ) {
3482 switch (onIndexError) {
3483 case kDrop:
3484 delete newtree->GetTreeIndex();
3485 newtree->SetTreeIndex(nullptr);
3486 withIndex = false;
3487 break;
3488 case kKeep:
3489 // Nothing to do really.
3490 break;
3491 case kBuild:
3492 // Build the index then copy it
3493 if (oldtree->GetTree()->BuildIndex(newtree->GetTreeIndex()->GetMajorName(), newtree->GetTreeIndex()->GetMinorName())) {
3494 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3495 // Clean up
3496 delete oldtree->GetTree()->GetTreeIndex();
3497 oldtree->GetTree()->SetTreeIndex(nullptr);
3498 }
3499 break;
3500 }
3501 } else {
3502 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3503 }
3504 } else if ( oldtree->GetTree()->GetTreeIndex() != nullptr ) {
3505 // We discover the first index in the middle of the chain.
3506 switch (onIndexError) {
3507 case kDrop:
3508 // Nothing to do really.
3509 break;
3510 case kKeep: {
3511 TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
3512 index->SetTree(newtree);
3513 newtree->SetTreeIndex(index);
3514 break;
3515 }
3516 case kBuild:
3517 if (newtree->GetEntries() == 0) {
3518 // Start an index.
3519 TVirtualIndex *index = (TVirtualIndex*) oldtree->GetTree()->GetTreeIndex()->Clone();
3520 index->SetTree(newtree);
3521 newtree->SetTreeIndex(index);
3522 } else {
3523 // Build the index so far.
3524 if (newtree->BuildIndex(oldtree->GetTree()->GetTreeIndex()->GetMajorName(), oldtree->GetTree()->GetTreeIndex()->GetMinorName())) {
3525 newtree->GetTreeIndex()->Append(oldtree->GetTree()->GetTreeIndex(), true);
3526 }
3527 }
3528 break;
3529 }
3530 } else if ( onIndexError == kDrop ) {
3531 // There is no index on this or on tree->GetTree(), we know we have to ignore any further
3532 // index
3533 withIndex = false;
3534 }
3535 return withIndex;
3536 }
3537}
3538
3539////////////////////////////////////////////////////////////////////////////////
3540/// Copy nentries from given tree to this tree.
3541/// This routines assumes that the branches that intended to be copied are
3542/// already connected. The typical case is that this tree was created using
3543/// tree->CloneTree(0).
3544///
3545/// By default copy all entries.
3546///
3547/// Returns number of bytes copied to this tree.
3548///
3549/// If 'option' contains the word 'fast' and nentries is -1, the cloning will be
3550/// done without unzipping or unstreaming the baskets (i.e., a direct copy of the
3551/// raw bytes on disk).
3552///
3553/// When 'fast' is specified, 'option' can also contains a sorting order for the
3554/// baskets in the output file.
3555///
3556/// There are currently 3 supported sorting order:
3557///
3558/// - SortBasketsByOffset (the default)
3559/// - SortBasketsByBranch
3560/// - SortBasketsByEntry
3561///
3562/// See TTree::CloneTree for a detailed explanation of the semantics of these 3 options.
3563///
3564/// If the tree or any of the underlying tree of the chain has an index, that index and any
3565/// index in the subsequent underlying TTree objects will be merged.
3566///
3567/// There are currently three 'options' to control this merging:
3568/// - NoIndex : all the TTreeIndex object are dropped.
3569/// - DropIndexOnError : if any of the underlying TTree object do no have a TTreeIndex,
3570/// they are all dropped.
3571/// - AsIsIndexOnError [default]: In case of missing TTreeIndex, the resulting TTree index has gaps.
3572/// - BuildIndexOnError : If any of the underlying TTree objects do not have a TTreeIndex,
3573/// all TTreeIndex are 'ignored' and the missing piece are rebuilt.
3575Long64_t TTree::CopyEntries(TTree* tree, Long64_t nentries /* = -1 */, Option_t* option /* = "" */, bool needCopyAddresses /* = false */)
3576{
3577 if (!tree) {
3578 return 0;
3579 }
3580 // Options
3581 TString opt = option;
3582 opt.ToLower();
3583 bool fastClone = opt.Contains("fast");
3584 bool withIndex = !opt.Contains("noindex");
3585 EOnIndexError onIndexError;
3586 if (opt.Contains("asisindex")) {
3588 } else if (opt.Contains("buildindex")) {
3590 } else if (opt.Contains("dropindex")) {
3592 } else {
3594 }
3595 Ssiz_t cacheSizeLoc = opt.Index("cachesize=");
3596 Long64_t cacheSize = -1;
3598 // If the parse faile, cacheSize stays at -1.
3599 Ssiz_t cacheSizeEnd = opt.Index(" ",cacheSizeLoc+10) - (cacheSizeLoc+10);
3603 Warning("CopyEntries","The cachesize option can not be parsed: %s. The default size will be used.",cacheSizeStr.String().Data());
3605 double m;
3606 const char *munit = nullptr;
3607 ROOT::ToHumanReadableSize(std::numeric_limits<decltype(cacheSize)>::max(),false,&m,&munit);
3608
3609 Warning("CopyEntries","The cachesize option is too large: %s (%g%s max). The default size will be used.",cacheSizeStr.String().Data(),m,munit);
3610 }
3611 }
3612 if (gDebug > 0 && cacheSize != -1) Info("CopyEntries","Using Cache size: %lld\n",cacheSize);
3613
3614 Long64_t nbytes = 0;
3616 if (nentries < 0) {
3618 } else if (nentries > treeEntries) {
3620 }
3621
3623 // Quickly copy the basket without decompression and streaming.
3625 for (Long64_t i = 0; i < nentries; i += tree->GetTree()->GetEntries()) {
3626 if (tree->LoadTree(i) < 0) {
3627 break;
3628 }
3629 if ( withIndex ) {
3630 withIndex = R__HandleIndex( onIndexError, this, tree );
3631 }
3632 if (this->GetDirectory()) {
3633 TFile* file2 = this->GetDirectory()->GetFile();
3634 if (file2 && (file2->GetEND() > TTree::GetMaxTreeSize())) {
3635 if (this->GetDirectory() == (TDirectory*) file2) {
3636 this->ChangeFile(file2);
3637 }
3638 }
3639 }
3641 if (cloner.IsValid()) {
3642 this->SetEntries(this->GetEntries() + tree->GetTree()->GetEntries());
3643 if (cacheSize != -1) cloner.SetCacheSize(cacheSize);
3644 cloner.Exec();
3645 } else {
3646 if (i == 0) {
3647 Warning("CopyEntries","%s",cloner.GetWarning());
3648 // If the first cloning does not work, something is really wrong
3649 // (since apriori the source and target are exactly the same structure!)
3650 return -1;
3651 } else {
3652 if (cloner.NeedConversion()) {
3653 TTree *localtree = tree->GetTree();
3654 Long64_t tentries = localtree->GetEntries();
3655 if (needCopyAddresses) {
3656 // Copy MakeClass status.
3657 tree->SetMakeClass(fMakeClass);
3658 // Copy branch addresses.
3659 CopyAddresses(tree);
3660 }
3661 for (Long64_t ii = 0; ii < tentries; ii++) {
3662 if (localtree->GetEntry(ii) <= 0) {
3663 break;
3664 }
3665 this->Fill();
3666 }
3667 if (needCopyAddresses)
3668 tree->ResetBranchAddresses();
3669 if (this->GetTreeIndex()) {
3670 this->GetTreeIndex()->Append(tree->GetTree()->GetTreeIndex(), true);
3671 }
3672 } else {
3673 Warning("CopyEntries","%s",cloner.GetWarning());
3674 if (tree->GetDirectory() && tree->GetDirectory()->GetFile()) {
3675 Warning("CopyEntries", "Skipped file %s\n", tree->GetDirectory()->GetFile()->GetName());
3676 } else {
3677 Warning("CopyEntries", "Skipped file number %d\n", tree->GetTreeNumber());
3678 }
3679 }
3680 }
3681 }
3682
3683 }
3684 if (this->GetTreeIndex()) {
3685 this->GetTreeIndex()->Append(nullptr,false); // Force the sorting
3686 }
3687 nbytes = GetTotBytes() - totbytes;
3688 } else {
3689 if (nentries < 0) {
3691 } else if (nentries > treeEntries) {
3693 }
3694 if (needCopyAddresses) {
3695 // Copy MakeClass status.
3696 tree->SetMakeClass(fMakeClass);
3697 // Copy branch addresses.
3698 CopyAddresses(tree);
3699 }
3700 Int_t treenumber = -1;
3701 for (Long64_t i = 0; i < nentries; i++) {
3702 if (tree->LoadTree(i) < 0) {
3703 break;
3704 }
3705 if (treenumber != tree->GetTreeNumber()) {
3706 if ( withIndex ) {
3707 withIndex = R__HandleIndex( onIndexError, this, tree );
3708 }
3709 treenumber = tree->GetTreeNumber();
3710 }
3711 if (tree->GetEntry(i) <= 0) {
3712 break;
3713 }
3714 nbytes += this->Fill();
3715 }
3716 if (needCopyAddresses)
3717 tree->ResetBranchAddresses();
3718 if (this->GetTreeIndex()) {
3719 this->GetTreeIndex()->Append(nullptr,false); // Force the sorting
3720 }
3721 }
3722 return nbytes;
3723}
3724
3725////////////////////////////////////////////////////////////////////////////////
3726/// Copy a tree with selection.
3727///
3728/// ### Important:
3729///
3730/// The returned copied tree stays connected with the original tree
3731/// until the original tree is deleted. In particular, any changes
3732/// to the branch addresses in the original tree are also made to
3733/// the copied tree. Any changes made to the branch addresses of the
3734/// copied tree are overridden anytime the original tree changes its
3735/// branch addresses. When the original tree is deleted, all the
3736/// branch addresses of the copied tree are set to zero.
3737///
3738/// For examples of CopyTree, see the tutorials:
3739///
3740/// - copytree.C:
3741/// Example macro to copy a subset of a tree to a new tree.
3742/// The input file was generated by running the program in
3743/// $ROOTSYS/test/Event in this way:
3744/// ~~~ {.cpp}
3745/// ./Event 1000 1 1 1
3746/// ~~~
3747/// - copytree2.C
3748/// Example macro to copy a subset of a tree to a new tree.
3749/// One branch of the new tree is written to a separate file.
3750/// The input file was generated by running the program in
3751/// $ROOTSYS/test/Event in this way:
3752/// ~~~ {.cpp}
3753/// ./Event 1000 1 1 1
3754/// ~~~
3755/// - copytree3.C
3756/// Example macro to copy a subset of a tree to a new tree.
3757/// Only selected entries are copied to the new tree.
3758/// NOTE that only the active branches are copied.
3760TTree* TTree::CopyTree(const char* selection, Option_t* option /* = 0 */, Long64_t nentries /* = TTree::kMaxEntries */, Long64_t firstentry /* = 0 */)
3761{
3762 GetPlayer();
3763 if (fPlayer) {
3765 }
3766 return nullptr;
3767}
3768
3769////////////////////////////////////////////////////////////////////////////////
3770/// Create a basket for this tree and given branch.
3773{
3774 if (!branch) {
3775 return nullptr;
3776 }
3777 return new TBasket(branch->GetName(), GetName(), branch);
3778}
3779
3780////////////////////////////////////////////////////////////////////////////////
3781/// Delete this tree from memory or/and disk.
3782///
3783/// - if option == "all" delete Tree object from memory AND from disk
3784/// all baskets on disk are deleted. All keys with same name
3785/// are deleted.
3786/// - if option =="" only Tree object in memory is deleted.
3788void TTree::Delete(Option_t* option /* = "" */)
3789{
3790 TFile *file = GetCurrentFile();
3791
3792 // delete all baskets and header from file
3793 if (file && option && !strcmp(option,"all")) {
3794 if (!file->IsWritable()) {
3795 Error("Delete","File : %s is not writable, cannot delete Tree:%s", file->GetName(),GetName());
3796 return;
3797 }
3798
3799 //find key and import Tree header in memory
3800 TKey *key = fDirectory->GetKey(GetName());
3801 if (!key) return;
3802
3804 file->cd();
3805
3806 //get list of leaves and loop on all the branches baskets
3807 TIter next(GetListOfLeaves());
3808 TLeaf *leaf;
3809 char header[16];
3810 Int_t ntot = 0;
3811 Int_t nbask = 0;
3813 while ((leaf = (TLeaf*)next())) {
3814 TBranch *branch = leaf->GetBranch();
3815 Int_t nbaskets = branch->GetMaxBaskets();
3816 for (Int_t i=0;i<nbaskets;i++) {
3817 Long64_t pos = branch->GetBasketSeek(i);
3818 if (!pos) continue;
3819 TFile *branchFile = branch->GetFile();
3820 if (!branchFile) continue;
3821 branchFile->GetRecordHeader(header,pos,16,nbytes,objlen,keylen);
3822 if (nbytes <= 0) continue;
3823 branchFile->MakeFree(pos,pos+nbytes-1);
3824 ntot += nbytes;
3825 nbask++;
3826 }
3827 }
3828
3829 // delete Tree header key and all keys with the same name
3830 // A Tree may have been saved many times. Previous cycles are invalid.
3831 while (key) {
3832 ntot += key->GetNbytes();
3833 key->Delete();
3834 delete key;
3835 key = fDirectory->GetKey(GetName());
3836 }
3837 if (dirsav) dirsav->cd();
3838 if (gDebug) Info("TTree::Delete", "Deleting Tree: %s: %d baskets deleted. Total space freed = %d bytes\n",GetName(),nbask,ntot);
3839 }
3840
3841 if (fDirectory) {
3842 fDirectory->Remove(this);
3843 //delete the file cache if it points to this Tree
3844 MoveReadCache(file,nullptr);
3845 fDirectory = nullptr;
3847 }
3848
3849 // Delete object from Cling symbol table so it can not be used anymore.
3850 gCling->DeleteGlobal(this);
3851
3852 // Warning: We have intentional invalidated this object while inside a member function!
3853 delete this;
3854}
3855
3856 ///////////////////////////////////////////////////////////////////////////////
3857 /// Called by TKey and TObject::Clone to automatically add us to a directory
3858 /// when we are read from a file.
3861{
3862 if (fDirectory == dir) return;
3863 if (fDirectory) {
3864 fDirectory->Remove(this);
3865 // Delete or move the file cache if it points to this Tree
3866 TFile *file = fDirectory->GetFile();
3867 MoveReadCache(file,dir);
3868 }
3869 fDirectory = dir;
3870 TBranch* b = nullptr;
3871 TIter next(GetListOfBranches());
3872 while((b = (TBranch*) next())) {
3873 b->UpdateFile();
3874 }
3875 if (fBranchRef) {
3877 }
3878 if (fDirectory) fDirectory->Append(this);
3879}
3880
3881////////////////////////////////////////////////////////////////////////////////
3882/// Draw expression varexp for specified entries.
3883///
3884/// \return -1 in case of error or number of selected events in case of success.
3885/// If `selection` involves an array variable `x[n]`, for example `x[] > 0` or
3886/// `x > 0`, then we return the number of selected instances rather than number of events.
3887/// In the output of `tree.Scan()`, instances are shown in individual printed rows, thus
3888/// each event (tree entry) is split across the various instances (lines) of the array.
3889/// In contrast, the function `GetEntries(selection)` always returns the number of entries selected.
3890///
3891/// This function accepts TCut objects as arguments.
3892/// Useful to use the string operator +
3893///
3894/// Example:
3895///
3896/// ~~~ {.cpp}
3897/// ntuple.Draw("x",cut1+cut2+cut3);
3898/// ~~~
3899
3904}
3905
3906/////////////////////////////////////////////////////////////////////////////////////////
3907/// \brief Draw expression varexp for entries and objects that pass a (optional) selection.
3908///
3909/// \return -1 in case of error or number of selected events in case of success.
3910/// If `selection` involves an array variable `x[n]`, for example `x[] > 0` or
3911/// `x > 0`, then we return the number of selected instances rather than number of events.
3912/// In the output of `tree.Scan()`, instances are shown in individual printed rows, thus
3913/// each event (tree entry) is split across the various instances (lines) of the array.
3914/// In contrast, the function `GetEntries(selection)` always returns the number of entries selected.
3915///
3916/// \param [in] varexp
3917/// \parblock
3918/// A string that takes one of these general forms:
3919/// - "e1" produces a 1-d histogram (TH1F) of expression "e1"
3920/// - "e1:e2" produces an unbinned 2-d scatter-plot (TGraph) of "e1"
3921/// on the y-axis versus "e2" on the x-axis
3922/// - "e1:e2:e3" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3923/// vs "e2" vs "e3" on the z-, y-, x-axis, respectively
3924/// - "e1:e2:e3:e4" produces an unbinned 3-d scatter-plot (TPolyMarker3D) of "e1"
3925/// vs "e2" vs "e3" and "e4" mapped on the current color palette.
3926/// (to create histograms in the 2, 3, and 4 dimensional case,
3927/// see section "Saving the result of Draw to an histogram")
3928/// - "e1:e2:e3:e4:e5" with option "GL5D" produces a 5D plot using OpenGL. `gStyle->SetCanvasPreferGL(true)` is
3929/// needed.
3930/// - Any number of variables no fewer than two can be used with the options "CANDLE" and "PARA"
3931/// - An arbitrary number of variables can be used with the option "GOFF"
3932///
3933/// Examples:
3934/// - "x": the simplest case, it draws a 1-Dim histogram of column x
3935/// - "sqrt(x)", "x*y/z": draw histogram with the values of the specified numerical expression across TTree events
3936/// - "y:sqrt(x)": 2-Dim histogram of y versus sqrt(x)
3937/// - "px:py:pz:2.5*E": produces a 3-d scatter-plot of px vs py ps pz
3938/// and the color number of each marker will be 2.5*E.
3939/// If the color number is negative it is set to 0.
3940/// If the color number is greater than the current number of colors
3941/// it is set to the highest color number. The default number of
3942/// colors is 50. See TStyle::SetPalette for setting a new color palette.
3943///
3944/// The expressions can use all the operations and built-in functions
3945/// supported by TFormula (see TFormula::Analyze()), including free
3946/// functions taking numerical arguments (e.g. TMath::Bessel()).
3947/// In addition, you can call member functions taking numerical
3948/// arguments. For example, these are two valid expressions:
3949/// ~~~ {.cpp}
3950/// TMath::BreitWigner(fPx,3,2)
3951/// event.GetHistogram()->GetXaxis()->GetXmax()
3952/// ~~~
3953/// \endparblock
3954/// \param [in] selection
3955/// \parblock
3956/// A string containing a selection expression.
3957/// In a selection all usual C++ mathematical and logical operators are allowed.
3958/// The value corresponding to the selection expression is used as a weight
3959/// to fill the histogram (a weight of 0 is equivalent to not filling the histogram).\n
3960/// \n
3961/// Examples:
3962/// - "x<y && sqrt(z)>3.2": returns a weight = 0 or 1
3963/// - "(x+y)*(sqrt(z)>3.2)": returns a weight = x+y if sqrt(z)>3.2, 0 otherwise\n
3964/// \n
3965/// If the selection expression returns an array, it is iterated over in sync with the
3966/// array returned by the varexp argument (as described below in "Drawing expressions using arrays and array
3967/// elements"). For example, if, for a given event, varexp evaluates to
3968/// `{1., 2., 3.}` and selection evaluates to `{0, 1, 0}`, the resulting histogram is filled with the value 2. For
3969/// example, for each event here we perform a simple object selection:
3970/// ~~~{.cpp}
3971/// // Muon_pt is an array: fill a histogram with the array elements > 100 in each event
3972/// tree->Draw('Muon_pt', 'Muon_pt > 100')
3973/// ~~~
3974/// \endparblock
3975/// \param [in] option
3976/// \parblock
3977/// The drawing option.
3978/// - When an histogram is produced it can be any histogram drawing option
3979/// listed in THistPainter.
3980/// - when no option is specified:
3981/// - the default histogram drawing option is used
3982/// if the expression is of the form "e1".
3983/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
3984/// unbinned 2D or 3D points is drawn respectively.
3985/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
3986/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
3987/// palette.
3988/// - If option COL is specified when varexp has three fields:
3989/// ~~~ {.cpp}
3990/// tree.Draw("e1:e2:e3","","col");
3991/// ~~~
3992/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
3993/// color palette. The colors for e3 are evaluated once in linear scale before
3994/// painting. Therefore changing the pad to log scale along Z as no effect
3995/// on the colors.
3996/// - if expression has more than four fields the option "PARA"or "CANDLE"
3997/// can be used.
3998/// - If option contains the string "goff", no graphics is generated.
3999/// \endparblock
4000/// \param [in] nentries The number of entries to process (default is all)
4001/// \param [in] firstentry The first entry to process (default is 0)
4002///
4003/// ### Drawing expressions using arrays and array elements
4004///
4005/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
4006/// or a TClonesArray.
4007/// In a TTree::Draw expression you can now access fMatrix using the following
4008/// syntaxes:
4009///
4010/// | String passed | What is used for each entry of the tree
4011/// |-----------------|--------------------------------------------------------|
4012/// | `fMatrix` | the 9 elements of fMatrix |
4013/// | `fMatrix[][]` | the 9 elements of fMatrix |
4014/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
4015/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
4016/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
4017/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
4018///
4019/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
4020///
4021/// In summary, if a specific index is not specified for a dimension, TTree::Draw
4022/// will loop through all the indices along this dimension. Leaving off the
4023/// last (right most) dimension of specifying then with the two characters '[]'
4024/// is equivalent. For variable size arrays (and TClonesArray) the range
4025/// of the first dimension is recalculated for each entry of the tree.
4026/// You can also specify the index as an expression of any other variables from the
4027/// tree.
4028///
4029/// TTree::Draw also now properly handling operations involving 2 or more arrays.
4030///
4031/// Let assume a second matrix fResults[5][2], here are a sample of some
4032/// of the possible combinations, the number of elements they produce and
4033/// the loop used:
4034///
4035/// | expression | element(s) | Loop |
4036/// |----------------------------------|------------|--------------------------|
4037/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
4038/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
4039/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
4040/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
4041/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
4042/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
4043/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
4044/// | `fMatrix[][fResult[][]]` | 30 | on 1st dim of fMatrix then on both dimensions of fResults. The
4045/// value if fResults[j][k] is used as the second index of fMatrix.|
4046///
4047///
4048/// In summary, TTree::Draw loops through all unspecified dimensions. To
4049/// figure out the range of each loop, we match each unspecified dimension
4050/// from left to right (ignoring ALL dimensions for which an index has been
4051/// specified), in the equivalent loop matched dimensions use the same index
4052/// and are restricted to the smallest range (of only the matched dimensions).
4053/// When involving variable arrays, the range can of course be different
4054/// for each entry of the tree.
4055///
4056/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
4057/// ~~~ {.cpp}
4058/// for (Int_t i0; i < min(3,2); i++) {
4059/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
4060/// }
4061/// ~~~
4062/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
4063/// ~~~ {.cpp}
4064/// for (Int_t i0; i < min(3,5); i++) {
4065/// for (Int_t i1; i1 < 2; i1++) {
4066/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
4067/// }
4068/// }
4069/// ~~~
4070/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
4071/// ~~~ {.cpp}
4072/// for (Int_t i0; i < min(3,5); i++) {
4073/// for (Int_t i1; i1 < min(3,2); i1++) {
4074/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
4075/// }
4076/// }
4077/// ~~~
4078/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
4079/// ~~~ {.cpp}
4080/// for (Int_t i0; i0 < 3; i0++) {
4081/// for (Int_t j2; j2 < 5; j2++) {
4082/// for (Int_t j3; j3 < 2; j3++) {
4083/// i1 = fResults[j2][j3];
4084/// use the value of fMatrix[i0][i1]
4085/// }
4086/// }
4087/// ~~~
4088/// ### Retrieving the result of Draw
4089///
4090/// By default a temporary histogram called `htemp` is created. It will be:
4091///
4092/// - A TH1F* in case of a mono-dimensional distribution: `Draw("e1")`,
4093/// - A TH2F* in case of a bi-dimensional distribution: `Draw("e1:e2")`,
4094/// - A TH3F* in case of a three-dimensional distribution: `Draw("e1:e2:e3")`.
4095///
4096/// In the one dimensional case the `htemp` is filled and drawn whatever the drawing
4097/// option is.
4098///
4099/// In the two and three dimensional cases, with the default drawing option (`""`),
4100/// a cloud of points is drawn and the histogram `htemp` is not filled. For all the other
4101/// drawing options `htemp` will be filled.
4102///
4103/// In all cases `htemp` can be retrieved by calling:
4104///
4105/// ~~~ {.cpp}
4106/// auto htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
4107/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp"); // 2D
4108/// auto htemp = (TH3F*)gPad->GetPrimitive("htemp"); // 3D
4109/// ~~~
4110///
4111/// In the two dimensional case (`Draw("e1;e2")`), with the default drawing option, the
4112/// data is filled into a TGraph named `Graph`. This TGraph can be retrieved by
4113/// calling
4114///
4115/// ~~~ {.cpp}
4116/// auto graph = (TGraph*)gPad->GetPrimitive("Graph");
4117/// ~~~
4118///
4119/// For the three and four dimensional cases, with the default drawing option, an unnamed
4120/// TPolyMarker3D is produced, and therefore cannot be retrieved.
4121///
4122/// In all cases `htemp` can be used to access the axes. For instance in the 2D case:
4123///
4124/// ~~~ {.cpp}
4125/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp");
4126/// auto xaxis = htemp->GetXaxis();
4127/// ~~~
4128///
4129/// When the option `"A"` is used (with TGraph painting option) to draw a 2D
4130/// distribution:
4131/// ~~~ {.cpp}
4132/// tree.Draw("e1:e2","","A*");
4133/// ~~~
4134/// a scatter plot is produced (with stars in that case) but the axis creation is
4135/// delegated to TGraph and `htemp` is not created.
4136///
4137/// ### Saving the result of Draw to a histogram
4138///
4139/// If `varexp` contains `>>hnew` (following the variable(s) name(s)),
4140/// the new histogram called `hnew` is created and it is kept in the current
4141/// directory (and also the current pad). This works for all dimensions.
4142///
4143/// Example:
4144/// ~~~ {.cpp}
4145/// tree.Draw("sqrt(x)>>hsqrt","y>0")
4146/// ~~~
4147/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
4148/// directory. To retrieve it do:
4149/// ~~~ {.cpp}
4150/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
4151/// ~~~
4152/// The binning information is taken from the environment variables
4153/// ~~~ {.cpp}
4154/// Hist.Binning.?D.?
4155/// ~~~
4156/// In addition, the name of the histogram can be followed by up to 9
4157/// numbers between '(' and ')', where the numbers describe the
4158/// following:
4159///
4160/// - 1 - bins in x-direction
4161/// - 2 - lower limit in x-direction
4162/// - 3 - upper limit in x-direction
4163/// - 4-6 same for y-direction
4164/// - 7-9 same for z-direction
4165///
4166/// When a new binning is used the new value will become the default.
4167/// Values can be skipped.
4168///
4169/// Example:
4170/// ~~~ {.cpp}
4171/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
4172/// // plot sqrt(x) between 10 and 20 using 500 bins
4173/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
4174/// // plot sqrt(x) against sin(y)
4175/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
4176/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
4177/// ~~~
4178/// By default, if a histogram with the same name is already registered to the current
4179/// ROOT directory, the specified histogram is reset. To continue to append data to an
4180/// existing histogram, use "+" in front of the histogram name.
4181///
4182/// A '+' in front of the histogram name is ignored, when the name is followed by
4183/// binning information as described in the previous paragraph.
4184/// ~~~ {.cpp}
4185/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
4186/// ~~~
4187/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
4188/// and 3-D histograms.
4189///
4190/// Note that when the automatic registration of histograms is off (see \ref DisableObjectAutoRegistration() ),
4191/// external histogram are not visible to TTree::Draw unless they are registered to the current directory explicitly.
4192/// ~~~ {.cpp}
4193/// auto histo = new TH1D("histo", ...);
4194/// histo->SetDirectory(gDirectory);
4195/// tree.Draw("sqrt(x)>>histo","y>0")
4196/// ~~~
4197/// When auto-registration is off, histograms created by TTree::Draw will still be registered to the current directory.
4198///
4199/// ### Accessing collection objects
4200///
4201/// TTree::Draw default's handling of collections is to assume that any
4202/// request on a collection pertain to it content. For example, if fTracks
4203/// is a collection of Track objects, the following:
4204/// ~~~ {.cpp}
4205/// tree->Draw("event.fTracks.fPx");
4206/// ~~~
4207/// will plot the value of fPx for each Track objects inside the collection.
4208/// Also
4209/// ~~~ {.cpp}
4210/// tree->Draw("event.fTracks.size()");
4211/// ~~~
4212/// would plot the result of the member function Track::size() for each
4213/// Track object inside the collection.
4214/// To access information about the collection itself, TTree::Draw support
4215/// the '@' notation. If a variable which points to a collection is prefixed
4216/// or postfixed with '@', the next part of the expression will pertain to
4217/// the collection object. For example:
4218/// ~~~ {.cpp}
4219/// tree->Draw("event.@fTracks.size()");
4220/// ~~~
4221/// will plot the size of the collection referred to by `fTracks` (i.e the number
4222/// of Track objects).
4223///
4224/// ### Drawing 'objects'
4225///
4226/// When a class has a member function named AsDouble or AsString, requesting
4227/// to directly draw the object will imply a call to one of the 2 functions.
4228/// If both AsDouble and AsString are present, AsDouble will be used.
4229/// AsString can return either a char*, a std::string or a TString.s
4230/// For example, the following
4231/// ~~~ {.cpp}
4232/// tree->Draw("event.myTTimeStamp");
4233/// ~~~
4234/// will draw the same histogram as
4235/// ~~~ {.cpp}
4236/// tree->Draw("event.myTTimeStamp.AsDouble()");
4237/// ~~~
4238/// In addition, when the object is a type TString or std::string, TTree::Draw
4239/// will call respectively `TString::Data` and `std::string::c_str()`
4240///
4241/// If the object is a TBits, the histogram will contain the index of the bit
4242/// that are turned on.
4243///
4244/// ### Retrieving information about the tree itself.
4245///
4246/// You can refer to the tree (or chain) containing the data by using the
4247/// string 'This'.
4248/// You can then could any TTree methods. For example:
4249/// ~~~ {.cpp}
4250/// tree->Draw("This->GetReadEntry()");
4251/// ~~~
4252/// will display the local entry numbers be read.
4253/// ~~~ {.cpp}
4254/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
4255/// ~~~
4256/// will display the name of the first 'user info' object.
4257///
4258/// ### Special functions and variables
4259///
4260/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
4261/// to access the entry number being read. For example to draw every
4262/// other entry use:
4263/// ~~~ {.cpp}
4264/// tree.Draw("myvar","Entry$%2==0");
4265/// ~~~
4266/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
4267/// - `LocalEntry$` : return the current entry number in the current tree of a
4268/// chain (`== GetTree()->GetReadEntry()`)
4269/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
4270/// - `LocalEntries$` : return the total number of entries in the current tree
4271/// of a chain (== GetTree()->TTree::GetEntries())
4272/// - `Length$` : return the total number of element of this formula for this
4273/// entry (`==TTreeFormula::GetNdata()`)
4274/// - `Iteration$` : return the current iteration over this formula for this
4275/// entry (i.e. varies from 0 to `Length$ - 1`).
4276/// - `Length$(formula )` : return the total number of element of the formula
4277/// given as a parameter.
4278/// - `Sum$(formula )` : return the sum of the value of the elements of the
4279/// formula given as a parameter. For example the mean for all the elements in
4280/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
4281/// - `Min$(formula )` : return the minimum (within one TTree entry) of the value of the
4282/// elements of the formula given as a parameter.
4283/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
4284/// elements of the formula given as a parameter.
4285/// - `MinIf$(formula,condition)`
4286/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
4287/// of the value of the elements of the formula given as a parameter
4288/// if they match the condition. If no element matches the condition,
4289/// the result is zero. To avoid the resulting peak at zero, use the
4290/// pattern:
4291/// ~~~ {.cpp}
4292/// tree->Draw("MinIf$(formula,condition)","condition");
4293/// ~~~
4294/// which will avoid calculation `MinIf$` for the entries that have no match
4295/// for the condition.
4296/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
4297/// for the current iteration otherwise return the value of "alternate".
4298/// For example, with arr1[3] and arr2[2]
4299/// ~~~ {.cpp}
4300/// tree->Draw("arr1+Alt$(arr2,0)");
4301/// ~~~
4302/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
4303/// Or with a variable size array arr3
4304/// ~~~ {.cpp}
4305/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
4306/// ~~~
4307/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
4308/// As a comparison
4309/// ~~~ {.cpp}
4310/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
4311/// ~~~
4312/// will draw the sum arr3 for the index 0 to 2 only if the
4313/// actual_size_of_arr3 is greater or equal to 3.
4314/// Note that the array in 'primary' is flattened/linearized thus using
4315/// `Alt$` with multi-dimensional arrays of different dimensions is unlikely
4316/// to yield the expected results. To visualize a bit more what elements
4317/// would be matched by TTree::Draw, TTree::Scan can be used:
4318/// ~~~ {.cpp}
4319/// tree->Scan("arr1:Alt$(arr2,0)");
4320/// ~~~
4321/// will print on one line the value of arr1 and (arr2,0) that will be
4322/// matched by
4323/// ~~~ {.cpp}
4324/// tree->Draw("arr1-Alt$(arr2,0)");
4325/// ~~~
4326/// The ternary operator is not directly supported in TTree::Draw however, to plot the
4327/// equivalent of `var2<20 ? -99 : var1`, you can use:
4328/// ~~~ {.cpp}
4329/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
4330/// ~~~
4331///
4332/// ### Drawing a user function accessing the TTree data directly
4333///
4334/// If the formula contains a file name, TTree::MakeProxy will be used
4335/// to load and execute this file. In particular it will draw the
4336/// result of a function with the same name as the file. The function
4337/// will be executed in a context where the name of the branches can
4338/// be used as a C++ variable.
4339///
4340/// For example draw px using the file hsimple.root (generated by the
4341/// hsimple.C tutorial), we need a file named hsimple.cxx:
4342/// ~~~ {.cpp}
4343/// double hsimple() {
4344/// return px;
4345/// }
4346/// ~~~
4347/// MakeProxy can then be used indirectly via the TTree::Draw interface
4348/// as follow:
4349/// ~~~ {.cpp}
4350/// new TFile("hsimple.root")
4351/// ntuple->Draw("hsimple.cxx");
4352/// ~~~
4353/// A more complete example is available in the tutorials directory:
4354/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
4355/// which reimplement the selector found in `h1analysis.C`
4356///
4357/// The main features of this facility are:
4358///
4359/// * on-demand loading of branches
4360/// * ability to use the 'branchname' as if it was a data member
4361/// * protection against array out-of-bound
4362/// * ability to use the branch data as object (when the user code is available)
4363///
4364/// See TTree::MakeProxy for more details.
4365///
4366/// ### Making a Profile histogram
4367///
4368/// In case of a 2-Dim expression, one can generate a TProfile histogram
4369/// instead of a TH2F histogram by specifying option=prof or option=profs
4370/// or option=profi or option=profg ; the trailing letter select the way
4371/// the bin error are computed, See TProfile2D::SetErrorOption for
4372/// details on the differences.
4373/// The option=prof is automatically selected in case of y:x>>pf
4374/// where pf is an existing TProfile histogram.
4375///
4376/// ### Making a 2D Profile histogram
4377///
4378/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
4379/// instead of a TH3F histogram by specifying option=prof or option=profs.
4380/// or option=profi or option=profg ; the trailing letter select the way
4381/// the bin error are computed, See TProfile2D::SetErrorOption for
4382/// details on the differences.
4383/// The option=prof is automatically selected in case of z:y:x>>pf
4384/// where pf is an existing TProfile2D histogram.
4385///
4386/// ### Making a 5D plot using GL
4387///
4388/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
4389/// using OpenGL. See tree502_staff.C as example.
4390///
4391/// ### Making a parallel coordinates plot
4392///
4393/// In case of a 2-Dim or more expression with the option=para, one can generate
4394/// a parallel coordinates plot. With that option, the number of dimensions is
4395/// arbitrary. Giving more than 4 variables without the option=para or
4396/// option=candle or option=goff will produce an error.
4397///
4398/// ### Making a candle sticks chart
4399///
4400/// In case of a 2-Dim or more expression with the option=candle, one can generate
4401/// a candle sticks chart. With that option, the number of dimensions is
4402/// arbitrary. Giving more than 4 variables without the option=para or
4403/// option=candle or option=goff will produce an error.
4404///
4405/// ### Normalizing the output histogram to 1
4406///
4407/// When option contains "norm" the output histogram is normalized to 1.
4408///
4409/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
4410///
4411/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
4412/// instead of histogramming one variable.
4413/// If varexp0 has the form >>elist , a TEventList object named "elist"
4414/// is created in the current directory. elist will contain the list
4415/// of entry numbers satisfying the current selection.
4416/// If option "entrylist" is used, a TEntryList object is created
4417/// If the selection contains arrays, vectors or any container class and option
4418/// "entrylistarray" is used, a TEntryListArray object is created
4419/// containing also the subentries satisfying the selection, i.e. the indices of
4420/// the branches which hold containers classes.
4421/// Example:
4422/// ~~~ {.cpp}
4423/// tree.Draw(">>yplus","y>0")
4424/// ~~~
4425/// will create a TEventList object named "yplus" in the current directory.
4426/// In an interactive session, one can type (after TTree::Draw)
4427/// ~~~ {.cpp}
4428/// yplus.Print("all")
4429/// ~~~
4430/// to print the list of entry numbers in the list.
4431/// ~~~ {.cpp}
4432/// tree.Draw(">>yplus", "y>0", "entrylist")
4433/// ~~~
4434/// will create a TEntryList object names "yplus" in the current directory
4435/// ~~~ {.cpp}
4436/// tree.Draw(">>yplus", "y>0", "entrylistarray")
4437/// ~~~
4438/// will create a TEntryListArray object names "yplus" in the current directory
4439///
4440/// By default, the specified entry list is reset.
4441/// To continue to append data to an existing list, use "+" in front
4442/// of the list name;
4443/// ~~~ {.cpp}
4444/// tree.Draw(">>+yplus","y>0")
4445/// ~~~
4446/// will not reset yplus, but will enter the selected entries at the end
4447/// of the existing list.
4448///
4449/// Note that when the automatic registration of event lists is off (see \ref DisableObjectAutoRegistration() ),
4450/// they are not visible to TTree::Draw unless they are registered to the current directory explicitly.
4451/// ~~~ {.cpp}
4452/// auto elist = new TEventList("elist", ...);
4453/// elist->SetDirectory(gDirectory);
4454/// tree.Draw(">>+elist","y>0")
4455/// ~~~
4456///
4457/// ### Using a TEventList, TEntryList or TEntryListArray as Input
4458///
4459/// Once a TEventList or a TEntryList object has been generated, it can be used as input
4460/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
4461/// current event list
4462///
4463/// Example 1:
4464/// ~~~ {.cpp}
4465/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
4466/// tree->SetEventList(elist);
4467/// tree->Draw("py");
4468/// ~~~
4469/// Example 2:
4470/// ~~~ {.cpp}
4471/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
4472/// tree->SetEntryList(elist);
4473/// tree->Draw("py");
4474/// ~~~
4475/// If a TEventList object is used as input, a new TEntryList object is created
4476/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
4477/// for this transformation. This new object is owned by the chain and is deleted
4478/// with it, unless the user extracts it by calling GetEntryList() function.
4479/// See also comments to SetEventList() function of TTree and TChain.
4480///
4481/// If arrays are used in the selection criteria and TEntryListArray is not used,
4482/// all the entries that have at least one element of the array that satisfy the selection
4483/// are entered in the list.
4484///
4485/// Example:
4486/// ~~~ {.cpp}
4487/// tree.Draw(">>pyplus","fTracks.fPy>0");
4488/// tree->SetEventList(pyplus);
4489/// tree->Draw("fTracks.fPy");
4490/// ~~~
4491/// will draw the fPy of ALL tracks in event with at least one track with
4492/// a positive fPy.
4493///
4494/// To select only the elements that did match the original selection
4495/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
4496///
4497/// Example:
4498/// ~~~ {.cpp}
4499/// tree.Draw(">>pyplus","fTracks.fPy>0");
4500/// pyplus->SetReapplyCut(true);
4501/// tree->SetEventList(pyplus);
4502/// tree->Draw("fTracks.fPy");
4503/// ~~~
4504/// will draw the fPy of only the tracks that have a positive fPy.
4505///
4506/// To draw only the elements that match a selection in case of arrays,
4507/// you can also use TEntryListArray (faster in case of a more general selection).
4508///
4509/// Example:
4510/// ~~~ {.cpp}
4511/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
4512/// tree->SetEntryList(pyplus);
4513/// tree->Draw("fTracks.fPy");
4514/// ~~~
4515/// will draw the fPy of only the tracks that have a positive fPy,
4516/// but without redoing the selection.
4517///
4518/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
4519///
4520/// ### How to obtain more info from TTree::Draw
4521///
4522/// Once TTree::Draw has been called, it is possible to access useful
4523/// information still stored in the TTree object via the following functions:
4524///
4525/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection
4526/// was specified, returns the number of values processed.
4527/// - GetV1() // returns a pointer to the double array of V1
4528/// - GetV2() // returns a pointer to the double array of V2
4529/// - GetV3() // returns a pointer to the double array of V3
4530/// - GetV4() // returns a pointer to the double array of V4
4531/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the
4532/// selection expression.
4533///
4534/// where V1,V2,V3 correspond to the expressions in
4535/// ~~~ {.cpp}
4536/// TTree::Draw("V1:V2:V3:V4",selection);
4537/// ~~~
4538/// If the expression has more than 4 component use GetVal(index)
4539///
4540/// Example:
4541/// ~~~ {.cpp}
4542/// Root > ntuple->Draw("py:px","pz>4");
4543/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
4544/// ntuple->GetV2(), ntuple->GetV1());
4545/// Root > gr->Draw("ap"); //draw graph in current pad
4546/// ~~~
4547///
4548/// A more complete complete tutorial (treegetval.C) shows how to use the
4549/// GetVal() method.
4550///
4551/// creates a TGraph object with a number of points corresponding to the
4552/// number of entries selected by the expression "pz>4", the x points of the graph
4553/// being the px values of the Tree and the y points the py values.
4554///
4555/// Important note: By default TTree::Draw creates the arrays obtained
4556/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
4557/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
4558/// values calculated.
4559/// By default fEstimate=1000000 and can be modified
4560/// via TTree::SetEstimate. To keep in memory all the results (in case
4561/// where there is only one result per entry), use
4562/// ~~~ {.cpp}
4563/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
4564/// ~~~
4565/// You must call SetEstimate if the expected number of selected rows
4566/// you need to look at is greater than 1000000.
4567///
4568/// You can use the option "goff" to turn off the graphics output
4569/// of TTree::Draw in the above example.
4570///
4571/// ### Automatic interface to TTree::Draw via the TTreeViewer
4572///
4573/// A complete graphical interface to this function is implemented
4574/// in the class TTreeViewer.
4575/// To start the TTreeViewer, three possibilities:
4576/// - select TTree context menu item "StartViewer"
4577/// - type the command "TTreeViewer TV(treeName)"
4578/// - execute statement "tree->StartViewer();"
4581{
4582 GetPlayer();
4583 if (fPlayer)
4585 return -1;
4586}
4587
4588////////////////////////////////////////////////////////////////////////////////
4589/// Remove some baskets from memory.
4591void TTree::DropBaskets()
4592{
4593 TBranch* branch = nullptr;
4595 for (Int_t i = 0; i < nb; ++i) {
4597 branch->DropBaskets("all");
4598 }
4599}
4600
4601////////////////////////////////////////////////////////////////////////////////
4602/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
4605{
4606 // Be careful not to remove current read/write buffers.
4608 for (Int_t i = 0; i < nleaves; ++i) {
4610 TBranch* branch = (TBranch*) leaf->GetBranch();
4611 Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
4612 for (Int_t j = 0; j < nbaskets - 1; ++j) {
4613 if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
4614 continue;
4615 }
4616 TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
4617 if (basket) {
4618 basket->DropBuffers();
4620 return;
4621 }
4622 }
4623 }
4624 }
4625}
4626
4627////////////////////////////////////////////////////////////////////////////////
4628/// Fill all branches.
4629///
4630/// This function loops on all the branches of this tree. For
4631/// each branch, it copies to the branch buffer (basket) the current
4632/// values of the leaves data types. If a leaf is a simple data type,
4633/// a simple conversion to a machine independent format has to be done.
4634///
4635/// This machine independent version of the data is copied into a
4636/// basket (each branch has its own basket). When a basket is full
4637/// (32k worth of data by default), it is then optionally compressed
4638/// and written to disk (this operation is also called committing or
4639/// 'flushing' the basket). The committed baskets are then
4640/// immediately removed from memory.
4641///
4642/// The function returns the number of bytes committed to the
4643/// individual branches.
4644///
4645/// If a write error occurs, the number of bytes returned is -1.
4646///
4647/// If no data are written, because, e.g., the branch is disabled,
4648/// the number of bytes returned is 0.
4649///
4650/// __The baskets are flushed and the Tree header saved at regular intervals__
4651///
4652/// At regular intervals, when the amount of data written so far is
4653/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
4654/// This makes future reading faster as it guarantees that baskets belonging to nearby
4655/// entries will be on the same disk region.
4656/// When the first call to flush the baskets happen, we also take this opportunity
4657/// to optimize the baskets buffers.
4658/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
4659/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
4660/// in case the program writing the Tree crashes.
4661/// The decisions to FlushBaskets and Auto Save can be made based either on the number
4662/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
4663/// written (fAutoFlush and fAutoSave positive).
4664/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
4665/// base on the number of events written instead of the number of bytes written.
4666///
4667/// \note Calling `TTree::FlushBaskets` too often increases the IO time.
4668///
4669/// \note Calling `TTree::AutoSave` too often increases the IO time and also the
4670/// file size.
4671///
4672/// \note This method calls `TTree::ChangeFile` when the tree reaches a size
4673/// greater than `TTree::fgMaxTreeSize`. This doesn't happen if the tree is
4674/// attached to a `TMemFile` or derivate.
4677{
4678 Int_t nbytes = 0;
4679 Int_t nwrite = 0;
4680 Int_t nerror = 0;
4682
4683 // Case of one single super branch. Automatically update
4684 // all the branch addresses if a new object was created.
4685 if (nbranches == 1)
4686 ((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
4687
4688 if (fBranchRef)
4689 fBranchRef->Clear();
4690
4691#ifdef R__USE_IMT
4694 if (useIMT) {
4695 fIMTFlush = true;
4696 fIMTZipBytes.store(0);
4697 fIMTTotBytes.store(0);
4698 }
4699#endif
4700
4701 for (Int_t i = 0; i < nbranches; ++i) {
4702 // Loop over all branches, filling and accumulating bytes written and error counts.
4704
4705 if (branch->TestBit(kDoNotProcess))
4706 continue;
4707
4708#ifndef R__USE_IMT
4709 nwrite = branch->FillImpl(nullptr);
4710#else
4711 nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
4712#endif
4713 if (nwrite < 0) {
4714 if (nerror < 2) {
4715 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
4716 " This error is symptomatic of a Tree created as a memory-resident Tree\n"
4717 " Instead of doing:\n"
4718 " TTree *T = new TTree(...)\n"
4719 " TFile *f = new TFile(...)\n"
4720 " you should do:\n"
4721 " TFile *f = new TFile(...)\n"
4722 " TTree *T = new TTree(...)\n\n",
4723 GetName(), branch->GetName(), nwrite, fEntries + 1);
4724 } else {
4725 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
4726 fEntries + 1);
4727 }
4728 ++nerror;
4729 } else {
4730 nbytes += nwrite;
4731 }
4732 }
4733
4734#ifdef R__USE_IMT
4735 if (fIMTFlush) {
4736 imtHelper.Wait();
4737 fIMTFlush = false;
4738 const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
4739 const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
4740 nbytes += imtHelper.GetNbytes();
4741 nerror += imtHelper.GetNerrors();
4742 }
4743#endif
4744
4745 if (fBranchRef)
4746 fBranchRef->Fill();
4747
4748 ++fEntries;
4749
4750 if (fEntries > fMaxEntries)
4751 KeepCircular();
4752
4753 if (gDebug > 0)
4754 Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
4756
4757 bool autoFlush = false;
4758 bool autoSave = false;
4759
4760 if (fAutoFlush != 0 || fAutoSave != 0) {
4761 // Is it time to flush or autosave baskets?
4762 if (fFlushedBytes == 0) {
4763 // If fFlushedBytes == 0, it means we never flushed or saved, so
4764 // we need to check if it's time to do it and recompute the values
4765 // of fAutoFlush and fAutoSave in terms of the number of entries.
4766 // Decision can be based initially either on the number of bytes
4767 // or the number of entries written.
4769
4770 if (fAutoFlush)
4772
4773 if (fAutoSave)
4774 autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
4775
4776 if (autoFlush || autoSave) {
4777 // First call FlushBasket to make sure that fTotBytes is up to date.
4779 autoFlush = false; // avoid auto flushing again later
4780
4781 // When we are in one-basket-per-cluster mode, there is no need to optimize basket:
4782 // they will automatically grow to the size needed for an event cluster (with the basket
4783 // shrinking preventing them from growing too much larger than the actually-used space).
4785 OptimizeBaskets(GetTotBytes(), 1, "");
4786 if (gDebug > 0)
4787 Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
4789 }
4791 fAutoFlush = fEntries; // Use test on entries rather than bytes
4792
4793 // subsequently in run
4794 if (fAutoSave < 0) {
4795 // Set fAutoSave to the largest integer multiple of
4796 // fAutoFlush events such that fAutoSave*fFlushedBytes
4797 // < (minus the input value of fAutoSave)
4799 if (zipBytes != 0) {
4801 } else if (totBytes != 0) {
4803 } else {
4805 TTree::Class()->WriteBuffer(b, (TTree *)this);
4806 Long64_t total = b.Length();
4808 }
4809 } else if (fAutoSave > 0) {
4811 }
4812
4813 if (fAutoSave != 0 && fEntries >= fAutoSave)
4814 autoSave = true;
4815
4816 if (gDebug > 0)
4817 Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
4818 }
4819 } else {
4820 // Check if we need to auto flush
4821 if (fAutoFlush) {
4822 if (fNClusterRange == 0)
4823 autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
4824 else
4826 }
4827 // Check if we need to auto save
4828 if (fAutoSave)
4829 autoSave = fEntries % fAutoSave == 0;
4830 }
4831 }
4832
4833 if (autoFlush) {
4835 if (gDebug > 0)
4836 Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
4839 }
4840
4841 if (autoSave) {
4842 AutoSave(); // does not call FlushBasketsImpl() again
4843 if (gDebug > 0)
4844 Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
4846 }
4847
4848 // Check that output file is still below the maximum size.
4849 // If above, close the current file and continue on a new file.
4850 // Currently, the automatic change of file is restricted
4851 // to the case where the tree is in the top level directory.
4852 if (fDirectory)
4853 if (TFile *file = fDirectory->GetFile())
4854 if (static_cast<TDirectory *>(file) == fDirectory && (file->GetEND() > fgMaxTreeSize))
4855 ChangeFile(file);
4856
4857 return nerror == 0 ? nbytes : -1;
4858}
4859
4860////////////////////////////////////////////////////////////////////////////////
4861/// Search in the array for a branch matching the branch name,
4862/// with the branch possibly expressed as a 'full' path name (with dots).
4864static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
4865 if (list==nullptr || branchname == nullptr || branchname[0] == '\0') return nullptr;
4866
4867 Int_t nbranches = list->GetEntries();
4868
4870
4871 for(Int_t index = 0; index < nbranches; ++index) {
4872 TBranch *where = (TBranch*)list->UncheckedAt(index);
4873
4874 const char *name = where->GetName();
4875 UInt_t len = strlen(name);
4876 if (len && name[len - 1] == ']' && (brlen == 0 || branchname[brlen - 1] != ']')) {
4877 const char *dim = strchr(name,'[');
4878 if (dim) {
4879 len = dim - name;
4880 }
4881 }
4882 if (brlen == len && strncmp(branchname,name,len)==0) {
4883 return where;
4884 }
4885 TBranch *next = nullptr;
4886 if ((brlen >= len) && (branchname[len] == '.')
4887 && strncmp(name, branchname, len) == 0) {
4888 // The prefix subbranch name match the branch name.
4889
4890 next = where->FindBranch(branchname);
4891 if (!next) {
4892 next = where->FindBranch(branchname+len+1);
4893 }
4894 if (next) return next;
4895 }
4896 const char *dot = strchr((char*)branchname,'.');
4897 if (dot) {
4898 if (len==(size_t)(dot-branchname) &&
4899 strncmp(branchname,name,dot-branchname)==0 ) {
4900 return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
4901 }
4902 }
4903 }
4904 return nullptr;
4905}
4906
4907////////////////////////////////////////////////////////////////////////////////
4908/// Return the branch that correspond to the path 'branchname', which can
4909/// include the name of the tree or the omitted name of the parent branches.
4910/// In case of ambiguity, returns the first match.
4911/// \sa TTree::GetBranch
4914{
4915 // We already have been visited while recursively looking
4916 // through the friends tree, let return
4918 return nullptr;
4919 }
4920
4921 if (!branchname)
4922 return nullptr;
4923
4924 TBranch* branch = nullptr;
4925 // If the first part of the name match the TTree name, look for the right part in the
4926 // list of branches.
4927 // This will allow the branchname to be preceded by
4928 // the name of this tree.
4929 if (strncmp(fName.Data(),branchname,fName.Length())==0 && branchname[fName.Length()]=='.') {
4931 if (branch) return branch;
4932 }
4933 // If we did not find it, let's try to find the full name in the list of branches.
4935 if (branch) return branch;
4936
4937 // If we still did not find, let's try to find it within each branch assuming it does not the branch name.
4938 TIter next(GetListOfBranches());
4939 while ((branch = (TBranch*) next())) {
4940 TBranch* nestedbranch = branch->FindBranch(branchname);
4941 if (nestedbranch) {
4942 return nestedbranch;
4943 }
4944 }
4945
4946 // Search in list of friends.
4947 if (!fFriends) {
4948 return nullptr;
4949 }
4950 TFriendLock lock(this, kFindBranch);
4952 TFriendElement* fe = nullptr;
4953 while ((fe = (TFriendElement*) nextf())) {
4954 TTree* t = fe->GetTree();
4955 if (!t) {
4956 continue;
4957 }
4958 // If the alias is present replace it with the real name.
4959 const char *subbranch = strstr(branchname, fe->GetName());
4960 if (subbranch != branchname) {
4961 subbranch = nullptr;
4962 }
4963 if (subbranch) {
4964 subbranch += strlen(fe->GetName());
4965 if (*subbranch != '.') {
4966 subbranch = nullptr;
4967 } else {
4968 ++subbranch;
4969 }
4970 }
4971 std::ostringstream name;
4972 if (subbranch) {
4973 name << t->GetName() << "." << subbranch;
4974 } else {
4975 name << branchname;
4976 }
4977 branch = t->FindBranch(name.str().c_str());
4978 if (branch) {
4979 return branch;
4980 }
4981 }
4982 return nullptr;
4983}
4984
4985////////////////////////////////////////////////////////////////////////////////
4986/// Find first leaf containing searchname.
4988TLeaf* TTree::FindLeaf(const char* searchname)
4989{
4990 if (!searchname)
4991 return nullptr;
4992
4993 // We already have been visited while recursively looking
4994 // through the friends tree, let's return.
4996 return nullptr;
4997 }
4998
4999 // This will allow the branchname to be preceded by
5000 // the name of this tree.
5001 const char* subsearchname = strstr(searchname, GetName());
5002 if (subsearchname != searchname) {
5003 subsearchname = nullptr;
5004 }
5005 if (subsearchname) {
5007 if (*subsearchname != '.') {
5008 subsearchname = nullptr;
5009 } else {
5010 ++subsearchname;
5011 if (subsearchname[0] == 0) {
5012 subsearchname = nullptr;
5013 }
5014 }
5015 }
5016
5021
5022 const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
5023
5024 // For leaves we allow for one level up to be prefixed to the name.
5025 TIter next(GetListOfLeaves());
5026 TLeaf* leaf = nullptr;
5027 while ((leaf = (TLeaf*) next())) {
5028 leafname = leaf->GetName();
5029 Ssiz_t dim = leafname.First('[');
5030 if (dim >= 0) leafname.Remove(dim);
5031
5032 if (leafname == searchname) {
5033 return leaf;
5034 }
5036 return leaf;
5037 }
5038 // The TLeafElement contains the branch name
5039 // in its name, let's use the title.
5040 leaftitle = leaf->GetTitle();
5041 dim = leaftitle.First('[');
5042 if (dim >= 0) leaftitle.Remove(dim);
5043
5044 if (leaftitle == searchname) {
5045 return leaf;
5046 }
5048 return leaf;
5049 }
5050 if (!searchnameHasDot)
5051 continue;
5052 TBranch* branch = leaf->GetBranch();
5053 if (branch) {
5054 longname.Form("%s.%s",branch->GetName(),leafname.Data());
5055 dim = longname.First('[');
5056 if (dim>=0) longname.Remove(dim);
5057 if (longname == searchname) {
5058 return leaf;
5059 }
5061 return leaf;
5062 }
5063 longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
5064 dim = longtitle.First('[');
5065 if (dim>=0) longtitle.Remove(dim);
5066 if (longtitle == searchname) {
5067 return leaf;
5068 }
5070 return leaf;
5071 }
5072 // The following is for the case where the branch is only
5073 // a sub-branch. Since we do not see it through
5074 // TTree::GetListOfBranches, we need to see it indirectly.
5075 // This is the less sturdy part of this search ... it may
5076 // need refining ...
5077 if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
5078 return leaf;
5079 }
5080 if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
5081 return leaf;
5082 }
5083 }
5084 }
5085 // Search in list of friends.
5086 if (!fFriends) {
5087 return nullptr;
5088 }
5089 TFriendLock lock(this, kFindLeaf);
5091 TFriendElement* fe = nullptr;
5092 while ((fe = (TFriendElement*) nextf())) {
5093 TTree* t = fe->GetTree();
5094 if (!t) {
5095 continue;
5096 }
5097 // If the alias is present replace it with the real name.
5098 subsearchname = strstr(searchname, fe->GetName());
5099 if (subsearchname != searchname) {
5100 subsearchname = nullptr;
5101 }
5102 if (subsearchname) {
5103 subsearchname += strlen(fe->GetName());
5104 if (*subsearchname != '.') {
5105 subsearchname = nullptr;
5106 } else {
5107 ++subsearchname;
5108 }
5109 }
5110 if (subsearchname) {
5111 leafname.Form("%s.%s",t->GetName(),subsearchname);
5112 } else {
5114 }
5115 leaf = t->FindLeaf(leafname);
5116 if (leaf) {
5117 return leaf;
5118 }
5119 }
5120 return nullptr;
5121}
5122
5123////////////////////////////////////////////////////////////////////////////////
5124/// Fit a projected item(s) from a tree.
5125///
5126/// funcname is a TF1 function.
5127///
5128/// See TTree::Draw() for explanations of the other parameters.
5129///
5130/// By default the temporary histogram created is called htemp.
5131/// If varexp contains >>hnew , the new histogram created is called hnew
5132/// and it is kept in the current directory.
5133///
5134/// The function returns the number of selected entries.
5135///
5136/// Example:
5137/// ~~~ {.cpp}
5138/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
5139/// ~~~
5140/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
5141/// directory.
5142///
5143/// See also TTree::UnbinnedFit
5144///
5145/// ## Return status
5146///
5147/// The function returns the status of the histogram fit (see TH1::Fit)
5148/// If no entries were selected, the function returns -1;
5149/// (i.e. fitResult is null if the fit is OK)
5152{
5153 GetPlayer();
5154 if (fPlayer) {
5156 }
5157 return -1;
5158}
5159
5160namespace {
5161struct BoolRAIIToggle {
5162 bool &m_val;
5163
5164 BoolRAIIToggle(bool &val) : m_val(val) { m_val = true; }
5165 ~BoolRAIIToggle() { m_val = false; }
5166};
5167}
5168
5169////////////////////////////////////////////////////////////////////////////////
5170/// Write to disk all the basket that have not yet been individually written and
5171/// create an event cluster boundary (by default).
5172///
5173/// If the caller wishes to flush the baskets but not create an event cluster,
5174/// then set create_cluster to false.
5175///
5176/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
5177/// via TThreadExecutor to do this operation; one per basket compression. If the
5178/// caller utilizes TBB also, care must be taken to prevent deadlocks.
5179///
5180/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
5181/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
5182/// run another one of the user's tasks in this thread. If the second user task
5183/// tries to acquire A, then a deadlock will occur. The example call sequence
5184/// looks like this:
5185///
5186/// - User acquires mutex A
5187/// - User calls FlushBaskets.
5188/// - ROOT launches N tasks and calls wait.
5189/// - TBB schedules another user task, T2.
5190/// - T2 tries to acquire mutex A.
5191///
5192/// At this point, the thread will deadlock: the code may function with IMT-mode
5193/// disabled if the user assumed the legacy code never would run their own TBB
5194/// tasks.
5195///
5196/// SO: users of TBB who want to enable IMT-mode should carefully review their
5197/// locking patterns and make sure they hold no coarse-grained application
5198/// locks when they invoke ROOT.
5199///
5200/// Return the number of bytes written or -1 in case of write error.
5202{
5204 if (retval == -1) return retval;
5205
5206 if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
5207 return retval;
5208}
5209
5210////////////////////////////////////////////////////////////////////////////////
5211/// Internal implementation of the FlushBaskets algorithm.
5212/// Unlike the public interface, this does NOT create an explicit event cluster
5213/// boundary; it is up to the (internal) caller to determine whether that should
5214/// done.
5215///
5216/// Otherwise, the comments for FlushBaskets applies.
5219{
5220 if (!fDirectory) return 0;
5221 Int_t nbytes = 0;
5222 Int_t nerror = 0;
5223 TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
5224 Int_t nb = lb->GetEntriesFast();
5225
5226#ifdef R__USE_IMT
5228 if (useIMT) {
5229 // ROOT-9668: here we need to check if the size of fSortedBranches is different from the
5230 // size of the list of branches before triggering the initialisation of the fSortedBranches
5231 // container to cover two cases:
5232 // 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
5233 // 2. We flushed at least once already but a branch has been be added to the tree since then
5234 if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
5235
5236 BoolRAIIToggle sentry(fIMTFlush);
5237 fIMTZipBytes.store(0);
5238 fIMTTotBytes.store(0);
5239 std::atomic<Int_t> nerrpar(0);
5240 std::atomic<Int_t> nbpar(0);
5241 std::atomic<Int_t> pos(0);
5242
5243 auto mapFunction = [&]() {
5244 // The branch to process is obtained when the task starts to run.
5245 // This way, since branches are sorted, we make sure that branches
5246 // leading to big tasks are processed first. If we assigned the
5247 // branch at task creation time, the scheduler would not necessarily
5248 // respect our sorting.
5249 Int_t j = pos.fetch_add(1);
5250
5251 auto branch = fSortedBranches[j].second;
5252 if (R__unlikely(!branch)) { return; }
5253
5254 if (R__unlikely(gDebug > 0)) {
5255 std::stringstream ss;
5256 ss << std::this_thread::get_id();
5257 Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
5258 Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5259 }
5260
5261 Int_t nbtask = branch->FlushBaskets();
5262
5263 if (nbtask < 0) { nerrpar++; }
5264 else { nbpar += nbtask; }
5265 };
5266
5268 pool.Foreach(mapFunction, nb);
5269
5270 fIMTFlush = false;
5271 const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
5272 const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
5273
5274 return nerrpar ? -1 : nbpar.load();
5275 }
5276#endif
5277 for (Int_t j = 0; j < nb; j++) {
5278 TBranch* branch = (TBranch*) lb->UncheckedAt(j);
5279 if (branch) {
5280 Int_t nwrite = branch->FlushBaskets();
5281 if (nwrite<0) {
5282 ++nerror;
5283 } else {
5284 nbytes += nwrite;
5285 }
5286 }
5287 }
5288 if (nerror) {
5289 return -1;
5290 } else {
5291 return nbytes;
5292 }
5293}
5294
5295////////////////////////////////////////////////////////////////////////////////
5296/// Returns the expanded value of the alias. Search in the friends if any.
5298const char* TTree::GetAlias(const char* aliasName) const
5299{
5300 // We already have been visited while recursively looking
5301 // through the friends tree, let's return.
5303 return nullptr;
5304 }
5305 if (fAliases) {
5307 if (alias) {
5308 return alias->GetTitle();
5309 }
5310 }
5311 if (!fFriends) {
5312 return nullptr;
5313 }
5314 TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
5316 TFriendElement* fe = nullptr;
5317 while ((fe = (TFriendElement*) nextf())) {
5318 TTree* t = fe->GetTree();
5319 if (t) {
5320 const char* alias = t->GetAlias(aliasName);
5321 if (alias) {
5322 return alias;
5323 }
5324 const char* subAliasName = strstr(aliasName, fe->GetName());
5325 if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
5326 alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
5327 if (alias) {
5328 return alias;
5329 }
5330 }
5331 }
5332 }
5333 return nullptr;
5334}
5335
5336namespace {
5337/// Do a breadth first search through the implied hierarchy
5338/// of branches.
5339/// To avoid scanning through the list multiple time
5340/// we also remember the 'depth-first' match.
5341TBranch *R__GetBranch(const TObjArray &branches, const char *name)
5342{
5343 TBranch *result = nullptr;
5344 Int_t nb = branches.GetEntriesFast();
5345 for (Int_t i = 0; i < nb; i++) {
5346 TBranch* b = (TBranch*)branches.UncheckedAt(i);
5347 if (!b)
5348 continue;
5349 if (!strcmp(b->GetName(), name)) {
5350 return b;
5351 }
5352 if (!strcmp(b->GetFullName(), name)) {
5353 return b;
5354 }
5355 if (!result)
5356 result = R__GetBranch(*(b->GetListOfBranches()), name);
5357 }
5358 return result;
5359}
5360}
5361
5362////////////////////////////////////////////////////////////////////////////////
5363/// Returns a pointer to the branch with the given name, if it can be found in
5364/// this tree. Otherwise, returns nullptr.
5365TBranch *TTree::GetBranchFromSelf(const char *branchName)
5366{
5367 // Look for an exact match in the list of top level
5368 // branches.
5369 if (auto *br = static_cast<TBranch *>(fBranches.FindObject(branchName)))
5370 return br;
5371
5372 // Look for an exact match in the mapping from branch name to TBranch *
5373 // gathered when first reading the TTree from disk.
5374 if (auto it = fNamesToBranches.find(branchName); it != fNamesToBranches.end())
5375 return it->second;
5376
5377 // Search using branches, breadth first.
5378 if (auto *br = R__GetBranch(fBranches, branchName))
5379 return br;
5380
5381 // Search using leaves.
5383 Int_t nleaves = leaves->GetEntriesFast();
5384 for (Int_t i = 0; i < nleaves; i++) {
5385 TLeaf *leaf = (TLeaf *)leaves->UncheckedAt(i);
5386 TBranch *branch = leaf->GetBranch();
5387 if (!strcmp(branch->GetName(), branchName)) {
5388 return branch;
5389 }
5390 if (!strcmp(branch->GetFullName(), branchName)) {
5391 return branch;
5392 }
5393 }
5394
5395 return nullptr;
5396}
5397
5398////////////////////////////////////////////////////////////////////////////////
5399/// Returns a pointer to the branch with the given name, if it can be found in
5400/// the list of friends of this tree. Otherwise, returns nullptr.
5401TBranch *TTree::GetBranchFromFriends(const char *branchName)
5402{
5403 if (!fFriends) {
5404 return nullptr;
5405 }
5406
5407 // Search in list of friends.
5408 TFriendLock lock(this, kGetBranch);
5409 TIter next(fFriends);
5410 TFriendElement *fe = nullptr;
5411 while ((fe = (TFriendElement *)next())) {
5412 TTree *t = fe->GetTree();
5413 if (t) {
5414 TBranch *branch = t->GetBranch(branchName);
5415 if (branch) {
5416 return branch;
5417 }
5418 }
5419 }
5420
5421 // Second pass in the list of friends when
5422 // the branch name is prefixed by the tree name.
5423 next.Reset();
5424 while ((fe = (TFriendElement *)next())) {
5425 TTree *t = fe->GetTree();
5426 if (!t) {
5427 continue;
5428 }
5429 const char *subname = strstr(branchName, fe->GetName());
5430 if (subname != branchName) {
5431 continue;
5432 }
5433 Int_t l = strlen(fe->GetName());
5434 subname += l;
5435 if (*subname != '.') {
5436 continue;
5437 }
5438 subname++;
5440 if (branch) {
5441 return branch;
5442 }
5443 }
5444
5445 return nullptr;
5446}
5447
5448////////////////////////////////////////////////////////////////////////////////
5449/// Return pointer to the branch with the given name in this tree or its friends.
5450/// The search is done breadth first.
5451/// \sa TTree::FindBranch
5453TBranch *TTree::GetBranch(const char *name)
5454{
5455 // We already have been visited while recursively
5456 // looking through the friends tree, let's return.
5458 return nullptr;
5459 }
5460
5461 if (!name)
5462 return nullptr;
5463
5464 if (auto *br = GetBranchFromSelf(name))
5465 return br;
5466
5467 if (auto *br = GetBranchFromFriends(name))
5468 return br;
5469
5470 return nullptr;
5471}
5472
5473////////////////////////////////////////////////////////////////////////////////
5474/// Return status of branch with name branchname.
5475///
5476/// - 0 if branch is not activated
5477/// - 1 if branch is activated
5479bool TTree::GetBranchStatus(const char* branchname) const
5480{
5481 TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
5482 if (br) {
5483 return br->TestBit(kDoNotProcess) == 0;
5484 }
5485 return false;
5486}
5487
5488////////////////////////////////////////////////////////////////////////////////
5489/// Static function returning the current branch style.
5490///
5491/// - style = 0 old Branch
5492/// - style = 1 new Bronch
5497}
5498
5499////////////////////////////////////////////////////////////////////////////////
5500/// Used for automatic sizing of the cache.
5501///
5502/// Estimates a suitable size in bytes for the tree cache based on AutoFlush.
5503/// A cache sizing factor is taken from the configuration. If this yields zero
5504/// and withDefault is true the historical algorithm for default size is used.
5506Long64_t TTree::GetCacheAutoSize(bool withDefault /* = false */ )
5507{
5509 {
5510 Long64_t cacheSize = 0;
5511 if (fAutoFlush < 0) {
5512 cacheSize = Long64_t(-cacheFactor * fAutoFlush);
5513 } else if (fAutoFlush == 0) {
5515 if (medianClusterSize > 0)
5516 cacheSize = Long64_t(cacheFactor * 1.5 * medianClusterSize * GetZipBytes() / (fEntries + 1));
5517 else
5518 cacheSize = Long64_t(cacheFactor * 1.5 * 30000000); // use the default value of fAutoFlush
5519 } else {
5520 cacheSize = Long64_t(cacheFactor * 1.5 * fAutoFlush * GetZipBytes() / (fEntries + 1));
5521 }
5522 if (cacheSize >= (INT_MAX / 4)) {
5523 cacheSize = INT_MAX / 4;
5524 }
5525 return cacheSize;
5526 };
5527
5528 const char *stcs;
5529 Double_t cacheFactor = 0.0;
5530 if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
5531 cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
5532 } else {
5534 }
5535
5536 if (cacheFactor < 0.0) {
5537 // ignore negative factors
5538 cacheFactor = 0.0;
5539 }
5540
5542
5543 if (cacheSize < 0) {
5544 cacheSize = 0;
5545 }
5546
5547 if (cacheSize == 0 && withDefault) {
5548 cacheSize = calculateCacheSize(1.0);
5549 }
5550
5551 return cacheSize;
5552}
5553
5554////////////////////////////////////////////////////////////////////////////////
5555/// Return an iterator over the cluster of baskets starting at firstentry.
5556///
5557/// This iterator is not yet supported for TChain object.
5558/// ~~~ {.cpp}
5559/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
5560/// Long64_t clusterStart;
5561/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
5562/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
5563/// }
5564/// ~~~
5567{
5568 // create cache if wanted
5569 if (fCacheDoAutoInit)
5571
5572 return TClusterIterator(this,firstentry);
5573}
5574
5575////////////////////////////////////////////////////////////////////////////////
5576/// Return pointer to the current file.
5579{
5580 if (!fDirectory || fDirectory==gROOT) {
5581 return nullptr;
5582 }
5583 return fDirectory->GetFile();
5584}
5585
5586////////////////////////////////////////////////////////////////////////////////
5587/// Return the number of entries matching the selection.
5588/// Return -1 in case of errors.
5589///
5590/// If the selection uses any arrays or containers, we return the number
5591/// of entries where at least one element match the selection.
5592/// GetEntries is implemented using the selector class TSelectorEntries,
5593/// which can be used directly (see code in TTreePlayer::GetEntries) for
5594/// additional option.
5595/// If SetEventList was used on the TTree or TChain, only that subset
5596/// of entries will be considered.
5599{
5600 GetPlayer();
5601 if (fPlayer) {
5602 return fPlayer->GetEntries(selection);
5603 }
5604 return -1;
5605}
5606
5607////////////////////////////////////////////////////////////////////////////////
5608/// Returns a number corresponding to:
5609/// - The number of entries in this tree, if greater than zero
5610/// - The number of entries in the first friend tree, if there are any friends
5611/// - 0 otherwise
5614{
5615 if (fEntries) return fEntries;
5616 if (!fFriends) return 0;
5618 if (!fr) return 0;
5619 TTree *t = fr->GetTree();
5620 if (t==nullptr) return 0;
5621 return t->GetEntriesFriend();
5622}
5623
5624////////////////////////////////////////////////////////////////////////////////
5625/// Read all branches of entry and return total number of bytes read.
5626///
5627/// - `getall = 0` : get only active branches
5628/// - `getall = 1` : get all branches
5629///
5630/// The function returns the number of bytes read from the input buffer.
5631/// If entry does not exist the function returns 0.
5632/// If an I/O error occurs, the function returns -1.
5633/// If all branches are disabled and getall == 0, it also returns 0
5634/// even if the specified entry exists in the tree, since zero bytes were read.
5635///
5636/// If the Tree has friends, also read the friends entry.
5637///
5638/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
5639/// For example, if you have a Tree with several hundred branches, and you
5640/// are interested only by branches named "a" and "b", do
5641/// ~~~ {.cpp}
5642/// mytree.SetBranchStatus("*",0); //disable all branches
5643/// mytree.SetBranchStatus("a",1);
5644/// mytree.SetBranchStatus("b",1);
5645/// ~~~
5646/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
5647///
5648/// __WARNING!!__
5649/// If your Tree has been created in split mode with a parent branch "parent.",
5650/// ~~~ {.cpp}
5651/// mytree.SetBranchStatus("parent",1);
5652/// ~~~
5653/// will not activate the sub-branches of "parent". You should do:
5654/// ~~~ {.cpp}
5655/// mytree.SetBranchStatus("parent*",1);
5656/// ~~~
5657/// Without the trailing dot in the branch creation you have no choice but to
5658/// call SetBranchStatus explicitly for each of the sub branches.
5659///
5660/// An alternative is to call directly
5661/// ~~~ {.cpp}
5662/// brancha.GetEntry(i)
5663/// branchb.GetEntry(i);
5664/// ~~~
5665/// ## IMPORTANT NOTE
5666///
5667/// By default, GetEntry reuses the space allocated by the previous object
5668/// for each branch. You can force the previous object to be automatically
5669/// deleted if you call mybranch.SetAutoDelete(true) (default is false).
5670///
5671/// Example:
5672///
5673/// Consider the example in $ROOTSYS/test/Event.h
5674/// The top level branch in the tree T is declared with:
5675/// ~~~ {.cpp}
5676/// Event *event = 0; //event must be null or point to a valid object
5677/// //it must be initialized
5678/// T.SetBranchAddress("event",&event);
5679/// ~~~
5680/// When reading the Tree, one can choose one of these 3 options:
5681///
5682/// ## OPTION 1
5683///
5684/// ~~~ {.cpp}
5685/// for (Long64_t i=0;i<nentries;i++) {
5686/// T.GetEntry(i);
5687/// // the object event has been filled at this point
5688/// }
5689/// ~~~
5690/// The default (recommended). At the first entry an object of the class
5691/// Event will be created and pointed by event. At the following entries,
5692/// event will be overwritten by the new data. All internal members that are
5693/// TObject* are automatically deleted. It is important that these members
5694/// be in a valid state when GetEntry is called. Pointers must be correctly
5695/// initialized. However these internal members will not be deleted if the
5696/// characters "->" are specified as the first characters in the comment
5697/// field of the data member declaration.
5698///
5699/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
5700/// In this case, it is assumed that the pointer is never null (case of
5701/// pointer TClonesArray *fTracks in the Event example). If "->" is not
5702/// specified, the pointer member is read via buf >> pointer. In this case
5703/// the pointer may be null. Note that the option with "->" is faster to
5704/// read or write and it also consumes less space in the file.
5705///
5706/// ## OPTION 2
5707///
5708/// The option AutoDelete is set
5709/// ~~~ {.cpp}
5710/// TBranch *branch = T.GetBranch("event");
5711/// branch->SetAddress(&event);
5712/// branch->SetAutoDelete(true);
5713/// for (Long64_t i=0;i<nentries;i++) {
5714/// T.GetEntry(i);
5715/// // the object event has been filled at this point
5716/// }
5717/// ~~~
5718/// In this case, at each iteration, the object event is deleted by GetEntry
5719/// and a new instance of Event is created and filled.
5720///
5721/// ## OPTION 3
5722///
5723/// ~~~ {.cpp}
5724/// Same as option 1, but you delete yourself the event.
5725///
5726/// for (Long64_t i=0;i<nentries;i++) {
5727/// delete event;
5728/// event = 0; // EXTREMELY IMPORTANT
5729/// T.GetEntry(i);
5730/// // the object event has been filled at this point
5731/// }
5732/// ~~~
5733/// It is strongly recommended to use the default option 1. It has the
5734/// additional advantage that functions like TTree::Draw (internally calling
5735/// TTree::GetEntry) will be functional even when the classes in the file are
5736/// not available.
5737///
5738/// Note: See the comments in TBranchElement::SetAddress() for the
5739/// object ownership policy of the underlying (user) data.
5742{
5743 // We already have been visited while recursively looking
5744 // through the friends tree, let return
5745 if (kGetEntry & fFriendLockStatus) return 0;
5746
5747 if (entry < 0 || entry >= fEntries) return 0;
5748 Int_t i;
5749 Int_t nbytes = 0;
5750 fReadEntry = entry;
5751
5752 // create cache if wanted
5753 if (fCacheDoAutoInit)
5755
5757 Int_t nb=0;
5758
5759 auto seqprocessing = [&]() {
5760 TBranch *branch;
5761 for (i=0;i<nbranches;i++) {
5763 nb = branch->GetEntry(entry, getall);
5764 if (nb < 0) break;
5765 nbytes += nb;
5766 }
5767 };
5768
5769#ifdef R__USE_IMT
5771 if (fSortedBranches.empty())
5773
5774 // Count branches are processed first and sequentially
5775 for (auto branch : fSeqBranches) {
5776 nb = branch->GetEntry(entry, getall);
5777 if (nb < 0) break;
5778 nbytes += nb;
5779 }
5780 if (nb < 0) return nb;
5781
5782 // Enable this IMT use case (activate its locks)
5784
5785 Int_t errnb = 0;
5786 std::atomic<Int_t> pos(0);
5787 std::atomic<Int_t> nbpar(0);
5788
5789 auto mapFunction = [&]() {
5790 // The branch to process is obtained when the task starts to run.
5791 // This way, since branches are sorted, we make sure that branches
5792 // leading to big tasks are processed first. If we assigned the
5793 // branch at task creation time, the scheduler would not necessarily
5794 // respect our sorting.
5795 Int_t j = pos.fetch_add(1);
5796
5797 Int_t nbtask = 0;
5798 auto branch = fSortedBranches[j].second;
5799
5800 if (gDebug > 0) {
5801 std::stringstream ss;
5802 ss << std::this_thread::get_id();
5803 Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
5804 Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5805 }
5806
5807 std::chrono::time_point<std::chrono::system_clock> start, end;
5808
5809 start = std::chrono::system_clock::now();
5810 nbtask = branch->GetEntry(entry, getall);
5811 end = std::chrono::system_clock::now();
5812
5813 Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
5814 fSortedBranches[j].first += tasktime;
5815
5816 if (nbtask < 0) errnb = nbtask;
5817 else nbpar += nbtask;
5818 };
5819
5821 pool.Foreach(mapFunction, fSortedBranches.size());
5822
5823 if (errnb < 0) {
5824 nb = errnb;
5825 }
5826 else {
5827 // Save the number of bytes read by the tasks
5828 nbytes += nbpar;
5829
5830 // Re-sort branches if necessary
5834 }
5835 }
5836 }
5837 else {
5838 seqprocessing();
5839 }
5840#else
5841 seqprocessing();
5842#endif
5843 if (nb < 0) return nb;
5844
5845 // GetEntry in list of friends
5846 if (!fFriends) return nbytes;
5847 TFriendLock lock(this,kGetEntry);
5850 while ((fe = (TFriendElement*)nextf())) {
5851 TTree *t = fe->GetTree();
5852 if (t) {
5853 if (fe->TestBit(TFriendElement::kFromChain)) {
5854 nb = t->GetEntry(t->GetReadEntry(),getall);
5855 } else {
5856 if ( t->LoadTreeFriend(entry,this) >= 0 ) {
5857 nb = t->GetEntry(t->GetReadEntry(),getall);
5858 } else nb = 0;
5859 }
5860 if (nb < 0) return nb;
5861 nbytes += nb;
5862 }
5863 }
5864 return nbytes;
5865}
5866
5867
5868////////////////////////////////////////////////////////////////////////////////
5869/// Divides the top-level branches into two vectors: (i) branches to be
5870/// processed sequentially and (ii) branches to be processed in parallel.
5871/// Even if IMT is on, some branches might need to be processed first and in a
5872/// sequential fashion: in the parallelization of GetEntry, those are the
5873/// branches that store the size of another branch for every entry
5874/// (e.g. the size of an array branch). If such branches were processed
5875/// in parallel with the rest, there could be two threads invoking
5876/// TBranch::GetEntry on one of them at the same time, since a branch that
5877/// depends on a size (or count) branch will also invoke GetEntry on the latter.
5878/// This method can be invoked several times during the event loop if the TTree
5879/// is being written, for example when adding new branches. In these cases, the
5880/// `checkLeafCount` parameter is false.
5881/// \param[in] checkLeafCount True if we need to check whether some branches are
5882/// count leaves.
5885{
5887
5888 // The special branch fBranchRef needs to be processed sequentially:
5889 // we add it once only.
5890 if (fBranchRef && fBranchRef != fSeqBranches[0]) {
5891 fSeqBranches.push_back(fBranchRef);
5892 }
5893
5894 // The branches to be processed sequentially are those that are the leaf count of another branch
5895 if (checkLeafCount) {
5896 for (Int_t i = 0; i < nbranches; i++) {
5898 auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
5899 if (leafCount) {
5900 auto countBranch = leafCount->GetBranch();
5901 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
5902 fSeqBranches.push_back(countBranch);
5903 }
5904 }
5905 }
5906 }
5907
5908 // Any branch that is not a leaf count can be safely processed in parallel when reading
5909 // We need to reset the vector to make sure we do not re-add several times the same branch.
5910 if (!checkLeafCount) {
5911 fSortedBranches.clear();
5912 }
5913 for (Int_t i = 0; i < nbranches; i++) {
5914 Long64_t bbytes = 0;
5916 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
5917 bbytes = branch->GetTotBytes("*");
5918 fSortedBranches.emplace_back(bbytes, branch);
5919 }
5920 }
5921
5922 // Initially sort parallel branches by size
5923 std::sort(fSortedBranches.begin(),
5924 fSortedBranches.end(),
5925 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5926 return a.first > b.first;
5927 });
5928
5929 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5930 fSortedBranches[i].first = 0LL;
5931 }
5932}
5933
5934////////////////////////////////////////////////////////////////////////////////
5935/// Sorts top-level branches by the last average task time recorded per branch.
5938{
5939 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5941 }
5942
5943 std::sort(fSortedBranches.begin(),
5944 fSortedBranches.end(),
5945 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5946 return a.first > b.first;
5947 });
5948
5949 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5950 fSortedBranches[i].first = 0LL;
5951 }
5952}
5953
5954////////////////////////////////////////////////////////////////////////////////
5955///Returns the entry list assigned to this tree
5958{
5959 return fEntryList;
5960}
5961
5962////////////////////////////////////////////////////////////////////////////////
5963/// Return entry number corresponding to entry.
5964///
5965/// if no TEntryList set returns entry
5966/// else returns the entry number corresponding to the list index=entry
5969{
5970 if (!fEntryList) {
5971 return entry;
5972 }
5973
5974 return fEntryList->GetEntry(entry);
5975}
5976
5977////////////////////////////////////////////////////////////////////////////////
5978/// Return entry number corresponding to major and minor number.
5979/// Note that this function returns only the entry number, not the data
5980/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5981/// the BuildIndex function has created a table of Long64_t* of sorted values
5982/// corresponding to val = major<<31 + minor;
5983/// The function performs binary search in this sorted table.
5984/// If it finds a pair that matches val, it returns directly the
5985/// index in the table.
5986/// If an entry corresponding to major and minor is not found, the function
5987/// returns the index of the major,minor pair immediately lower than the
5988/// requested value, ie it will return -1 if the pair is lower than
5989/// the first entry in the index.
5990///
5991/// See also GetEntryNumberWithIndex
5999}
6000
6001////////////////////////////////////////////////////////////////////////////////
6002/// Return entry number corresponding to major and minor number.
6003/// Note that this function returns only the entry number, not the data
6004/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
6005/// the BuildIndex function has created a table of Long64_t* of sorted values
6006/// corresponding to val = major<<31 + minor;
6007/// The function performs binary search in this sorted table.
6008/// If it finds a pair that matches val, it returns directly the
6009/// index in the table, otherwise it returns -1.
6010///
6011/// See also GetEntryNumberWithBestIndex
6014{
6015 if (!fTreeIndex) {
6016 return -1;
6017 }
6019}
6020
6021////////////////////////////////////////////////////////////////////////////////
6022/// Read entry corresponding to major and minor number.
6023///
6024/// The function returns the total number of bytes read; -1 if entry not found.
6025/// If the Tree has friend trees, the corresponding entry with
6026/// the index values (major,minor) is read. Note that the master Tree
6027/// and its friend may have different entry serial numbers corresponding
6028/// to (major,minor).
6029/// \note See TTreeIndex::GetEntryNumberWithIndex for information about the maximum values accepted for major and minor
6032{
6033 // We already have been visited while recursively looking
6034 // through the friends tree, let's return.
6036 return 0;
6037 }
6039 if (serial < 0) {
6040 return -1;
6041 }
6042 // create cache if wanted
6043 if (fCacheDoAutoInit)
6045
6046 Int_t i;
6047 Int_t nbytes = 0;
6048 fReadEntry = serial;
6049 TBranch *branch;
6051 Int_t nb;
6052 for (i = 0; i < nbranches; ++i) {
6054 nb = branch->GetEntry(serial);
6055 if (nb < 0) return nb;
6056 nbytes += nb;
6057 }
6058 // GetEntry in list of friends
6059 if (!fFriends) return nbytes;
6062 TFriendElement* fe = nullptr;
6063 while ((fe = (TFriendElement*) nextf())) {
6064 TTree *t = fe->GetTree();
6065 if (t) {
6066 serial = t->GetEntryNumberWithIndex(major,minor);
6067 if (serial <0) return -nbytes;
6068 nb = t->GetEntry(serial);
6069 if (nb < 0) return nb;
6070 nbytes += nb;
6071 }
6072 }
6073 return nbytes;
6074}
6075
6076////////////////////////////////////////////////////////////////////////////////
6077/// Return a pointer to the TTree friend whose name or alias is `friendname`.
6079TTree* TTree::GetFriend(const char *friendname) const
6080{
6081
6082 // We already have been visited while recursively
6083 // looking through the friends tree, let's return.
6085 return nullptr;
6086 }
6087 if (!fFriends) {
6088 return nullptr;
6089 }
6090 TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
6092 TFriendElement* fe = nullptr;
6093 while ((fe = (TFriendElement*) nextf())) {
6094 if (strcmp(friendname,fe->GetName())==0
6095 || strcmp(friendname,fe->GetTreeName())==0) {
6096 return fe->GetTree();
6097 }
6098 }
6099 // After looking at the first level,
6100 // let's see if it is a friend of friends.
6101 nextf.Reset();
6102 fe = nullptr;
6103 while ((fe = (TFriendElement*) nextf())) {
6104 TTree *res = fe->GetTree()->GetFriend(friendname);
6105 if (res) {
6106 return res;
6107 }
6108 }
6109 return nullptr;
6110}
6111
6112////////////////////////////////////////////////////////////////////////////////
6113/// If the 'tree' is a friend, this method returns its alias name.
6114///
6115/// This alias is an alternate name for the tree.
6116///
6117/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
6118/// to specify in which particular tree the branch or leaf can be found if
6119/// the friend trees have branches or leaves with the same name as the master
6120/// tree.
6121///
6122/// It can also be used in conjunction with an alias created using
6123/// TTree::SetAlias in a TTreeFormula, e.g.:
6124/// ~~~ {.cpp}
6125/// maintree->Draw("treealias.fPx - treealias.myAlias");
6126/// ~~~
6127/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
6128/// was created using TTree::SetAlias on the friend tree.
6129///
6130/// However, note that 'treealias.myAlias' will be expanded literally,
6131/// without remembering that it comes from the aliased friend and thus
6132/// the branch name might not be disambiguated properly, which means
6133/// that you may not be able to take advantage of this feature.
6134///
6136const char *TTree::GetFriendAlias(TTree *tree) const
6137{
6138 if ((tree == this) || (tree == GetTree())) {
6139 return nullptr;
6140 }
6141
6142 // We already have been visited while recursively
6143 // looking through the friends tree, let's return.
6145 return nullptr;
6146 }
6147
6148 // This is a TTree and it does not have any friends, we can return early
6149 if (GetTree() == this && !fFriends)
6150 return nullptr;
6151
6152 TFriendLock lock(const_cast<TTree *>(this), kGetFriendAlias);
6153
6154 auto lookForFriendNameInListOfFriends = [tree](const TList &friends) -> const char * {
6156 auto *frElTree = frEl->GetTree();
6157 // Simplest case: we found a friend which tree is the same as the input tree
6158 if (frElTree == tree)
6159 return frEl->GetName();
6160 // Try again: the friend tree might be actually a TChain
6161 if (frElTree && frElTree->GetTree() == tree)
6162 return frEl->GetName();
6163 }
6164 return nullptr;
6165 };
6166
6167 // First, look for the immediate friends of this tree
6168 if (fFriends) {
6170 if (friendAlias)
6171 return friendAlias;
6172 }
6173
6174 // Then, check if this is a TChain and the current tree has friends
6175 // The non-redundant scenario here is that the currently-available
6176 // inner TTree of this TChain has a list of friends which the TChain
6177 // itself doesn't know anything about.
6178 if (const auto *innerListOfFriends = GetTree()->GetListOfFriends();
6181 if (friendAlias)
6182 return friendAlias;
6183 }
6184
6185 // Recursively look into the list of friends of this tree
6186 if (fFriends) {
6188 const char *friendAlias = frEl->GetTree()->GetFriendAlias(tree);
6189 if (friendAlias)
6190 return friendAlias;
6191 }
6192 }
6193
6194 // Recursively look into the list of friends of the inner tree
6195 if (const auto *innerListOfFriends = GetTree()->GetListOfFriends();
6198 const char *friendAlias = frEl->GetTree()->GetFriendAlias(tree);
6199 if (friendAlias)
6200 return friendAlias;
6201 }
6202 }
6203 return nullptr;
6204}
6205
6206////////////////////////////////////////////////////////////////////////////////
6207/// Returns the current set of IO settings
6209{
6210 return fIOFeatures;
6211}
6212
6213////////////////////////////////////////////////////////////////////////////////
6214/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
6217{
6218 return new TTreeFriendLeafIter(this, dir);
6219}
6220
6221////////////////////////////////////////////////////////////////////////////////
6222/// Return pointer to the 1st Leaf named name in any Branch of this
6223/// Tree or any branch in the list of friend trees.
6224///
6225/// The leaf name can contain the name of a friend tree with the
6226/// syntax: friend_dir_and_tree.full_leaf_name
6227/// the friend_dir_and_tree can be of the form:
6228/// ~~~ {.cpp}
6229/// TDirectoryName/TreeName
6230/// ~~~
6232TLeaf* TTree::GetLeafImpl(const char* branchname, const char *leafname)
6233{
6234 TLeaf *leaf = nullptr;
6235 if (branchname) {
6237 if (branch) {
6238 leaf = branch->GetLeaf(leafname);
6239 if (leaf) {
6240 return leaf;
6241 }
6242 }
6243 }
6245 while ((leaf = (TLeaf*)nextl())) {
6246 if (strcmp(leaf->GetFullName(), leafname) != 0 && strcmp(leaf->GetName(), leafname) != 0)
6247 continue; // leafname does not match GetName() nor GetFullName(), this is not the right leaf
6248 if (branchname) {
6249 // check the branchname is also a match
6250 TBranch *br = leaf->GetBranch();
6251 // if a quick comparison with the branch full name is a match, we are done
6252 if (!strcmp(br->GetFullName(), branchname))
6253 return leaf;
6255 const char* brname = br->GetName();
6256 TBranch *mother = br->GetMother();
6258 if (mother != br) {
6259 const char *mothername = mother->GetName();
6261 if (!strcmp(mothername, branchname)) {
6262 return leaf;
6263 } else if (nbch > motherlen && strncmp(mothername,branchname,motherlen)==0 && (mothername[motherlen-1]=='.' || branchname[motherlen]=='.')) {
6264 // 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.
6266 // No it does not
6267 continue;
6268 } // else we have match so we can proceed.
6269 } else {
6270 // no match
6271 continue;
6272 }
6273 } else {
6274 continue;
6275 }
6276 }
6277 // The start of the branch name is identical to the content
6278 // of 'aname' before the first '/'.
6279 // Let's make sure that it is not longer (we are trying
6280 // to avoid having jet2/value match the branch jet23
6281 if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
6282 continue;
6283 }
6284 }
6285 return leaf;
6286 }
6287 if (!fFriends) return nullptr;
6288 TFriendLock lock(this,kGetLeaf);
6289 TIter next(fFriends);
6291 while ((fe = (TFriendElement*)next())) {
6292 TTree *t = fe->GetTree();
6293 if (t) {
6295 if (leaf) return leaf;
6296 }
6297 }
6298
6299 //second pass in the list of friends when the leaf name
6300 //is prefixed by the tree name
6302 next.Reset();
6303 while ((fe = (TFriendElement*)next())) {
6304 TTree *t = fe->GetTree();
6305 if (!t) continue;
6306 const char *subname = strstr(leafname,fe->GetName());
6307 if (subname != leafname) continue;
6308 Int_t l = strlen(fe->GetName());
6309 subname += l;
6310 if (*subname != '.') continue;
6311 subname++;
6314 if (leaf) return leaf;
6315 }
6316 return nullptr;
6317}
6318
6319////////////////////////////////////////////////////////////////////////////////
6320/// Return pointer to the 1st Leaf named name in any Branch of this
6321/// Tree or any branch in the list of friend trees.
6322///
6323/// The leaf name can contain the name of a friend tree with the
6324/// syntax: friend_dir_and_tree.full_leaf_name
6325/// the friend_dir_and_tree can be of the form:
6326///
6327/// TDirectoryName/TreeName
6329TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
6330{
6331 if (leafname == nullptr) return nullptr;
6332
6333 // We already have been visited while recursively looking
6334 // through the friends tree, let return
6336 return nullptr;
6337 }
6338
6340}
6341
6342////////////////////////////////////////////////////////////////////////////////
6343/// Return pointer to first leaf named "name" in any branch of this
6344/// tree or its friend trees.
6345///
6346/// \param[in] name may be in the form 'branch/leaf'
6347///
6349TLeaf* TTree::GetLeaf(const char *name)
6350{
6351 // Return nullptr if name is invalid or if we have
6352 // already been visited while searching friend trees
6353 if (!name || (kGetLeaf & fFriendLockStatus))
6354 return nullptr;
6355
6356 std::string path(name);
6357 const auto sep = path.find_last_of('/');
6358 if (sep != std::string::npos)
6359 return GetLeafImpl(path.substr(0, sep).c_str(), name+sep+1);
6360
6361 return GetLeafImpl(nullptr, name);
6362}
6363
6364////////////////////////////////////////////////////////////////////////////////
6365/// Return maximum of column with name columname.
6366/// if the Tree has an associated TEventList or TEntryList, the maximum
6367/// is computed for the entries in this list.
6370{
6371 TLeaf* leaf = this->GetLeaf(columname);
6372 if (!leaf) {
6373 return 0;
6374 }
6375
6376 // create cache if wanted
6377 if (fCacheDoAutoInit)
6379
6380 TBranch* branch = leaf->GetBranch();
6382 for (Long64_t i = 0; i < fEntries; ++i) {
6384 if (entryNumber < 0) break;
6385 branch->GetEntry(entryNumber);
6386 for (Int_t j = 0; j < leaf->GetLen(); ++j) {
6387 Double_t val = leaf->GetValue(j);
6388 if (val > cmax) {
6389 cmax = val;
6390 }
6391 }
6392 }
6393 return cmax;
6394}
6395
6396////////////////////////////////////////////////////////////////////////////////
6397/// Static function which returns the tree file size limit in bytes.
6402}
6403
6404////////////////////////////////////////////////////////////////////////////////
6405/// Return minimum of column with name columname.
6406/// if the Tree has an associated TEventList or TEntryList, the minimum
6407/// is computed for the entries in this list.
6410{
6411 TLeaf* leaf = this->GetLeaf(columname);
6412 if (!leaf) {
6413 return 0;
6414 }
6415
6416 // create cache if wanted
6417 if (fCacheDoAutoInit)
6419
6420 TBranch* branch = leaf->GetBranch();
6422 for (Long64_t i = 0; i < fEntries; ++i) {
6424 if (entryNumber < 0) break;
6425 branch->GetEntry(entryNumber);
6426 for (Int_t j = 0;j < leaf->GetLen(); ++j) {
6427 Double_t val = leaf->GetValue(j);
6428 if (val < cmin) {
6429 cmin = val;
6430 }
6431 }
6432 }
6433 return cmin;
6434}
6435
6436////////////////////////////////////////////////////////////////////////////////
6437/// Load the TTreePlayer (if not already done).
6440{
6441 if (fPlayer) {
6442 return fPlayer;
6443 }
6445 return fPlayer;
6446}
6447
6448////////////////////////////////////////////////////////////////////////////////
6449/// Find and return the TTreeCache registered with the file and which may
6450/// contain branches for us.
6453{
6454 TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6455 if (pe && pe->GetTree() != GetTree())
6456 pe = nullptr;
6457 return pe;
6458}
6459
6460////////////////////////////////////////////////////////////////////////////////
6461/// Find and return the TTreeCache registered with the file and which may
6462/// contain branches for us. If create is true and there is no cache
6463/// a new cache is created with default size.
6465TTreeCache *TTree::GetReadCache(TFile *file, bool create)
6466{
6467 TTreeCache *pe = GetReadCache(file);
6468 if (create && !pe) {
6469 if (fCacheDoAutoInit)
6470 SetCacheSizeAux(true, -1);
6471 pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6472 if (pe && pe->GetTree() != GetTree()) pe = nullptr;
6473 }
6474 return pe;
6475}
6476
6477////////////////////////////////////////////////////////////////////////////////
6478/// Return a pointer to the list containing user objects associated to this tree.
6479///
6480/// The list is automatically created if it does not exist.
6481///
6482/// WARNING: By default the TTree destructor will delete all objects added
6483/// to this list. If you do not want these objects to be deleted,
6484/// call:
6485///
6486/// mytree->GetUserInfo()->Clear();
6487///
6488/// before deleting the tree.
6491{
6492 if (!fUserInfo) {
6493 fUserInfo = new TList();
6494 fUserInfo->SetName("UserInfo");
6495 }
6496 return fUserInfo;
6497}
6498
6499////////////////////////////////////////////////////////////////////////////////
6500/// Appends the cluster range information stored in 'fromtree' to this tree,
6501/// including the value of fAutoFlush.
6502///
6503/// This is used when doing a fast cloning (by TTreeCloner).
6504/// See also fAutoFlush and fAutoSave if needed.
6507{
6508 Long64_t autoflush = fromtree->GetAutoFlush();
6509 if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
6510 // nothing to do
6511 } else if (fNClusterRange || fromtree->fNClusterRange) {
6512 Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
6513 if (newsize > fMaxClusterRange) {
6514 if (fMaxClusterRange) {
6516 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6518 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6520 } else {
6524 }
6525 }
6526 if (fEntries) {
6530 }
6531 for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
6532 fClusterRangeEnd[fNClusterRange] = fEntries + fromtree->fClusterRangeEnd[i];
6533 fClusterSize[fNClusterRange] = fromtree->fClusterSize[i];
6535 }
6537 } else {
6539 }
6541 if (autoflush > 0 && autosave > 0) {
6543 }
6544}
6545
6546////////////////////////////////////////////////////////////////////////////////
6547/// Keep a maximum of fMaxEntries in memory.
6550{
6553 for (Int_t i = 0; i < nb; ++i) {
6555 branch->KeepCircular(maxEntries);
6556 }
6557 if (fNClusterRange) {
6560 for(Int_t i = 0, j = 0; j < oldsize; ++j) {
6563 ++i;
6564 } else {
6566 }
6567 }
6568 }
6570 fReadEntry = -1;
6571}
6572
6573////////////////////////////////////////////////////////////////////////////////
6574/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
6575///
6576/// If maxmemory is non null and positive SetMaxVirtualSize is called
6577/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
6578/// The function returns the total number of baskets read into memory
6579/// if negative an error occurred while loading the branches.
6580/// This method may be called to force branch baskets in memory
6581/// when random access to branch entries is required.
6582/// If random access to only a few branches is required, you should
6583/// call directly TBranch::LoadBaskets.
6586{
6588
6589 TIter next(GetListOfLeaves());
6590 TLeaf *leaf;
6591 Int_t nimported = 0;
6592 while ((leaf=(TLeaf*)next())) {
6593 nimported += leaf->GetBranch()->LoadBaskets();//break;
6594 }
6595 return nimported;
6596}
6597
6598////////////////////////////////////////////////////////////////////////////////
6599/// Set current entry.
6600///
6601/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
6602/// Returns -6 if an error occurs in the notification callback (just as TChain::LoadTree()).
6603///
6604/// Calls fNotify->Notify() (if fNotify is not null) when starting the processing of a new tree.
6605///
6606/// \note This function is overloaded in TChain.
6608{
6609 // We have already been visited while recursively looking
6610 // through the friend trees, let's return
6612 // We need to return a negative value to avoid a circular list of friends
6613 // to think that there is always an entry somewhere in the list.
6614 return -1;
6615 }
6616
6617 // create cache if wanted
6618 if (fCacheDoAutoInit && entry >=0)
6620
6621 if (fNotify) {
6622 if (fReadEntry < 0) {
6623 fNotify->Notify();
6624 }
6625 }
6626 fReadEntry = entry;
6627
6628 bool friendHasEntry = false;
6629 if (fFriends) {
6630 // Set current entry in friends as well.
6631 //
6632 // An alternative would move this code to each of the
6633 // functions calling LoadTree (and to overload a few more).
6634 bool needUpdate = false;
6635 {
6636 // This scope is need to insure the lock is released at the right time
6638 TFriendLock lock(this, kLoadTree);
6639 TFriendElement* fe = nullptr;
6640 while ((fe = (TFriendElement*) nextf())) {
6641 if (fe->TestBit(TFriendElement::kFromChain)) {
6642 // This friend element was added by the chain that owns this
6643 // tree, the chain will deal with loading the correct entry.
6644 continue;
6645 }
6646 TTree* friendTree = fe->GetTree();
6647 if (friendTree) {
6648 if (friendTree->LoadTreeFriend(entry, this) >= 0) {
6649 friendHasEntry = true;
6650 }
6651 }
6652 if (fe->IsUpdated()) {
6653 needUpdate = true;
6654 fe->ResetUpdated();
6655 }
6656 } // for each friend
6657 }
6658 if (needUpdate) {
6659 //update list of leaves in all TTreeFormula of the TTreePlayer (if any)
6660 if (fPlayer) {
6662 }
6663 //Notify user if requested
6664 if (fNotify) {
6665 if(!fNotify->Notify()) return -6;
6666 }
6667 // We cannot know a priori if the branch(es) of the friend TChain(s) that were just
6668 // updated were supposed to be connected to possibly a TChainElement of another chain
6669 // that has befriended this TTree (i.e., one of the "external friends"). Thus, we
6670 // forward the notification that one or more friend trees were updated to the friends
6671 // of this TTree.
6672 if (fExternalFriends)
6674 external_fe->MarkUpdated();
6675 }
6676 }
6677
6678 if ((fReadEntry >= fEntries) && !friendHasEntry) {
6679 fReadEntry = -1;
6680 return -2;
6681 }
6682 return fReadEntry;
6683}
6684
6685////////////////////////////////////////////////////////////////////////////////
6686/// Load entry on behalf of our master tree, we may use an index.
6687///
6688/// Called by LoadTree() when the masterTree looks for the entry
6689/// number in a friend tree (us) corresponding to the passed entry
6690/// number in the masterTree.
6691///
6692/// If we have no index, our entry number and the masterTree entry
6693/// number are the same.
6694///
6695/// If we *do* have an index, we must find the (major, minor) value pair
6696/// in masterTree to locate our corresponding entry.
6697///
6705}
6706
6707////////////////////////////////////////////////////////////////////////////////
6708/// Generate a skeleton analysis class for this tree.
6709///
6710/// The following files are produced: classname.h and classname.C.
6711/// If classname is 0, classname will be called "nameoftree".
6712///
6713/// The generated code in classname.h includes the following:
6714///
6715/// - Identification of the original tree and the input file name.
6716/// - Definition of an analysis class (data members and member functions).
6717/// - The following member functions:
6718/// - constructor (by default opening the tree file),
6719/// - GetEntry(Long64_t entry),
6720/// - Init(TTree* tree) to initialize a new TTree,
6721/// - Show(Long64_t entry) to read and dump entry.
6722///
6723/// The generated code in classname.C includes only the main
6724/// analysis function Loop.
6725///
6726/// To use this function:
6727///
6728/// - Open your tree file (eg: TFile f("myfile.root");)
6729/// - T->MakeClass("MyClass");
6730///
6731/// where T is the name of the TTree in file myfile.root,
6732/// and MyClass.h, MyClass.C the name of the files created by this function.
6733/// In a ROOT session, you can do:
6734/// ~~~ {.cpp}
6735/// root > .L MyClass.C
6736/// root > MyClass* t = new MyClass;
6737/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
6738/// root > t->Show(); // Show values of entry 12.
6739/// root > t->Show(16); // Read and show values of entry 16.
6740/// root > t->Loop(); // Loop on all entries.
6741/// ~~~
6742/// NOTE: Do not use the code generated for a single TTree which is part
6743/// of a TChain to process that entire TChain. The maximum dimensions
6744/// calculated for arrays on the basis of a single TTree from the TChain
6745/// might be (will be!) too small when processing all of the TTrees in
6746/// the TChain. You must use myChain.MakeClass() to generate the code,
6747/// not myTree.MakeClass(...).
6749Int_t TTree::MakeClass(const char* classname, Option_t* option)
6750{
6751 GetPlayer();
6752 if (!fPlayer) {
6753 return 0;
6754 }
6755 return fPlayer->MakeClass(classname, option);
6756}
6757
6758////////////////////////////////////////////////////////////////////////////////
6759/// Generate a skeleton function for this tree.
6760///
6761/// The function code is written on filename.
6762/// If filename is 0, filename will be called nameoftree.C
6763///
6764/// The generated code includes the following:
6765/// - Identification of the original Tree and Input file name,
6766/// - Opening the Tree file,
6767/// - Declaration of Tree variables,
6768/// - Setting of branches addresses,
6769/// - A skeleton for the entry loop.
6770///
6771/// To use this function:
6772///
6773/// - Open your Tree file (eg: TFile f("myfile.root");)
6774/// - T->MakeCode("MyAnalysis.C");
6775///
6776/// where T is the name of the TTree in file myfile.root
6777/// and MyAnalysis.C the name of the file created by this function.
6778///
6779/// NOTE: Since the implementation of this function, a new and better
6780/// function TTree::MakeClass() has been developed.
6782Int_t TTree::MakeCode(const char* filename)
6783{
6784 Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
6785
6786 GetPlayer();
6787 if (!fPlayer) return 0;
6788 return fPlayer->MakeCode(filename);
6789}
6790
6791////////////////////////////////////////////////////////////////////////////////
6792/// Generate a skeleton analysis class for this Tree using TBranchProxy.
6793///
6794/// TBranchProxy is the base of a class hierarchy implementing an
6795/// indirect access to the content of the branches of a TTree.
6796///
6797/// "proxyClassname" is expected to be of the form:
6798/// ~~~ {.cpp}
6799/// [path/]fileprefix
6800/// ~~~
6801/// The skeleton will then be generated in the file:
6802/// ~~~ {.cpp}
6803/// fileprefix.h
6804/// ~~~
6805/// located in the current directory or in 'path/' if it is specified.
6806/// The class generated will be named 'fileprefix'
6807///
6808/// "macrofilename" and optionally "cutfilename" are expected to point
6809/// to source files which will be included by the generated skeleton.
6810/// Method of the same name as the file(minus the extension and path)
6811/// will be called by the generated skeleton's Process method as follow:
6812/// ~~~ {.cpp}
6813/// [if (cutfilename())] htemp->Fill(macrofilename());
6814/// ~~~
6815/// "option" can be used select some of the optional features during
6816/// the code generation. The possible options are:
6817///
6818/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
6819///
6820/// 'maxUnrolling' controls how deep in the class hierarchy does the
6821/// system 'unroll' classes that are not split. Unrolling a class
6822/// allows direct access to its data members (this emulates the behavior
6823/// of TTreeFormula).
6824///
6825/// The main features of this skeleton are:
6826///
6827/// * on-demand loading of branches
6828/// * ability to use the 'branchname' as if it was a data member
6829/// * protection against array out-of-bounds errors
6830/// * ability to use the branch data as an object (when the user code is available)
6831///
6832/// For example with Event.root, if
6833/// ~~~ {.cpp}
6834/// Double_t somePx = fTracks.fPx[2];
6835/// ~~~
6836/// is executed by one of the method of the skeleton,
6837/// somePx will updated with the current value of fPx of the 3rd track.
6838///
6839/// Both macrofilename and the optional cutfilename are expected to be
6840/// the name of source files which contain at least a free standing
6841/// function with the signature:
6842/// ~~~ {.cpp}
6843/// x_t macrofilename(); // i.e function with the same name as the file
6844/// ~~~
6845/// and
6846/// ~~~ {.cpp}
6847/// y_t cutfilename(); // i.e function with the same name as the file
6848/// ~~~
6849/// x_t and y_t needs to be types that can convert respectively to a double
6850/// and a bool (because the skeleton uses:
6851///
6852/// if (cutfilename()) htemp->Fill(macrofilename());
6853///
6854/// These two functions are run in a context such that the branch names are
6855/// available as local variables of the correct (read-only) type.
6856///
6857/// Note that if you use the same 'variable' twice, it is more efficient
6858/// to 'cache' the value. For example:
6859/// ~~~ {.cpp}
6860/// Int_t n = fEventNumber; // Read fEventNumber
6861/// if (n<10 || n>10) { ... }
6862/// ~~~
6863/// is more efficient than
6864/// ~~~ {.cpp}
6865/// if (fEventNumber<10 || fEventNumber>10)
6866/// ~~~
6867/// Also, optionally, the generated selector will also call methods named
6868/// macrofilename_methodname in each of 6 main selector methods if the method
6869/// macrofilename_methodname exist (Where macrofilename is stripped of its
6870/// extension).
6871///
6872/// Concretely, with the script named h1analysisProxy.C,
6873///
6874/// - The method calls the method (if it exist)
6875/// - Begin -> void h1analysisProxy_Begin(TTree*);
6876/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
6877/// - Notify -> bool h1analysisProxy_Notify();
6878/// - Process -> bool h1analysisProxy_Process(Long64_t);
6879/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
6880/// - Terminate -> void h1analysisProxy_Terminate();
6881///
6882/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
6883/// it is included before the declaration of the proxy class. This can
6884/// be used in particular to insure that the include files needed by
6885/// the macro file are properly loaded.
6886///
6887/// The default histogram is accessible via the variable named 'htemp'.
6888///
6889/// If the library of the classes describing the data in the branch is
6890/// loaded, the skeleton will add the needed `include` statements and
6891/// give the ability to access the object stored in the branches.
6892///
6893/// To draw px using the file hsimple.root (generated by the
6894/// hsimple.C tutorial), we need a file named hsimple.cxx:
6895/// ~~~ {.cpp}
6896/// double hsimple() {
6897/// return px;
6898/// }
6899/// ~~~
6900/// MakeProxy can then be used indirectly via the TTree::Draw interface
6901/// as follow:
6902/// ~~~ {.cpp}
6903/// new TFile("hsimple.root")
6904/// ntuple->Draw("hsimple.cxx");
6905/// ~~~
6906/// A more complete example is available in the tutorials directory:
6907/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
6908/// which reimplement the selector found in h1analysis.C
6910Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
6911{
6912 GetPlayer();
6913 if (!fPlayer) return 0;
6915}
6916
6917////////////////////////////////////////////////////////////////////////////////
6918/// Generate skeleton selector class for this tree.
6919///
6920/// The following files are produced: selector.h and selector.C.
6921/// If selector is 0, the selector will be called "nameoftree".
6922/// The option can be used to specify the branches that will have a data member.
6923/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
6924/// members and branch pointers instead of TTreeReaders).
6925/// - If option is empty, readers will be generated for each leaf.
6926/// - If option is "@", readers will be generated for the topmost branches.
6927/// - Individual branches can also be picked by their name:
6928/// - "X" generates readers for leaves of X.
6929/// - "@X" generates a reader for X as a whole.
6930/// - "@X;Y" generates a reader for X as a whole and also readers for the
6931/// leaves of Y.
6932/// - For further examples see the figure below.
6933///
6934/// \image html ttree_makeselector_option_examples.png
6935///
6936/// The generated code in selector.h includes the following:
6937/// - Identification of the original Tree and Input file name
6938/// - Definition of selector class (data and functions)
6939/// - The following class functions:
6940/// - constructor and destructor
6941/// - void Begin(TTree *tree)
6942/// - void SlaveBegin(TTree *tree)
6943/// - void Init(TTree *tree)
6944/// - bool Notify()
6945/// - bool Process(Long64_t entry)
6946/// - void Terminate()
6947/// - void SlaveTerminate()
6948///
6949/// The class selector derives from TSelector.
6950/// The generated code in selector.C includes empty functions defined above.
6951///
6952/// To use this function:
6953///
6954/// - connect your Tree file (eg: `TFile f("myfile.root");`)
6955/// - `T->MakeSelector("myselect");`
6956///
6957/// where T is the name of the Tree in file myfile.root
6958/// and myselect.h, myselect.C the name of the files created by this function.
6959/// In a ROOT session, you can do:
6960/// ~~~ {.cpp}
6961/// root > T->Process("myselect.C")
6962/// ~~~
6964Int_t TTree::MakeSelector(const char* selector, Option_t* option)
6965{
6966 TString opt(option);
6967 if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
6968 return MakeClass(selector, "selector");
6969 } else {
6970 GetPlayer();
6971 if (!fPlayer) return 0;
6972 return fPlayer->MakeReader(selector, option);
6973 }
6974}
6975
6976////////////////////////////////////////////////////////////////////////////////
6977/// Check if adding nbytes to memory we are still below MaxVirtualsize.
6980{
6982 return false;
6983 }
6984 return true;
6985}
6986
6987////////////////////////////////////////////////////////////////////////////////
6988/// Static function merging the trees in the TList into a new tree.
6989///
6990/// Trees in the list can be memory or disk-resident trees.
6991/// The new tree is created in the current directory (memory if gROOT).
6992/// Trees with no branches will be skipped, the branch structure
6993/// will be taken from the first non-zero-branch Tree of {li}
6996{
6997 if (!li) return nullptr;
6998 TIter next(li);
6999 TTree *newtree = nullptr;
7000 TObject *obj;
7001
7002 while ((obj=next())) {
7003 if (!obj->InheritsFrom(TTree::Class())) continue;
7004 TTree *tree = (TTree*)obj;
7005 if (tree->GetListOfBranches()->IsEmpty()) {
7006 if (gDebug > 2) {
7007 tree->Warning("MergeTrees","TTree %s has no branches, skipping.", tree->GetName());
7008 }
7009 continue; // Completely ignore the empty trees.
7010 }
7011 Long64_t nentries = tree->GetEntries();
7012 if (newtree && nentries == 0)
7013 continue; // If we already have the structure and we have no entry, save time and skip
7014 if (!newtree) {
7015 newtree = (TTree*)tree->CloneTree(-1, options);
7016 if (!newtree) continue;
7017
7018 // Once the cloning is done, separate the trees,
7019 // to avoid as many side-effects as possible
7020 // The list of clones is guaranteed to exist since we
7021 // just cloned the tree.
7022 tree->GetListOfClones()->Remove(newtree);
7023 tree->ResetBranchAddresses();
7024 newtree->ResetBranchAddresses();
7025 continue;
7026 }
7027 if (nentries == 0)
7028 continue;
7029 newtree->CopyEntries(tree, -1, options, true);
7030 }
7031 if (newtree && newtree->GetTreeIndex()) {
7032 newtree->GetTreeIndex()->Append(nullptr,false); // Force the sorting
7033 }
7034 return newtree;
7035}
7036
7037////////////////////////////////////////////////////////////////////////////////
7038/// Merge the trees in the TList into this tree.
7039///
7040/// Returns the total number of entries in the merged tree.
7041/// Trees with no branches will be skipped, the branch structure
7042/// will be taken from the first non-zero-branch Tree of {this+li}
7045{
7046 if (fBranches.IsEmpty()) {
7047 if (!li || li->IsEmpty())
7048 return 0; // Nothing to do ....
7049 // Let's find the first non-empty
7050 TIter next(li);
7051 TTree *tree;
7052 while ((tree = (TTree *)next())) {
7053 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
7054 if (gDebug > 2) {
7055 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
7056 }
7057 continue;
7058 }
7059 // We could come from a list made up of different names, the first one still wins
7060 tree->SetName(this->GetName());
7061 auto prevEntries = tree->GetEntries();
7062 auto result = tree->Merge(li, options);
7063 if (result != prevEntries) {
7064 // If there is no additional entries, the first write was enough.
7065 tree->Write();
7066 }
7067 // Make sure things are really written out to disk before attempting any reading.
7068 if (tree->GetCurrentFile()) {
7069 tree->GetCurrentFile()->Flush();
7070 // Read back the complete info in this TTree, so that caller does not
7071 // inadvertently write the empty tree.
7072 tree->GetDirectory()->ReadTObject(this, this->GetName());
7073 }
7074 return result;
7075 }
7076 return 0; // All trees have empty branches
7077 }
7078 if (!li) return 0;
7080 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
7081 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
7082 // Also since this is part of a merging operation, the output file is not as precious as in
7083 // the general case since the input file should still be around.
7084 fAutoSave = 0;
7085 TIter next(li);
7086 TTree *tree;
7087 while ((tree = (TTree*)next())) {
7088 if (tree==this) continue;
7089 if (!tree->InheritsFrom(TTree::Class())) {
7090 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
7092 return -1;
7093 }
7094
7095 Long64_t nentries = tree->GetEntries();
7096 if (nentries == 0) continue;
7097
7098 CopyEntries(tree, -1, options, true);
7099 }
7101 return GetEntries();
7102}
7103
7104////////////////////////////////////////////////////////////////////////////////
7105/// Merge the trees in the TList into this tree.
7106/// If info->fIsFirst is true, first we clone this TTree info the directory
7107/// info->fOutputDirectory and then overlay the new TTree information onto
7108/// this TTree object (so that this TTree object is now the appropriate to
7109/// use for further merging).
7110/// Trees with no branches will be skipped, the branch structure
7111/// will be taken from the first non-zero-branch Tree of {this+li}
7112///
7113/// Returns the total number of entries in the merged tree.
7116{
7117 if (fBranches.IsEmpty()) {
7118 if (!li || li->IsEmpty())
7119 return 0; // Nothing to do ....
7120 // Let's find the first non-empty
7121 TIter next(li);
7122 TTree *tree;
7123 while ((tree = (TTree *)next())) {
7124 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
7125 if (gDebug > 2) {
7126 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
7127 }
7128 continue;
7129 }
7130 // We could come from a list made up of different names, the first one still wins
7131 tree->SetName(this->GetName());
7132 auto prevEntries = tree->GetEntries();
7133 auto result = tree->Merge(li, info);
7134 if (result != prevEntries) {
7135 // If there is no additional entries, the first write was enough.
7136 tree->Write();
7137 }
7138 // Make sure things are really written out to disk before attempting any reading.
7139 info->fOutputDirectory->GetFile()->Flush();
7140 // Read back the complete info in this TTree, so that TFileMerge does not
7141 // inadvertently write the empty tree.
7142 info->fOutputDirectory->ReadTObject(this, this->GetName());
7143 return result;
7144 }
7145 return 0; // All trees have empty branches
7146 }
7147 const char *options = info ? info->fOptions.Data() : "";
7148 if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
7149 if (GetCurrentFile() == nullptr) {
7150 // In memory TTree, all we need to do is ... write it.
7151 SetDirectory(info->fOutputDirectory);
7153 fDirectory->WriteTObject(this);
7154 } else if (info->fOptions.Contains("fast")) {
7155 InPlaceClone(info->fOutputDirectory);
7156 } else {
7157 TDirectory::TContext ctxt(info->fOutputDirectory);
7159 TTree *newtree = CloneTree(-1, options);
7160 if (info->fIOFeatures)
7161 fIOFeatures = *(info->fIOFeatures);
7162 else
7164 if (newtree) {
7165 newtree->Write();
7166 delete newtree;
7167 }
7168 // Make sure things are really written out to disk before attempting any reading.
7169 info->fOutputDirectory->GetFile()->Flush();
7170 info->fOutputDirectory->ReadTObject(this,this->GetName());
7171 }
7172 }
7173 if (!li) return 0;
7175 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
7176 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
7177 // Also since this is part of a merging operation, the output file is not as precious as in
7178 // the general case since the input file should still be around.
7179 fAutoSave = 0;
7180 TIter next(li);
7181 TTree *tree;
7182 while ((tree = (TTree*)next())) {
7183 if (tree==this) continue;
7184 if (!tree->InheritsFrom(TTree::Class())) {
7185 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
7187 return -1;
7188 }
7189
7190 CopyEntries(tree, -1, options, true);
7191 }
7193 return GetEntries();
7194}
7195
7196////////////////////////////////////////////////////////////////////////////////
7197/// Move a cache from a file to the current file in dir.
7198/// if src is null no operation is done, if dir is null or there is no
7199/// current file the cache is deleted.
7202{
7203 if (!src) return;
7204 TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : nullptr;
7205 if (src == dst) return;
7206
7208 if (dst) {
7209 src->SetCacheRead(nullptr,this);
7210 dst->SetCacheRead(pf, this);
7211 } else {
7212 if (pf) {
7213 pf->WaitFinishPrefetch();
7214 }
7215 src->SetCacheRead(nullptr,this);
7216 delete pf;
7217 }
7218}
7219
7220////////////////////////////////////////////////////////////////////////////////
7221/// Copy the content to a new new file, update this TTree with the new
7222/// location information and attach this TTree to the new directory.
7223///
7224/// options: Indicates a basket sorting method, see TTreeCloner::TTreeCloner for
7225/// details
7226///
7227/// If new and old directory are in the same file, the data is untouched,
7228/// this "just" does a call to SetDirectory.
7229/// Equivalent to an "in place" cloning of the TTree.
7230bool TTree::InPlaceClone(TDirectory *newdirectory, const char *options)
7231{
7232 if (!newdirectory) {
7234 SetDirectory(nullptr);
7235 return true;
7236 }
7237 if (newdirectory->GetFile() == GetCurrentFile()) {
7239 return true;
7240 }
7241 TTreeCloner cloner(this, newdirectory, options);
7242 if (cloner.IsValid())
7243 return cloner.Exec();
7244 else
7245 return false;
7246}
7247
7248////////////////////////////////////////////////////////////////////////////////
7249/// Function called when loading a new class library.
7251bool TTree::Notify()
7252{
7253 TIter next(GetListOfLeaves());
7254 TLeaf* leaf = nullptr;
7255 while ((leaf = (TLeaf*) next())) {
7256 leaf->Notify();
7257 leaf->GetBranch()->Notify();
7258 }
7259 return true;
7260}
7261
7262////////////////////////////////////////////////////////////////////////////////
7263/// This function may be called after having filled some entries in a Tree.
7264/// Using the information in the existing branch buffers, it will reassign
7265/// new branch buffer sizes to optimize time and memory.
7266///
7267/// The function computes the best values for branch buffer sizes such that
7268/// the total buffer sizes is less than maxMemory and nearby entries written
7269/// at the same time.
7270/// In case the branch compression factor for the data written so far is less
7271/// than compMin, the compression is disabled.
7272///
7273/// if option ="d" an analysis report is printed.
7276{
7277 //Flush existing baskets if the file is writable
7278 if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
7279
7280 TString opt( option );
7281 opt.ToLower();
7282 bool pDebug = opt.Contains("d");
7283 TObjArray *leaves = this->GetListOfLeaves();
7284 Int_t nleaves = leaves->GetEntries();
7286
7287 if (nleaves == 0 || treeSize == 0) {
7288 // We're being called too early, we really have nothing to do ...
7289 return;
7290 }
7292 UInt_t bmin = 512;
7293 UInt_t bmax = 256000;
7294 Double_t memFactor = 1;
7297
7298 //we make two passes
7299 //one pass to compute the relative branch buffer sizes
7300 //a second pass to compute the absolute values
7301 for (Int_t pass =0;pass<2;pass++) {
7302 oldMemsize = 0; //to count size of baskets in memory with old buffer size
7303 newMemsize = 0; //to count size of baskets in memory with new buffer size
7304 oldBaskets = 0; //to count number of baskets with old buffer size
7305 newBaskets = 0; //to count number of baskets with new buffer size
7306 for (i=0;i<nleaves;i++) {
7307 TLeaf *leaf = (TLeaf*)leaves->At(i);
7308 TBranch *branch = leaf->GetBranch();
7309 Double_t totBytes = (Double_t)branch->GetTotBytes();
7312 if (branch->GetEntries() == 0) {
7313 // There is no data, so let's make a guess ...
7315 } else {
7316 sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
7317 }
7318 Int_t oldBsize = branch->GetBasketSize();
7321 Int_t nb = branch->GetListOfBranches()->GetEntries();
7322 if (nb > 0) {
7324 continue;
7325 }
7326 Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
7327 if (bsize < 0) bsize = bmax;
7328 if (bsize > bmax) bsize = bmax;
7330 if (pass) { // only on the second pass so that it doesn't interfere with scaling
7331 // If there is an entry offset, it will be stored in the same buffer as the object data; hence,
7332 // we must bump up the size of the branch to account for this extra footprint.
7333 // If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
7334 // the value of GetEntries().
7335 Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
7336 if (branch->GetEntryOffsetLen()) {
7337 newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
7338 }
7339 // We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
7340 // with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
7341 // resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
7342 // at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
7343 // stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
7344 // structures we found a factor of 2 fewer baskets needed in the new scheme.
7345 // rounds up, increases basket size to ensure all entries fit into single basket as intended
7346 newBsize = newBsize - newBsize%512 + 512;
7347 }
7349 if (newBsize < bmin) newBsize = bmin;
7350 if (newBsize > 10000000) newBsize = bmax;
7351 if (pass) {
7352 if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
7353 branch->SetBasketSize(newBsize);
7354 }
7356 // For this number to be somewhat accurate when newBsize is 'low'
7357 // we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
7358 // not let it be lower than 100+TBranch::fEntryOffsetLen.
7360 if (pass == 0) continue;
7361 //Reset the compression level in case the compression factor is small
7362 Double_t comp = 1;
7363 if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
7364 if (comp > 1 && comp < minComp) {
7365 if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
7367 }
7368 }
7369 // coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
7371 if (memFactor > 100) memFactor = 100;
7374 static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
7375
7376 // Really, really never go lower than 8 bytes (we use this number
7377 // so that the calculation of the number of basket is consistent
7378 // but in fact SetBasketSize will not let the size go below
7379 // TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
7380 // (The 2nd part being a slight over estimate of the key length.
7381 static const UInt_t hardmin = 8;
7384 }
7385 if (pDebug) {
7386 Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
7387 Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
7388 }
7389}
7390
7391////////////////////////////////////////////////////////////////////////////////
7392/// Interface to the Principal Components Analysis class.
7393///
7394/// Create an instance of TPrincipal
7395///
7396/// Fill it with the selected variables
7397///
7398/// - if option "n" is specified, the TPrincipal object is filled with
7399/// normalized variables.
7400/// - If option "p" is specified, compute the principal components
7401/// - If option "p" and "d" print results of analysis
7402/// - If option "p" and "h" generate standard histograms
7403/// - If option "p" and "c" generate code of conversion functions
7404/// - return a pointer to the TPrincipal object. It is the user responsibility
7405/// - to delete this object.
7406/// - The option default value is "np"
7407///
7408/// see TTree::Draw for explanation of the other parameters.
7409///
7410/// The created object is named "principal" and a reference to it
7411/// is added to the list of specials Root objects.
7412/// you can retrieve a pointer to the created object via:
7413/// ~~~ {.cpp}
7414/// TPrincipal *principal =
7415/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
7416/// ~~~
7419{
7420 GetPlayer();
7421 if (fPlayer) {
7423 }
7424 return nullptr;
7425}
7426
7427////////////////////////////////////////////////////////////////////////////////
7428/// Print a summary of the tree contents.
7429///
7430/// - If option contains "all" friend trees are also printed.
7431/// - If option contains "toponly" only the top level branches are printed.
7432/// - If option contains "clusters" information about the cluster of baskets is printed.
7433///
7434/// Wildcarding can be used to print only a subset of the branches, e.g.,
7435/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
7437void TTree::Print(Option_t* option) const
7438{
7439 // We already have been visited while recursively looking
7440 // through the friends tree, let's return.
7441 if (kPrint & fFriendLockStatus) {
7442 return;
7443 }
7444 Int_t s = 0;
7445 Int_t skey = 0;
7446 if (fDirectory) {
7447 TKey* key = fDirectory->GetKey(GetName());
7448 if (key) {
7449 skey = key->GetKeylen();
7450 s = key->GetNbytes();
7451 }
7452 }
7455 if (zipBytes > 0) {
7456 total += GetTotBytes();
7457 }
7459 TTree::Class()->WriteBuffer(b, (TTree*) this);
7460 total += b.Length();
7461 Long64_t file = zipBytes + s;
7462 Float_t cx = 1;
7463 if (zipBytes) {
7464 cx = (GetTotBytes() + 0.00001) / zipBytes;
7465 }
7466 Printf("******************************************************************************");
7467 Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
7468 Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
7469 Printf("* : : Tree compression factor = %6.2f *", cx);
7470 Printf("******************************************************************************");
7471
7472 // Avoid many check of option validity
7473 if (!option)
7474 option = "";
7475
7476 if (strncmp(option,"clusters",std::char_traits<char>::length("clusters"))==0) {
7477 Printf("%-16s %-16s %-16s %8s %20s",
7478 "Cluster Range #", "Entry Start", "Last Entry", "Size", "Number of clusters");
7479 Int_t index= 0;
7482 bool estimated = false;
7483 bool unknown = false;
7485 Long64_t nclusters = 0;
7486 if (recordedSize > 0) {
7487 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / recordedSize);
7488 Printf("%-16d %-16lld %-16lld %8lld %10lld",
7489 ind, start, end, recordedSize, nclusters);
7490 } else {
7491 // NOTE: const_cast ... DO NOT Merge for now
7492 TClusterIterator iter((TTree*)this, start);
7493 iter.Next();
7494 auto estimated_size = iter.GetNextEntry() - start;
7495 if (estimated_size > 0) {
7496 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / estimated_size);
7497 Printf("%-16d %-16lld %-16lld %8lld %10lld (estimated)",
7498 ind, start, end, recordedSize, nclusters);
7499 estimated = true;
7500 } else {
7501 Printf("%-16d %-16lld %-16lld %8lld (unknown)",
7502 ind, start, end, recordedSize);
7503 unknown = true;
7504 }
7505 }
7506 start = end + 1;
7508 };
7509 if (fNClusterRange) {
7510 for( ; index < fNClusterRange; ++index) {
7513 }
7514 }
7516 if (unknown) {
7517 Printf("Total number of clusters: (unknown)");
7518 } else {
7519 Printf("Total number of clusters: %lld %s", totalClusters, estimated ? "(estimated)" : "");
7520 }
7521 return;
7522 }
7523
7524 Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
7525 Int_t l;
7526 TBranch* br = nullptr;
7527 TLeaf* leaf = nullptr;
7528 if (strstr(option, "toponly")) {
7529 Long64_t *count = new Long64_t[nl];
7530 Int_t keep =0;
7531 for (l=0;l<nl;l++) {
7532 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7533 br = leaf->GetBranch();
7534 // branch is its own (top level) mother only for the top level branches.
7535 if (br != br->GetMother()) {
7536 count[l] = -1;
7537 count[keep] += br->GetZipBytes();
7538 } else {
7539 keep = l;
7540 count[keep] = br->GetZipBytes();
7541 }
7542 }
7543 for (l=0;l<nl;l++) {
7544 if (count[l] < 0) continue;
7545 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7546 br = leaf->GetBranch();
7547 Printf("branch: %-20s %9lld",br->GetName(),count[l]);
7548 }
7549 delete [] count;
7550 } else {
7551 TString reg = "*";
7552 if (strlen(option) && strchr(option,'*')) reg = option;
7553 TRegexp re(reg,true);
7554 TIter next(const_cast<TTree*>(this)->GetListOfBranches());
7556 while ((br= (TBranch*)next())) {
7557 TString st = br->GetName();
7558 st.ReplaceAll("/","_");
7559 if (st.Index(re) == kNPOS) continue;
7560 br->Print(option);
7561 }
7562 }
7563
7564 //print TRefTable (if one)
7566
7567 //print friends if option "all"
7568 if (!fFriends || !strstr(option,"all")) return;
7570 TFriendLock lock(const_cast<TTree*>(this),kPrint);
7571 TFriendElement *fr;
7572 while ((fr = (TFriendElement*)nextf())) {
7573 TTree * t = fr->GetTree();
7574 if (t) t->Print(option);
7575 }
7576}
7577
7578////////////////////////////////////////////////////////////////////////////////
7579/// Print statistics about the TreeCache for this tree.
7580/// Like:
7581/// ~~~ {.cpp}
7582/// ******TreeCache statistics for file: cms2.root ******
7583/// Reading 73921562 bytes in 716 transactions
7584/// Average transaction = 103.242405 Kbytes
7585/// Number of blocks in current cache: 202, total size : 6001193
7586/// ~~~
7587/// if option = "a" the list of blocks in the cache is printed
7590{
7591 TFile *f = GetCurrentFile();
7592 if (!f) return;
7594 if (tc) tc->Print(option);
7595}
7596
7597////////////////////////////////////////////////////////////////////////////////
7598/// Process this tree executing the TSelector code in the specified filename.
7599/// The return value is -1 in case of error and TSelector::GetStatus() in
7600/// in case of success.
7601///
7602/// The code in filename is loaded (interpreted or compiled, see below),
7603/// filename must contain a valid class implementation derived from TSelector,
7604/// where TSelector has the following member functions:
7605///
7606/// - `Begin()`: called every time a loop on the tree starts,
7607/// a convenient place to create your histograms.
7608/// - `SlaveBegin()`: called after Begin()
7609/// - `Process()`: called for each event, in this function you decide what
7610/// to read and fill your histograms.
7611/// - `SlaveTerminate()`: called at the end of the loop on the tree
7612/// - `Terminate()`: called at the end of the loop on the tree,
7613/// a convenient place to draw/fit your histograms.
7614///
7615/// If filename is of the form file.C, the file will be interpreted.
7616///
7617/// If filename is of the form file.C++, the file file.C will be compiled
7618/// and dynamically loaded.
7619///
7620/// If filename is of the form file.C+, the file file.C will be compiled
7621/// and dynamically loaded. At next call, if file.C is older than file.o
7622/// and file.so, the file.C is not compiled, only file.so is loaded.
7623///
7624/// ## NOTE1
7625///
7626/// It may be more interesting to invoke directly the other Process function
7627/// accepting a TSelector* as argument.eg
7628/// ~~~ {.cpp}
7629/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
7630/// selector->CallSomeFunction(..);
7631/// mytree.Process(selector,..);
7632/// ~~~
7633/// ## NOTE2
7634//
7635/// One should not call this function twice with the same selector file
7636/// in the same script. If this is required, proceed as indicated in NOTE1,
7637/// by getting a pointer to the corresponding TSelector,eg
7638///
7639/// ### Workaround 1
7640///
7641/// ~~~ {.cpp}
7642/// void stubs1() {
7643/// TSelector *selector = TSelector::GetSelector("h1test.C");
7644/// TFile *f1 = new TFile("stubs_nood_le1.root");
7645/// TTree *h1 = (TTree*)f1->Get("h1");
7646/// h1->Process(selector);
7647/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7648/// TTree *h2 = (TTree*)f2->Get("h1");
7649/// h2->Process(selector);
7650/// }
7651/// ~~~
7652/// or use ACLIC to compile the selector
7653///
7654/// ### Workaround 2
7655///
7656/// ~~~ {.cpp}
7657/// void stubs2() {
7658/// TFile *f1 = new TFile("stubs_nood_le1.root");
7659/// TTree *h1 = (TTree*)f1->Get("h1");
7660/// h1->Process("h1test.C+");
7661/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7662/// TTree *h2 = (TTree*)f2->Get("h1");
7663/// h2->Process("h1test.C+");
7664/// }
7665/// ~~~
7668{
7669 GetPlayer();
7670 if (fPlayer) {
7672 }
7673 return -1;
7674}
7675
7676////////////////////////////////////////////////////////////////////////////////
7677/// Process this tree executing the code in the specified selector.
7678/// The return value is -1 in case of error and TSelector::GetStatus() in
7679/// in case of success.
7680///
7681/// The TSelector class has the following member functions:
7682///
7683/// - `Begin()`: called every time a loop on the tree starts,
7684/// a convenient place to create your histograms.
7685/// - `SlaveBegin()`: called after Begin()
7686/// - `Process()`: called for each event, in this function you decide what
7687/// to read and fill your histograms.
7688/// - `SlaveTerminate()`: called at the end of the loop on the tree
7689/// - `Terminate()`: called at the end of the loop on the tree,
7690/// a convenient place to draw/fit your histograms.
7691///
7692/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
7693/// of the EventList, starting at firstentry, otherwise the loop is on the
7694/// specified Tree entries.
7697{
7698 GetPlayer();
7699 if (fPlayer) {
7700 return fPlayer->Process(selector, option, nentries, firstentry);
7701 }
7702 return -1;
7703}
7704
7705////////////////////////////////////////////////////////////////////////////////
7706/// Make a projection of a tree using selections.
7707///
7708/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
7709/// projection of the tree will be filled in histogram hname.
7710/// Note that the dimension of hname must match with the dimension of varexp.
7711///
7714{
7715 TString var;
7716 var.Form("%s>>%s", varexp, hname);
7717 TString opt("goff");
7718 if (option) {
7719 opt.Form("%sgoff", option);
7720 }
7722 return nsel;
7723}
7724
7725////////////////////////////////////////////////////////////////////////////////
7726/// Loop over entries and return a TSQLResult object containing entries following selection.
7729{
7730 GetPlayer();
7731 if (fPlayer) {
7733 }
7734 return nullptr;
7735}
7736
7737////////////////////////////////////////////////////////////////////////////////
7738/// Create or simply read branches from filename.
7739///
7740/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
7741/// is given in the first line of the file with a syntax like
7742/// ~~~ {.cpp}
7743/// A/D:Table[2]/F:Ntracks/I:astring/C
7744/// ~~~
7745/// otherwise branchDescriptor must be specified with the above syntax.
7746/// See all available datatypes [here](\ref addcolumnoffundamentaltypes).
7747///
7748/// - If the type of the first variable is not specified, it is assumed to be "/F"
7749/// - If the type of any other variable is not specified, the type of the previous
7750/// variable is assumed. eg
7751/// - `x:y:z` (all variables are assumed of type "F")
7752/// - `x/D:y:z` (all variables are of type "D")
7753/// - `x:y/D:z` (x is type "F", y and z of type "D")
7754///
7755/// delimiter allows for the use of another delimiter besides whitespace.
7756/// This provides support for direct import of common data file formats
7757/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
7758/// branch description is taken from the first line in the file, but
7759/// delimiter is used for the branch names tokenization rather than ':'.
7760/// Note however that if the values in the first line do not use the
7761/// /[type] syntax, all variables are assumed to be of type "F".
7762/// If the filename ends with extensions .csv or .CSV and a delimiter is
7763/// not specified (besides ' '), the delimiter is automatically set to ','.
7764///
7765/// Lines in the input file starting with "#" are ignored. Leading whitespace
7766/// for each column data is skipped. Empty lines are skipped.
7767///
7768/// A TBranch object is created for each variable in the expression.
7769/// The total number of rows read from the file is returned.
7770///
7771/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
7772///
7773/// To fill a TTree with multiple input text files, proceed as indicated above
7774/// for the first input file and omit the second argument for subsequent calls
7775/// ~~~ {.cpp}
7776/// T.ReadFile("file1.dat","branch descriptor");
7777/// T.ReadFile("file2.dat");
7778/// ~~~
7780Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
7781{
7782 if (!filename || !*filename) {
7783 Error("ReadFile","File name not specified");
7784 return 0;
7785 }
7786
7787 std::ifstream in;
7788 in.open(filename);
7789 if (!in.good()) {
7790 Error("ReadFile","Cannot open file: %s",filename);
7791 return 0;
7792 }
7793 const char* ext = strrchr(filename, '.');
7794 if(ext && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
7795 delimiter = ',';
7796 }
7798}
7799
7800////////////////////////////////////////////////////////////////////////////////
7801/// Determine which newline this file is using.
7802/// Return '\\r' for Windows '\\r\\n' as that already terminates.
7804char TTree::GetNewlineValue(std::istream &inputStream)
7805{
7806 Long_t inPos = inputStream.tellg();
7807 char newline = '\n';
7808 while(true) {
7809 char c = 0;
7810 inputStream.get(c);
7811 if(!inputStream.good()) {
7812 Error("ReadStream","Error reading stream: no newline found.");
7813 return 0;
7814 }
7815 if(c == newline) break;
7816 if(c == '\r') {
7817 newline = '\r';
7818 break;
7819 }
7820 }
7821 inputStream.clear();
7822 inputStream.seekg(inPos);
7823 return newline;
7824}
7825
7826////////////////////////////////////////////////////////////////////////////////
7827/// Create or simply read branches from an input stream.
7828///
7829/// \see TTree::ReadFile
7831Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
7832{
7833 char newline = 0;
7834 std::stringstream ss;
7835 std::istream *inTemp;
7836 Long_t inPos = inputStream.tellg();
7837 if (!inputStream.good()) {
7838 Error("ReadStream","Error reading stream");
7839 return 0;
7840 }
7841 if (inPos == -1) {
7842 ss << std::cin.rdbuf();
7844 inTemp = &ss;
7845 } else {
7848 }
7849 std::istream& in = *inTemp;
7850 Long64_t nlines = 0;
7851
7852 TBranch *branch = nullptr;
7854 if (nbranches == 0) {
7855 char *bdname = new char[4000];
7856 char *bd = new char[100000];
7857 Int_t nch = 0;
7859 // branch Descriptor is null, read its definition from the first line in the file
7860 if (!nch) {
7861 do {
7862 in.getline(bd, 100000, newline);
7863 if (!in.good()) {
7864 delete [] bdname;
7865 delete [] bd;
7866 Error("ReadStream","Error reading stream");
7867 return 0;
7868 }
7869 char *cursor = bd;
7870 while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
7871 ++cursor;
7872 }
7873 if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
7874 break;
7875 }
7876 } while (true);
7877 ++nlines;
7878 nch = strlen(bd);
7879 } else {
7880 strlcpy(bd,branchDescriptor,100000);
7881 }
7882
7883 //parse the branch descriptor and create a branch for each element
7884 //separated by ":"
7885 void *address = &bd[90000];
7886 char *bdcur = bd;
7887 TString desc="", olddesc="F";
7888 char bdelim = ':';
7889 if(delimiter != ' ') {
7890 bdelim = delimiter;
7891 if (strchr(bdcur,bdelim)==nullptr && strchr(bdcur,':') != nullptr) {
7892 // revert to the default
7893 bdelim = ':';
7894 }
7895 }
7896 while (bdcur) {
7897 char *colon = strchr(bdcur,bdelim);
7898 if (colon) *colon = 0;
7899 strlcpy(bdname,bdcur,4000);
7900 char *slash = strchr(bdname,'/');
7901 if (slash) {
7902 *slash = 0;
7903 desc = bdcur;
7904 olddesc = slash+1;
7905 } else {
7906 desc.Form("%s/%s",bdname,olddesc.Data());
7907 }
7908 char *bracket = strchr(bdname,'[');
7909 if (bracket) {
7910 *bracket = 0;
7911 }
7912 branch = new TBranch(this,bdname,address,desc.Data(),32000);
7913 if (branch->IsZombie()) {
7914 delete branch;
7915 Warning("ReadStream","Illegal branch definition: %s",bdcur);
7916 } else {
7918 branch->SetAddress(nullptr);
7919 }
7920 if (!colon)break;
7921 bdcur = colon+1;
7922 }
7923 delete [] bdname;
7924 delete [] bd;
7925 }
7926
7928
7929 if (gDebug > 1) {
7930 Info("ReadStream", "Will use branches:");
7931 for (int i = 0 ; i < nbranches; ++i) {
7932 TBranch* br = (TBranch*) fBranches.At(i);
7933 Info("ReadStream", " %s: %s [%s]", br->GetName(),
7934 br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
7935 }
7936 if (gDebug > 3) {
7937 Info("ReadStream", "Dumping read tokens, format:");
7938 Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
7939 Info("ReadStream", " L: line number");
7940 Info("ReadStream", " B: branch number");
7941 Info("ReadStream", " gfbe: good / fail / bad / eof of token");
7942 Info("ReadStream", " GFBE: good / fail / bad / eof of file");
7943 Info("ReadStream", " T: Token being read");
7944 }
7945 }
7946
7947 //loop on all lines in the file
7948 Long64_t nGoodLines = 0;
7949 std::string line;
7950 const char sDelimBuf[2] = { delimiter, 0 };
7951 const char* sDelim = sDelimBuf;
7952 if (delimiter == ' ') {
7953 // ' ' really means whitespace
7954 sDelim = "[ \t]";
7955 }
7956 while(in.good()) {
7957 if (newline == '\r' && in.peek() == '\n') {
7958 // Windows, skip '\n':
7959 in.get();
7960 }
7961 std::getline(in, line, newline);
7962 ++nlines;
7963
7965 sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
7966 if (sLine.IsNull()) {
7967 if (gDebug > 2) {
7968 Info("ReadStream", "Skipping empty line number %lld", nlines);
7969 }
7970 continue; // silently skip empty lines
7971 }
7972 if (sLine[0] == '#') {
7973 if (gDebug > 2) {
7974 Info("ReadStream", "Skipping comment line number %lld: '%s'",
7975 nlines, line.c_str());
7976 }
7977 continue;
7978 }
7979 if (gDebug > 2) {
7980 Info("ReadStream", "Parsing line number %lld: '%s'",
7981 nlines, line.c_str());
7982 }
7983
7984 // Loop on branches and read the branch values into their buffer
7985 branch = nullptr;
7986 TString tok; // one column's data
7987 TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
7988 std::stringstream sToken; // string stream feeding leafData into leaves
7989 Ssiz_t pos = 0;
7990 Int_t iBranch = 0;
7991 bool goodLine = true; // whether the row can be filled into the tree
7992 Int_t remainingLeafLen = 0; // remaining columns for the current leaf
7993 while (goodLine && iBranch < nbranches
7994 && sLine.Tokenize(tok, pos, sDelim)) {
7995 tok = tok.Strip(TString::kLeading); // skip leading whitespace
7996 if (tok.IsNull() && delimiter == ' ') {
7997 // 1 2 should not be interpreted as 1,,,2 but 1, 2.
7998 // Thus continue until we have a non-empty token.
7999 continue;
8000 }
8001
8002 if (!remainingLeafLen) {
8003 // next branch!
8005 }
8006 TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
8007 if (!remainingLeafLen) {
8008 remainingLeafLen = leaf->GetLen();
8009 if (leaf->GetMaximum() > 0) {
8010 // This is a dynamic leaf length, i.e. most likely a TLeafC's
8011 // string size. This still translates into one token:
8012 remainingLeafLen = 1;
8013 }
8014
8015 leafData = tok;
8016 } else {
8017 // append token to laf data:
8018 leafData += " ";
8019 leafData += tok;
8020 }
8022 if (remainingLeafLen) {
8023 // need more columns for this branch:
8024 continue;
8025 }
8026 ++iBranch;
8027
8028 // initialize stringstream with token
8029 sToken.clear();
8030 sToken.seekp(0, std::ios_base::beg);
8031 sToken.str(leafData.Data());
8032 sToken.seekg(0, std::ios_base::beg);
8033 leaf->ReadValue(sToken, 0 /* 0 = "all" */);
8034 if (gDebug > 3) {
8035 Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
8036 nlines, iBranch,
8037 (int)sToken.good(), (int)sToken.fail(),
8038 (int)sToken.bad(), (int)sToken.eof(),
8039 (int)in.good(), (int)in.fail(),
8040 (int)in.bad(), (int)in.eof(),
8041 sToken.str().c_str());
8042 }
8043
8044 // Error handling
8045 if (sToken.bad()) {
8046 // How could that happen for a stringstream?
8047 Warning("ReadStream",
8048 "Buffer error while reading data for branch %s on line %lld",
8049 branch->GetName(), nlines);
8050 } else if (!sToken.eof()) {
8051 if (sToken.fail()) {
8052 Warning("ReadStream",
8053 "Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
8054 tok.Data(), branch->GetName(), nlines);
8055 goodLine = false;
8056 } else {
8057 std::string remainder;
8058 std::getline(sToken, remainder, newline);
8059 if (!remainder.empty()) {
8060 Warning("ReadStream",
8061 "Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
8062 remainder.c_str(), branch->GetName(), nlines);
8063 }
8064 }
8065 }
8066 } // tokenizer loop
8067
8068 if (iBranch < nbranches) {
8069 Warning("ReadStream",
8070 "Read too few columns (%d < %d) in line %lld; ignoring line",
8072 goodLine = false;
8073 } else if (pos != kNPOS) {
8075 if (pos < sLine.Length()) {
8076 Warning("ReadStream",
8077 "Ignoring trailing \"%s\" while reading line %lld",
8078 sLine.Data() + pos - 1 /* also print delimiter */,
8079 nlines);
8080 }
8081 }
8082
8083 //we are now ready to fill the tree
8084 if (goodLine) {
8085 Fill();
8086 ++nGoodLines;
8087 }
8088 }
8089
8090 return nGoodLines;
8091}
8092
8093////////////////////////////////////////////////////////////////////////////////
8094/// Make sure that obj (which is being deleted or will soon be) is no
8095/// longer referenced by this TTree.
8098{
8099 if (obj == fEventList) {
8100 fEventList = nullptr;
8101 }
8102 if (obj == fEntryList) {
8103 fEntryList = nullptr;
8104 }
8105 if (fUserInfo) {
8107 }
8108 if (fPlayer == obj) {
8109 fPlayer = nullptr;
8110 }
8111 if (fTreeIndex == obj) {
8112 fTreeIndex = nullptr;
8113 }
8114 if (fAliases == obj) {
8115 fAliases = nullptr;
8116 } else if (fAliases) {
8118 }
8119 if (fFriends == obj) {
8120 fFriends = nullptr;
8121 } else if (fFriends) {
8123 }
8124}
8125
8126////////////////////////////////////////////////////////////////////////////////
8127/// Refresh contents of this tree and its branches from the current status on disk.
8128///
8129/// One can call this function in case the tree file is being
8130/// updated by another process.
8132void TTree::Refresh()
8133{
8134 if (!fDirectory->GetFile()) {
8135 return;
8136 }
8138 fDirectory->Remove(this);
8139 TTree* tree; fDirectory->GetObject(GetName(),tree);
8140 if (!tree) {
8141 return;
8142 }
8143 //copy info from tree header into this Tree
8144 fEntries = 0;
8145 fNClusterRange = 0;
8146 ImportClusterRanges(tree);
8147
8148 fAutoSave = tree->fAutoSave;
8149 fEntries = tree->fEntries;
8150 fTotBytes = tree->GetTotBytes();
8151 fZipBytes = tree->GetZipBytes();
8152 fSavedBytes = tree->fSavedBytes;
8153 fTotalBuffers = tree->fTotalBuffers.load();
8154
8155 //loop on all branches and update them
8157 for (Int_t i = 0; i < nleaves; i++) {
8159 TBranch* branch = (TBranch*) leaf->GetBranch();
8160 branch->Refresh(tree->GetBranch(branch->GetName()));
8161 }
8162 fDirectory->Remove(tree);
8163 fDirectory->Append(this);
8164 delete tree;
8165 tree = nullptr;
8166}
8167
8168////////////////////////////////////////////////////////////////////////////////
8169/// Record a TFriendElement that we need to warn when the chain switches to
8170/// a new file (typically this is because this chain is a friend of another
8171/// TChain)
8178}
8179
8180
8181////////////////////////////////////////////////////////////////////////////////
8182/// Removes external friend
8187}
8188
8189
8190////////////////////////////////////////////////////////////////////////////////
8191/// Remove a friend from the list of friends.
8194{
8195 // We already have been visited while recursively looking
8196 // through the friends tree, let return
8198 return;
8199 }
8200 if (!fFriends) {
8201 return;
8202 }
8203 TFriendLock lock(this, kRemoveFriend);
8205 TFriendElement* fe = nullptr;
8206 while ((fe = (TFriendElement*) nextf())) {
8207 TTree* friend_t = fe->GetTree();
8208 if (friend_t == oldFriend) {
8209 fFriends->Remove(fe);
8210 delete fe;
8211 fe = nullptr;
8212 }
8213 }
8214}
8215
8216////////////////////////////////////////////////////////////////////////////////
8217/// Reset baskets, buffers and entries count in all branches and leaves.
8220{
8221 fNotify = nullptr;
8222 fEntries = 0;
8223 fNClusterRange = 0;
8224 fTotBytes = 0;
8225 fZipBytes = 0;
8226 fFlushedBytes = 0;
8227 fSavedBytes = 0;
8228 fTotalBuffers = 0;
8229 fChainOffset = 0;
8230 fReadEntry = -1;
8231
8232 delete fTreeIndex;
8233 fTreeIndex = nullptr;
8234
8236 for (Int_t i = 0; i < nb; ++i) {
8238 branch->Reset(option);
8239 }
8240
8241 if (fBranchRef) {
8242 fBranchRef->Reset();
8243 }
8244}
8245
8246////////////////////////////////////////////////////////////////////////////////
8247/// Resets the state of this TTree after a merge (keep the customization but
8248/// forget the data).
8251{
8252 fEntries = 0;
8253 fNClusterRange = 0;
8254 fTotBytes = 0;
8255 fZipBytes = 0;
8256 fSavedBytes = 0;
8257 fFlushedBytes = 0;
8258 fTotalBuffers = 0;
8259 fChainOffset = 0;
8260 fReadEntry = -1;
8261
8262 delete fTreeIndex;
8263 fTreeIndex = nullptr;
8264
8266 for (Int_t i = 0; i < nb; ++i) {
8268 branch->ResetAfterMerge(info);
8269 }
8270
8271 if (fBranchRef) {
8273 }
8274}
8275
8276////////////////////////////////////////////////////////////////////////////////
8277/// Tell a branch to set its address to zero.
8278///
8279/// @note If the branch owns any objects, they are deleted.
8282{
8283 if (br && br->GetTree()) {
8284 br->ResetAddress();
8285 }
8286}
8287
8288////////////////////////////////////////////////////////////////////////////////
8289/// Tell all of our branches to drop their current objects and allocate new ones.
8292{
8293 // We already have been visited while recursively looking
8294 // through the friends tree, let return
8296 return;
8297 }
8299 Int_t nbranches = branches->GetEntriesFast();
8300 for (Int_t i = 0; i < nbranches; ++i) {
8301 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
8302 branch->ResetAddress();
8303 }
8304 if (fFriends) {
8307 auto *frTree = frEl->GetTree();
8308 if (frTree) {
8309 frTree->ResetBranchAddresses();
8310 }
8311 }
8312 }
8313}
8314
8315////////////////////////////////////////////////////////////////////////////////
8316/// Loop over tree entries and print entries passing selection. Interactive
8317/// pagination break is on by default.
8318///
8319/// - If varexp is 0 (or "") then print only first 8 columns.
8320/// - If varexp = "*" print all columns.
8321///
8322/// Otherwise a columns selection can be made using "var1:var2:var3".
8323///
8324/// \param firstentry first entry to scan
8325/// \param nentries total number of entries to scan (starting from firstentry). Defaults to all entries.
8326/// \note see TTree::SetScanField to control how many lines are printed between pagination breaks (Use 0 to disable pagination)
8327/// \see TTreePlayer::Scan, TTreePlayer::SetScanFileName, TTreePlayer::SetScanRedirect
8330{
8331 GetPlayer();
8332 if (fPlayer) {
8334 }
8335 return -1;
8336}
8337
8338////////////////////////////////////////////////////////////////////////////////
8339/// Set a tree variable alias.
8340///
8341/// Set an alias for an expression/formula based on the tree 'variables'.
8342///
8343/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
8344/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
8345/// 'aliasFormula'.
8346///
8347/// If the content of 'aliasFormula' only contains symbol names, periods and
8348/// array index specification (for example event.fTracks[3]), then
8349/// the content of 'aliasName' can be used as the start of symbol.
8350///
8351/// If the alias 'aliasName' already existed, it is replaced by the new
8352/// value.
8353///
8354/// When being used, the alias can be preceded by an eventual 'Friend Alias'
8355/// (see TTree::GetFriendAlias)
8356///
8357/// Return true if it was added properly.
8358///
8359/// For example:
8360/// ~~~ {.cpp}
8361/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
8362/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
8363/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
8364/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
8365/// tree->Draw("y2-y1:x2-x1");
8366///
8367/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
8368/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
8369/// ~~~
8371bool TTree::SetAlias(const char* aliasName, const char* aliasFormula)
8372{
8373 if (!aliasName || !aliasFormula) {
8374 return false;
8375 }
8376 if (!aliasName[0] || !aliasFormula[0]) {
8377 return false;
8378 }
8379 if (!fAliases) {
8380 fAliases = new TList;
8381 } else {
8383 if (oldHolder) {
8384 oldHolder->SetTitle(aliasFormula);
8385 return true;
8386 }
8387 }
8390 return true;
8391}
8392
8393////////////////////////////////////////////////////////////////////////////////
8394/// This function may be called at the start of a program to change
8395/// the default value for fAutoFlush.
8396///
8397/// ### CASE 1 : autof > 0
8398///
8399/// autof is the number of consecutive entries after which TTree::Fill will
8400/// flush all branch buffers to disk.
8401///
8402/// ### CASE 2 : autof < 0
8403///
8404/// When filling the Tree the branch buffers will be flushed to disk when
8405/// more than autof bytes have been written to the file. At the first FlushBaskets
8406/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
8407///
8408/// Calling this function with autof<0 is interesting when it is hard to estimate
8409/// the size of one entry. This value is also independent of the Tree.
8410///
8411/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
8412/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
8413///
8414/// ### CASE 3 : autof = 0
8415///
8416/// The AutoFlush mechanism is disabled.
8417///
8418/// Flushing the buffers at regular intervals optimize the location of
8419/// consecutive entries on the disk by creating clusters of baskets.
8420///
8421/// A cluster of baskets is a set of baskets that contains all
8422/// the data for a (consecutive) set of entries and that is stored
8423/// consecutively on the disk. When reading all the branches, this
8424/// is the minimum set of baskets that the TTreeCache will read.
8426void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
8427{
8428 // Implementation note:
8429 //
8430 // A positive value of autoflush determines the size (in number of entries) of
8431 // a cluster of baskets.
8432 //
8433 // If the value of autoflush is changed over time (this happens in
8434 // particular when the TTree results from fast merging many trees),
8435 // we record the values of fAutoFlush in the data members:
8436 // fClusterRangeEnd and fClusterSize.
8437 // In the code we refer to a range of entries where the size of the
8438 // cluster of baskets is the same (i.e the value of AutoFlush was
8439 // constant) is called a ClusterRange.
8440 //
8441 // The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
8442 // active (used) values and have fMaxClusterRange allocated entries.
8443 //
8444 // fClusterRangeEnd contains the last entries number of a cluster range.
8445 // In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
8446 // fClusterSize contains the size in number of entries of all the cluster
8447 // within the given range.
8448 // The last range (and the only one if fNClusterRange is zero) start at
8449 // fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
8450 // size of the cluster in this range is given by the value of fAutoFlush.
8451 //
8452 // For example printing the beginning and end of each the ranges can be done by:
8453 //
8454 // Printf("%-16s %-16s %-16s %5s",
8455 // "Cluster Range #", "Entry Start", "Last Entry", "Size");
8456 // Int_t index= 0;
8457 // Long64_t clusterRangeStart = 0;
8458 // if (fNClusterRange) {
8459 // for( ; index < fNClusterRange; ++index) {
8460 // Printf("%-16d %-16lld %-16lld %5lld",
8461 // index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
8462 // clusterRangeStart = fClusterRangeEnd[index] + 1;
8463 // }
8464 // }
8465 // Printf("%-16d %-16lld %-16lld %5lld",
8466 // index, prevEntry, fEntries - 1, fAutoFlush);
8467 //
8468
8469 // Note: We store the entry number corresponding to the end of the cluster
8470 // rather than its start in order to avoid using the array if the cluster
8471 // size never varies (If there is only one value of AutoFlush for the whole TTree).
8472
8473 if( fAutoFlush != autof) {
8474 if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
8475 // The mechanism was already enabled, let's record the previous
8476 // cluster if needed.
8478 }
8479 fAutoFlush = autof;
8480 }
8481}
8482
8483////////////////////////////////////////////////////////////////////////////////
8484/// Mark the previous event as being at the end of the event cluster.
8485///
8486/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
8487/// is called, then the first cluster has 9 events.
8489{
8490 if (!fEntries) return;
8491
8492 if ( (fNClusterRange+1) > fMaxClusterRange ) {
8493 if (fMaxClusterRange) {
8494 // Resize arrays to hold a larger event cluster.
8497 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8499 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8501 } else {
8502 // Cluster ranges have never been initialized; create them now.
8503 fMaxClusterRange = 2;
8506 }
8507 }
8509 // If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
8510 if (fAutoFlush > 0) {
8511 // Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
8512 // will appropriately go to the next event range.
8514 // Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
8515 } else if (fNClusterRange == 0) {
8517 } else {
8519 }
8521}
8522
8523/// Estimate the median cluster size for the TTree.
8524/// This value provides e.g. a reasonable cache size default if other heuristics fail.
8525/// Clusters with size 0 and the very last cluster range, that might not have been committed to fClusterSize yet,
8526/// are ignored for the purposes of the calculation.
8528{
8529 std::vector<Long64_t> clusterSizesPerRange;
8531
8532 // We ignore cluster sizes of 0 for the purposes of this function.
8533 // We also ignore the very last cluster range which might not have been committed to fClusterSize.
8534 std::copy_if(fClusterSize, fClusterSize + fNClusterRange, std::back_inserter(clusterSizesPerRange),
8535 [](Long64_t size) { return size != 0; });
8536
8537 std::vector<double> nClustersInRange; // we need to store doubles because of the signature of TMath::Median
8538 nClustersInRange.reserve(clusterSizesPerRange.size());
8539
8540 auto clusterRangeStart = 0ll;
8541 for (int i = 0; i < fNClusterRange; ++i) {
8542 const auto size = fClusterSize[i];
8543 R__ASSERT(size >= 0);
8544 if (fClusterSize[i] == 0)
8545 continue;
8546 const auto nClusters = (1 + fClusterRangeEnd[i] - clusterRangeStart) / fClusterSize[i];
8547 nClustersInRange.emplace_back(nClusters);
8549 }
8550
8552 const auto medianClusterSize =
8554 return medianClusterSize;
8555}
8556
8557////////////////////////////////////////////////////////////////////////////////
8558/// In case of a program crash, it will be possible to recover the data in the
8559/// tree up to the last AutoSave point.
8560/// This function may be called before filling a TTree to specify when the
8561/// branch buffers and TTree header are flushed to disk as part of
8562/// TTree::Fill().
8563/// The default is -300000000, ie the TTree will write data to disk once it
8564/// exceeds 300 MBytes.
8565/// CASE 1: If fAutoSave is positive the watermark is reached when a multiple of
8566/// fAutoSave entries have been filled.
8567/// CASE 2: If fAutoSave is negative the watermark is reached when -fAutoSave
8568/// bytes can be written to the file.
8569/// CASE 3: If fAutoSave is 0, AutoSave() will never be called automatically
8570/// as part of TTree::Fill().
8575}
8576
8577////////////////////////////////////////////////////////////////////////////////
8578/// Set a branch's basket size.
8579///
8580/// bname is the name of a branch.
8581///
8582/// - if bname="*", apply to all branches.
8583/// - if bname="xxx*", apply to all branches with name starting with xxx
8584///
8585/// see TRegexp for wildcarding options
8586/// bufsize = branch basket size
8588void TTree::SetBasketSize(const char* bname, Int_t bufsize)
8589{
8591 TRegexp re(bname, true);
8592 Int_t nb = 0;
8593 for (Int_t i = 0; i < nleaves; i++) {
8595 TBranch* branch = (TBranch*) leaf->GetBranch();
8596 TString s = branch->GetName();
8597 if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
8598 continue;
8599 }
8600 nb++;
8601 branch->SetBasketSize(bufsize);
8602 }
8603 if (!nb) {
8604 Error("SetBasketSize", "unknown branch -> '%s'", bname);
8605 }
8606}
8607
8608////////////////////////////////////////////////////////////////////////////////
8609/// Change branch address, dealing with clone trees properly.
8610/// See TTree::CheckBranchAddressType for the semantic of the return value.
8611///
8612/// Note: See the comments in TBranchElement::SetAddress() for the
8613/// meaning of the addr parameter and the object ownership policy.
8615Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
8616{
8617 TBranch* branch = GetBranch(bname);
8618 if (!branch) {
8619 if (ptr) *ptr = nullptr;
8620 Error("SetBranchAddress", "unknown branch -> %s", bname);
8621 return kMissingBranch;
8622 }
8623 return SetBranchAddressImp(branch,addr,ptr);
8624}
8625
8626////////////////////////////////////////////////////////////////////////////////
8627/// Verify the validity of the type of addr before calling SetBranchAddress.
8628/// See TTree::CheckBranchAddressType for the semantic of the return value.
8629///
8630/// Note: See the comments in TBranchElement::SetAddress() for the
8631/// meaning of the addr parameter and the object ownership policy.
8633Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, bool isptr)
8634{
8635 return SetBranchAddress(bname, addr, nullptr, ptrClass, datatype, isptr);
8636}
8639 bool isptr)
8640{
8641 if (auto *branchFromSelf = GetBranchFromSelf(bname)) {
8643
8644 // This will set the value of *ptr to branch.
8645 if (res >= 0) {
8646 // The check succeeded.
8647 if ((res & kNeedEnableDecomposedObj) && !branchFromSelf->GetMakeClass())
8648 branchFromSelf->SetMakeClass(true);
8650 } else {
8651 if (ptr)
8652 *ptr = nullptr;
8653 }
8654 return res;
8655 }
8656
8657 // Check friends
8658 if (fFriends) {
8659 int status{kMissingBranch};
8661 if (auto *tree = fe->GetTree()) {
8662 status = tree->SetBranchAddress(bname, addr, ptr, ptrClass, datatype, isptr, true);
8663 // We exit early from visiting all friends only if a perfect match was found
8664 if (status == kMatch)
8665 return status;
8666 }
8667 }
8668 // This allows for the valid case of friend TChain(s) which might hold
8669 // the requested branch, but might not know it yet since they haven't loaded
8670 // the tree. This is encoded in the kNoCheck == 5 value.
8671 if (status != kMissingBranch)
8672 return status;
8673 }
8674
8675 // Branch not found
8676 if (ptr)
8677 *ptr = nullptr;
8678
8679 return kMissingBranch;
8680}
8681
8682////////////////////////////////////////////////////////////////////////////////
8683/// Verify the validity of the type of addr before calling SetBranchAddress.
8684/// See TTree::CheckBranchAddressType for the semantic of the return value.
8685///
8686/// Note: See the comments in TBranchElement::SetAddress() for the
8687/// meaning of the addr parameter and the object ownership policy.
8689Int_t TTree::SetBranchAddress(const char *bname, void *addr, TBranch **ptr, TClass *ptrClass, EDataType datatype,
8690 bool isptr)
8691{
8692 auto res = SetBranchAddressImp(bname, addr, ptr, ptrClass, datatype, isptr);
8693 if (res == kMissingBranch)
8694 Error("SetBranchAddress", "unknown branch -> %s", bname);
8695 return res;
8696}
8698Int_t TTree::SetBranchAddress(const char *bname, void *addr, TBranch **ptr, TClass *ptrClass, EDataType datatype,
8699 bool isptr, bool)
8700{
8701 // This has been called while setting the branch address of friends of a TTree. We can't know a priori
8702 // which friend actually has the branch bname, so we avoid printing an error in case of missing branch
8703 return SetBranchAddressImp(bname, addr, ptr, ptrClass, datatype, isptr);
8704}
8705
8706////////////////////////////////////////////////////////////////////////////////
8707/// Change branch address, dealing with clone trees properly.
8708/// See TTree::CheckBranchAddressType for the semantic of the return value.
8709///
8710/// Note: See the comments in TBranchElement::SetAddress() for the
8711/// meaning of the addr parameter and the object ownership policy.
8714{
8715 if (ptr) {
8716 *ptr = branch;
8717 }
8718 if (fClones) {
8719 void* oldAddr = branch->GetAddress();
8720 TIter next(fClones);
8721 TTree* clone = nullptr;
8722 const char *bname = branch->GetName();
8723 while ((clone = (TTree*) next())) {
8724 TBranch* cloneBr = clone->GetBranch(bname);
8725 if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
8726 cloneBr->SetAddress(addr);
8727 }
8728 }
8729 }
8730 branch->SetAddress(addr);
8731 return kVoidPtr;
8732}
8733
8734////////////////////////////////////////////////////////////////////////////////
8735/// Set branch status to Process or DoNotProcess.
8736///
8737/// When reading a Tree, by default, all branches are read.
8738/// One can speed up considerably the analysis phase by activating
8739/// only the branches that hold variables involved in a query.
8740///
8741/// bname is the name of a branch.
8742///
8743/// - if bname="*", apply to all branches.
8744/// - if bname="xxx*", apply to all branches with name starting with xxx
8745///
8746/// see TRegexp for wildcarding options
8747///
8748/// - status = 1 branch will be processed
8749/// - = 0 branch will not be processed
8750///
8751/// Example:
8752///
8753/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
8754/// when doing T.GetEntry(i) all branches are read for entry i.
8755/// to read only the branches c and e, one can do
8756/// ~~~ {.cpp}
8757/// T.SetBranchStatus("*",0); //disable all branches
8758/// T.SetBranchStatus("c",1);
8759/// T.setBranchStatus("e",1);
8760/// T.GetEntry(i);
8761/// ~~~
8762/// bname is interpreted as a wild-carded TRegexp (see TRegexp::MakeWildcard).
8763/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
8764/// "b", but not any other branch with an "a" followed at some point by a
8765/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
8766/// support '|', and so you cannot select, e.g. track and shower branches
8767/// with "track|shower".
8768///
8769/// __WARNING! WARNING! WARNING!__
8770///
8771/// SetBranchStatus is matching the branch based on match of the branch
8772/// 'name' and not on the branch hierarchy! In order to be able to
8773/// selectively enable a top level object that is 'split' you need to make
8774/// sure the name of the top level branch is prefixed to the sub-branches'
8775/// name (by adding a dot ('.') at the end of the Branch creation and use the
8776/// corresponding bname.
8777///
8778/// I.e If your Tree has been created in split mode with a parent branch "parent."
8779/// (note the trailing dot).
8780/// ~~~ {.cpp}
8781/// T.SetBranchStatus("parent",1);
8782/// ~~~
8783/// will not activate the sub-branches of "parent". You should do:
8784/// ~~~ {.cpp}
8785/// T.SetBranchStatus("parent*",1);
8786/// ~~~
8787/// Without the trailing dot in the branch creation you have no choice but to
8788/// call SetBranchStatus explicitly for each of the sub branches.
8789///
8790/// An alternative to this function is to read directly and only
8791/// the interesting branches. Example:
8792/// ~~~ {.cpp}
8793/// TBranch *brc = T.GetBranch("c");
8794/// TBranch *bre = T.GetBranch("e");
8795/// brc->GetEntry(i);
8796/// bre->GetEntry(i);
8797/// ~~~
8798/// If found is not 0, the number of branch(es) found matching the regular
8799/// expression is returned in *found AND the error message 'unknown branch'
8800/// is suppressed.
8802void TTree::SetBranchStatus(const char* bname, bool status, UInt_t* found)
8803{
8804 // We already have been visited while recursively looking
8805 // through the friends tree, let return
8807 return;
8808 }
8809
8810 if (!bname || !*bname) {
8811 Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
8812 return;
8813 }
8814
8816 TLeaf *leaf, *leafcount;
8817
8818 Int_t i,j;
8820 TRegexp re(bname,true);
8821 Int_t nb = 0;
8822
8823 // first pass, loop on all branches
8824 // for leafcount branches activate/deactivate in function of status
8825 for (i=0;i<nleaves;i++) {
8827 branch = (TBranch*)leaf->GetBranch();
8828 TString s = branch->GetName();
8829 if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
8831 longname.Form("%s.%s",GetName(),branch->GetName());
8832 if (strcmp(bname,branch->GetName())
8833 && longname != bname
8834 && s.Index(re) == kNPOS) continue;
8835 }
8836 nb++;
8837 if (status) branch->ResetBit(kDoNotProcess);
8838 else branch->SetBit(kDoNotProcess);
8839 leafcount = leaf->GetLeafCount();
8840 if (leafcount) {
8841 bcount = leafcount->GetBranch();
8842 if (status) bcount->ResetBit(kDoNotProcess);
8843 else bcount->SetBit(kDoNotProcess);
8844 }
8845 }
8846 if (nb==0 && !strchr(bname,'*')) {
8847 branch = GetBranch(bname);
8848 if (branch) {
8849 if (status) branch->ResetBit(kDoNotProcess);
8850 else branch->SetBit(kDoNotProcess);
8851 ++nb;
8852 }
8853 }
8854
8855 //search in list of friends
8857 if (fFriends) {
8858 TFriendLock lock(this,kSetBranchStatus);
8861 TString name;
8862 while ((fe = (TFriendElement*)nextf())) {
8863 TTree *t = fe->GetTree();
8864 if (!t) continue;
8865
8866 // If the alias is present replace it with the real name.
8867 const char *subbranch = strstr(bname,fe->GetName());
8868 if (subbranch!=bname) subbranch = nullptr;
8869 if (subbranch) {
8870 subbranch += strlen(fe->GetName());
8871 if ( *subbranch != '.' ) subbranch = nullptr;
8872 else subbranch ++;
8873 }
8874 if (subbranch) {
8875 name.Form("%s.%s",t->GetName(),subbranch);
8876 } else {
8877 name = bname;
8878 }
8879 t->SetBranchStatus(name,status, &foundInFriend);
8880 }
8881 }
8882 if (!nb && !foundInFriend) {
8883 if (!found) {
8884 if (status) {
8885 if (strchr(bname,'*') != nullptr)
8886 Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8887 else
8888 Error("SetBranchStatus", "unknown branch -> %s", bname);
8889 } else {
8890 if (strchr(bname,'*') != nullptr)
8891 Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8892 else
8893 Warning("SetBranchStatus", "unknown branch -> %s", bname);
8894 }
8895 }
8896 return;
8897 }
8898 if (found) *found = nb + foundInFriend;
8899
8900 // second pass, loop again on all branches
8901 // activate leafcount branches for active branches only
8902 for (i = 0; i < nleaves; i++) {
8904 branch = (TBranch*)leaf->GetBranch();
8905 if (!branch->TestBit(kDoNotProcess)) {
8906 leafcount = leaf->GetLeafCount();
8907 if (leafcount) {
8908 bcount = leafcount->GetBranch();
8909 bcount->ResetBit(kDoNotProcess);
8910 }
8911 } else {
8912 //Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
8913 Int_t nbranches = branch->GetListOfBranches()->GetEntries();
8914 for (j=0;j<nbranches;j++) {
8915 bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
8916 if (!bson) continue;
8917 if (!bson->TestBit(kDoNotProcess)) {
8918 if (bson->GetNleaves() <= 0) continue;
8919 branch->ResetBit(kDoNotProcess);
8920 break;
8921 }
8922 }
8923 }
8924 }
8925}
8926
8927////////////////////////////////////////////////////////////////////////////////
8928/// Set the current branch style. (static function)
8929///
8930/// - style = 0 old Branch
8931/// - style = 1 new Bronch
8936}
8937
8938////////////////////////////////////////////////////////////////////////////////
8939/// Set maximum size of the file cache (TTreeCache) in bytes.
8940//
8941/// - if cachesize = 0 the existing cache (if any) is disabled (deleted if any).
8942/// - if cachesize > 0, the cache is enabled or extended, if necessary
8943/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
8944/// the Tree (default is 30 MBytes).
8945///
8946/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
8947///
8948/// TTreeCache's 'real' job is to actually prefetch (early grab from disk) the compressed data.
8949/// The cachesize controls the size of the read bytes from disk.
8950///
8951/// Returns:
8952/// - 0 size set, cache was created if possible
8953/// - -1 on error
8956{
8957 // remember that the user has requested an explicit cache setup
8958 fCacheUserSet = true;
8959
8960 return SetCacheSizeAux(false, cacheSize);
8961}
8962
8963////////////////////////////////////////////////////////////////////////////////
8964/// Set the maximum size of the file cache (TTreeCache) in bytes and create it if possible.
8965///
8966/// If autocache is true:
8967/// this may be an autocreated cache, possibly enlarging an existing
8968/// autocreated cache. The size is calculated. The value passed in cacheSize:
8969/// - cacheSize = 0 make cache if default cache creation is enabled.
8970/// - cachesize > 0 the cache is enabled or extended, if necessary
8971/// - cacheSize = -1 make a default sized cache in any case
8972///
8973/// If autocache is false:
8974/// this is a user requested cache. cacheSize is used to size the cache.
8975/// This cache should never be automatically adjusted. If cachesize is
8976/// 0, the cache is disabled (deleted if any).
8977///
8978/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
8979///
8980/// TTreeCache's 'real' job is to actually prefetch (early grab from disk) the compressed data.
8981/// The cachesize controls the size of the read bytes from disk.
8982///
8983/// Returns:
8984/// - 0 size set, or existing autosized cache almost large enough.
8985/// (cache was created if possible)
8986/// - -1 on error
8988Int_t TTree::SetCacheSizeAux(bool autocache /* = true */, Long64_t cacheSize /* = 0 */ )
8989{
8990 if (autocache) {
8991 // used as a once only control for automatic cache setup
8992 fCacheDoAutoInit = false;
8993 }
8994
8995 if (!autocache) {
8996 // negative size means the user requests the default
8997 if (cacheSize < 0) {
8998 cacheSize = GetCacheAutoSize(true);
8999 }
9000 } else {
9001 if (cacheSize == 0) {
9002 cacheSize = GetCacheAutoSize();
9003 } else if (cacheSize < 0) {
9004 cacheSize = GetCacheAutoSize(true);
9005 }
9006 }
9007
9008 TFile* file = GetCurrentFile();
9009 if (!file || GetTree() != this) {
9010 // if there's no file or we are not a plain tree (e.g. if we're a TChain)
9011 // do not create a cache, only record the size if one was given
9012 if (!autocache) {
9013 fCacheSize = cacheSize;
9014 }
9015 if (GetTree() != this) {
9016 return 0;
9017 }
9018 if (!autocache && cacheSize>0) {
9019 Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
9020 }
9021 return 0;
9022 }
9023
9024 // Check for an existing cache
9025 TTreeCache* pf = GetReadCache(file);
9026 if (pf) {
9027 if (autocache) {
9028 // reset our cache status tracking in case existing cache was added
9029 // by the user without using one of the TTree methods
9030 fCacheSize = pf->GetBufferSize();
9031 fCacheUserSet = !pf->IsAutoCreated();
9032
9033 if (fCacheUserSet) {
9034 // existing cache was created by the user, don't change it
9035 return 0;
9036 }
9037 } else {
9038 // update the cache to ensure it records the user has explicitly
9039 // requested it
9040 pf->SetAutoCreated(false);
9041 }
9042
9043 // if we're using an automatically calculated size and the existing
9044 // cache is already almost large enough don't resize
9045 if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
9046 // already large enough
9047 return 0;
9048 }
9049
9050 if (cacheSize == fCacheSize) {
9051 return 0;
9052 }
9053
9054 if (cacheSize == 0) {
9055 // delete existing cache
9056 pf->WaitFinishPrefetch();
9057 file->SetCacheRead(nullptr,this);
9058 delete pf;
9059 pf = nullptr;
9060 } else {
9061 // resize
9062 Int_t res = pf->SetBufferSize(cacheSize);
9063 if (res < 0) {
9064 return -1;
9065 }
9066 cacheSize = pf->GetBufferSize(); // update after potential clamp
9067 }
9068 } else {
9069 // no existing cache
9070 if (autocache) {
9071 if (fCacheUserSet) {
9072 // value was already set manually.
9073 if (fCacheSize == 0) return 0;
9074 // Expected a cache should exist; perhaps the user moved it
9075 // Do nothing more here.
9076 if (cacheSize) {
9077 Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
9078 }
9079 return -1;
9080 }
9081 }
9082 }
9083
9084 fCacheSize = cacheSize;
9085 if (cacheSize == 0 || pf) {
9086 return 0;
9087 }
9088
9089#ifdef R__USE_IMT
9091 pf = new TTreeCacheUnzip(this, cacheSize);
9092 else
9093#endif
9094 pf = new TTreeCache(this, cacheSize);
9095
9096 pf->SetAutoCreated(autocache);
9097
9098 return 0;
9099}
9100
9101////////////////////////////////////////////////////////////////////////////////
9102///interface to TTreeCache to set the cache entry range
9103///
9104/// Returns:
9105/// - 0 entry range set
9106/// - -1 on error
9109{
9110 if (!GetTree()) {
9111 if (LoadTree(0)<0) {
9112 Error("SetCacheEntryRange","Could not load a tree");
9113 return -1;
9114 }
9115 }
9116 if (GetTree()) {
9117 if (GetTree() != this) {
9118 return GetTree()->SetCacheEntryRange(first, last);
9119 }
9120 } else {
9121 Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
9122 return -1;
9123 }
9124
9125 TFile *f = GetCurrentFile();
9126 if (!f) {
9127 Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
9128 return -1;
9129 }
9130 TTreeCache *tc = GetReadCache(f,true);
9131 if (!tc) {
9132 Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
9133 return -1;
9134 }
9135 tc->SetEntryRange(first,last);
9136 return 0;
9137}
9138
9139////////////////////////////////////////////////////////////////////////////////
9140/// Interface to TTreeCache to set the number of entries for the learning phase
9145}
9146
9147////////////////////////////////////////////////////////////////////////////////
9148/// Enable/Disable circularity for this tree.
9149///
9150/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
9151/// per branch in memory.
9152/// Note that when this function is called (maxEntries>0) the Tree
9153/// must be empty or having only one basket per branch.
9154/// if maxEntries <= 0 the tree circularity is disabled.
9155///
9156/// #### NOTE 1:
9157/// Circular Trees are interesting in online real time environments
9158/// to store the results of the last maxEntries events.
9159/// #### NOTE 2:
9160/// Calling SetCircular with maxEntries <= 0 is necessary before
9161/// merging circular Trees that have been saved on files.
9162/// #### NOTE 3:
9163/// SetCircular with maxEntries <= 0 is automatically called
9164/// by TChain::Merge
9165/// #### NOTE 4:
9166/// A circular Tree can still be saved in a file. When read back,
9167/// it is still a circular Tree and can be filled again.
9170{
9171 if (maxEntries <= 0) {
9172 // Disable circularity.
9173 fMaxEntries = 1000000000;
9174 fMaxEntries *= 1000;
9176 //in case the Tree was originally created in gROOT, the branch
9177 //compression level was set to -1. If the Tree is now associated to
9178 //a file, reset the compression level to the file compression level
9179 if (fDirectory) {
9182 if (bfile) {
9183 compress = bfile->GetCompressionSettings();
9184 }
9186 for (Int_t i = 0; i < nb; i++) {
9188 branch->SetCompressionSettings(compress);
9189 }
9190 }
9191 } else {
9192 // Enable circularity.
9195 }
9196}
9197
9198////////////////////////////////////////////////////////////////////////////////
9199/// Set the debug level and the debug range.
9200///
9201/// For entries in the debug range, the functions TBranchElement::Fill
9202/// and TBranchElement::GetEntry will print the number of bytes filled
9203/// or read for each branch.
9205void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
9206{
9207 fDebug = level;
9208 fDebugMin = min;
9209 fDebugMax = max;
9210}
9211
9212////////////////////////////////////////////////////////////////////////////////
9213/// Update the default value for the branch's fEntryOffsetLen.
9214/// If updateExisting is true, also update all the existing branches.
9215/// If newdefault is less than 10, the new default value will be 10.
9218{
9219 if (newdefault < 10) {
9220 newdefault = 10;
9221 }
9223 if (updateExisting) {
9224 TIter next( GetListOfBranches() );
9225 TBranch *b;
9226 while ( ( b = (TBranch*)next() ) ) {
9227 b->SetEntryOffsetLen( newdefault, true );
9228 }
9229 if (fBranchRef) {
9231 }
9232 }
9233}
9234
9235////////////////////////////////////////////////////////////////////////////////
9236/// Change the tree's directory.
9237///
9238/// Remove reference to this tree from current directory and
9239/// add reference to new directory dir. The dir parameter can
9240/// be 0 in which case the tree does not belong to any directory.
9241///
9244{
9245 if (fDirectory == dir) {
9246 return;
9247 }
9248 if (fDirectory) {
9249 fDirectory->Remove(this);
9250
9251 // Delete or move the file cache if it points to this Tree
9252 TFile *file = fDirectory->GetFile();
9253 MoveReadCache(file,dir);
9254 }
9255 fDirectory = dir;
9256 if (fDirectory) {
9257 fDirectory->Append(this);
9258 }
9259 TFile* file = nullptr;
9260 if (fDirectory) {
9261 file = fDirectory->GetFile();
9262 }
9263 if (fBranchRef) {
9264 fBranchRef->SetFile(file);
9265 }
9266 TBranch* b = nullptr;
9267 TIter next(GetListOfBranches());
9268 while((b = (TBranch*) next())) {
9269 b->SetFile(file);
9270 }
9271}
9272
9273////////////////////////////////////////////////////////////////////////////////
9274/// Change number of entries in the tree.
9275///
9276/// If n >= 0, set number of entries in the tree = n.
9277///
9278/// If n < 0, set number of entries in the tree to match the
9279/// number of entries in each branch. (default for n is -1)
9280///
9281/// This function should be called only when one fills each branch
9282/// independently via TBranch::Fill without calling TTree::Fill.
9283/// Calling TTree::SetEntries() make sense only if the number of entries
9284/// in each branch is identical, a warning is issued otherwise.
9285/// The function returns the number of entries.
9286///
9289{
9290 // case 1 : force number of entries to n
9291 if (n >= 0) {
9292 fEntries = n;
9293 return n;
9294 }
9295
9296 // case 2; compute the number of entries from the number of entries in the branches
9297 TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
9299 Long64_t nMax = 0;
9300 TIter next(GetListOfBranches());
9301 while((b = (TBranch*) next())){
9302 Long64_t n2 = b->GetEntries();
9303 if (!bMin || n2 < nMin) {
9304 nMin = n2;
9305 bMin = b;
9306 }
9307 if (!bMax || n2 > nMax) {
9308 nMax = n2;
9309 bMax = b;
9310 }
9311 }
9312 if (bMin && nMin != nMax) {
9313 Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
9314 bMin->GetName(), nMin, bMax->GetName(), nMax);
9315 }
9316 fEntries = nMax;
9317 return fEntries;
9318}
9319
9320////////////////////////////////////////////////////////////////////////////////
9321/// Set an EntryList
9324{
9325 if (fEntryList) {
9326 //check if the previous entry list is owned by the tree
9328 delete fEntryList;
9329 }
9330 }
9331 fEventList = nullptr;
9332 if (!enlist) {
9333 fEntryList = nullptr;
9334 return;
9335 }
9337 fEntryList->SetTree(this);
9338
9339}
9340
9341////////////////////////////////////////////////////////////////////////////////
9342/// This function transfroms the given TEventList into a TEntryList
9343/// The new TEntryList is owned by the TTree and gets deleted when the tree
9344/// is deleted. This TEntryList can be returned by GetEntryList() function.
9347{
9349 if (fEntryList){
9352 fEntryList = nullptr; // Avoid problem with RecursiveRemove.
9353 delete tmp;
9354 } else {
9355 fEntryList = nullptr;
9356 }
9357 }
9358
9359 if (!evlist) {
9360 fEntryList = nullptr;
9361 fEventList = nullptr;
9362 return;
9363 }
9364
9366 char enlistname[100];
9367 snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
9368 fEntryList = new TEntryList(enlistname, evlist->GetTitle());
9369 fEntryList->SetDirectory(nullptr); // We own this.
9370 Int_t nsel = evlist->GetN();
9371 fEntryList->SetTree(this);
9373 for (Int_t i=0; i<nsel; i++){
9374 entry = evlist->GetEntry(i);
9376 }
9377 fEntryList->SetReapplyCut(evlist->GetReapplyCut());
9379}
9380
9381////////////////////////////////////////////////////////////////////////////////
9382/// Set number of entries to estimate variable limits.
9383/// If n is -1, the estimate is set to be the current maximum
9384/// for the tree (i.e. GetEntries() + 1)
9385/// If n is less than -1, the behavior is undefined.
9387void TTree::SetEstimate(Long64_t n /* = 1000000 */)
9388{
9389 if (n == 0) {
9390 n = 10000;
9391 } else if (n < 0) {
9392 n = fEntries - n;
9393 }
9394 fEstimate = n;
9395 GetPlayer();
9396 if (fPlayer) {
9398 }
9399}
9400
9401////////////////////////////////////////////////////////////////////////////////
9402/// Provide the end-user with the ability to enable/disable various experimental
9403/// IO features for this TTree.
9404///
9405/// Returns all the newly-set IO settings.
9408{
9409 // Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
9410 // error of their ways; this is just a safety check.
9412
9417
9419 return newSettings;
9420}
9421
9422////////////////////////////////////////////////////////////////////////////////
9423/// Set fFileNumber to number.
9424/// fFileNumber is used by TTree::Fill to set the file name
9425/// for a new file to be created when the current file exceeds fgTreeMaxSize.
9426/// (see TTree::ChangeFile)
9427/// if fFileNumber=10, the new file name will have a suffix "_11",
9428/// ie, fFileNumber is incremented before setting the file name
9430void TTree::SetFileNumber(Int_t number)
9431{
9432 if (fFileNumber < 0) {
9433 Warning("SetFileNumber", "file number must be positive. Set to 0");
9434 fFileNumber = 0;
9435 return;
9436 }
9437 fFileNumber = number;
9438}
9439
9440////////////////////////////////////////////////////////////////////////////////
9441/// Set all the branches in this TTree to be in decomposed object mode
9442/// (also known as MakeClass mode).
9443///
9444/// For MakeClass mode 0, the TTree expects the address where the data is stored
9445/// to be set by either the user or the TTree to the address of a full object
9446/// through the top level branch.
9447/// For MakeClass mode 1, this address is expected to point to a numerical type
9448/// or C-style array (variable or not) of numerical type, representing the
9449/// primitive data members.
9450/// The function's primary purpose is to allow the user to access the data
9451/// directly with numerical type variable rather than having to have the original
9452/// set of classes (or a reproduction thereof).
9453/// In other words, SetMakeClass sets the branch(es) into a
9454/// mode that allow its reading via a set of independent variables
9455/// (see the result of running TTree::MakeClass on your TTree) by changing the
9456/// interpretation of the address passed to SetAddress from being the beginning
9457/// of the object containing the data to being the exact location where the data
9458/// should be loaded. If you have the shared library corresponding to your object,
9459/// it is better if you do
9460/// `MyClass *objp = 0; tree->SetBranchAddress("toplevel",&objp);`, whereas
9461/// if you do not have the shared library but know your branch data type, e.g.
9462/// `Int_t* ptr = new Int_t[10];`, then:
9463/// `tree->SetMakeClass(1); tree->GetBranch("x")->SetAddress(ptr)` is the way to go.
9465void TTree::SetMakeClass(Int_t make)
9466{
9467 fMakeClass = make;
9468
9470 for (Int_t i = 0; i < nb; ++i) {
9472 branch->SetMakeClass(make);
9473 }
9474}
9475
9476////////////////////////////////////////////////////////////////////////////////
9477/// Set the maximum size in bytes of a Tree file (static function).
9478/// The default size is 100000000000LL, ie 100 Gigabytes.
9479///
9480/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
9481/// the function closes the current file and starts writing into
9482/// a new file with a name of the style "file_1.root" if the original
9483/// requested file name was "file.root".
9488}
9489
9490////////////////////////////////////////////////////////////////////////////////
9491/// Change the name of this tree.
9493void TTree::SetName(const char* name)
9494{
9495 if (gPad) {
9496 gPad->Modified();
9497 }
9498 // Trees are named objects in a THashList.
9499 // We must update hashlists if we change the name.
9500 TFile *file = nullptr;
9501 TTreeCache *pf = nullptr;
9502 if (fDirectory) {
9503 fDirectory->Remove(this);
9504 if ((file = GetCurrentFile())) {
9505 pf = GetReadCache(file);
9506 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9507 }
9508 }
9509 // This changes our hash value.
9510 fName = name;
9511 if (fDirectory) {
9512 fDirectory->Append(this);
9513 if (pf) {
9515 }
9516 }
9517}
9519void TTree::SetNotify(TObject *obj)
9520{
9521 if (obj && fNotify && dynamic_cast<TNotifyLinkBase *>(fNotify)) {
9522 auto *oldLink = static_cast<TNotifyLinkBase *>(fNotify);
9523 auto *newLink = dynamic_cast<TNotifyLinkBase *>(obj);
9524 if (!newLink) {
9525 Warning("TTree::SetNotify",
9526 "The tree or chain already has a fNotify registered and it is a TNotifyLink, while the new object is "
9527 "not a TNotifyLink. Setting fNotify to the new value will lead to an orphan linked list of "
9528 "TNotifyLinks and it is most likely not intended. If this is the intended goal, please call "
9529 "SetNotify(nullptr) first to silence this warning.");
9530 } else if (newLink->GetNext() != oldLink && oldLink->GetNext() != newLink) {
9531 // If newLink->GetNext() == oldLink then we are prepending the new head, as in TNotifyLink::PrependLink
9532 // If oldLink->GetNext() == newLink then we are removing the head of the list, as in TNotifyLink::RemoveLink
9533 // Otherwise newLink and oldLink are unrelated:
9534 Warning("TTree::SetNotify",
9535 "The tree or chain already has a TNotifyLink registered, and the new TNotifyLink `obj` does not link "
9536 "to it. Setting fNotify to the new value will lead to an orphan linked list of TNotifyLinks and it is "
9537 "most likely not intended. If this is the intended goal, please call SetNotify(nullptr) first to "
9538 "silence this warning.");
9539 }
9540 }
9541
9542 fNotify = obj;
9543}
9544
9545////////////////////////////////////////////////////////////////////////////////
9546/// Change the name and title of this tree.
9548void TTree::SetObject(const char* name, const char* title)
9549{
9550 if (gPad) {
9551 gPad->Modified();
9552 }
9553
9554 // Trees are named objects in a THashList.
9555 // We must update hashlists if we change the name
9556 TFile *file = nullptr;
9557 TTreeCache *pf = nullptr;
9558 if (fDirectory) {
9559 fDirectory->Remove(this);
9560 if ((file = GetCurrentFile())) {
9561 pf = GetReadCache(file);
9562 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9563 }
9564 }
9565 // This changes our hash value.
9566 fName = name;
9567 fTitle = title;
9568 if (fDirectory) {
9569 fDirectory->Append(this);
9570 if (pf) {
9572 }
9573 }
9574}
9575
9576////////////////////////////////////////////////////////////////////////////////
9577/// Enable or disable parallel unzipping of Tree buffers.
9580{
9581#ifdef R__USE_IMT
9582 if (GetTree() == nullptr) {
9584 if (!GetTree())
9585 return;
9586 }
9587 if (GetTree() != this) {
9588 GetTree()->SetParallelUnzip(opt, RelSize);
9589 return;
9590 }
9591 TFile* file = GetCurrentFile();
9592 if (!file)
9593 return;
9594
9595 TTreeCache* pf = GetReadCache(file);
9596 if (pf && !( opt ^ (nullptr != dynamic_cast<TTreeCacheUnzip*>(pf)))) {
9597 // done with opt and type are in agreement.
9598 return;
9599 }
9600 delete pf;
9601 auto cacheSize = GetCacheAutoSize(true);
9602 if (opt) {
9603 auto unzip = new TTreeCacheUnzip(this, cacheSize);
9604 unzip->SetUnzipBufferSize( Long64_t(cacheSize * RelSize) );
9605 } else {
9606 pf = new TTreeCache(this, cacheSize);
9607 }
9608#else
9609 (void)opt;
9610 (void)RelSize;
9611#endif
9612}
9613
9614////////////////////////////////////////////////////////////////////////////////
9615/// Set perf stats
9620}
9621
9622////////////////////////////////////////////////////////////////////////////////
9623/// The current TreeIndex is replaced by the new index.
9624/// Note that this function does not delete the previous index.
9625/// This gives the possibility to play with more than one index, e.g.,
9626/// ~~~ {.cpp}
9627/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
9628/// tree.SetTreeIndex(newIndex);
9629/// tree.Draw();
9630/// tree.SetTreeIndex(oldIndex);
9631/// tree.Draw(); etc
9632/// ~~~
9635{
9636 if (fTreeIndex) {
9637 fTreeIndex->SetTree(nullptr);
9638 }
9639 fTreeIndex = index;
9640}
9641
9642////////////////////////////////////////////////////////////////////////////////
9643/// Set tree weight.
9644///
9645/// The weight is used by TTree::Draw to automatically weight each
9646/// selected entry in the resulting histogram.
9647///
9648/// For example the equivalent of:
9649/// ~~~ {.cpp}
9650/// T.Draw("x", "w")
9651/// ~~~
9652/// is:
9653/// ~~~ {.cpp}
9654/// T.SetWeight(w);
9655/// T.Draw("x");
9656/// ~~~
9657/// This function is redefined by TChain::SetWeight. In case of a
9658/// TChain, an option "global" may be specified to set the same weight
9659/// for all trees in the TChain instead of the default behaviour
9660/// using the weights of each tree in the chain (see TChain::SetWeight).
9663{
9664 fWeight = w;
9665}
9666
9667////////////////////////////////////////////////////////////////////////////////
9668/// Print values of all active leaves for entry.
9669///
9670/// - if entry==-1, print current entry (default)
9671/// - if a leaf is an array, a maximum of lenmax elements is printed.
9674{
9675 if (entry != -1) {
9677 if (ret == -2) {
9678 Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
9679 return;
9680 } else if (ret == -1) {
9681 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9682 return;
9683 }
9684 ret = GetEntry(entry);
9685 if (ret == -1) {
9686 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9687 return;
9688 } else if (ret == 0) {
9689 Error("Show()", "Cannot read entry %lld (no data read)", entry);
9690 return;
9691 }
9692 }
9693 printf("======> EVENT:%lld\n", fReadEntry);
9695 Int_t nleaves = leaves->GetEntriesFast();
9696 Int_t ltype;
9697 for (Int_t i = 0; i < nleaves; i++) {
9698 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
9699 TBranch* branch = leaf->GetBranch();
9700 if (branch->TestBit(kDoNotProcess)) {
9701 continue;
9702 }
9703 Int_t len = leaf->GetLen();
9704 if (len <= 0) {
9705 continue;
9706 }
9708 if (leaf->IsA() == TLeafElement::Class()) {
9709 leaf->PrintValue(lenmax);
9710 continue;
9711 }
9712 if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
9713 continue;
9714 }
9715 ltype = 10;
9716 if (leaf->IsA() == TLeafF::Class()) {
9717 ltype = 5;
9718 }
9719 if (leaf->IsA() == TLeafD::Class()) {
9720 ltype = 5;
9721 }
9722 if (leaf->IsA() == TLeafC::Class()) {
9723 len = 1;
9724 ltype = 5;
9725 };
9726 printf(" %-15s = ", leaf->GetName());
9727 for (Int_t l = 0; l < len; l++) {
9728 leaf->PrintValue(l);
9729 if (l == (len - 1)) {
9730 printf("\n");
9731 continue;
9732 }
9733 printf(", ");
9734 if ((l % ltype) == 0) {
9735 printf("\n ");
9736 }
9737 }
9738 }
9739}
9740
9741////////////////////////////////////////////////////////////////////////////////
9742/// Start the TTreeViewer on this tree.
9743///
9744/// - ww is the width of the canvas in pixels
9745/// - wh is the height of the canvas in pixels
9747void TTree::StartViewer()
9748{
9749 GetPlayer();
9750 if (fPlayer) {
9751 fPlayer->StartViewer(600, 400);
9752 }
9753}
9754
9755////////////////////////////////////////////////////////////////////////////////
9756/// Stop the cache learning phase
9757///
9758/// Returns:
9759/// - 0 learning phase stopped or not active
9760/// - -1 on error
9763{
9764 if (!GetTree()) {
9765 if (LoadTree(0)<0) {
9766 Error("StopCacheLearningPhase","Could not load a tree");
9767 return -1;
9768 }
9769 }
9770 if (GetTree()) {
9771 if (GetTree() != this) {
9772 return GetTree()->StopCacheLearningPhase();
9773 }
9774 } else {
9775 Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
9776 return -1;
9777 }
9778
9779 TFile *f = GetCurrentFile();
9780 if (!f) {
9781 Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
9782 return -1;
9783 }
9784 TTreeCache *tc = GetReadCache(f,true);
9785 if (!tc) {
9786 Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
9787 return -1;
9788 }
9789 tc->StopLearningPhase();
9790 return 0;
9791}
9792
9793////////////////////////////////////////////////////////////////////////////////
9794/// Set the fTree member for all branches and sub branches.
9797{
9798 Int_t nb = branches.GetEntriesFast();
9799 for (Int_t i = 0; i < nb; ++i) {
9800 TBranch* br = (TBranch*) branches.UncheckedAt(i);
9801 br->SetTree(tree);
9802
9803 Int_t writeBasket = br->GetWriteBasket();
9804 for (Int_t j = writeBasket; j >= 0; --j) {
9805 TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
9806 if (bk) {
9807 tree->IncrementTotalBuffers(bk->GetBufferSize());
9808 }
9809 }
9810
9811 tree->RegisterBranchFullName({std::string{br->GetFullName()}, br});
9812
9813 ROOT::Internal::TreeUtils::TBranch__SetTree(tree, *br->GetListOfBranches());
9814 }
9815}
9816
9817////////////////////////////////////////////////////////////////////////////////
9818/// Set the fTree member for all friend elements.
9821{
9822 if (frlist) {
9823 TObjLink *lnk = frlist->FirstLink();
9824 while (lnk) {
9825 TFriendElement *elem = (TFriendElement*)lnk->GetObject();
9826 elem->fParentTree = tree;
9827 lnk = lnk->Next();
9828 }
9829 }
9830}
9831
9832////////////////////////////////////////////////////////////////////////////////
9833/// Stream a class object.
9836{
9837 if (b.IsReading()) {
9838 UInt_t R__s, R__c;
9839 if (fDirectory) {
9840 fDirectory->Remove(this);
9841 //delete the file cache if it points to this Tree
9842 TFile *file = fDirectory->GetFile();
9843 MoveReadCache(file,nullptr);
9844 }
9845 fDirectory = nullptr;
9846 fCacheDoAutoInit = true;
9847 fCacheUserSet = false;
9848 fNamesToBranches.clear();
9849 Version_t R__v = b.ReadVersion(&R__s, &R__c);
9850 if (R__v > 4) {
9851 b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
9852
9853 fBranches.SetOwner(true); // True needed only for R__v < 19 and most R__v == 19
9854
9855 if (fBranchRef) fBranchRef->SetTree(this);
9858
9859 if (fTreeIndex) {
9860 fTreeIndex->SetTree(this);
9861 }
9862 if (fIndex.fN) {
9863 Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
9864 fIndex.Set(0);
9865 fIndexValues.Set(0);
9866 }
9867 if (fEstimate <= 10000) {
9868 fEstimate = 1000000;
9869 }
9870
9871 if (fNClusterRange) {
9872 // The I/O allocated just enough memory to hold the
9873 // current set of ranges.
9875 }
9876
9877 // Throughs calls to `GetCacheAutoSize` or `EnableCache` (for example
9878 // by TTreePlayer::Process, the cache size will be automatically
9879 // determined unless the user explicitly call `SetCacheSize`
9880 fCacheSize = 0;
9881 fCacheUserSet = false;
9882
9884 return;
9885 }
9886 //====process old versions before automatic schema evolution
9887 Stat_t djunk;
9888 Int_t ijunk;
9893 b >> fScanField;
9896 b >> djunk; fEntries = (Long64_t)djunk;
9901 if (fEstimate <= 10000) fEstimate = 1000000;
9903 if (fBranchRef) fBranchRef->SetTree(this);
9907 if (R__v > 1) fIndexValues.Streamer(b);
9908 if (R__v > 2) fIndex.Streamer(b);
9909 if (R__v > 3) {
9911 OldInfoList.Streamer(b);
9912 OldInfoList.Delete();
9913 }
9914 fNClusterRange = 0;
9917 b.CheckByteCount(R__s, R__c, TTree::IsA());
9918 //====end of old versions
9919 } else {
9920 if (fBranchRef) {
9921 fBranchRef->Clear();
9922 }
9924 if (table) TRefTable::SetRefTable(nullptr);
9925
9926 b.WriteClassBuffer(TTree::Class(), this);
9927
9928 if (table) TRefTable::SetRefTable(table);
9929 }
9930}
9931
9932////////////////////////////////////////////////////////////////////////////////
9933/// Unbinned fit of one or more variable(s) from a tree.
9934///
9935/// funcname is a TF1 function.
9936///
9937/// \note see TTree::Draw for explanations of the other parameters.
9938///
9939/// Fit the variable varexp using the function funcname using the
9940/// selection cuts given by selection.
9941///
9942/// The list of fit options is given in parameter option.
9943///
9944/// - option = "Q" Quiet mode (minimum printing)
9945/// - option = "V" Verbose mode (default is between Q and V)
9946/// - option = "E" Perform better Errors estimation using Minos technique
9947/// - option = "M" More. Improve fit results
9948///
9949/// You can specify boundary limits for some or all parameters via
9950/// ~~~ {.cpp}
9951/// func->SetParLimits(p_number, parmin, parmax);
9952/// ~~~
9953/// if parmin>=parmax, the parameter is fixed
9954///
9955/// Note that you are not forced to fix the limits for all parameters.
9956/// For example, if you fit a function with 6 parameters, you can do:
9957/// ~~~ {.cpp}
9958/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
9959/// func->SetParLimits(4,-10,-4);
9960/// func->SetParLimits(5, 1,1);
9961/// ~~~
9962/// With this setup:
9963///
9964/// - Parameters 0->3 can vary freely
9965/// - Parameter 4 has boundaries [-10,-4] with initial value -8
9966/// - Parameter 5 is fixed to 100.
9967///
9968/// For the fit to be meaningful, the function must be self-normalized.
9969///
9970/// i.e. It must have the same integral regardless of the parameter
9971/// settings. Otherwise the fit will effectively just maximize the
9972/// area.
9973///
9974/// It is mandatory to have a normalization variable
9975/// which is fixed for the fit. e.g.
9976/// ~~~ {.cpp}
9977/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
9978/// f1->SetParameters(1, 3.1, 0.01);
9979/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
9980/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
9981/// ~~~
9982/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
9983///
9984/// Return status:
9985///
9986/// - The function return the status of the fit in the following form
9987/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
9988/// - The fitResult is 0 is the fit is OK.
9989/// - The fitResult is negative in case of an error not connected with the fit.
9990/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
9991/// - If the number of selected entries is null the function returns -1
9994{
9995 GetPlayer();
9996 if (fPlayer) {
9998 }
9999 return -1;
10000}
10001
10002////////////////////////////////////////////////////////////////////////////////
10003/// Replace current attributes by current style.
10026}
10027
10028////////////////////////////////////////////////////////////////////////////////
10029/// Write this object to the current directory. For more see TObject::Write
10030/// If option & kFlushBasket, call FlushBasket before writing the tree.
10032Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
10033{
10036 return 0;
10038}
10039
10040////////////////////////////////////////////////////////////////////////////////
10041/// Write this object to the current directory. For more see TObject::Write
10042/// If option & kFlushBasket, call FlushBasket before writing the tree.
10045{
10046 return ((const TTree*)this)->Write(name, option, bufsize);
10047}
10048
10049////////////////////////////////////////////////////////////////////////////////
10050/// \class TTreeFriendLeafIter
10051///
10052/// Iterator on all the leaves in a TTree and its friend
10053
10054
10055////////////////////////////////////////////////////////////////////////////////
10056/// Create a new iterator. By default the iteration direction
10057/// is kIterForward. To go backward use kIterBackward.
10060: fTree(const_cast<TTree*>(tree))
10061, fLeafIter(nullptr)
10062, fTreeIter(nullptr)
10063, fDirection(dir)
10064{
10065}
10066
10067////////////////////////////////////////////////////////////////////////////////
10068/// Copy constructor. Does NOT copy the 'cursor' location!
10071: TIterator(iter)
10072, fTree(iter.fTree)
10073, fLeafIter(nullptr)
10074, fTreeIter(nullptr)
10075, fDirection(iter.fDirection)
10076{
10077}
10078
10079////////////////////////////////////////////////////////////////////////////////
10080/// Overridden assignment operator. Does NOT copy the 'cursor' location!
10083{
10084 if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
10086 fDirection = rhs1.fDirection;
10087 }
10088 return *this;
10089}
10090
10091////////////////////////////////////////////////////////////////////////////////
10092/// Overridden assignment operator. Does NOT copy the 'cursor' location!
10095{
10096 if (this != &rhs) {
10097 fDirection = rhs.fDirection;
10098 }
10099 return *this;
10100}
10101
10102////////////////////////////////////////////////////////////////////////////////
10103/// Go the next friend element
10106{
10107 if (!fTree) return nullptr;
10108
10109 TObject * next;
10110 TTree * nextTree;
10111
10112 if (!fLeafIter) {
10113 TObjArray *list = fTree->GetListOfLeaves();
10114 if (!list) return nullptr; // Can happen with an empty chain.
10115 fLeafIter = list->MakeIterator(fDirection);
10116 if (!fLeafIter) return nullptr;
10117 }
10118
10119 next = fLeafIter->Next();
10120 if (!next) {
10121 if (!fTreeIter) {
10123 if (!list) return next;
10124 fTreeIter = list->MakeIterator(fDirection);
10125 if (!fTreeIter) return nullptr;
10126 }
10128 ///nextTree = (TTree*)fTreeIter->Next();
10129 if (nextFriend) {
10130 nextTree = const_cast<TTree*>(nextFriend->GetTree());
10131 if (!nextTree) return Next();
10133 fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
10134 if (!fLeafIter) return nullptr;
10135 next = fLeafIter->Next();
10136 }
10137 }
10138 return next;
10139}
10140
10141////////////////////////////////////////////////////////////////////////////////
10142/// Returns the object option stored in the list.
10145{
10146 if (fLeafIter) return fLeafIter->GetOption();
10147 return "";
10148}
10154}
10160}
#define R__unlikely(expr)
Definition RConfig.hxx:592
#define SafeDelete(p)
Definition RConfig.hxx:531
#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
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
short Version_t
Class version identifier (short)
Definition RtypesCore.h:80
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:69
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:61
float Float_t
Float 4 bytes (float)
Definition RtypesCore.h:72
double Double_t
Double 8 bytes.
Definition RtypesCore.h:74
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:132
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:84
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:85
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
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:385
R__EXTERN TEnv * gEnv
Definition TEnv.h:126
#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:208
#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:148
int nentries
R__EXTERN TInterpreter * gCling
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:792
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:417
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2584
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
constexpr Int_t kNEntriesResort
Definition TTree.cxx:474
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:4863
static char DataTypeToChar(EDataType datatype)
Definition TTree.cxx:485
void TFriendElement__SetTree(TTree *tree, TList *frlist)
Set the fTree member for all friend elements.
Definition TTree.cxx:9819
bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
Definition TTree.cxx:1267
constexpr Float_t kNEntriesResortInv
Definition TTree.cxx:475
#define R__LOCKGUARD(mutex)
#define gPad
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:148
void Set(Int_t n) override
Set size of this array to n doubles.
Definition TArrayD.cxx:105
void Set(Int_t n) override
Set size of this array to n ints.
Definition TArrayI.cxx:104
void Streamer(TBuffer &) override
Stream a TArrayI object.
Definition TArrayI.cxx:147
Int_t fN
Definition TArray.h:38
Fill Area Attributes class.
Definition TAttFill.h:21
virtual void Streamer(TBuffer &)
virtual Color_t GetFillColor() const
Return the fill area color.
Definition TAttFill.h:32
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition TAttFill.h:33
Line Attributes class.
Definition TAttLine.h:21
virtual void Streamer(TBuffer &)
virtual Color_t GetLineColor() const
Return the line color.
Definition TAttLine.h:36
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:46
virtual Width_t GetLineWidth() const
Return the line width.
Definition TAttLine.h:38
virtual Style_t GetLineStyle() const
Return the line style.
Definition TAttLine.h:37
Marker Attributes class.
Definition TAttMarker.h:22
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition TAttMarker.h:35
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition TAttMarker.h:34
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition TAttMarker.h:36
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
virtual void Streamer(TBuffer &)
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
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:255
virtual void SetTree(TTree *tree)
Definition TBranch.h:296
static void ResetCount()
Static function resetting fgCount.
Definition TBranch.cxx:2673
virtual void SetFile(TFile *file=nullptr)
Set file where this branch writes/reads its buffers.
Definition TBranch.cxx:2875
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:2833
virtual void UpdateFile()
Refresh the value of fDirectory (i.e.
Definition TBranch.cxx:3324
Int_t Fill()
Definition TBranch.h:214
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:222
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:2326
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2907
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:5048
Bool_t HasDataMemberInfo() const
Definition TClass.h:420
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:524
void Destructor(void *obj, Bool_t dtorOnly=kFALSE)
Explicitly call destructor for object.
Definition TClass.cxx:5470
void BuildRealData(void *pointer=nullptr, Bool_t isTransient=kFALSE)
Build a full list of persistent data members.
Definition TClass.cxx:2038
TList * GetListOfRealData() const
Definition TClass.h:468
Bool_t CanIgnoreTObjectStreamer()
Definition TClass.h:406
TList * GetListOfBases()
Return list containing the TBaseClass(es) of a class.
Definition TClass.cxx:3694
Bool_t IsTObject() const
Return kTRUE is the class inherits from TObject.
Definition TClass.cxx:6043
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:4657
Bool_t InheritsFrom(const char *cl) const override
Return kTRUE if this class inherits from a class with name "classname".
Definition TClass.cxx:4932
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:2918
Version_t GetClassVersion() const
Definition TClass.h:434
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:2994
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:71
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:223
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:221
virtual Int_t ReadKeys(Bool_t=kTRUE)
Definition TDirectory.h:249
virtual Bool_t IsWritable() const
Definition TDirectory.h:238
virtual TKey * GetKey(const char *, Short_t=9999) const
Definition TDirectory.h:222
virtual Int_t ReadTObject(TObject *, const char *)
Definition TDirectory.h:250
virtual void SaveSelf(Bool_t=kFALSE)
Definition TDirectory.h:256
virtual TList * GetListOfKeys() const
Definition TDirectory.h:224
void GetObject(const char *namecycle, T *&ptr)
Get an object with proper type checking.
Definition TDirectory.h:213
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:511
<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 class to pass information from the TFileMerger to the objects being merged.
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
virtual void SetCacheRead(TFileCacheRead *cache, TObject *tree=nullptr, ECacheAction action=kDisconnect)
Set a pointer to the read cache.
Definition TFile.cxx:2427
Int_t GetCompressionSettings() const
Definition TFile.h:489
Int_t GetCompressionLevel() const
Definition TFile.h:483
virtual void WriteStreamerInfo()
Write the list of TStreamerInfo as a single object in this file The class Streamer description for al...
Definition TFile.cxx:3500
@ kDoNotDisconnect
Definition TFile.h:148
virtual void Flush()
Synchronize a file's in-memory and on-disk states.
Definition TFile.cxx:1161
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:3797
virtual void WriteHeader()
Write File Header.
Definition TFile.cxx:2677
@ kCancelTTreeChangeRequest
Definition TFile.h:275
TFileCacheRead * GetCacheRead(const TObject *tree=nullptr) const
Return a pointer to the current read cache.
Definition TFile.cxx:1282
<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:584
Int_t GetKeylen() const
Definition TKey.h:86
Int_t GetNbytes() const
Definition TKey.h:88
virtual const char * GetClassName() const
Definition TKey.h:77
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:136
virtual Int_t GetLen() const
Return the number of effective elements of this leaf, for the current entry.
Definition TLeaf.cxx:405
@ kNewValue
Set if we own the value buffer and so must delete it ourselves.
Definition TLeaf.h:99
@ kIndirectAddress
Data member is a pointer to an array of basic types.
Definition TLeaf.h:98
virtual Int_t GetOffset() const
Definition TLeaf.h:140
A doubly linked list.
Definition TList.h:38
void Clear(Option_t *option="") override
Remove all objects from the list.
Definition TList.cxx:532
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void RecursiveRemove(TObject *obj) override
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition TList.cxx:894
void Add(TObject *obj) override
Definition TList.h:81
TObject * Remove(TObject *obj) override
Remove object from the list.
Definition TList.cxx:952
virtual TObjLink * FirstLink() const
Definition TList.h:107
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:600
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:487
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:27
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:170
TObject * UncheckedAt(Int_t i) const
Definition TObjArray.h:90
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:42
virtual Bool_t Notify()
This method must be overridden to handle object notification (the base implementation is no-op).
Definition TObject.cxx:617
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
@ kBitMask
Definition TObject.h:95
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:1082
R__ALWAYS_INLINE Bool_t IsZombie() const
Definition TObject.h:161
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:987
@ kOnlyPrepStep
Used to request that the class specific implementation of TObject::Write just prepare the objects to ...
Definition TObject.h:115
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:886
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:548
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1124
virtual TClass * IsA() const
Definition TObject.h:248
void ResetBit(UInt_t f)
Definition TObject.h:203
@ kCanDelete
if object in a list can be deleted
Definition TObject.h:71
@ kMustCleanup
if object destructor must call RecursiveRemove()
Definition TObject.h:73
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1070
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:182
Describes a persistent version of a class.
Basic string class.
Definition TString.h:138
Ssiz_t Length() const
Definition TString.h:427
void ToLower()
Change string to lower-case.
Definition TString.cxx:1189
static constexpr Ssiz_t kNPOS
Definition TString.h:286
Double_t Atof() const
Return floating-point value contained in string.
Definition TString.cxx:2134
const char * Data() const
Definition TString.h:386
Bool_t EqualTo(const char *cs, ECaseCompare cmp=kExact) const
Definition TString.h:656
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:715
@ kLeading
Definition TString.h:284
@ kTrailing
Definition TString.h:284
@ kIgnoreCase
Definition TString.h:285
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:2459
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2437
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:643
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:662
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:84
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1680
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:1311
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:768
TTree * fTree
tree being iterated
Definition TTree.h:771
TIterator & operator=(const TIterator &rhs) override
Overridden assignment operator. Does NOT copy the 'cursor' location!
Definition TTree.cxx:10081
TObject * Next() override
Go the next friend element.
Definition TTree.cxx:10104
TIterator * fLeafIter
current leaf sub-iterator.
Definition TTree.h:772
Option_t * GetOption() const override
Returns the object option stored in the list.
Definition TTree.cxx:10143
TIterator * fTreeIter
current tree sub-iterator.
Definition TTree.h:773
bool fDirection
iteration direction
Definition TTree.h:774
static TClass * Class()
Helper class to iterate over cluster of baskets.
Definition TTree.h:314
Long64_t GetEstimatedClusterSize()
Estimate the cluster size.
Definition TTree.cxx:638
Long64_t Previous()
Move on to the previous cluster and return the starting entry of this previous cluster.
Definition TTree.cxx:721
Long64_t Next()
Move on to the next cluster and return the starting entry of this next cluster.
Definition TTree.cxx:677
Long64_t GetNextEntry()
Definition TTree.h:351
TClusterIterator(TTree *tree, Long64_t firstEntry)
Regular constructor.
Definition TTree.cxx:587
Helper class to prevent infinite recursion in the usage of TTree Friends.
Definition TTree.h:221
TFriendLock & operator=(const TFriendLock &)
Assignment operator.
Definition TTree.cxx:553
TFriendLock(const TFriendLock &)
Copy constructor.
Definition TTree.cxx:543
UInt_t fMethodBit
Definition TTree.h:225
TTree * fTree
Definition TTree.h:224
~TFriendLock()
Restore the state of tree the same as before we set the lock.
Definition TTree.cxx:566
A TTree represents a columnar dataset.
Definition TTree.h:89
virtual Int_t Fill()
Fill all branches.
Definition TTree.cxx:4675
virtual TFriendElement * AddFriend(const char *treename, const char *filename="")
Add a TFriendElement to the list of friends.
Definition TTree.cxx:1359
TBranchRef * fBranchRef
Branch supporting the TRefTable (if any)
Definition TTree.h:146
TStreamerInfo * BuildStreamerInfo(TClass *cl, void *pointer=nullptr, bool canOptimize=true)
Build StreamerInfo for class cl.
Definition TTree.cxx:2682
TBranch * GetBranchFromFriends(const char *branchName)
Returns a pointer to the branch with the given name, if it can be found in the list of friends of thi...
Definition TTree.cxx:5400
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr, TClass *realClass, EDataType datatype, bool isptr, bool suppressMissingBranchError)
Definition TTree.cxx:8697
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:4912
virtual void SetBranchStatus(const char *bname, bool status=true, UInt_t *found=nullptr)
Set branch status to Process or DoNotProcess.
Definition TTree.cxx:8801
bool EnableCache()
Enable the TTreeCache unless explicitly disabled for this TTree by a prior call to SetCacheSize(0).
Definition TTree.cxx:2715
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition TTree.cxx:5452
static Int_t GetBranchStyle()
Static function returning the current branch style.
Definition TTree.cxx:5493
TList * fFriends
pointer to list of friend elements
Definition TTree.h:140
bool fIMTEnabled
! true if implicit multi-threading is enabled for this tree
Definition TTree.h:152
virtual bool GetBranchStatus(const char *branchname) const
Return status of branch with name branchname.
Definition TTree.cxx:5478
UInt_t fFriendLockStatus
! Record which method is locking the friend recursion
Definition TTree.h:147
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:6231
Long64_t fTotBytes
Total number of bytes in all branches before compression.
Definition TTree.h:96
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:5200
Int_t fMaxClusterRange
! Memory allocated for the cluster range.
Definition TTree.h:106
virtual void Show(Long64_t entry=-1, Int_t lenmax=20)
Print values of all active leaves for entry.
Definition TTree.cxx:9672
TEventList * fEventList
! Pointer to event selection list (if one)
Definition TTree.h:135
virtual Long64_t GetAutoSave() const
Definition TTree.h:495
virtual Int_t StopCacheLearningPhase()
Stop the cache learning phase.
Definition TTree.cxx:9761
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:5740
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:154
virtual void SetCircular(Long64_t maxEntries)
Enable/Disable circularity for this tree.
Definition TTree.cxx:9168
Long64_t fSavedBytes
Number of autosaved bytes.
Definition TTree.h:98
virtual Int_t AddBranchToCache(const char *bname, bool subbranches=false)
Add branch with name bname to the Tree cache.
Definition TTree.cxx:1086
Long64_t GetMedianClusterSize()
Estimate the median cluster size for the TTree.
Definition TTree.cxx:8526
virtual TClusterIterator GetClusterIterator(Long64_t firstentry)
Return an iterator over the cluster of baskets starting at firstentry.
Definition TTree.cxx:5565
virtual void ResetBranchAddress(TBranch *)
Tell a branch to set its address to zero.
Definition TTree.cxx:8280
bool fCacheUserSet
! true if the cache setting was explicitly given by user
Definition TTree.h:151
char GetNewlineValue(std::istream &inputStream)
Determine which newline this file is using.
Definition TTree.cxx:7803
TIOFeatures fIOFeatures
IO features to define for newly-written baskets and branches.
Definition TTree.h:124
virtual Long64_t GetEntryNumberWithIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:6012
Long64_t fDebugMin
! First entry number to debug
Definition TTree.h:122
virtual Long64_t SetEntries(Long64_t n=-1)
Change number of entries in the tree.
Definition TTree.cxx:9287
virtual TObjArray * GetListOfLeaves()
Definition TTree.h:576
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:2104
virtual Int_t GetEntryWithIndex(Long64_t major, Long64_t minor=0)
Read entry corresponding to major and minor number.
Definition TTree.cxx:6030
Long64_t GetCacheAutoSize(bool withDefault=false)
Used for automatic sizing of the cache.
Definition TTree.cxx:5505
virtual TBranch * BranchRef()
Build the optional branch supporting the TRefTable.
Definition TTree.cxx:2358
TFile * GetCurrentFile() const
Return pointer to the current file.
Definition TTree.cxx:5577
TList * fAliases
List of aliases for expressions based on the tree branches.
Definition TTree.h:134
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:3759
virtual Int_t DropBranchFromCache(const char *bname, bool subbranches=false)
Remove the branch with name 'bname' from the Tree cache.
Definition TTree.cxx:1169
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:5150
Long64_t * fClusterRangeEnd
[fNClusterRange] Last entry of a cluster range.
Definition TTree.h:113
void Streamer(TBuffer &) override
Stream a class object.
Definition TTree.cxx:9834
std::atomic< Long64_t > fIMTZipBytes
! Zip bytes for the IMT flush baskets.
Definition TTree.h:171
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:8096
TVirtualTreePlayer * GetPlayer()
Load the TTreePlayer (if not already done).
Definition TTree.cxx:6438
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:6909
virtual Long64_t ReadStream(std::istream &inputStream, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from an input stream.
Definition TTree.cxx:7830
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:9204
Int_t fScanField
Number of runs before prompting in Scan.
Definition TTree.h:102
void Draw(Option_t *opt) override
Default Draw method for all objects.
Definition TTree.h:478
virtual TTree * GetFriend(const char *) const
Return a pointer to the TTree friend whose name or alias is friendname.
Definition TTree.cxx:6078
virtual void SetNotify(TObject *obj)
Sets the address of the object to be notified when the tree is loaded.
Definition TTree.cxx:9518
virtual Double_t GetMaximum(const char *columname)
Return maximum of column with name columname.
Definition TTree.cxx:6368
virtual Long64_t GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5992
static void SetMaxTreeSize(Long64_t maxsize=100000000000LL)
Set the maximum size in bytes of a Tree file (static function).
Definition TTree.cxx:9484
void Print(Option_t *option="") const override
Print a summary of the tree contents.
Definition TTree.cxx:7436
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:9992
Int_t fNClusterRange
Number of Cluster range in addition to the one defined by 'AutoFlush'.
Definition TTree.h:105
virtual void PrintCacheStats(Option_t *option="") const
Print statistics about the TreeCache for this tree.
Definition TTree.cxx:7588
TVirtualTreePlayer * fPlayer
! Pointer to current Tree player
Definition TTree.h:144
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:6215
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:9464
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:7229
virtual void IncrementTotalBuffers(Int_t nbytes)
Definition TTree.h:633
TObjArray fBranches
List of Branches.
Definition TTree.h:132
TDirectory * GetDirectory() const
Definition TTree.h:509
bool fCacheDoAutoInit
! true if cache auto creation or resize check is needed
Definition TTree.h:149
TTreeCache * GetReadCache(TFile *file) const
Find and return the TTreeCache registered with the file and which may contain branches for us.
Definition TTree.cxx:6451
@ kSplitCollectionOfPointers
Definition TTree.h:310
Long64_t fEntries
Number of entries.
Definition TTree.h:94
virtual TFile * ChangeFile(TFile *file)
Called by TTree::Fill() when file has reached its maximum fgMaxTreeSize.
Definition TTree.cxx:2779
virtual TEntryList * GetEntryList()
Returns the entry list assigned to this tree.
Definition TTree.cxx:5956
virtual void SetWeight(Double_t w=1, Option_t *option="")
Set tree weight.
Definition TTree.cxx:9661
void InitializeBranchLists(bool checkLeafCount)
Divides the top-level branches into two vectors: (i) branches to be processed sequentially and (ii) b...
Definition TTree.cxx:5883
Long64_t * fClusterSize
[fNClusterRange] Number of entries in each cluster for a given range.
Definition TTree.h:114
Long64_t fFlushedBytes
Number of auto-flushed bytes.
Definition TTree.h:99
virtual void SetPerfStats(TVirtualPerfStats *perf)
Set perf stats.
Definition TTree.cxx:9616
std::atomic< Long64_t > fIMTTotBytes
! Total bytes for the IMT flush baskets
Definition TTree.h:170
virtual void SetCacheLearnEntries(Int_t n=10)
Interface to TTreeCache to set the number of entries for the learning phase.
Definition TTree.cxx:9141
TEntryList * fEntryList
! Pointer to event selection list (if one)
Definition TTree.h:136
virtual TVirtualIndex * GetTreeIndex() const
Definition TTree.h:605
TList * fExternalFriends
! List of TFriendsElement pointing to us and need to be notified of LoadTree. Content not owned.
Definition TTree.h:141
virtual Long64_t Merge(TCollection *list, Option_t *option="")
Merge the trees in the TList into this tree.
Definition TTree.cxx:7043
virtual void SetMaxVirtualSize(Long64_t size=0)
Definition TTree.h:717
virtual void DropBaskets()
Remove some baskets from memory.
Definition TTree.cxx:4590
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:8571
Long64_t fMaxEntryLoop
Maximum number of entries to process.
Definition TTree.h:108
virtual void SetParallelUnzip(bool opt=true, Float_t RelSize=-1)
Enable or disable parallel unzipping of Tree buffers.
Definition TTree.cxx:9578
virtual void SetDirectory(TDirectory *dir)
Change the tree's directory.
Definition TTree.cxx:9242
void SortBranchesByTime()
Sorts top-level branches by the last average task time recorded per branch.
Definition TTree.cxx:5936
void Delete(Option_t *option="") override
Delete this tree from memory or/and disk.
Definition TTree.cxx:3787
virtual TBranchRef * GetBranchRef() const
Definition TTree.h:497
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:7666
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:1662
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:9345
void MoveReadCache(TFile *src, TDirectory *dir)
Move a cache from a file to the current file in dir.
Definition TTree.cxx:7200
Long64_t fAutoFlush
Auto-flush tree when fAutoFlush entries written or -fAutoFlush (compressed) bytes produced.
Definition TTree.h:111
Int_t fUpdate
Update frequency for EntryLoop.
Definition TTree.h:103
virtual void ResetAfterMerge(TFileMergeInfo *)
Resets the state of this TTree after a merge (keep the customization but forget the data).
Definition TTree.cxx:8249
virtual Long64_t GetEntries() const
Definition TTree.h:510
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition TTree.cxx:9386
Int_t fTimerInterval
Timer interval in milliseconds.
Definition TTree.h:101
Int_t fDebug
! Debug level
Definition TTree.h:121
Int_t SetCacheSizeAux(bool autocache=true, Long64_t cacheSize=0)
Set the maximum size of the file cache (TTreeCache) in bytes and create it if possible.
Definition TTree.cxx:8987
virtual Long64_t AutoSave(Option_t *option="")
AutoSave tree header every fAutoSave bytes.
Definition TTree.cxx:1527
virtual Long64_t GetEntryNumber(Long64_t entry) const
Return entry number corresponding to entry.
Definition TTree.cxx:5967
virtual TTree * CloneTree(Long64_t nentries=-1, Option_t *option="")
Create a clone of this tree and copy nentries.
Definition TTree.cxx:3173
Int_t fFileNumber
! current file number (if file extensions)
Definition TTree.h:126
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:6328
virtual Long64_t GetZipBytes() const
Definition TTree.h:632
TObjArray fLeaves
Direct pointers to individual branch leaves.
Definition TTree.h:133
virtual void Reset(Option_t *option="")
Reset baskets, buffers and entries count in all branches and leaves.
Definition TTree.cxx:8218
virtual void KeepCircular()
Keep a maximum of fMaxEntries in memory.
Definition TTree.cxx:6548
virtual void SetDefaultEntryOffsetLen(Int_t newdefault, bool updateExisting=false)
Update the default value for the branch's fEntryOffsetLen.
Definition TTree.cxx:9216
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:3859
Long64_t fMaxVirtualSize
Maximum total size of buffers kept in memory.
Definition TTree.h:109
virtual Long64_t GetTotBytes() const
Definition TTree.h:603
virtual Int_t MakeSelector(const char *selector=nullptr, Option_t *option="")
Generate skeleton selector class for this tree.
Definition TTree.cxx:6963
virtual void SetObject(const char *name, const char *title)
Change the name and title of this tree.
Definition TTree.cxx:9547
TVirtualPerfStats * fPerfStats
! pointer to the current perf stats object
Definition TTree.h:142
Double_t fWeight
Tree weight (see TTree::SetWeight)
Definition TTree.h:100
std::vector< TBranch * > fSeqBranches
! Branches to be processed sequentially when IMT is on
Definition TTree.h:155
Long64_t fDebugMax
! Last entry number to debug
Definition TTree.h:123
Int_t fDefaultEntryOffsetLen
Initial Length of fEntryOffset table in the basket buffers.
Definition TTree.h:104
TBranch * GetBranchFromSelf(const char *branchName)
Returns a pointer to the branch with the given name, if it can be found in this tree.
Definition TTree.cxx:5364
TTree()
Default constructor and I/O constructor.
Definition TTree.cxx:764
Long64_t fAutoSave
Autosave tree when fAutoSave entries written or -fAutoSave (compressed) bytes produced.
Definition TTree.h:110
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:397
std::atomic< UInt_t > fAllocationCount
indicates basket should be resized to exact memory usage, but causes significant
Definition TTree.h:162
static TTree * MergeTrees(TList *list, Option_t *option="")
Static function merging the trees in the TList into a new tree.
Definition TTree.cxx:6994
bool MemoryFull(Int_t nbytes)
Check if adding nbytes to memory we are still below MaxVirtualsize.
Definition TTree.cxx:6978
virtual Long64_t GetReadEntry() const
Definition TTree.h:596
virtual TObjArray * GetListOfBranches()
Definition TTree.h:575
Long64_t fZipBytes
Total number of bytes in all branches after compression.
Definition TTree.h:97
virtual TTree * GetTree() const
Definition TTree.h:604
TBuffer * fTransientBuffer
! Pointer to the current transient buffer.
Definition TTree.h:148
virtual void SetEntryList(TEntryList *list, Option_t *opt="")
Set an EntryList.
Definition TTree.cxx:9322
bool Notify() override
Function called when loading a new class library.
Definition TTree.cxx:7250
virtual void AddZipBytes(Int_t zip)
Definition TTree.h:376
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition TTree.cxx:6606
virtual Long64_t ReadFile(const char *filename, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from filename.
Definition TTree.cxx:7779
virtual const char * GetAlias(const char *aliasName) const
Returns the expanded value of the alias. Search in the friends if any.
Definition TTree.cxx:5297
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:9406
virtual TBasket * CreateBasket(TBranch *)
Create a basket for this tree and given branch.
Definition TTree.cxx:3771
TList * fUserInfo
pointer to a list of user objects associated to this Tree
Definition TTree.h:143
virtual Double_t GetMinimum(const char *columname)
Return minimum of column with name columname.
Definition TTree.cxx:6408
virtual void RemoveFriend(TTree *)
Remove a friend from the list of friends.
Definition TTree.cxx:8192
virtual Long64_t GetEntriesFast() const
Return a number greater or equal to the total number of entries in the dataset.
Definition TTree.h:552
void Browse(TBrowser *) override
Browse content of the TTree.
Definition TTree.cxx:2639
virtual TList * GetUserInfo()
Return a pointer to the list containing user objects associated to this tree.
Definition TTree.cxx:6489
void RegisterBranchFullName(std::pair< std::string, TBranch * > &&kv)
Definition TTree.h:182
Long64_t fChainOffset
! Offset of 1st entry of this Tree in a TChain
Definition TTree.h:116
@ kOnlyFlushAtCluster
If set, the branch's buffers will grow until an event cluster boundary is hit, guaranteeing a basket ...
Definition TTree.h:300
@ kEntriesReshuffled
If set, signals that this TTree is the output of the processing of another TTree, and the entries are...
Definition TTree.h:305
@ kCircular
Definition TTree.h:296
virtual Long64_t GetEntriesFriend() const
Returns a number corresponding to:
Definition TTree.cxx:5612
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:7727
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:2434
virtual void SetBasketSize(const char *bname, Int_t buffsize=16000)
Set a branch's basket size.
Definition TTree.cxx:8587
static void SetBranchStyle(Int_t style=1)
Set the current branch style.
Definition TTree.cxx:8932
~TTree() override
Destructor.
Definition TTree.cxx:947
void ImportClusterRanges(TTree *fromtree)
Appends the cluster range information stored in 'fromtree' to this tree, including the value of fAuto...
Definition TTree.cxx:6505
TClass * IsA() const override
Definition TTree.h:757
Long64_t fEstimate
Number of entries to estimate histogram limits.
Definition TTree.h:112
Int_t FlushBasketsImpl() const
Internal implementation of the FlushBaskets algorithm.
Definition TTree.cxx:5217
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:6698
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:10043
TVirtualIndex * fTreeIndex
Pointer to the tree Index (if any)
Definition TTree.h:139
void UseCurrentStyle() override
Replace current attributes by current style.
Definition TTree.cxx:10004
virtual Int_t GetTreeNumber() const
Definition TTree.h:606
TObject * fNotify
Object to be notified when loading a Tree.
Definition TTree.h:130
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:1581
virtual TList * GetListOfClones()
Definition TTree.h:574
Long64_t fCacheSize
! Maximum size of file buffers
Definition TTree.h:115
TList * fClones
! List of cloned trees which share our addresses
Definition TTree.h:145
std::atomic< Long64_t > fTotalBuffers
! Total number of bytes in branch buffers
Definition TTree.h:118
static TClass * Class()
@ kFindBranch
Definition TTree.h:245
@ kResetBranchAddresses
Definition TTree.h:266
@ kFindLeaf
Definition TTree.h:246
@ kGetEntryWithIndex
Definition TTree.h:250
@ kPrint
Definition TTree.h:260
@ kGetFriend
Definition TTree.h:251
@ kGetBranch
Definition TTree.h:248
@ kSetBranchStatus
Definition TTree.h:265
@ kLoadTree
Definition TTree.h:254
@ kGetEntry
Definition TTree.h:249
@ kGetLeaf
Definition TTree.h:253
@ kRemoveFriend
Definition TTree.h:264
@ kGetFriendAlias
Definition TTree.h:252
@ kGetAlias
Definition TTree.h:247
virtual void SetTreeIndex(TVirtualIndex *index)
The current TreeIndex is replaced by the new index.
Definition TTree.cxx:9633
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:7274
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:7712
virtual Int_t SetCacheEntryRange(Long64_t first, Long64_t last)
interface to TTreeCache to set the cache entry range
Definition TTree.cxx:9107
static Long64_t GetMaxTreeSize()
Static function which returns the tree file size limit in bytes.
Definition TTree.cxx:6398
bool fCacheDoClusterPrefetch
! true if cache is prefetching whole clusters
Definition TTree.h:150
virtual bool SetAlias(const char *aliasName, const char *aliasFormula)
Set a tree variable alias.
Definition TTree.cxx:8370
virtual void CopyAddresses(TTree *, bool undo=false)
Set branch addresses of passed tree equal to ours.
Definition TTree.cxx:3339
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:2667
Long64_t fMaxEntries
Maximum number of entries in case of circular buffers.
Definition TTree.h:107
virtual void DropBuffers(Int_t nbytes)
Drop branch buffers to accommodate nbytes below MaxVirtualsize.
Definition TTree.cxx:4603
virtual TList * GetListOfFriends() const
Definition TTree.h:577
virtual void Refresh()
Refresh contents of this tree and its branches from the current status on disk.
Definition TTree.cxx:8131
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:8425
static Long64_t fgMaxTreeSize
Maximum size of a file containing a Tree.
Definition TTree.h:165
Long64_t fReadEntry
! Number of the entry being processed
Definition TTree.h:117
TArrayD fIndexValues
Sorted index values.
Definition TTree.h:137
void MarkEventCluster()
Mark the previous event as being at the end of the event cluster.
Definition TTree.cxx:8487
UInt_t fNEntriesSinceSorting
! Number of entries processed since the last re-sorting of branches
Definition TTree.h:153
virtual void SetFileNumber(Int_t number=0)
Set fFileNumber to number.
Definition TTree.cxx:9429
virtual TLeaf * FindLeaf(const char *name)
Find first leaf containing searchname.
Definition TTree.cxx:4987
virtual void StartViewer()
Start the TTreeViewer on this tree.
Definition TTree.cxx:9746
Int_t GetMakeClass() const
Definition TTree.h:582
virtual Int_t MakeCode(const char *filename=nullptr)
Generate a skeleton function for this tree.
Definition TTree.cxx:6781
bool fIMTFlush
! True if we are doing a multithreaded flush.
Definition TTree.h:169
TDirectory * fDirectory
! Pointer to directory holding this tree
Definition TTree.h:131
@ kNeedEnableDecomposedObj
Definition TTree.h:288
@ kClassMismatch
Definition TTree.h:281
@ kVoidPtr
Definition TTree.h:286
@ kMatchConversionCollection
Definition TTree.h:284
@ kMissingCompiledCollectionProxy
Definition TTree.h:279
@ kMismatch
Definition TTree.h:280
@ kMatchConversion
Definition TTree.h:283
@ kInternalError
Definition TTree.h:278
@ kMatch
Definition TTree.h:282
@ kMissingBranch
Definition TTree.h:277
@ kMakeClass
Definition TTree.h:285
static Int_t fgBranchStyle
Old/New branch style.
Definition TTree.h:164
virtual void ResetBranchAddresses()
Tell all of our branches to drop their current objects and allocate new ones.
Definition TTree.cxx:8290
Int_t fNfill
! Local for EntryLoop
Definition TTree.h:120
void SetName(const char *name) override
Change the name of this tree.
Definition TTree.cxx:9492
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:8172
TArrayI fIndex
Index of sorted values.
Definition TTree.h:138
Int_t SetBranchAddressImp(const char *bname, void *add, TBranch **ptr, TClass *realClass, EDataType datatype, bool isptr)
Definition TTree.cxx:8637
virtual Int_t SetCacheSize(Long64_t cachesize=-1)
Set maximum size of the file cache (TTreeCache) in bytes.
Definition TTree.cxx:8954
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:1246
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:2901
TBuffer * GetTransientBuffer(Int_t size)
Returns the transient buffer currently used by this TTree for reading/writing baskets.
Definition TTree.cxx:1064
ROOT::TIOFeatures GetIOFeatures() const
Returns the current set of IO settings.
Definition TTree.cxx:6207
virtual Int_t MakeClass(const char *classname=nullptr, Option_t *option="")
Generate a skeleton analysis class for this tree.
Definition TTree.cxx:6748
virtual const char * GetFriendAlias(TTree *) const
If the 'tree' is a friend, this method returns its alias name.
Definition TTree.cxx:6135
virtual void RemoveExternalFriend(TFriendElement *)
Removes external friend.
Definition TTree.cxx:8183
Int_t fPacketSize
! Number of entries in one packet for parallel root
Definition TTree.h:119
virtual TBranch * BranchImpArr(const char *branchname, EDataType datatype, std::size_t N, void *addobj, Int_t bufsize, Int_t splitlevel)
Definition TTree.cxx:1758
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:8328
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:2442
virtual void AddTotBytes(Int_t tot)
Definition TTree.h:375
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:3574
Int_t fMakeClass
! not zero when processing code generated by MakeClass
Definition TTree.h:125
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:6584
static constexpr Long64_t kMaxEntries
Used as the max value for any TTree range operation.
Definition TTree.h:273
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:7417
std::unordered_map< std::string, TBranch * > fNamesToBranches
! maps names to their branches, useful when retrieving branches by name
Definition TTree.h:174
virtual Long64_t GetAutoFlush() const
Definition TTree.h:494
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 an 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
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:395
TBranch * CallBranchImp(TTree &tree, const char *branchname, TClass *ptrClass, void *addobj, Int_t bufsize=32000, Int_t splitlevel=99)
Definition TTree.cxx:10155
TBranch * CallBranchImpRef(TTree &tree, const char *branchname, TClass *ptrClass, EDataType datatype, void *addobj, Int_t bufsize=32000, Int_t splitlevel=99)
Definition TTree.cxx:10149
void TBranch__SetTree(TTree *tree, TObjArray &branches)
Set the fTree member for all branches and sub branches.
Definition TTree.cxx:9795
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:673
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:406
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:249
Double_t Median(Long64_t n, const T *a, const Double_t *w=nullptr, Long64_t *work=nullptr)
Returns the median of the array a where each entry i has weight w[i] .
Definition TMath.h:1365
Double_t Ceil(Double_t x)
Rounds x upward, returning the smallest integral value that is not less than x.
Definition TMath.h:681
Short_t Min(Short_t a, Short_t b)
Returns the smallest of a and b.
Definition TMathBase.h:197
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:329
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