Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TTree.cxx
Go to the documentation of this file.
1// @(#)root/tree:$Id$
2// Author: Rene Brun 12/01/96
3
4/*************************************************************************
5 * Copyright (C) 1995-2024, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11/**
12 \defgroup tree Tree Library
13
14 RNTuple is the modern way of storing columnar datasets: please consider to use it
15 before starting new projects based on TTree and related classes.
16
17 In order to store columnar datasets, ROOT historically provides the TTree, TChain,
18 TNtuple and TNtupleD classes.
19 The TTree class represents a columnar dataset. Any C++ type can be stored in the
20 columns. The TTree has allowed to store about **1 EB** of data coming from the LHC alone:
21 it is demonstrated to scale and it's battle tested. It has been optimized during the years
22 to reduce dataset sizes on disk and to deliver excellent runtime performance.
23 It allows to access only part of the columns of the datasets, too.
24 The TNtuple and TNtupleD classes are specialisations of the TTree class which can
25 only hold single precision and double precision floating-point numbers respectively;
26 The TChain is a collection of TTrees, which can be located also in different files.
27
28*/
29
30/** \class TTree
31\ingroup tree
32
33A TTree represents a columnar dataset. Any C++ type can be stored in its columns. The modern
34version of TTree is RNTuple: please consider using it before opting for TTree.
35
36A TTree, often called in jargon *tree*, consists of a list of independent columns or *branches*,
37represented by the TBranch class.
38Behind each branch, buffers are allocated automatically by ROOT.
39Such buffers are automatically written to disk or kept in memory until the size stored in the
40attribute fMaxVirtualSize is reached.
41Variables of one branch are written to the same buffer. A branch buffer is
42automatically compressed if the file compression attribute is set (default).
43Branches may be written to different files (see TBranch::SetFile).
44
45The ROOT user can decide to make one single branch and serialize one object into
46one single I/O buffer or to make several branches.
47Making several branches is particularly interesting in the data analysis phase,
48when it is desirable to have a high reading rate and not all columns are equally interesting
49
50\anchor creatingattreetoc
51## Create a TTree to store columnar data
52- [Construct a TTree](\ref creatingattree)
53- [Add a column of Fundamental Types and Arrays thereof](\ref addcolumnoffundamentaltypes)
54- [Add a column of a STL Collection instances](\ref addingacolumnofstl)
55- [Add a column holding an object](\ref addingacolumnofobjs)
56- [Add a column holding a 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 needed.
3929/// - Any number of variables no fewer than two can be used with the options "CANDLE" and "PARA"
3930/// - An arbitrary number of variables can be used with the option "GOFF"
3931///
3932/// Examples:
3933/// - "x": the simplest case, it draws a 1-Dim histogram of column x
3934/// - "sqrt(x)", "x*y/z": draw histogram with the values of the specified numerical expression across TTree events
3935/// - "y:sqrt(x)": 2-Dim histogram of y versus sqrt(x)
3936/// - "px:py:pz:2.5*E": produces a 3-d scatter-plot of px vs py ps pz
3937/// and the color number of each marker will be 2.5*E.
3938/// If the color number is negative it is set to 0.
3939/// If the color number is greater than the current number of colors
3940/// it is set to the highest color number. The default number of
3941/// colors is 50. See TStyle::SetPalette for setting a new color palette.
3942///
3943/// The expressions can use all the operations and built-in functions
3944/// supported by TFormula (see TFormula::Analyze()), including free
3945/// functions taking numerical arguments (e.g. TMath::Bessel()).
3946/// In addition, you can call member functions taking numerical
3947/// arguments. For example, these are two valid expressions:
3948/// ~~~ {.cpp}
3949/// TMath::BreitWigner(fPx,3,2)
3950/// event.GetHistogram()->GetXaxis()->GetXmax()
3951/// ~~~
3952/// \endparblock
3953/// \param [in] selection
3954/// \parblock
3955/// A string containing a selection expression.
3956/// In a selection all usual C++ mathematical and logical operators are allowed.
3957/// The value corresponding to the selection expression is used as a weight
3958/// to fill the histogram (a weight of 0 is equivalent to not filling the histogram).\n
3959/// \n
3960/// Examples:
3961/// - "x<y && sqrt(z)>3.2": returns a weight = 0 or 1
3962/// - "(x+y)*(sqrt(z)>3.2)": returns a weight = x+y if sqrt(z)>3.2, 0 otherwise\n
3963/// \n
3964/// If the selection expression returns an array, it is iterated over in sync with the
3965/// array returned by the varexp argument (as described below in "Drawing expressions using arrays and array
3966/// elements"). For example, if, for a given event, varexp evaluates to
3967/// `{1., 2., 3.}` and selection evaluates to `{0, 1, 0}`, the resulting histogram is filled with the value 2. For example, for each event here we perform a simple object selection:
3968/// ~~~{.cpp}
3969/// // Muon_pt is an array: fill a histogram with the array elements > 100 in each event
3970/// tree->Draw('Muon_pt', 'Muon_pt > 100')
3971/// ~~~
3972/// \endparblock
3973/// \param [in] option
3974/// \parblock
3975/// The drawing option.
3976/// - When an histogram is produced it can be any histogram drawing option
3977/// listed in THistPainter.
3978/// - when no option is specified:
3979/// - the default histogram drawing option is used
3980/// if the expression is of the form "e1".
3981/// - if the expression is of the form "e1:e2"or "e1:e2:e3" a cloud of
3982/// unbinned 2D or 3D points is drawn respectively.
3983/// - if the expression has four fields "e1:e2:e3:e4" a cloud of unbinned 3D
3984/// points is produced with e1 vs e2 vs e3, and e4 is mapped on the current color
3985/// palette.
3986/// - If option COL is specified when varexp has three fields:
3987/// ~~~ {.cpp}
3988/// tree.Draw("e1:e2:e3","","col");
3989/// ~~~
3990/// a 2D scatter is produced with e1 vs e2, and e3 is mapped on the current
3991/// color palette. The colors for e3 are evaluated once in linear scale before
3992/// painting. Therefore changing the pad to log scale along Z as no effect
3993/// on the colors.
3994/// - if expression has more than four fields the option "PARA"or "CANDLE"
3995/// can be used.
3996/// - If option contains the string "goff", no graphics is generated.
3997/// \endparblock
3998/// \param [in] nentries The number of entries to process (default is all)
3999/// \param [in] firstentry The first entry to process (default is 0)
4000///
4001/// ### Drawing expressions using arrays and array elements
4002///
4003/// Let assumes, a leaf fMatrix, on the branch fEvent, which is a 3 by 3 array,
4004/// or a TClonesArray.
4005/// In a TTree::Draw expression you can now access fMatrix using the following
4006/// syntaxes:
4007///
4008/// | String passed | What is used for each entry of the tree
4009/// |-----------------|--------------------------------------------------------|
4010/// | `fMatrix` | the 9 elements of fMatrix |
4011/// | `fMatrix[][]` | the 9 elements of fMatrix |
4012/// | `fMatrix[2][2]` | only the elements fMatrix[2][2] |
4013/// | `fMatrix[1]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
4014/// | `fMatrix[1][]` | the 3 elements fMatrix[1][0], fMatrix[1][1] and fMatrix[1][2] |
4015/// | `fMatrix[][0]` | the 3 elements fMatrix[0][0], fMatrix[1][0] and fMatrix[2][0] |
4016///
4017/// "fEvent.fMatrix...." same as "fMatrix..." (unless there is more than one leaf named fMatrix!).
4018///
4019/// In summary, if a specific index is not specified for a dimension, TTree::Draw
4020/// will loop through all the indices along this dimension. Leaving off the
4021/// last (right most) dimension of specifying then with the two characters '[]'
4022/// is equivalent. For variable size arrays (and TClonesArray) the range
4023/// of the first dimension is recalculated for each entry of the tree.
4024/// You can also specify the index as an expression of any other variables from the
4025/// tree.
4026///
4027/// TTree::Draw also now properly handling operations involving 2 or more arrays.
4028///
4029/// Let assume a second matrix fResults[5][2], here are a sample of some
4030/// of the possible combinations, the number of elements they produce and
4031/// the loop used:
4032///
4033/// | expression | element(s) | Loop |
4034/// |----------------------------------|------------|--------------------------|
4035/// | `fMatrix[2][1] - fResults[5][2]` | one | no loop |
4036/// | `fMatrix[2][] - fResults[5][2]` | three | on 2nd dim fMatrix |
4037/// | `fMatrix[2][] - fResults[5][]` | two | on both 2nd dimensions |
4038/// | `fMatrix[][2] - fResults[][1]` | three | on both 1st dimensions |
4039/// | `fMatrix[][2] - fResults[][]` | six | on both 1st and 2nd dimensions of fResults |
4040/// | `fMatrix[][2] - fResults[3][]` | two | on 1st dim of fMatrix and 2nd of fResults (at the same time) |
4041/// | `fMatrix[][] - fResults[][]` | six | on 1st dim then on 2nd dim |
4042/// | `fMatrix[][fResult[][]]` | 30 | on 1st dim of fMatrix then on both dimensions of fResults. The value if fResults[j][k] is used as the second index of fMatrix.|
4043///
4044///
4045/// In summary, TTree::Draw loops through all unspecified dimensions. To
4046/// figure out the range of each loop, we match each unspecified dimension
4047/// from left to right (ignoring ALL dimensions for which an index has been
4048/// specified), in the equivalent loop matched dimensions use the same index
4049/// and are restricted to the smallest range (of only the matched dimensions).
4050/// When involving variable arrays, the range can of course be different
4051/// for each entry of the tree.
4052///
4053/// So the loop equivalent to "fMatrix[][2] - fResults[3][]" is:
4054/// ~~~ {.cpp}
4055/// for (Int_t i0; i < min(3,2); i++) {
4056/// use the value of (fMatrix[i0][2] - fMatrix[3][i0])
4057/// }
4058/// ~~~
4059/// So the loop equivalent to "fMatrix[][2] - fResults[][]" is:
4060/// ~~~ {.cpp}
4061/// for (Int_t i0; i < min(3,5); i++) {
4062/// for (Int_t i1; i1 < 2; i1++) {
4063/// use the value of (fMatrix[i0][2] - fMatrix[i0][i1])
4064/// }
4065/// }
4066/// ~~~
4067/// So the loop equivalent to "fMatrix[][] - fResults[][]" is:
4068/// ~~~ {.cpp}
4069/// for (Int_t i0; i < min(3,5); i++) {
4070/// for (Int_t i1; i1 < min(3,2); i1++) {
4071/// use the value of (fMatrix[i0][i1] - fMatrix[i0][i1])
4072/// }
4073/// }
4074/// ~~~
4075/// So the loop equivalent to "fMatrix[][fResults[][]]" is:
4076/// ~~~ {.cpp}
4077/// for (Int_t i0; i0 < 3; i0++) {
4078/// for (Int_t j2; j2 < 5; j2++) {
4079/// for (Int_t j3; j3 < 2; j3++) {
4080/// i1 = fResults[j2][j3];
4081/// use the value of fMatrix[i0][i1]
4082/// }
4083/// }
4084/// ~~~
4085/// ### Retrieving the result of Draw
4086///
4087/// By default a temporary histogram called `htemp` is created. It will be:
4088///
4089/// - A TH1F* in case of a mono-dimensional distribution: `Draw("e1")`,
4090/// - A TH2F* in case of a bi-dimensional distribution: `Draw("e1:e2")`,
4091/// - A TH3F* in case of a three-dimensional distribution: `Draw("e1:e2:e3")`.
4092///
4093/// In the one dimensional case the `htemp` is filled and drawn whatever the drawing
4094/// option is.
4095///
4096/// In the two and three dimensional cases, with the default drawing option (`""`),
4097/// a cloud of points is drawn and the histogram `htemp` is not filled. For all the other
4098/// drawing options `htemp` will be filled.
4099///
4100/// In all cases `htemp` can be retrieved by calling:
4101///
4102/// ~~~ {.cpp}
4103/// auto htemp = (TH1F*)gPad->GetPrimitive("htemp"); // 1D
4104/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp"); // 2D
4105/// auto htemp = (TH3F*)gPad->GetPrimitive("htemp"); // 3D
4106/// ~~~
4107///
4108/// In the two dimensional case (`Draw("e1;e2")`), with the default drawing option, the
4109/// data is filled into a TGraph named `Graph`. This TGraph can be retrieved by
4110/// calling
4111///
4112/// ~~~ {.cpp}
4113/// auto graph = (TGraph*)gPad->GetPrimitive("Graph");
4114/// ~~~
4115///
4116/// For the three and four dimensional cases, with the default drawing option, an unnamed
4117/// TPolyMarker3D is produced, and therefore cannot be retrieved.
4118///
4119/// In all cases `htemp` can be used to access the axes. For instance in the 2D case:
4120///
4121/// ~~~ {.cpp}
4122/// auto htemp = (TH2F*)gPad->GetPrimitive("htemp");
4123/// auto xaxis = htemp->GetXaxis();
4124/// ~~~
4125///
4126/// When the option `"A"` is used (with TGraph painting option) to draw a 2D
4127/// distribution:
4128/// ~~~ {.cpp}
4129/// tree.Draw("e1:e2","","A*");
4130/// ~~~
4131/// a scatter plot is produced (with stars in that case) but the axis creation is
4132/// delegated to TGraph and `htemp` is not created.
4133///
4134/// ### Saving the result of Draw to a histogram
4135///
4136/// If `varexp` contains `>>hnew` (following the variable(s) name(s)),
4137/// the new histogram called `hnew` is created and it is kept in the current
4138/// directory (and also the current pad). This works for all dimensions.
4139///
4140/// Example:
4141/// ~~~ {.cpp}
4142/// tree.Draw("sqrt(x)>>hsqrt","y>0")
4143/// ~~~
4144/// will draw `sqrt(x)` and save the histogram as "hsqrt" in the current
4145/// directory. To retrieve it do:
4146/// ~~~ {.cpp}
4147/// TH1F *hsqrt = (TH1F*)gDirectory->Get("hsqrt");
4148/// ~~~
4149/// The binning information is taken from the environment variables
4150/// ~~~ {.cpp}
4151/// Hist.Binning.?D.?
4152/// ~~~
4153/// In addition, the name of the histogram can be followed by up to 9
4154/// numbers between '(' and ')', where the numbers describe the
4155/// following:
4156///
4157/// - 1 - bins in x-direction
4158/// - 2 - lower limit in x-direction
4159/// - 3 - upper limit in x-direction
4160/// - 4-6 same for y-direction
4161/// - 7-9 same for z-direction
4162///
4163/// When a new binning is used the new value will become the default.
4164/// Values can be skipped.
4165///
4166/// Example:
4167/// ~~~ {.cpp}
4168/// tree.Draw("sqrt(x)>>hsqrt(500,10,20)")
4169/// // plot sqrt(x) between 10 and 20 using 500 bins
4170/// tree.Draw("sqrt(x):sin(y)>>hsqrt(100,10,60,50,.1,.5)")
4171/// // plot sqrt(x) against sin(y)
4172/// // 100 bins in x-direction; lower limit on x-axis is 10; upper limit is 60
4173/// // 50 bins in y-direction; lower limit on y-axis is .1; upper limit is .5
4174/// ~~~
4175/// By default, the specified histogram is reset.
4176/// To continue to append data to an existing histogram, use "+" in front
4177/// of the histogram name.
4178///
4179/// A '+' in front of the histogram name is ignored, when the name is followed by
4180/// binning information as described in the previous paragraph.
4181/// ~~~ {.cpp}
4182/// tree.Draw("sqrt(x)>>+hsqrt","y>0")
4183/// ~~~
4184/// will not reset `hsqrt`, but will continue filling. This works for 1-D, 2-D
4185/// and 3-D histograms.
4186///
4187/// ### Accessing collection objects
4188///
4189/// TTree::Draw default's handling of collections is to assume that any
4190/// request on a collection pertain to it content. For example, if fTracks
4191/// is a collection of Track objects, the following:
4192/// ~~~ {.cpp}
4193/// tree->Draw("event.fTracks.fPx");
4194/// ~~~
4195/// will plot the value of fPx for each Track objects inside the collection.
4196/// Also
4197/// ~~~ {.cpp}
4198/// tree->Draw("event.fTracks.size()");
4199/// ~~~
4200/// would plot the result of the member function Track::size() for each
4201/// Track object inside the collection.
4202/// To access information about the collection itself, TTree::Draw support
4203/// the '@' notation. If a variable which points to a collection is prefixed
4204/// or postfixed with '@', the next part of the expression will pertain to
4205/// the collection object. For example:
4206/// ~~~ {.cpp}
4207/// tree->Draw("event.@fTracks.size()");
4208/// ~~~
4209/// will plot the size of the collection referred to by `fTracks` (i.e the number
4210/// of Track objects).
4211///
4212/// ### Drawing 'objects'
4213///
4214/// When a class has a member function named AsDouble or AsString, requesting
4215/// to directly draw the object will imply a call to one of the 2 functions.
4216/// If both AsDouble and AsString are present, AsDouble will be used.
4217/// AsString can return either a char*, a std::string or a TString.s
4218/// For example, the following
4219/// ~~~ {.cpp}
4220/// tree->Draw("event.myTTimeStamp");
4221/// ~~~
4222/// will draw the same histogram as
4223/// ~~~ {.cpp}
4224/// tree->Draw("event.myTTimeStamp.AsDouble()");
4225/// ~~~
4226/// In addition, when the object is a type TString or std::string, TTree::Draw
4227/// will call respectively `TString::Data` and `std::string::c_str()`
4228///
4229/// If the object is a TBits, the histogram will contain the index of the bit
4230/// that are turned on.
4231///
4232/// ### Retrieving information about the tree itself.
4233///
4234/// You can refer to the tree (or chain) containing the data by using the
4235/// string 'This'.
4236/// You can then could any TTree methods. For example:
4237/// ~~~ {.cpp}
4238/// tree->Draw("This->GetReadEntry()");
4239/// ~~~
4240/// will display the local entry numbers be read.
4241/// ~~~ {.cpp}
4242/// tree->Draw("This->GetUserInfo()->At(0)->GetName()");
4243/// ~~~
4244/// will display the name of the first 'user info' object.
4245///
4246/// ### Special functions and variables
4247///
4248/// `Entry$`: A TTree::Draw formula can use the special variable `Entry$`
4249/// to access the entry number being read. For example to draw every
4250/// other entry use:
4251/// ~~~ {.cpp}
4252/// tree.Draw("myvar","Entry$%2==0");
4253/// ~~~
4254/// - `Entry$` : return the current entry number (`== TTree::GetReadEntry()`)
4255/// - `LocalEntry$` : return the current entry number in the current tree of a
4256/// chain (`== GetTree()->GetReadEntry()`)
4257/// - `Entries$` : return the total number of entries (== TTree::GetEntries())
4258/// - `LocalEntries$` : return the total number of entries in the current tree
4259/// of a chain (== GetTree()->TTree::GetEntries())
4260/// - `Length$` : return the total number of element of this formula for this
4261/// entry (`==TTreeFormula::GetNdata()`)
4262/// - `Iteration$` : return the current iteration over this formula for this
4263/// entry (i.e. varies from 0 to `Length$ - 1`).
4264/// - `Length$(formula )` : return the total number of element of the formula
4265/// given as a parameter.
4266/// - `Sum$(formula )` : return the sum of the value of the elements of the
4267/// formula given as a parameter. For example the mean for all the elements in
4268/// one entry can be calculated with: `Sum$(formula )/Length$(formula )`
4269/// - `Min$(formula )` : return the minimum (within one TTree entry) of the value of the
4270/// elements of the formula given as a parameter.
4271/// - `Max$(formula )` : return the maximum (within one TTree entry) of the value of the
4272/// elements of the formula given as a parameter.
4273/// - `MinIf$(formula,condition)`
4274/// - `MaxIf$(formula,condition)` : return the minimum (maximum) (within one TTree entry)
4275/// of the value of the elements of the formula given as a parameter
4276/// if they match the condition. If no element matches the condition,
4277/// the result is zero. To avoid the resulting peak at zero, use the
4278/// pattern:
4279/// ~~~ {.cpp}
4280/// tree->Draw("MinIf$(formula,condition)","condition");
4281/// ~~~
4282/// which will avoid calculation `MinIf$` for the entries that have no match
4283/// for the condition.
4284/// - `Alt$(primary,alternate)` : return the value of "primary" if it is available
4285/// for the current iteration otherwise return the value of "alternate".
4286/// For example, with arr1[3] and arr2[2]
4287/// ~~~ {.cpp}
4288/// tree->Draw("arr1+Alt$(arr2,0)");
4289/// ~~~
4290/// will draw arr1[0]+arr2[0] ; arr1[1]+arr2[1] and arr1[2]+0
4291/// Or with a variable size array arr3
4292/// ~~~ {.cpp}
4293/// tree->Draw("Alt$(arr3[0],0)+Alt$(arr3[1],0)+Alt$(arr3[2],0)");
4294/// ~~~
4295/// will draw the sum arr3 for the index 0 to min(2,actual_size_of_arr3-1)
4296/// As a comparison
4297/// ~~~ {.cpp}
4298/// tree->Draw("arr3[0]+arr3[1]+arr3[2]");
4299/// ~~~
4300/// will draw the sum arr3 for the index 0 to 2 only if the
4301/// actual_size_of_arr3 is greater or equal to 3.
4302/// Note that the array in 'primary' is flattened/linearized thus using
4303/// `Alt$` with multi-dimensional arrays of different dimensions is unlikely
4304/// to yield the expected results. To visualize a bit more what elements
4305/// would be matched by TTree::Draw, TTree::Scan can be used:
4306/// ~~~ {.cpp}
4307/// tree->Scan("arr1:Alt$(arr2,0)");
4308/// ~~~
4309/// will print on one line the value of arr1 and (arr2,0) that will be
4310/// matched by
4311/// ~~~ {.cpp}
4312/// tree->Draw("arr1-Alt$(arr2,0)");
4313/// ~~~
4314/// The ternary operator is not directly supported in TTree::Draw however, to plot the
4315/// equivalent of `var2<20 ? -99 : var1`, you can use:
4316/// ~~~ {.cpp}
4317/// tree->Draw("(var2<20)*99+(var2>=20)*var1","");
4318/// ~~~
4319///
4320/// ### Drawing a user function accessing the TTree data directly
4321///
4322/// If the formula contains a file name, TTree::MakeProxy will be used
4323/// to load and execute this file. In particular it will draw the
4324/// result of a function with the same name as the file. The function
4325/// will be executed in a context where the name of the branches can
4326/// be used as a C++ variable.
4327///
4328/// For example draw px using the file hsimple.root (generated by the
4329/// hsimple.C tutorial), we need a file named hsimple.cxx:
4330/// ~~~ {.cpp}
4331/// double hsimple() {
4332/// return px;
4333/// }
4334/// ~~~
4335/// MakeProxy can then be used indirectly via the TTree::Draw interface
4336/// as follow:
4337/// ~~~ {.cpp}
4338/// new TFile("hsimple.root")
4339/// ntuple->Draw("hsimple.cxx");
4340/// ~~~
4341/// A more complete example is available in the tutorials directory:
4342/// `h1analysisProxy.cxx`, `h1analysProxy.h` and `h1analysisProxyCut.C`
4343/// which reimplement the selector found in `h1analysis.C`
4344///
4345/// The main features of this facility are:
4346///
4347/// * on-demand loading of branches
4348/// * ability to use the 'branchname' as if it was a data member
4349/// * protection against array out-of-bound
4350/// * ability to use the branch data as object (when the user code is available)
4351///
4352/// See TTree::MakeProxy for more details.
4353///
4354/// ### Making a Profile histogram
4355///
4356/// In case of a 2-Dim expression, one can generate a TProfile histogram
4357/// instead of a TH2F histogram by specifying option=prof or option=profs
4358/// or option=profi or option=profg ; the trailing letter select the way
4359/// the bin error are computed, See TProfile2D::SetErrorOption for
4360/// details on the differences.
4361/// The option=prof is automatically selected in case of y:x>>pf
4362/// where pf is an existing TProfile histogram.
4363///
4364/// ### Making a 2D Profile histogram
4365///
4366/// In case of a 3-Dim expression, one can generate a TProfile2D histogram
4367/// instead of a TH3F histogram by specifying option=prof or option=profs.
4368/// or option=profi or option=profg ; the trailing letter select the way
4369/// the bin error are computed, See TProfile2D::SetErrorOption for
4370/// details on the differences.
4371/// The option=prof is automatically selected in case of z:y:x>>pf
4372/// where pf is an existing TProfile2D histogram.
4373///
4374/// ### Making a 5D plot using GL
4375///
4376/// If option GL5D is specified together with 5 variables, a 5D plot is drawn
4377/// using OpenGL. See tree502_staff.C as example.
4378///
4379/// ### Making a parallel coordinates plot
4380///
4381/// In case of a 2-Dim or more expression with the option=para, one can generate
4382/// a parallel coordinates plot. With that option, the number of dimensions is
4383/// arbitrary. Giving more than 4 variables without the option=para or
4384/// option=candle or option=goff will produce an error.
4385///
4386/// ### Making a candle sticks chart
4387///
4388/// In case of a 2-Dim or more expression with the option=candle, one can generate
4389/// a candle sticks chart. With that option, the number of dimensions is
4390/// arbitrary. Giving more than 4 variables without the option=para or
4391/// option=candle or option=goff will produce an error.
4392///
4393/// ### Normalizing the output histogram to 1
4394///
4395/// When option contains "norm" the output histogram is normalized to 1.
4396///
4397/// ### Saving the result of Draw to a TEventList, a TEntryList or a TEntryListArray
4398///
4399/// TTree::Draw can be used to fill a TEventList object (list of entry numbers)
4400/// instead of histogramming one variable.
4401/// If varexp0 has the form >>elist , a TEventList object named "elist"
4402/// is created in the current directory. elist will contain the list
4403/// of entry numbers satisfying the current selection.
4404/// If option "entrylist" is used, a TEntryList object is created
4405/// If the selection contains arrays, vectors or any container class and option
4406/// "entrylistarray" is used, a TEntryListArray object is created
4407/// containing also the subentries satisfying the selection, i.e. the indices of
4408/// the branches which hold containers classes.
4409/// Example:
4410/// ~~~ {.cpp}
4411/// tree.Draw(">>yplus","y>0")
4412/// ~~~
4413/// will create a TEventList object named "yplus" in the current directory.
4414/// In an interactive session, one can type (after TTree::Draw)
4415/// ~~~ {.cpp}
4416/// yplus.Print("all")
4417/// ~~~
4418/// to print the list of entry numbers in the list.
4419/// ~~~ {.cpp}
4420/// tree.Draw(">>yplus", "y>0", "entrylist")
4421/// ~~~
4422/// will create a TEntryList object names "yplus" in the current directory
4423/// ~~~ {.cpp}
4424/// tree.Draw(">>yplus", "y>0", "entrylistarray")
4425/// ~~~
4426/// will create a TEntryListArray object names "yplus" in the current directory
4427///
4428/// By default, the specified entry list is reset.
4429/// To continue to append data to an existing list, use "+" in front
4430/// of the list name;
4431/// ~~~ {.cpp}
4432/// tree.Draw(">>+yplus","y>0")
4433/// ~~~
4434/// will not reset yplus, but will enter the selected entries at the end
4435/// of the existing list.
4436///
4437/// ### Using a TEventList, TEntryList or TEntryListArray as Input
4438///
4439/// Once a TEventList or a TEntryList object has been generated, it can be used as input
4440/// for TTree::Draw. Use TTree::SetEventList or TTree::SetEntryList to set the
4441/// current event list
4442///
4443/// Example 1:
4444/// ~~~ {.cpp}
4445/// TEventList *elist = (TEventList*)gDirectory->Get("yplus");
4446/// tree->SetEventList(elist);
4447/// tree->Draw("py");
4448/// ~~~
4449/// Example 2:
4450/// ~~~ {.cpp}
4451/// TEntryList *elist = (TEntryList*)gDirectory->Get("yplus");
4452/// tree->SetEntryList(elist);
4453/// tree->Draw("py");
4454/// ~~~
4455/// If a TEventList object is used as input, a new TEntryList object is created
4456/// inside the SetEventList function. In case of a TChain, all tree headers are loaded
4457/// for this transformation. This new object is owned by the chain and is deleted
4458/// with it, unless the user extracts it by calling GetEntryList() function.
4459/// See also comments to SetEventList() function of TTree and TChain.
4460///
4461/// If arrays are used in the selection criteria and TEntryListArray is not used,
4462/// all the entries that have at least one element of the array that satisfy the selection
4463/// are entered in the list.
4464///
4465/// Example:
4466/// ~~~ {.cpp}
4467/// tree.Draw(">>pyplus","fTracks.fPy>0");
4468/// tree->SetEventList(pyplus);
4469/// tree->Draw("fTracks.fPy");
4470/// ~~~
4471/// will draw the fPy of ALL tracks in event with at least one track with
4472/// a positive fPy.
4473///
4474/// To select only the elements that did match the original selection
4475/// use TEventList::SetReapplyCut or TEntryList::SetReapplyCut.
4476///
4477/// Example:
4478/// ~~~ {.cpp}
4479/// tree.Draw(">>pyplus","fTracks.fPy>0");
4480/// pyplus->SetReapplyCut(true);
4481/// tree->SetEventList(pyplus);
4482/// tree->Draw("fTracks.fPy");
4483/// ~~~
4484/// will draw the fPy of only the tracks that have a positive fPy.
4485///
4486/// To draw only the elements that match a selection in case of arrays,
4487/// you can also use TEntryListArray (faster in case of a more general selection).
4488///
4489/// Example:
4490/// ~~~ {.cpp}
4491/// tree.Draw(">>pyplus","fTracks.fPy>0", "entrylistarray");
4492/// tree->SetEntryList(pyplus);
4493/// tree->Draw("fTracks.fPy");
4494/// ~~~
4495/// will draw the fPy of only the tracks that have a positive fPy,
4496/// but without redoing the selection.
4497///
4498/// Note: Use tree->SetEventList(0) if you do not want use the list as input.
4499///
4500/// ### How to obtain more info from TTree::Draw
4501///
4502/// Once TTree::Draw has been called, it is possible to access useful
4503/// information still stored in the TTree object via the following functions:
4504///
4505/// - GetSelectedRows() // return the number of values accepted by the selection expression. In case where no selection was specified, returns the number of values processed.
4506/// - GetV1() // returns a pointer to the double array of V1
4507/// - GetV2() // returns a pointer to the double array of V2
4508/// - GetV3() // returns a pointer to the double array of V3
4509/// - GetV4() // returns a pointer to the double array of V4
4510/// - GetW() // returns a pointer to the double array of Weights where weight equal the result of the selection expression.
4511///
4512/// where V1,V2,V3 correspond to the expressions in
4513/// ~~~ {.cpp}
4514/// TTree::Draw("V1:V2:V3:V4",selection);
4515/// ~~~
4516/// If the expression has more than 4 component use GetVal(index)
4517///
4518/// Example:
4519/// ~~~ {.cpp}
4520/// Root > ntuple->Draw("py:px","pz>4");
4521/// Root > TGraph *gr = new TGraph(ntuple->GetSelectedRows(),
4522/// ntuple->GetV2(), ntuple->GetV1());
4523/// Root > gr->Draw("ap"); //draw graph in current pad
4524/// ~~~
4525///
4526/// A more complete complete tutorial (treegetval.C) shows how to use the
4527/// GetVal() method.
4528///
4529/// creates a TGraph object with a number of points corresponding to the
4530/// number of entries selected by the expression "pz>4", the x points of the graph
4531/// being the px values of the Tree and the y points the py values.
4532///
4533/// Important note: By default TTree::Draw creates the arrays obtained
4534/// with GetW, GetV1, GetV2, GetV3, GetV4, GetVal with a length corresponding
4535/// to the parameter fEstimate. The content will be the last `GetSelectedRows() % GetEstimate()`
4536/// values calculated.
4537/// By default fEstimate=1000000 and can be modified
4538/// via TTree::SetEstimate. To keep in memory all the results (in case
4539/// where there is only one result per entry), use
4540/// ~~~ {.cpp}
4541/// tree->SetEstimate(tree->GetEntries()+1); // same as tree->SetEstimate(-1);
4542/// ~~~
4543/// You must call SetEstimate if the expected number of selected rows
4544/// you need to look at is greater than 1000000.
4545///
4546/// You can use the option "goff" to turn off the graphics output
4547/// of TTree::Draw in the above example.
4548///
4549/// ### Automatic interface to TTree::Draw via the TTreeViewer
4550///
4551/// A complete graphical interface to this function is implemented
4552/// in the class TTreeViewer.
4553/// To start the TTreeViewer, three possibilities:
4554/// - select TTree context menu item "StartViewer"
4555/// - type the command "TTreeViewer TV(treeName)"
4556/// - execute statement "tree->StartViewer();"
4559{
4560 GetPlayer();
4561 if (fPlayer)
4563 return -1;
4564}
4565
4566////////////////////////////////////////////////////////////////////////////////
4567/// Remove some baskets from memory.
4569void TTree::DropBaskets()
4570{
4571 TBranch* branch = nullptr;
4573 for (Int_t i = 0; i < nb; ++i) {
4575 branch->DropBaskets("all");
4576 }
4577}
4578
4579////////////////////////////////////////////////////////////////////////////////
4580/// Drop branch buffers to accommodate nbytes below MaxVirtualsize.
4583{
4584 // Be careful not to remove current read/write buffers.
4586 for (Int_t i = 0; i < nleaves; ++i) {
4588 TBranch* branch = (TBranch*) leaf->GetBranch();
4589 Int_t nbaskets = branch->GetListOfBaskets()->GetEntries();
4590 for (Int_t j = 0; j < nbaskets - 1; ++j) {
4591 if ((j == branch->GetReadBasket()) || (j == branch->GetWriteBasket())) {
4592 continue;
4593 }
4594 TBasket* basket = (TBasket*)branch->GetListOfBaskets()->UncheckedAt(j);
4595 if (basket) {
4596 basket->DropBuffers();
4598 return;
4599 }
4600 }
4601 }
4602 }
4603}
4604
4605////////////////////////////////////////////////////////////////////////////////
4606/// Fill all branches.
4607///
4608/// This function loops on all the branches of this tree. For
4609/// each branch, it copies to the branch buffer (basket) the current
4610/// values of the leaves data types. If a leaf is a simple data type,
4611/// a simple conversion to a machine independent format has to be done.
4612///
4613/// This machine independent version of the data is copied into a
4614/// basket (each branch has its own basket). When a basket is full
4615/// (32k worth of data by default), it is then optionally compressed
4616/// and written to disk (this operation is also called committing or
4617/// 'flushing' the basket). The committed baskets are then
4618/// immediately removed from memory.
4619///
4620/// The function returns the number of bytes committed to the
4621/// individual branches.
4622///
4623/// If a write error occurs, the number of bytes returned is -1.
4624///
4625/// If no data are written, because, e.g., the branch is disabled,
4626/// the number of bytes returned is 0.
4627///
4628/// __The baskets are flushed and the Tree header saved at regular intervals__
4629///
4630/// At regular intervals, when the amount of data written so far is
4631/// greater than fAutoFlush (see SetAutoFlush) all the baskets are flushed to disk.
4632/// This makes future reading faster as it guarantees that baskets belonging to nearby
4633/// entries will be on the same disk region.
4634/// When the first call to flush the baskets happen, we also take this opportunity
4635/// to optimize the baskets buffers.
4636/// We also check if the amount of data written is greater than fAutoSave (see SetAutoSave).
4637/// In this case we also write the Tree header. This makes the Tree recoverable up to this point
4638/// in case the program writing the Tree crashes.
4639/// The decisions to FlushBaskets and Auto Save can be made based either on the number
4640/// of bytes written (fAutoFlush and fAutoSave negative) or on the number of entries
4641/// written (fAutoFlush and fAutoSave positive).
4642/// Note that the user can decide to call FlushBaskets and AutoSave in her event loop
4643/// base on the number of events written instead of the number of bytes written.
4644///
4645/// \note Calling `TTree::FlushBaskets` too often increases the IO time.
4646///
4647/// \note Calling `TTree::AutoSave` too often increases the IO time and also the
4648/// file size.
4649///
4650/// \note This method calls `TTree::ChangeFile` when the tree reaches a size
4651/// greater than `TTree::fgMaxTreeSize`. This doesn't happen if the tree is
4652/// attached to a `TMemFile` or derivate.
4655{
4656 Int_t nbytes = 0;
4657 Int_t nwrite = 0;
4658 Int_t nerror = 0;
4660
4661 // Case of one single super branch. Automatically update
4662 // all the branch addresses if a new object was created.
4663 if (nbranches == 1)
4664 ((TBranch *)fBranches.UncheckedAt(0))->UpdateAddress();
4665
4666 if (fBranchRef)
4667 fBranchRef->Clear();
4668
4669#ifdef R__USE_IMT
4672 if (useIMT) {
4673 fIMTFlush = true;
4674 fIMTZipBytes.store(0);
4675 fIMTTotBytes.store(0);
4676 }
4677#endif
4678
4679 for (Int_t i = 0; i < nbranches; ++i) {
4680 // Loop over all branches, filling and accumulating bytes written and error counts.
4682
4683 if (branch->TestBit(kDoNotProcess))
4684 continue;
4685
4686#ifndef R__USE_IMT
4687 nwrite = branch->FillImpl(nullptr);
4688#else
4689 nwrite = branch->FillImpl(useIMT ? &imtHelper : nullptr);
4690#endif
4691 if (nwrite < 0) {
4692 if (nerror < 2) {
4693 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld\n"
4694 " This error is symptomatic of a Tree created as a memory-resident Tree\n"
4695 " Instead of doing:\n"
4696 " TTree *T = new TTree(...)\n"
4697 " TFile *f = new TFile(...)\n"
4698 " you should do:\n"
4699 " TFile *f = new TFile(...)\n"
4700 " TTree *T = new TTree(...)\n\n",
4701 GetName(), branch->GetName(), nwrite, fEntries + 1);
4702 } else {
4703 Error("Fill", "Failed filling branch:%s.%s, nbytes=%d, entry=%lld", GetName(), branch->GetName(), nwrite,
4704 fEntries + 1);
4705 }
4706 ++nerror;
4707 } else {
4708 nbytes += nwrite;
4709 }
4710 }
4711
4712#ifdef R__USE_IMT
4713 if (fIMTFlush) {
4714 imtHelper.Wait();
4715 fIMTFlush = false;
4716 const_cast<TTree *>(this)->AddTotBytes(fIMTTotBytes);
4717 const_cast<TTree *>(this)->AddZipBytes(fIMTZipBytes);
4718 nbytes += imtHelper.GetNbytes();
4719 nerror += imtHelper.GetNerrors();
4720 }
4721#endif
4722
4723 if (fBranchRef)
4724 fBranchRef->Fill();
4725
4726 ++fEntries;
4727
4728 if (fEntries > fMaxEntries)
4729 KeepCircular();
4730
4731 if (gDebug > 0)
4732 Info("TTree::Fill", " - A: %d %lld %lld %lld %lld %lld %lld \n", nbytes, fEntries, fAutoFlush, fAutoSave,
4734
4735 bool autoFlush = false;
4736 bool autoSave = false;
4737
4738 if (fAutoFlush != 0 || fAutoSave != 0) {
4739 // Is it time to flush or autosave baskets?
4740 if (fFlushedBytes == 0) {
4741 // If fFlushedBytes == 0, it means we never flushed or saved, so
4742 // we need to check if it's time to do it and recompute the values
4743 // of fAutoFlush and fAutoSave in terms of the number of entries.
4744 // Decision can be based initially either on the number of bytes
4745 // or the number of entries written.
4747
4748 if (fAutoFlush)
4750
4751 if (fAutoSave)
4752 autoSave = fAutoSave < 0 ? (zipBytes > -fAutoSave) : fEntries % fAutoSave == 0;
4753
4754 if (autoFlush || autoSave) {
4755 // First call FlushBasket to make sure that fTotBytes is up to date.
4757 autoFlush = false; // avoid auto flushing again later
4758
4759 // When we are in one-basket-per-cluster mode, there is no need to optimize basket:
4760 // they will automatically grow to the size needed for an event cluster (with the basket
4761 // shrinking preventing them from growing too much larger than the actually-used space).
4763 OptimizeBaskets(GetTotBytes(), 1, "");
4764 if (gDebug > 0)
4765 Info("TTree::Fill", "OptimizeBaskets called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n",
4767 }
4769 fAutoFlush = fEntries; // Use test on entries rather than bytes
4770
4771 // subsequently in run
4772 if (fAutoSave < 0) {
4773 // Set fAutoSave to the largest integer multiple of
4774 // fAutoFlush events such that fAutoSave*fFlushedBytes
4775 // < (minus the input value of fAutoSave)
4777 if (zipBytes != 0) {
4779 } else if (totBytes != 0) {
4781 } else {
4783 TTree::Class()->WriteBuffer(b, (TTree *)this);
4784 Long64_t total = b.Length();
4786 }
4787 } else if (fAutoSave > 0) {
4789 }
4790
4791 if (fAutoSave != 0 && fEntries >= fAutoSave)
4792 autoSave = true;
4793
4794 if (gDebug > 0)
4795 Info("TTree::Fill", "First AutoFlush. fAutoFlush = %lld, fAutoSave = %lld\n", fAutoFlush, fAutoSave);
4796 }
4797 } else {
4798 // Check if we need to auto flush
4799 if (fAutoFlush) {
4800 if (fNClusterRange == 0)
4801 autoFlush = fEntries > 1 && fEntries % fAutoFlush == 0;
4802 else
4804 }
4805 // Check if we need to auto save
4806 if (fAutoSave)
4807 autoSave = fEntries % fAutoSave == 0;
4808 }
4809 }
4810
4811 if (autoFlush) {
4813 if (gDebug > 0)
4814 Info("TTree::Fill", "FlushBaskets() called at entry %lld, fZipBytes=%lld, fFlushedBytes=%lld\n", fEntries,
4817 }
4818
4819 if (autoSave) {
4820 AutoSave(); // does not call FlushBasketsImpl() again
4821 if (gDebug > 0)
4822 Info("TTree::Fill", "AutoSave called at entry %lld, fZipBytes=%lld, fSavedBytes=%lld\n", fEntries,
4824 }
4825
4826 // Check that output file is still below the maximum size.
4827 // If above, close the current file and continue on a new file.
4828 // Currently, the automatic change of file is restricted
4829 // to the case where the tree is in the top level directory.
4830 if (fDirectory)
4831 if (TFile *file = fDirectory->GetFile())
4832 if (static_cast<TDirectory *>(file) == fDirectory && (file->GetEND() > fgMaxTreeSize))
4833 ChangeFile(file);
4834
4835 return nerror == 0 ? nbytes : -1;
4836}
4837
4838////////////////////////////////////////////////////////////////////////////////
4839/// Search in the array for a branch matching the branch name,
4840/// with the branch possibly expressed as a 'full' path name (with dots).
4842static TBranch *R__FindBranchHelper(TObjArray *list, const char *branchname) {
4843 if (list==nullptr || branchname == nullptr || branchname[0] == '\0') return nullptr;
4844
4845 Int_t nbranches = list->GetEntries();
4846
4848
4849 for(Int_t index = 0; index < nbranches; ++index) {
4850 TBranch *where = (TBranch*)list->UncheckedAt(index);
4851
4852 const char *name = where->GetName();
4853 UInt_t len = strlen(name);
4854 if (len && name[len - 1] == ']' && (brlen == 0 || branchname[brlen - 1] != ']')) {
4855 const char *dim = strchr(name,'[');
4856 if (dim) {
4857 len = dim - name;
4858 }
4859 }
4860 if (brlen == len && strncmp(branchname,name,len)==0) {
4861 return where;
4862 }
4863 TBranch *next = nullptr;
4864 if ((brlen >= len) && (branchname[len] == '.')
4865 && strncmp(name, branchname, len) == 0) {
4866 // The prefix subbranch name match the branch name.
4867
4868 next = where->FindBranch(branchname);
4869 if (!next) {
4870 next = where->FindBranch(branchname+len+1);
4871 }
4872 if (next) return next;
4873 }
4874 const char *dot = strchr((char*)branchname,'.');
4875 if (dot) {
4876 if (len==(size_t)(dot-branchname) &&
4877 strncmp(branchname,name,dot-branchname)==0 ) {
4878 return R__FindBranchHelper(where->GetListOfBranches(),dot+1);
4879 }
4880 }
4881 }
4882 return nullptr;
4883}
4885TBranch *TTree::FindBranchFromSelf(const char *branchName)
4886{
4887 // If the first part of the name match the TTree name, look for the right part in the
4888 // list of branches. This will allow the branchName to be preceded by the name of this tree.
4889 if (strncmp(fName.Data(), branchName, fName.Length()) == 0 && branchName[fName.Length()] == '.')
4890 if (auto *br = R__FindBranchHelper(GetListOfBranches(), branchName + fName.Length() + 1))
4891 return br;
4892
4893 // If we did not find it, let's try to find the full name in the list of branches.
4894 if (auto *br = R__FindBranchHelper(GetListOfBranches(), branchName))
4895 return br;
4896
4897 // If we still did not find, let's try to find it within each branch assuming it does not contain the branch name.
4899 if (auto *nestedbranch = branch->FindBranch(branchName))
4900 return nestedbranch;
4901
4902 return nullptr;
4903}
4905TBranch *TTree::FindBranchFromFriends(const char *branchName)
4906{
4907 if (!fFriends) {
4908 return nullptr;
4909 }
4910
4911 TFriendLock lock(this, kFindBranch);
4913 TTree *t = frEl->GetTree();
4914 if (!t) {
4915 continue;
4916 }
4917 // If the alias is present replace it with the real name.
4918 const char *subbranch = strstr(branchName, frEl->GetName());
4919 if (subbranch != branchName) {
4920 subbranch = nullptr;
4921 }
4922 if (subbranch) {
4923 subbranch += strlen(frEl->GetName());
4924 if (*subbranch != '.') {
4925 subbranch = nullptr;
4926 } else {
4927 ++subbranch;
4928 }
4929 }
4930 std::ostringstream name;
4931 if (subbranch) {
4932 name << t->GetName() << "." << subbranch;
4933 } else {
4934 name << branchName;
4935 }
4936 if (auto *br = t->FindBranch(name.str().c_str()))
4937 return br;
4938 }
4939
4940 return nullptr;
4941}
4942
4943////////////////////////////////////////////////////////////////////////////////
4944/// Return the branch that correspond to the path 'branchname', which can
4945/// include the name of the tree or the omitted name of the parent branches.
4946/// In case of ambiguity, returns the first match.
4947/// \sa TTree::GetBranch
4950{
4951 // We already have been visited while recursively looking
4952 // through the friends tree, let return
4954 return nullptr;
4955 }
4956
4957 if (!branchname)
4958 return nullptr;
4959
4960 if (auto *br = FindBranchFromSelf(branchname))
4961 return br;
4962
4963 if (auto *br = FindBranchFromFriends(branchname))
4964 return br;
4965
4966 return nullptr;
4967}
4968
4969////////////////////////////////////////////////////////////////////////////////
4970/// Find first leaf containing searchname.
4972TLeaf* TTree::FindLeaf(const char* searchname)
4973{
4974 if (!searchname)
4975 return nullptr;
4976
4977 // We already have been visited while recursively looking
4978 // through the friends tree, let's return.
4980 return nullptr;
4981 }
4982
4983 // This will allow the branchname to be preceded by
4984 // the name of this tree.
4985 const char* subsearchname = strstr(searchname, GetName());
4986 if (subsearchname != searchname) {
4987 subsearchname = nullptr;
4988 }
4989 if (subsearchname) {
4991 if (*subsearchname != '.') {
4992 subsearchname = nullptr;
4993 } else {
4994 ++subsearchname;
4995 if (subsearchname[0] == 0) {
4996 subsearchname = nullptr;
4997 }
4998 }
4999 }
5000
5005
5006 const bool searchnameHasDot = strchr(searchname, '.') != nullptr;
5007
5008 // For leaves we allow for one level up to be prefixed to the name.
5009 TIter next(GetListOfLeaves());
5010 TLeaf* leaf = nullptr;
5011 while ((leaf = (TLeaf*) next())) {
5012 leafname = leaf->GetName();
5013 Ssiz_t dim = leafname.First('[');
5014 if (dim >= 0) leafname.Remove(dim);
5015
5016 if (leafname == searchname) {
5017 return leaf;
5018 }
5020 return leaf;
5021 }
5022 // The TLeafElement contains the branch name
5023 // in its name, let's use the title.
5024 leaftitle = leaf->GetTitle();
5025 dim = leaftitle.First('[');
5026 if (dim >= 0) leaftitle.Remove(dim);
5027
5028 if (leaftitle == searchname) {
5029 return leaf;
5030 }
5032 return leaf;
5033 }
5034 if (!searchnameHasDot)
5035 continue;
5036 TBranch* branch = leaf->GetBranch();
5037 if (branch) {
5038 longname.Form("%s.%s",branch->GetName(),leafname.Data());
5039 dim = longname.First('[');
5040 if (dim>=0) longname.Remove(dim);
5041 if (longname == searchname) {
5042 return leaf;
5043 }
5045 return leaf;
5046 }
5047 longtitle.Form("%s.%s",branch->GetName(),leaftitle.Data());
5048 dim = longtitle.First('[');
5049 if (dim>=0) longtitle.Remove(dim);
5050 if (longtitle == searchname) {
5051 return leaf;
5052 }
5054 return leaf;
5055 }
5056 // The following is for the case where the branch is only
5057 // a sub-branch. Since we do not see it through
5058 // TTree::GetListOfBranches, we need to see it indirectly.
5059 // This is the less sturdy part of this search ... it may
5060 // need refining ...
5061 if (strstr(searchname, ".") && !strcmp(searchname, branch->GetName())) {
5062 return leaf;
5063 }
5064 if (subsearchname && strstr(subsearchname, ".") && !strcmp(subsearchname, branch->GetName())) {
5065 return leaf;
5066 }
5067 }
5068 }
5069 // Search in list of friends.
5070 if (!fFriends) {
5071 return nullptr;
5072 }
5073 TFriendLock lock(this, kFindLeaf);
5075 TFriendElement* fe = nullptr;
5076 while ((fe = (TFriendElement*) nextf())) {
5077 TTree* t = fe->GetTree();
5078 if (!t) {
5079 continue;
5080 }
5081 // If the alias is present replace it with the real name.
5082 subsearchname = strstr(searchname, fe->GetName());
5083 if (subsearchname != searchname) {
5084 subsearchname = nullptr;
5085 }
5086 if (subsearchname) {
5087 subsearchname += strlen(fe->GetName());
5088 if (*subsearchname != '.') {
5089 subsearchname = nullptr;
5090 } else {
5091 ++subsearchname;
5092 }
5093 }
5094 if (subsearchname) {
5095 leafname.Form("%s.%s",t->GetName(),subsearchname);
5096 } else {
5098 }
5099 leaf = t->FindLeaf(leafname);
5100 if (leaf) {
5101 return leaf;
5102 }
5103 }
5104 return nullptr;
5105}
5106
5107////////////////////////////////////////////////////////////////////////////////
5108/// Fit a projected item(s) from a tree.
5109///
5110/// funcname is a TF1 function.
5111///
5112/// See TTree::Draw() for explanations of the other parameters.
5113///
5114/// By default the temporary histogram created is called htemp.
5115/// If varexp contains >>hnew , the new histogram created is called hnew
5116/// and it is kept in the current directory.
5117///
5118/// The function returns the number of selected entries.
5119///
5120/// Example:
5121/// ~~~ {.cpp}
5122/// tree.Fit(pol4,"sqrt(x)>>hsqrt","y>0")
5123/// ~~~
5124/// will fit sqrt(x) and save the histogram as "hsqrt" in the current
5125/// directory.
5126///
5127/// See also TTree::UnbinnedFit
5128///
5129/// ## Return status
5130///
5131/// The function returns the status of the histogram fit (see TH1::Fit)
5132/// If no entries were selected, the function returns -1;
5133/// (i.e. fitResult is null if the fit is OK)
5136{
5137 GetPlayer();
5138 if (fPlayer) {
5140 }
5141 return -1;
5142}
5143
5144namespace {
5145struct BoolRAIIToggle {
5146 bool &m_val;
5147
5148 BoolRAIIToggle(bool &val) : m_val(val) { m_val = true; }
5149 ~BoolRAIIToggle() { m_val = false; }
5150};
5151}
5152
5153////////////////////////////////////////////////////////////////////////////////
5154/// Write to disk all the basket that have not yet been individually written and
5155/// create an event cluster boundary (by default).
5156///
5157/// If the caller wishes to flush the baskets but not create an event cluster,
5158/// then set create_cluster to false.
5159///
5160/// If ROOT has IMT-mode enabled, this will launch multiple TBB tasks in parallel
5161/// via TThreadExecutor to do this operation; one per basket compression. If the
5162/// caller utilizes TBB also, care must be taken to prevent deadlocks.
5163///
5164/// For example, let's say the caller holds mutex A and calls FlushBaskets; while
5165/// TBB is waiting for the ROOT compression tasks to complete, it may decide to
5166/// run another one of the user's tasks in this thread. If the second user task
5167/// tries to acquire A, then a deadlock will occur. The example call sequence
5168/// looks like this:
5169///
5170/// - User acquires mutex A
5171/// - User calls FlushBaskets.
5172/// - ROOT launches N tasks and calls wait.
5173/// - TBB schedules another user task, T2.
5174/// - T2 tries to acquire mutex A.
5175///
5176/// At this point, the thread will deadlock: the code may function with IMT-mode
5177/// disabled if the user assumed the legacy code never would run their own TBB
5178/// tasks.
5179///
5180/// SO: users of TBB who want to enable IMT-mode should carefully review their
5181/// locking patterns and make sure they hold no coarse-grained application
5182/// locks when they invoke ROOT.
5183///
5184/// Return the number of bytes written or -1 in case of write error.
5186{
5188 if (retval == -1) return retval;
5189
5190 if (create_cluster) const_cast<TTree *>(this)->MarkEventCluster();
5191 return retval;
5192}
5193
5194////////////////////////////////////////////////////////////////////////////////
5195/// Internal implementation of the FlushBaskets algorithm.
5196/// Unlike the public interface, this does NOT create an explicit event cluster
5197/// boundary; it is up to the (internal) caller to determine whether that should
5198/// done.
5199///
5200/// Otherwise, the comments for FlushBaskets applies.
5203{
5204 if (!fDirectory) return 0;
5205 Int_t nbytes = 0;
5206 Int_t nerror = 0;
5207 TObjArray *lb = const_cast<TTree*>(this)->GetListOfBranches();
5208 Int_t nb = lb->GetEntriesFast();
5209
5210#ifdef R__USE_IMT
5212 if (useIMT) {
5213 // ROOT-9668: here we need to check if the size of fSortedBranches is different from the
5214 // size of the list of branches before triggering the initialisation of the fSortedBranches
5215 // container to cover two cases:
5216 // 1. This is the first time we flush. fSortedBranches is empty and we need to fill it.
5217 // 2. We flushed at least once already but a branch has been be added to the tree since then
5218 if (fSortedBranches.size() != unsigned(nb)) { const_cast<TTree*>(this)->InitializeBranchLists(false); }
5219
5220 BoolRAIIToggle sentry(fIMTFlush);
5221 fIMTZipBytes.store(0);
5222 fIMTTotBytes.store(0);
5223 std::atomic<Int_t> nerrpar(0);
5224 std::atomic<Int_t> nbpar(0);
5225 std::atomic<Int_t> pos(0);
5226
5227 auto mapFunction = [&]() {
5228 // The branch to process is obtained when the task starts to run.
5229 // This way, since branches are sorted, we make sure that branches
5230 // leading to big tasks are processed first. If we assigned the
5231 // branch at task creation time, the scheduler would not necessarily
5232 // respect our sorting.
5233 Int_t j = pos.fetch_add(1);
5234
5235 auto branch = fSortedBranches[j].second;
5236 if (R__unlikely(!branch)) { return; }
5237
5238 if (R__unlikely(gDebug > 0)) {
5239 std::stringstream ss;
5240 ss << std::this_thread::get_id();
5241 Info("FlushBaskets", "[IMT] Thread %s", ss.str().c_str());
5242 Info("FlushBaskets", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5243 }
5244
5245 Int_t nbtask = branch->FlushBaskets();
5246
5247 if (nbtask < 0) { nerrpar++; }
5248 else { nbpar += nbtask; }
5249 };
5250
5252 pool.Foreach(mapFunction, nb);
5253
5254 fIMTFlush = false;
5255 const_cast<TTree*>(this)->AddTotBytes(fIMTTotBytes);
5256 const_cast<TTree*>(this)->AddZipBytes(fIMTZipBytes);
5257
5258 return nerrpar ? -1 : nbpar.load();
5259 }
5260#endif
5261 for (Int_t j = 0; j < nb; j++) {
5262 TBranch* branch = (TBranch*) lb->UncheckedAt(j);
5263 if (branch) {
5264 Int_t nwrite = branch->FlushBaskets();
5265 if (nwrite<0) {
5266 ++nerror;
5267 } else {
5268 nbytes += nwrite;
5269 }
5270 }
5271 }
5272 if (nerror) {
5273 return -1;
5274 } else {
5275 return nbytes;
5276 }
5277}
5278
5279////////////////////////////////////////////////////////////////////////////////
5280/// Returns the expanded value of the alias. Search in the friends if any.
5282const char* TTree::GetAlias(const char* aliasName) const
5283{
5284 // We already have been visited while recursively looking
5285 // through the friends tree, let's return.
5287 return nullptr;
5288 }
5289 if (fAliases) {
5291 if (alias) {
5292 return alias->GetTitle();
5293 }
5294 }
5295 if (!fFriends) {
5296 return nullptr;
5297 }
5298 TFriendLock lock(const_cast<TTree*>(this), kGetAlias);
5300 TFriendElement* fe = nullptr;
5301 while ((fe = (TFriendElement*) nextf())) {
5302 TTree* t = fe->GetTree();
5303 if (t) {
5304 const char* alias = t->GetAlias(aliasName);
5305 if (alias) {
5306 return alias;
5307 }
5308 const char* subAliasName = strstr(aliasName, fe->GetName());
5309 if (subAliasName && (subAliasName[strlen(fe->GetName())] == '.')) {
5310 alias = t->GetAlias(aliasName + strlen(fe->GetName()) + 1);
5311 if (alias) {
5312 return alias;
5313 }
5314 }
5315 }
5316 }
5317 return nullptr;
5318}
5319
5320namespace {
5321/// Do a breadth first search through the implied hierarchy
5322/// of branches.
5323/// To avoid scanning through the list multiple time
5324/// we also remember the 'depth-first' match.
5325TBranch *R__GetBranch(const TObjArray &branches, const char *name)
5326{
5327 TBranch *result = nullptr;
5328 Int_t nb = branches.GetEntriesFast();
5329 for (Int_t i = 0; i < nb; i++) {
5330 TBranch* b = (TBranch*)branches.UncheckedAt(i);
5331 if (!b)
5332 continue;
5333 if (!strcmp(b->GetName(), name)) {
5334 return b;
5335 }
5336 if (!strcmp(b->GetFullName(), name)) {
5337 return b;
5338 }
5339 if (!result)
5340 result = R__GetBranch(*(b->GetListOfBranches()), name);
5341 }
5342 return result;
5343}
5344}
5345
5346////////////////////////////////////////////////////////////////////////////////
5347/// Returns a pointer to the branch with the given name, if it can be found in
5348/// this tree. Otherwise, returns nullptr.
5349TBranch *TTree::GetBranchFromSelf(const char *branchName)
5350{
5351 // Look for an exact match in the list of top level
5352 // branches.
5353 if (auto *br = static_cast<TBranch *>(fBranches.FindObject(branchName)))
5354 return br;
5355
5356 // Look for an exact match in the mapping from branch name to TBranch *
5357 // gathered when first reading the TTree from disk.
5358 if (auto it = fNamesToBranches.find(branchName); it != fNamesToBranches.end())
5359 return it->second;
5360
5361 // Search using branches, breadth first.
5362 if (auto *br = R__GetBranch(fBranches, branchName))
5363 return br;
5364
5365 // Search using leaves.
5367 Int_t nleaves = leaves->GetEntriesFast();
5368 for (Int_t i = 0; i < nleaves; i++) {
5369 TLeaf *leaf = (TLeaf *)leaves->UncheckedAt(i);
5370 TBranch *branch = leaf->GetBranch();
5371 if (!strcmp(branch->GetName(), branchName)) {
5372 return branch;
5373 }
5374 if (!strcmp(branch->GetFullName(), branchName)) {
5375 return branch;
5376 }
5377 }
5378
5379 return nullptr;
5380}
5381
5382////////////////////////////////////////////////////////////////////////////////
5383/// Returns a pointer to the branch with the given name, if it can be found in
5384/// the list of friends of this tree. Otherwise, returns nullptr.
5385TBranch *TTree::GetBranchFromFriends(const char *branchName)
5386{
5387 if (!fFriends) {
5388 return nullptr;
5389 }
5390
5391 // Search in list of friends.
5392 TFriendLock lock(this, kGetBranch);
5393 TIter next(fFriends);
5394 TFriendElement *fe = nullptr;
5395 while ((fe = (TFriendElement *)next())) {
5396 TTree *t = fe->GetTree();
5397 if (t) {
5398 TBranch *branch = t->GetBranch(branchName);
5399 if (branch) {
5400 return branch;
5401 }
5402 }
5403 }
5404
5405 // Second pass in the list of friends when
5406 // the branch name is prefixed by the tree name.
5407 next.Reset();
5408 while ((fe = (TFriendElement *)next())) {
5409 TTree *t = fe->GetTree();
5410 if (!t) {
5411 continue;
5412 }
5413 const char *subname = strstr(branchName, fe->GetName());
5414 if (subname != branchName) {
5415 continue;
5416 }
5417 Int_t l = strlen(fe->GetName());
5418 subname += l;
5419 if (*subname != '.') {
5420 continue;
5421 }
5422 subname++;
5424 if (branch) {
5425 return branch;
5426 }
5427 }
5428
5429 return nullptr;
5430}
5431
5432////////////////////////////////////////////////////////////////////////////////
5433/// Return pointer to the branch with the given name in this tree or its friends.
5434/// The search is done breadth first.
5435/// \sa TTree::FindBranch
5437TBranch *TTree::GetBranch(const char *name)
5438{
5439 // We already have been visited while recursively
5440 // looking through the friends tree, let's return.
5442 return nullptr;
5443 }
5444
5445 if (!name)
5446 return nullptr;
5447
5448 if (auto *br = GetBranchFromSelf(name))
5449 return br;
5450
5451 if (auto *br = GetBranchFromFriends(name))
5452 return br;
5453
5454 return nullptr;
5455}
5456
5457////////////////////////////////////////////////////////////////////////////////
5458/// Return status of branch with name branchname.
5459///
5460/// - 0 if branch is not activated
5461/// - 1 if branch is activated
5463bool TTree::GetBranchStatus(const char* branchname) const
5464{
5465 TBranch* br = const_cast<TTree*>(this)->GetBranch(branchname);
5466 if (br) {
5467 return br->TestBit(kDoNotProcess) == 0;
5468 }
5469 return false;
5470}
5471
5472////////////////////////////////////////////////////////////////////////////////
5473/// Static function returning the current branch style.
5474///
5475/// - style = 0 old Branch
5476/// - style = 1 new Bronch
5481}
5482
5483////////////////////////////////////////////////////////////////////////////////
5484/// Used for automatic sizing of the cache.
5485///
5486/// Estimates a suitable size in bytes for the tree cache based on AutoFlush.
5487/// A cache sizing factor is taken from the configuration. If this yields zero
5488/// and withDefault is true the historical algorithm for default size is used.
5490Long64_t TTree::GetCacheAutoSize(bool withDefault /* = false */ )
5491{
5493 {
5494 Long64_t cacheSize = 0;
5495 if (fAutoFlush < 0) {
5496 cacheSize = Long64_t(-cacheFactor * fAutoFlush);
5497 } else if (fAutoFlush == 0) {
5499 if (medianClusterSize > 0)
5500 cacheSize = Long64_t(cacheFactor * 1.5 * medianClusterSize * GetZipBytes() / (fEntries + 1));
5501 else
5502 cacheSize = Long64_t(cacheFactor * 1.5 * 30000000); // use the default value of fAutoFlush
5503 } else {
5504 cacheSize = Long64_t(cacheFactor * 1.5 * fAutoFlush * GetZipBytes() / (fEntries + 1));
5505 }
5506 if (cacheSize >= (INT_MAX / 4)) {
5507 cacheSize = INT_MAX / 4;
5508 }
5509 return cacheSize;
5510 };
5511
5512 const char *stcs;
5513 Double_t cacheFactor = 0.0;
5514 if (!(stcs = gSystem->Getenv("ROOT_TTREECACHE_SIZE")) || !*stcs) {
5515 cacheFactor = gEnv->GetValue("TTreeCache.Size", 1.0);
5516 } else {
5518 }
5519
5520 if (cacheFactor < 0.0) {
5521 // ignore negative factors
5522 cacheFactor = 0.0;
5523 }
5524
5526
5527 if (cacheSize < 0) {
5528 cacheSize = 0;
5529 }
5530
5531 if (cacheSize == 0 && withDefault) {
5532 cacheSize = calculateCacheSize(1.0);
5533 }
5534
5535 return cacheSize;
5536}
5537
5538////////////////////////////////////////////////////////////////////////////////
5539/// Return an iterator over the cluster of baskets starting at firstentry.
5540///
5541/// This iterator is not yet supported for TChain object.
5542/// ~~~ {.cpp}
5543/// TTree::TClusterIterator clusterIter = tree->GetClusterIterator(entry);
5544/// Long64_t clusterStart;
5545/// while( (clusterStart = clusterIter()) < tree->GetEntries() ) {
5546/// printf("The cluster starts at %lld and ends at %lld (inclusive)\n",clusterStart,clusterIter.GetNextEntry()-1);
5547/// }
5548/// ~~~
5551{
5552 // create cache if wanted
5553 if (fCacheDoAutoInit)
5555
5556 return TClusterIterator(this,firstentry);
5557}
5558
5559////////////////////////////////////////////////////////////////////////////////
5560/// Return pointer to the current file.
5563{
5564 if (!fDirectory || fDirectory==gROOT) {
5565 return nullptr;
5566 }
5567 return fDirectory->GetFile();
5568}
5569
5570////////////////////////////////////////////////////////////////////////////////
5571/// Return the number of entries matching the selection.
5572/// Return -1 in case of errors.
5573///
5574/// If the selection uses any arrays or containers, we return the number
5575/// of entries where at least one element match the selection.
5576/// GetEntries is implemented using the selector class TSelectorEntries,
5577/// which can be used directly (see code in TTreePlayer::GetEntries) for
5578/// additional option.
5579/// If SetEventList was used on the TTree or TChain, only that subset
5580/// of entries will be considered.
5583{
5584 GetPlayer();
5585 if (fPlayer) {
5586 return fPlayer->GetEntries(selection);
5587 }
5588 return -1;
5589}
5590
5591////////////////////////////////////////////////////////////////////////////////
5592/// Returns a number corresponding to:
5593/// - The number of entries in this tree, if greater than zero
5594/// - The number of entries in the first friend tree, if there are any friends
5595/// - 0 otherwise
5598{
5599 if (fEntries) return fEntries;
5600 if (!fFriends) return 0;
5602 if (!fr) return 0;
5603 TTree *t = fr->GetTree();
5604 if (t==nullptr) return 0;
5605 return t->GetEntriesFriend();
5606}
5607
5608////////////////////////////////////////////////////////////////////////////////
5609/// Read all branches of entry and return total number of bytes read.
5610///
5611/// - `getall = 0` : get only active branches
5612/// - `getall = 1` : get all branches
5613///
5614/// The function returns the number of bytes read from the input buffer.
5615/// If entry does not exist the function returns 0.
5616/// If an I/O error occurs, the function returns -1.
5617/// If all branches are disabled and getall == 0, it also returns 0
5618/// even if the specified entry exists in the tree, since zero bytes were read.
5619///
5620/// If the Tree has friends, also read the friends entry.
5621///
5622/// To activate/deactivate one or more branches, use TBranch::SetBranchStatus
5623/// For example, if you have a Tree with several hundred branches, and you
5624/// are interested only by branches named "a" and "b", do
5625/// ~~~ {.cpp}
5626/// mytree.SetBranchStatus("*",0); //disable all branches
5627/// mytree.SetBranchStatus("a",1);
5628/// mytree.SetBranchStatus("b",1);
5629/// ~~~
5630/// when calling mytree.GetEntry(i); only branches "a" and "b" will be read.
5631///
5632/// __WARNING!!__
5633/// If your Tree has been created in split mode with a parent branch "parent.",
5634/// ~~~ {.cpp}
5635/// mytree.SetBranchStatus("parent",1);
5636/// ~~~
5637/// will not activate the sub-branches of "parent". You should do:
5638/// ~~~ {.cpp}
5639/// mytree.SetBranchStatus("parent*",1);
5640/// ~~~
5641/// Without the trailing dot in the branch creation you have no choice but to
5642/// call SetBranchStatus explicitly for each of the sub branches.
5643///
5644/// An alternative is to call directly
5645/// ~~~ {.cpp}
5646/// brancha.GetEntry(i)
5647/// branchb.GetEntry(i);
5648/// ~~~
5649/// ## IMPORTANT NOTE
5650///
5651/// By default, GetEntry reuses the space allocated by the previous object
5652/// for each branch. You can force the previous object to be automatically
5653/// deleted if you call mybranch.SetAutoDelete(true) (default is false).
5654///
5655/// Example:
5656///
5657/// Consider the example in $ROOTSYS/test/Event.h
5658/// The top level branch in the tree T is declared with:
5659/// ~~~ {.cpp}
5660/// Event *event = 0; //event must be null or point to a valid object
5661/// //it must be initialized
5662/// T.SetBranchAddress("event",&event);
5663/// ~~~
5664/// When reading the Tree, one can choose one of these 3 options:
5665///
5666/// ## OPTION 1
5667///
5668/// ~~~ {.cpp}
5669/// for (Long64_t i=0;i<nentries;i++) {
5670/// T.GetEntry(i);
5671/// // the object event has been filled at this point
5672/// }
5673/// ~~~
5674/// The default (recommended). At the first entry an object of the class
5675/// Event will be created and pointed by event. At the following entries,
5676/// event will be overwritten by the new data. All internal members that are
5677/// TObject* are automatically deleted. It is important that these members
5678/// be in a valid state when GetEntry is called. Pointers must be correctly
5679/// initialized. However these internal members will not be deleted if the
5680/// characters "->" are specified as the first characters in the comment
5681/// field of the data member declaration.
5682///
5683/// If "->" is specified, the pointer member is read via pointer->Streamer(buf).
5684/// In this case, it is assumed that the pointer is never null (case of
5685/// pointer TClonesArray *fTracks in the Event example). If "->" is not
5686/// specified, the pointer member is read via buf >> pointer. In this case
5687/// the pointer may be null. Note that the option with "->" is faster to
5688/// read or write and it also consumes less space in the file.
5689///
5690/// ## OPTION 2
5691///
5692/// The option AutoDelete is set
5693/// ~~~ {.cpp}
5694/// TBranch *branch = T.GetBranch("event");
5695/// branch->SetAddress(&event);
5696/// branch->SetAutoDelete(true);
5697/// for (Long64_t i=0;i<nentries;i++) {
5698/// T.GetEntry(i);
5699/// // the object event has been filled at this point
5700/// }
5701/// ~~~
5702/// In this case, at each iteration, the object event is deleted by GetEntry
5703/// and a new instance of Event is created and filled.
5704///
5705/// ## OPTION 3
5706///
5707/// ~~~ {.cpp}
5708/// Same as option 1, but you delete yourself the event.
5709///
5710/// for (Long64_t i=0;i<nentries;i++) {
5711/// delete event;
5712/// event = 0; // EXTREMELY IMPORTANT
5713/// T.GetEntry(i);
5714/// // the object event has been filled at this point
5715/// }
5716/// ~~~
5717/// It is strongly recommended to use the default option 1. It has the
5718/// additional advantage that functions like TTree::Draw (internally calling
5719/// TTree::GetEntry) will be functional even when the classes in the file are
5720/// not available.
5721///
5722/// Note: See the comments in TBranchElement::SetAddress() for the
5723/// object ownership policy of the underlying (user) data.
5726{
5727 // We already have been visited while recursively looking
5728 // through the friends tree, let return
5729 if (kGetEntry & fFriendLockStatus) return 0;
5730
5731 if (entry < 0 || entry >= fEntries) return 0;
5732 Int_t i;
5733 Int_t nbytes = 0;
5734 fReadEntry = entry;
5735
5736 // create cache if wanted
5737 if (fCacheDoAutoInit)
5739
5741 Int_t nb=0;
5742
5743 auto seqprocessing = [&]() {
5744 TBranch *branch;
5745 for (i=0;i<nbranches;i++) {
5747 nb = branch->GetEntry(entry, getall);
5748 if (nb < 0) break;
5749 nbytes += nb;
5750 }
5751 };
5752
5753#ifdef R__USE_IMT
5755 if (fSortedBranches.empty())
5757
5758 // Count branches are processed first and sequentially
5759 for (auto branch : fSeqBranches) {
5760 nb = branch->GetEntry(entry, getall);
5761 if (nb < 0) break;
5762 nbytes += nb;
5763 }
5764 if (nb < 0) return nb;
5765
5766 // Enable this IMT use case (activate its locks)
5768
5769 Int_t errnb = 0;
5770 std::atomic<Int_t> pos(0);
5771 std::atomic<Int_t> nbpar(0);
5772
5773 auto mapFunction = [&]() {
5774 // The branch to process is obtained when the task starts to run.
5775 // This way, since branches are sorted, we make sure that branches
5776 // leading to big tasks are processed first. If we assigned the
5777 // branch at task creation time, the scheduler would not necessarily
5778 // respect our sorting.
5779 Int_t j = pos.fetch_add(1);
5780
5781 Int_t nbtask = 0;
5782 auto branch = fSortedBranches[j].second;
5783
5784 if (gDebug > 0) {
5785 std::stringstream ss;
5786 ss << std::this_thread::get_id();
5787 Info("GetEntry", "[IMT] Thread %s", ss.str().c_str());
5788 Info("GetEntry", "[IMT] Running task for branch #%d: %s", j, branch->GetName());
5789 }
5790
5791 std::chrono::time_point<std::chrono::system_clock> start, end;
5792
5793 start = std::chrono::system_clock::now();
5794 nbtask = branch->GetEntry(entry, getall);
5795 end = std::chrono::system_clock::now();
5796
5797 Long64_t tasktime = (Long64_t)std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
5798 fSortedBranches[j].first += tasktime;
5799
5800 if (nbtask < 0) errnb = nbtask;
5801 else nbpar += nbtask;
5802 };
5803
5805 pool.Foreach(mapFunction, fSortedBranches.size());
5806
5807 if (errnb < 0) {
5808 nb = errnb;
5809 }
5810 else {
5811 // Save the number of bytes read by the tasks
5812 nbytes += nbpar;
5813
5814 // Re-sort branches if necessary
5818 }
5819 }
5820 }
5821 else {
5822 seqprocessing();
5823 }
5824#else
5825 seqprocessing();
5826#endif
5827 if (nb < 0) return nb;
5828
5829 // GetEntry in list of friends
5830 if (!fFriends) return nbytes;
5831 TFriendLock lock(this,kGetEntry);
5834 while ((fe = (TFriendElement*)nextf())) {
5835 TTree *t = fe->GetTree();
5836 if (t) {
5837 if (fe->TestBit(TFriendElement::kFromChain)) {
5838 nb = t->GetEntry(t->GetReadEntry(),getall);
5839 } else {
5840 if ( t->LoadTreeFriend(entry,this) >= 0 ) {
5841 nb = t->GetEntry(t->GetReadEntry(),getall);
5842 } else nb = 0;
5843 }
5844 if (nb < 0) return nb;
5845 nbytes += nb;
5846 }
5847 }
5848 return nbytes;
5849}
5850
5851
5852////////////////////////////////////////////////////////////////////////////////
5853/// Divides the top-level branches into two vectors: (i) branches to be
5854/// processed sequentially and (ii) branches to be processed in parallel.
5855/// Even if IMT is on, some branches might need to be processed first and in a
5856/// sequential fashion: in the parallelization of GetEntry, those are the
5857/// branches that store the size of another branch for every entry
5858/// (e.g. the size of an array branch). If such branches were processed
5859/// in parallel with the rest, there could be two threads invoking
5860/// TBranch::GetEntry on one of them at the same time, since a branch that
5861/// depends on a size (or count) branch will also invoke GetEntry on the latter.
5862/// This method can be invoked several times during the event loop if the TTree
5863/// is being written, for example when adding new branches. In these cases, the
5864/// `checkLeafCount` parameter is false.
5865/// \param[in] checkLeafCount True if we need to check whether some branches are
5866/// count leaves.
5869{
5871
5872 // The special branch fBranchRef needs to be processed sequentially:
5873 // we add it once only.
5874 if (fBranchRef && fBranchRef != fSeqBranches[0]) {
5875 fSeqBranches.push_back(fBranchRef);
5876 }
5877
5878 // The branches to be processed sequentially are those that are the leaf count of another branch
5879 if (checkLeafCount) {
5880 for (Int_t i = 0; i < nbranches; i++) {
5882 auto leafCount = ((TLeaf*)branch->GetListOfLeaves()->At(0))->GetLeafCount();
5883 if (leafCount) {
5884 auto countBranch = leafCount->GetBranch();
5885 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), countBranch) == fSeqBranches.end()) {
5886 fSeqBranches.push_back(countBranch);
5887 }
5888 }
5889 }
5890 }
5891
5892 // Any branch that is not a leaf count can be safely processed in parallel when reading
5893 // We need to reset the vector to make sure we do not re-add several times the same branch.
5894 if (!checkLeafCount) {
5895 fSortedBranches.clear();
5896 }
5897 for (Int_t i = 0; i < nbranches; i++) {
5898 Long64_t bbytes = 0;
5900 if (std::find(fSeqBranches.begin(), fSeqBranches.end(), branch) == fSeqBranches.end()) {
5901 bbytes = branch->GetTotBytes("*");
5902 fSortedBranches.emplace_back(bbytes, branch);
5903 }
5904 }
5905
5906 // Initially sort parallel branches by size
5907 std::sort(fSortedBranches.begin(),
5908 fSortedBranches.end(),
5909 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5910 return a.first > b.first;
5911 });
5912
5913 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5914 fSortedBranches[i].first = 0LL;
5915 }
5916}
5917
5918////////////////////////////////////////////////////////////////////////////////
5919/// Sorts top-level branches by the last average task time recorded per branch.
5922{
5923 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5925 }
5926
5927 std::sort(fSortedBranches.begin(),
5928 fSortedBranches.end(),
5929 [](std::pair<Long64_t,TBranch*> a, std::pair<Long64_t,TBranch*> b) {
5930 return a.first > b.first;
5931 });
5932
5933 for (size_t i = 0; i < fSortedBranches.size(); i++) {
5934 fSortedBranches[i].first = 0LL;
5935 }
5936}
5937
5938////////////////////////////////////////////////////////////////////////////////
5939///Returns the entry list assigned to this tree
5942{
5943 return fEntryList;
5944}
5945
5946////////////////////////////////////////////////////////////////////////////////
5947/// Return entry number corresponding to entry.
5948///
5949/// if no TEntryList set returns entry
5950/// else returns the entry number corresponding to the list index=entry
5953{
5954 if (!fEntryList) {
5955 return entry;
5956 }
5957
5958 return fEntryList->GetEntry(entry);
5959}
5960
5961////////////////////////////////////////////////////////////////////////////////
5962/// Return entry number corresponding to major and minor number.
5963/// Note that this function returns only the entry number, not the data
5964/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5965/// the BuildIndex function has created a table of Long64_t* of sorted values
5966/// corresponding to val = major<<31 + minor;
5967/// The function performs binary search in this sorted table.
5968/// If it finds a pair that matches val, it returns directly the
5969/// index in the table.
5970/// If an entry corresponding to major and minor is not found, the function
5971/// returns the index of the major,minor pair immediately lower than the
5972/// requested value, ie it will return -1 if the pair is lower than
5973/// the first entry in the index.
5974///
5975/// See also GetEntryNumberWithIndex
5983}
5984
5985////////////////////////////////////////////////////////////////////////////////
5986/// Return entry number corresponding to major and minor number.
5987/// Note that this function returns only the entry number, not the data
5988/// To read the data corresponding to an entry number, use TTree::GetEntryWithIndex
5989/// the BuildIndex function has created a table of Long64_t* of sorted values
5990/// corresponding to val = major<<31 + minor;
5991/// The function performs binary search in this sorted table.
5992/// If it finds a pair that matches val, it returns directly the
5993/// index in the table, otherwise it returns -1.
5994///
5995/// See also GetEntryNumberWithBestIndex
5998{
5999 if (!fTreeIndex) {
6000 return -1;
6001 }
6003}
6004
6005////////////////////////////////////////////////////////////////////////////////
6006/// Read entry corresponding to major and minor number.
6007///
6008/// The function returns the total number of bytes read; -1 if entry not found.
6009/// If the Tree has friend trees, the corresponding entry with
6010/// the index values (major,minor) is read. Note that the master Tree
6011/// and its friend may have different entry serial numbers corresponding
6012/// to (major,minor).
6013/// \note See TTreeIndex::GetEntryNumberWithIndex for information about the maximum values accepted for major and minor
6016{
6017 // We already have been visited while recursively looking
6018 // through the friends tree, let's return.
6020 return 0;
6021 }
6023 if (serial < 0) {
6024 return -1;
6025 }
6026 // create cache if wanted
6027 if (fCacheDoAutoInit)
6029
6030 Int_t i;
6031 Int_t nbytes = 0;
6032 fReadEntry = serial;
6033 TBranch *branch;
6035 Int_t nb;
6036 for (i = 0; i < nbranches; ++i) {
6038 nb = branch->GetEntry(serial);
6039 if (nb < 0) return nb;
6040 nbytes += nb;
6041 }
6042 // GetEntry in list of friends
6043 if (!fFriends) return nbytes;
6046 TFriendElement* fe = nullptr;
6047 while ((fe = (TFriendElement*) nextf())) {
6048 TTree *t = fe->GetTree();
6049 if (t) {
6050 serial = t->GetEntryNumberWithIndex(major,minor);
6051 if (serial <0) return -nbytes;
6052 nb = t->GetEntry(serial);
6053 if (nb < 0) return nb;
6054 nbytes += nb;
6055 }
6056 }
6057 return nbytes;
6058}
6059
6060////////////////////////////////////////////////////////////////////////////////
6061/// Return a pointer to the TTree friend whose name or alias is `friendname`.
6063TTree* TTree::GetFriend(const char *friendname) const
6064{
6065
6066 // We already have been visited while recursively
6067 // looking through the friends tree, let's return.
6069 return nullptr;
6070 }
6071 if (!fFriends) {
6072 return nullptr;
6073 }
6074 TFriendLock lock(const_cast<TTree*>(this), kGetFriend);
6076 TFriendElement* fe = nullptr;
6077 while ((fe = (TFriendElement*) nextf())) {
6078 if (strcmp(friendname,fe->GetName())==0
6079 || strcmp(friendname,fe->GetTreeName())==0) {
6080 return fe->GetTree();
6081 }
6082 }
6083 // After looking at the first level,
6084 // let's see if it is a friend of friends.
6085 nextf.Reset();
6086 fe = nullptr;
6087 while ((fe = (TFriendElement*) nextf())) {
6088 TTree *res = fe->GetTree()->GetFriend(friendname);
6089 if (res) {
6090 return res;
6091 }
6092 }
6093 return nullptr;
6094}
6095
6096////////////////////////////////////////////////////////////////////////////////
6097/// If the 'tree' is a friend, this method returns its alias name.
6098///
6099/// This alias is an alternate name for the tree.
6100///
6101/// It can be used in conjunction with a branch or leaf name in a TTreeFormula,
6102/// to specify in which particular tree the branch or leaf can be found if
6103/// the friend trees have branches or leaves with the same name as the master
6104/// tree.
6105///
6106/// It can also be used in conjunction with an alias created using
6107/// TTree::SetAlias in a TTreeFormula, e.g.:
6108/// ~~~ {.cpp}
6109/// maintree->Draw("treealias.fPx - treealias.myAlias");
6110/// ~~~
6111/// where fPx is a branch of the friend tree aliased as 'treealias' and 'myAlias'
6112/// was created using TTree::SetAlias on the friend tree.
6113///
6114/// However, note that 'treealias.myAlias' will be expanded literally,
6115/// without remembering that it comes from the aliased friend and thus
6116/// the branch name might not be disambiguated properly, which means
6117/// that you may not be able to take advantage of this feature.
6118///
6120const char *TTree::GetFriendAlias(TTree *tree) const
6121{
6122 if ((tree == this) || (tree == GetTree())) {
6123 return nullptr;
6124 }
6125
6126 // We already have been visited while recursively
6127 // looking through the friends tree, let's return.
6129 return nullptr;
6130 }
6131
6132 // This is a TTree and it does not have any friends, we can return early
6133 if (GetTree() == this && !fFriends)
6134 return nullptr;
6135
6136 TFriendLock lock(const_cast<TTree *>(this), kGetFriendAlias);
6137
6138 auto lookForFriendNameInListOfFriends = [tree](const TList &friends) -> const char * {
6140 auto *frElTree = frEl->GetTree();
6141 // Simplest case: we found a friend which tree is the same as the input tree
6142 if (frElTree == tree)
6143 return frEl->GetName();
6144 // Try again: the friend tree might be actually a TChain
6145 if (frElTree && frElTree->GetTree() == tree)
6146 return frEl->GetName();
6147 }
6148 return nullptr;
6149 };
6150
6151 // First, look for the immediate friends of this tree
6152 if (fFriends) {
6154 if (friendAlias)
6155 return friendAlias;
6156 }
6157
6158 // Then, check if this is a TChain and the current tree has friends
6159 // The non-redundant scenario here is that the currently-available
6160 // inner TTree of this TChain has a list of friends which the TChain
6161 // itself doesn't know anything about.
6162 if (const auto *innerListOfFriends = GetTree()->GetListOfFriends();
6165 if (friendAlias)
6166 return friendAlias;
6167 }
6168
6169 // Recursively look into the list of friends of this tree
6170 if (fFriends) {
6172 const char *friendAlias = frEl->GetTree()->GetFriendAlias(tree);
6173 if (friendAlias)
6174 return friendAlias;
6175 }
6176 }
6177
6178 // Recursively look into the list of friends of the inner tree
6179 if (const auto *innerListOfFriends = GetTree()->GetListOfFriends();
6182 const char *friendAlias = frEl->GetTree()->GetFriendAlias(tree);
6183 if (friendAlias)
6184 return friendAlias;
6185 }
6186 }
6187 return nullptr;
6188}
6189
6190////////////////////////////////////////////////////////////////////////////////
6191/// Returns the current set of IO settings
6193{
6194 return fIOFeatures;
6195}
6196
6197////////////////////////////////////////////////////////////////////////////////
6198/// Creates a new iterator that will go through all the leaves on the tree itself and its friend.
6201{
6202 return new TTreeFriendLeafIter(this, dir);
6203}
6205TLeaf *TTree::SearchLeafInListOfLeaves(const char *branchName, const char *leafName)
6206{
6208 if (strcmp(leaf->GetFullName(), leafName) != 0 && strcmp(leaf->GetName(), leafName) != 0)
6209 continue; // leafName does not match GetName() nor GetFullName(), this is not the right leaf
6210 if (branchName) {
6211 // check the branchName is also a match
6212 TBranch *br = leaf->GetBranch();
6213 // if a quick comparison with the branch full name is a match, we are done
6214 if (!strcmp(br->GetFullName(), branchName))
6215 return leaf;
6216 UInt_t nbch = strlen(branchName);
6217 const char* brname = br->GetName();
6218 TBranch *mother = br->GetMother();
6219 if (strncmp(brname, branchName, nbch)) {
6220 if (mother != br) {
6221 const char *mothername = mother->GetName();
6223 if (!strcmp(mothername, branchName)) {
6224 return leaf;
6225 } else if (nbch > motherlen && strncmp(mothername, branchName, motherlen) == 0 &&
6226 (mothername[motherlen - 1] == '.' || branchName[motherlen] == '.')) {
6227 // 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.
6228 if (strncmp(brname, branchName + motherlen + 1, nbch - motherlen - 1)) {
6229 // No it does not
6230 continue;
6231 } // else we have match so we can proceed.
6232 } else {
6233 // no match
6234 continue;
6235 }
6236 } else {
6237 continue;
6238 }
6239 }
6240 // The start of the branch name is identical to the content
6241 // of 'aname' before the first '/'.
6242 // Let's make sure that it is not longer (we are trying
6243 // to avoid having jet2/value match the branch jet23
6244 if ((strlen(brname) > nbch) && (brname[nbch] != '.') && (brname[nbch] != '[')) {
6245 continue;
6246 }
6247 }
6248 return leaf;
6249 }
6250
6251 return nullptr;
6252}
6254TLeaf *TTree::SearchLeafInListOfFriends(const char *branchName, const char *leafName)
6255{
6256 if (!fFriends) return nullptr;
6257 // The corresponding check is in GetLeaf
6258 TFriendLock lock(this, kGetLeaf);
6259
6261 if (auto *t = frEl->GetTree())
6262 if (auto *leaf = t->GetLeaf(branchName, leafName))
6263 return leaf;
6264
6265 // Second pass in the list of friends when the leaf name is prefixed by the tree name
6268 TTree *t = frEl->GetTree();
6269 if (!t) continue;
6270 const char *subLeafName = strstr(leafName, frEl->GetName());
6271 if (subLeafName != leafName)
6272 continue;
6273 Int_t l = strlen(frEl->GetName());
6274 subLeafName += l;
6275 if (*subLeafName != '.')
6276 continue;
6277 subLeafName++;
6279 if (auto *leaf = t->GetLeaf(branchName, subLeafName))
6280 return leaf;
6281 }
6282
6283 return nullptr;
6284}
6285
6286////////////////////////////////////////////////////////////////////////////////
6287/// Searches in this tree and any of its friends for a leaf named \p leafname in branch \p branchname , returns first
6288/// match or nullptr if no match.
6289///
6290/// Search order:
6291///
6292/// 1. Look for a \p branchname match (via FindBranch(branchname)):
6293/// a. In the list of branches of this tree
6294/// b. Recursively in nested branches of each branch of this tree
6295/// c. In the friends of this tree
6296/// 2. Look for matching \p branchname and \p leafname in list of leaves of this tree
6297/// 3. Look for matching \p branchname and \p leafname in friends of this tree (eventually calling GetLeaf on each
6298/// friend)
6299///
6300/// \note \p branchname can be an empty string, in which case the function will return the first leaf with matching
6301/// \p leafname in any branch of this tree or any of its friends following the search order above.
6302///
6303/// \note \p leafname can contain the name of a friend tree with the syntax: `friend_dir_and_tree.full_leaf_name`. In
6304/// particular, `friend_dir_and_tree` can be of the form `TDirectoryName/TreeName`.
6305TLeaf* TTree::GetLeaf(const char* branchname, const char *leafname)
6306{
6307 if (leafname == nullptr) return nullptr;
6308
6309 // We already have been visited while recursively looking
6310 // through the friends tree, let return
6312 return nullptr;
6313 }
6314
6315 if (auto *br = FindBranch(branchname))
6316 if (auto leaf = br->GetLeaf(leafname))
6317 return leaf;
6318
6320 return leaf;
6321
6323 return leaf;
6324
6325 return nullptr;
6326}
6327
6328////////////////////////////////////////////////////////////////////////////////
6329/// Searches in this tree and any of its friends for a leaf named \p leafname , returns first leaf matching in any
6330/// branch.
6331///
6332/// See TTree::GetLeaf(const char* branchname, const char *leafname) for a description of the search order.
6333///
6334/// \note \p name may be in the form `branch/leaf`
6336TLeaf* TTree::GetLeaf(const char *name)
6337{
6338 // Return nullptr if name is invalid or if we have
6339 // already been visited while searching friend trees
6340 if (!name || (kGetLeaf & fFriendLockStatus))
6341 return nullptr;
6342
6343 std::string path(name);
6344 const auto sep = path.find_last_of('/');
6345 if (sep != std::string::npos)
6346 return GetLeaf(path.substr(0, sep).c_str(), name + sep + 1);
6347
6348 return GetLeaf(nullptr, name);
6349}
6350
6351namespace {
6352
6353////////////////////////////////////////////////////////////////////////////////
6354/// \brief Helper detecting *any* file transition of a tree dataset
6355///
6356/// This is a generic helper, works if the dataset is a TTree or a TChain, and
6357/// transitively detects transitions in friends.
6358///
6359/// Comparing `TChain::GetTreeNumber()` before and after a call to
6360/// `TChain::LoadTree` only detects that the chain itself switched to another of
6361/// its own sub-trees. It does *not* detect that one of the (possibly indirect)
6362/// friends of the chain switched to a new file: in that case the cached
6363/// TLeaf/TBranch pointers become dangling even though the tree number of the
6364/// chain is unchanged.
6365///
6366/// `TChain::LoadTree` (both when the chain itself moves to a new tree and, via
6367/// `TChain::RefreshFriendAddresses`, when only a friend was updated) calls
6368/// `fNotify->Notify()`. Subscribing to that notification is therefore the
6369/// reliable way to know that anything in the friend graph moved.
6370///
6371/// This derives directly from TNotifyLinkBase rather than using TNotifyLink<T>
6372/// because the latter would require a dictionary for the instantiation.
6373///
6374/// We could also use
6375/// ```
6376/// struct TLeafRefresher {
6377/// bool fDirty = true;
6378/// bool Notify() { fDirty = true; return true; }
6379/// };
6380/// ```
6381/// declared in TChain.h or InternalTreeUtils.hxx and genereate a dictionary for
6382/// TNotifyLink<TLeafRefresher>.
6383class FileTransitionDetector final : public TNotifyLinkBase {
6384 /// Set to true initially so that the very first iteration performs the lookup.
6385 bool fChanged = true;
6386 TTree &fChain;
6387
6388public:
6389 FileTransitionDetector(TTree &chain) : fChain(chain) { PrependLink(fChain); }
6390
6391 ~FileTransitionDetector() override { RemoveLink(fChain); }
6392 FileTransitionDetector(const FileTransitionDetector &) = delete;
6393 FileTransitionDetector &operator=(const FileTransitionDetector &) = delete;
6394 FileTransitionDetector(FileTransitionDetector &&) = delete;
6395 FileTransitionDetector &operator=(FileTransitionDetector &&) = delete;
6396
6397 /// Must return true: returning false would make TChain::LoadTree fail with -6.
6398 Bool_t Notify() override
6399 {
6400 fChanged = true;
6401 // Propagate to the rest of the list of subscribers, as TNotifyLink does.
6402 if (fNext)
6403 return fNext->Notify();
6404 return true;
6405 }
6406
6407 /// Returns true (once) if the chain or any of its direct or indirect friends
6408 /// switched to a new tree since the last call.
6409 bool CheckAndReset()
6410 {
6411 bool changed = fChanged;
6412 fChanged = false;
6413 return changed;
6414 }
6415};
6416} // anonymous namespace
6417
6418////////////////////////////////////////////////////////////////////////////////
6419/// Computes the extremum (minimum or maximum) for the input column name
6420///
6421/// It takes into account the following situations:
6422///
6423/// * The dataset is a TTree and contains the input column
6424/// * The dataset is a TChain and contains the input column, in which case the methods detect file switching and update
6425/// the leaf pointer correctly.
6426/// * The dataset is a TChain, contains the input column, but some files miss it, in which case the methods skip the
6427/// entries from those files.
6428/// * The dataset has a friend TTree which contains the input column
6429/// * The dataset is a TChain and has a friend TChain which contains the input column, in which case the methods detect
6430/// file switching on the friend and update the leaf pointer correctly.
6431/// * The dataset is a TChain and has a friend TChain. The input column is partially available in either the main or the
6432/// friend chain. This can happen for example if the main chain has some files missing the input column and the user
6433/// knowingly injects the input column in the files of the friend chain. In this case, the methods detect file switching
6434/// at the boundary between files of the main chain, but also detect if there are file switches in the friend chain.
6435/// Notably, the entries must still be overall aligned between the main chain and the friend one.
6436double TTree::ComputeExtremum(const char *columname, double errVal, bool (*cmp)(double, double))
6437{
6438 // Ensure the TTree cursor is brought back to the current entry after computing the value
6439 struct CurrentEntryRAII {
6440
6441 Long64_t fCurrentEntry;
6442 TTree &fTree;
6443
6444 CurrentEntryRAII(TTree &tree) : fCurrentEntry(tree.GetReadEntry()), fTree(tree) {}
6445
6446 ~CurrentEntryRAII() { fTree.LoadTree(fCurrentEntry); }
6447 } raii{*this};
6448
6449 // Initial lookup of the leaf name, this will find it whether it's in the
6450 // current tree or in any of its friends
6452 if (!leaf) {
6453 return 0;
6454 }
6455 TBranch *branch = leaf->GetBranch();
6456 assert(branch); // leaf without a branch is not allowed by construction
6457
6458 // create cache if wanted
6459 if (fCacheDoAutoInit)
6461
6462 FileTransitionDetector fileTransition{*this};
6463 double extremum{errVal};
6464 for (Long64_t i = 0; i < fEntries; ++i) {
6465 const auto entryNumber = GetEntryNumber(i);
6466 if (entryNumber < 0) break;
6468 if (localEntryNumber < 0)
6469 break;
6470
6471 // At every entry, we check if the processing has triggered a switch to
6472 // a new file. We detect both a switch of the current tree in the chain
6473 // (if this tree is a TChain) as well as a switch in any of its direct
6474 // and indirect friends (if they are also a TChain)
6475 if (fileTransition.CheckAndReset()) {
6476 branch = nullptr;
6478 if (leaf) {
6479 branch = leaf->GetBranch();
6480 assert(branch); // leaf without a branch is not allowed by construction
6481 }
6482 }
6483
6484 // We accept that the leaf may not be present in one or more files in case
6485 // it was found in a chain, we just continue processing the next entry
6486 if (!leaf)
6487 continue;
6488
6489 // If the branch belongs to a friend, the local entry number of the friend
6490 // may differ from the one of the chain (e.g. when the friend is indexed).
6491 // The owning TTree has already been positioned by TChain::LoadTree, so
6492 // its read entry is the correct one to use.
6493 auto *owningTree = branch->GetTree();
6494 branch->GetEntry(owningTree->GetReadEntry());
6495
6496 auto leafLen{leaf->GetLen()};
6497 for (decltype(leafLen) j = 0; j < leafLen; ++j) {
6498 auto val = leaf->GetValue(j);
6499 if (cmp(val, extremum)) {
6500 extremum = val;
6501 }
6502 }
6503 }
6504
6505 return extremum;
6506}
6507
6508////////////////////////////////////////////////////////////////////////////////
6509/// Return maximum of column with name columname.
6510/// if the Tree has an associated TEventList or TEntryList, the maximum
6511/// is computed for the entries in this list.
6514{
6515 return ComputeExtremum(columname, std::numeric_limits<double>::lowest(), [](double a, double b) { return a > b; });
6516}
6517
6518////////////////////////////////////////////////////////////////////////////////
6519/// Static function which returns the tree file size limit in bytes.
6524}
6525
6526////////////////////////////////////////////////////////////////////////////////
6527/// Return minimum of column with name columname.
6528/// if the Tree has an associated TEventList or TEntryList, the minimum
6529/// is computed for the entries in this list.
6532{
6533 return ComputeExtremum(columname, std::numeric_limits<double>::max(), [](double a, double b) { return a < b; });
6534}
6535
6536////////////////////////////////////////////////////////////////////////////////
6537/// Load the TTreePlayer (if not already done).
6540{
6541 if (fPlayer) {
6542 return fPlayer;
6543 }
6545 return fPlayer;
6546}
6547
6548////////////////////////////////////////////////////////////////////////////////
6549/// Find and return the TTreeCache registered with the file and which may
6550/// contain branches for us.
6553{
6554 TTreeCache *pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6555 if (pe && pe->GetTree() != GetTree())
6556 pe = nullptr;
6557 return pe;
6558}
6559
6560////////////////////////////////////////////////////////////////////////////////
6561/// Find and return the TTreeCache registered with the file and which may
6562/// contain branches for us. If create is true and there is no cache
6563/// a new cache is created with default size.
6565TTreeCache *TTree::GetReadCache(TFile *file, bool create)
6566{
6567 TTreeCache *pe = GetReadCache(file);
6568 if (create && !pe) {
6569 if (fCacheDoAutoInit)
6570 SetCacheSizeAux(true, -1);
6571 pe = dynamic_cast<TTreeCache*>(file->GetCacheRead(GetTree()));
6572 if (pe && pe->GetTree() != GetTree()) pe = nullptr;
6573 }
6574 return pe;
6575}
6576
6577////////////////////////////////////////////////////////////////////////////////
6578/// Return a pointer to the list containing user objects associated to this tree.
6579///
6580/// The list is automatically created if it does not exist.
6581///
6582/// WARNING: By default the TTree destructor will delete all objects added
6583/// to this list. If you do not want these objects to be deleted,
6584/// call:
6585///
6586/// mytree->GetUserInfo()->Clear();
6587///
6588/// before deleting the tree.
6591{
6592 if (!fUserInfo) {
6593 fUserInfo = new TList();
6594 fUserInfo->SetName("UserInfo");
6595 }
6596 return fUserInfo;
6597}
6598
6599////////////////////////////////////////////////////////////////////////////////
6600/// Appends the cluster range information stored in 'fromtree' to this tree,
6601/// including the value of fAutoFlush.
6602///
6603/// This is used when doing a fast cloning (by TTreeCloner).
6604/// See also fAutoFlush and fAutoSave if needed.
6607{
6608 Long64_t autoflush = fromtree->GetAutoFlush();
6609 if (fromtree->fNClusterRange == 0 && fromtree->fAutoFlush == fAutoFlush) {
6610 // nothing to do
6611 } else if (fNClusterRange || fromtree->fNClusterRange) {
6612 Int_t newsize = fNClusterRange + 1 + fromtree->fNClusterRange;
6613 if (newsize > fMaxClusterRange) {
6614 if (fMaxClusterRange) {
6616 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6618 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
6620 } else {
6624 }
6625 }
6626 if (fEntries) {
6630 }
6631 for (Int_t i = 0 ; i < fromtree->fNClusterRange; ++i) {
6632 fClusterRangeEnd[fNClusterRange] = fEntries + fromtree->fClusterRangeEnd[i];
6633 fClusterSize[fNClusterRange] = fromtree->fClusterSize[i];
6635 }
6637 } else {
6639 }
6641 if (autoflush > 0 && autosave > 0) {
6643 }
6644}
6645
6646////////////////////////////////////////////////////////////////////////////////
6647/// Keep a maximum of fMaxEntries in memory.
6650{
6653 for (Int_t i = 0; i < nb; ++i) {
6655 branch->KeepCircular(maxEntries);
6656 }
6657 if (fNClusterRange) {
6660 for(Int_t i = 0, j = 0; j < oldsize; ++j) {
6663 ++i;
6664 } else {
6666 }
6667 }
6668 }
6670 fReadEntry = -1;
6671}
6672
6673////////////////////////////////////////////////////////////////////////////////
6674/// Read in memory all baskets from all branches up to the limit of maxmemory bytes.
6675///
6676/// If maxmemory is non null and positive SetMaxVirtualSize is called
6677/// with this value. Default for maxmemory is 2000000000 (2 Gigabytes).
6678/// The function returns the total number of baskets read into memory
6679/// if negative an error occurred while loading the branches.
6680/// This method may be called to force branch baskets in memory
6681/// when random access to branch entries is required.
6682/// If random access to only a few branches is required, you should
6683/// call directly TBranch::LoadBaskets.
6686{
6688
6689 TIter next(GetListOfLeaves());
6690 TLeaf *leaf;
6691 Int_t nimported = 0;
6692 while ((leaf=(TLeaf*)next())) {
6693 nimported += leaf->GetBranch()->LoadBaskets();//break;
6694 }
6695 return nimported;
6696}
6697
6698////////////////////////////////////////////////////////////////////////////////
6699/// Set current entry.
6700///
6701/// Returns -2 if entry does not exist (just as TChain::LoadTree()).
6702/// Returns -6 if an error occurs in the notification callback (just as TChain::LoadTree()).
6703///
6704/// Calls fNotify->Notify() (if fNotify is not null) when starting the processing of a new tree.
6705///
6706/// \note This function is overloaded in TChain.
6708{
6709 // We have already been visited while recursively looking
6710 // through the friend trees, let's return
6712 // We need to return a negative value to avoid a circular list of friends
6713 // to think that there is always an entry somewhere in the list.
6714 return -1;
6715 }
6716
6717 // create cache if wanted
6718 if (fCacheDoAutoInit && entry >=0)
6720
6721 if (fNotify) {
6722 if (fReadEntry < 0) {
6723 fNotify->Notify();
6724 }
6725 }
6726 fReadEntry = entry;
6727
6728 bool friendHasEntry = false;
6729 if (fFriends) {
6730 // Set current entry in friends as well.
6731 //
6732 // An alternative would move this code to each of the
6733 // functions calling LoadTree (and to overload a few more).
6734 bool needUpdate = false;
6735 {
6736 // This scope is need to insure the lock is released at the right time
6738 TFriendLock lock(this, kLoadTree);
6739 TFriendElement* fe = nullptr;
6740 while ((fe = (TFriendElement*) nextf())) {
6741 if (fe->TestBit(TFriendElement::kFromChain)) {
6742 // This friend element was added by the chain that owns this
6743 // tree, the chain will deal with loading the correct entry.
6744 continue;
6745 }
6746 TTree* friendTree = fe->GetTree();
6747 if (friendTree) {
6748 if (friendTree->LoadTreeFriend(entry, this) >= 0) {
6749 friendHasEntry = true;
6750 }
6751 }
6752 if (fe->IsUpdated()) {
6753 needUpdate = true;
6754 fe->ResetUpdated();
6755 }
6756 } // for each friend
6757 }
6758 if (needUpdate) {
6759 //update list of leaves in all TTreeFormula of the TTreePlayer (if any)
6760 if (fPlayer) {
6762 }
6763 //Notify user if requested
6764 if (fNotify) {
6765 if(!fNotify->Notify()) return -6;
6766 }
6767 // We cannot know a priori if the branch(es) of the friend TChain(s) that were just
6768 // updated were supposed to be connected to possibly a TChainElement of another chain
6769 // that has befriended this TTree (i.e., one of the "external friends"). Thus, we
6770 // forward the notification that one or more friend trees were updated to the friends
6771 // of this TTree.
6772 if (fExternalFriends)
6774 external_fe->MarkUpdated();
6775 }
6776 }
6777
6778 if ((fReadEntry >= fEntries) && !friendHasEntry) {
6779 fReadEntry = -1;
6780 return -2;
6781 }
6782 return fReadEntry;
6783}
6784
6785////////////////////////////////////////////////////////////////////////////////
6786/// Load entry on behalf of our master tree, we may use an index.
6787///
6788/// Called by LoadTree() when the masterTree looks for the entry
6789/// number in a friend tree (us) corresponding to the passed entry
6790/// number in the masterTree.
6791///
6792/// If we have no index, our entry number and the masterTree entry
6793/// number are the same.
6794///
6795/// If we *do* have an index, we must find the (major, minor) value pair
6796/// in masterTree to locate our corresponding entry.
6797///
6805}
6806
6807////////////////////////////////////////////////////////////////////////////////
6808/// Generate a skeleton analysis class for this tree.
6809///
6810/// The following files are produced: classname.h and classname.C.
6811/// If classname is 0, classname will be called "nameoftree".
6812///
6813/// The generated code in classname.h includes the following:
6814///
6815/// - Identification of the original tree and the input file name.
6816/// - Definition of an analysis class (data members and member functions).
6817/// - The following member functions:
6818/// - constructor (by default opening the tree file),
6819/// - GetEntry(Long64_t entry),
6820/// - Init(TTree* tree) to initialize a new TTree,
6821/// - Show(Long64_t entry) to read and dump entry.
6822///
6823/// The generated code in classname.C includes only the main
6824/// analysis function Loop.
6825///
6826/// To use this function:
6827///
6828/// - Open your tree file (eg: TFile f("myfile.root");)
6829/// - T->MakeClass("MyClass");
6830///
6831/// where T is the name of the TTree in file myfile.root,
6832/// and MyClass.h, MyClass.C the name of the files created by this function.
6833/// In a ROOT session, you can do:
6834/// ~~~ {.cpp}
6835/// root > .L MyClass.C
6836/// root > MyClass* t = new MyClass;
6837/// root > t->GetEntry(12); // Fill data members of t with entry number 12.
6838/// root > t->Show(); // Show values of entry 12.
6839/// root > t->Show(16); // Read and show values of entry 16.
6840/// root > t->Loop(); // Loop on all entries.
6841/// ~~~
6842/// NOTE: Do not use the code generated for a single TTree which is part
6843/// of a TChain to process that entire TChain. The maximum dimensions
6844/// calculated for arrays on the basis of a single TTree from the TChain
6845/// might be (will be!) too small when processing all of the TTrees in
6846/// the TChain. You must use myChain.MakeClass() to generate the code,
6847/// not myTree.MakeClass(...).
6849Int_t TTree::MakeClass(const char* classname, Option_t* option)
6850{
6851 GetPlayer();
6852 if (!fPlayer) {
6853 return 0;
6854 }
6855 return fPlayer->MakeClass(classname, option);
6856}
6857
6858////////////////////////////////////////////////////////////////////////////////
6859/// Generate a skeleton function for this tree.
6860///
6861/// The function code is written on filename.
6862/// If filename is 0, filename will be called nameoftree.C
6863///
6864/// The generated code includes the following:
6865/// - Identification of the original Tree and Input file name,
6866/// - Opening the Tree file,
6867/// - Declaration of Tree variables,
6868/// - Setting of branches addresses,
6869/// - A skeleton for the entry loop.
6870///
6871/// To use this function:
6872///
6873/// - Open your Tree file (eg: TFile f("myfile.root");)
6874/// - T->MakeCode("MyAnalysis.C");
6875///
6876/// where T is the name of the TTree in file myfile.root
6877/// and MyAnalysis.C the name of the file created by this function.
6878///
6879/// NOTE: Since the implementation of this function, a new and better
6880/// function TTree::MakeClass() has been developed.
6882Int_t TTree::MakeCode(const char* filename)
6883{
6884 Warning("MakeCode", "MakeCode is obsolete. Use MakeClass or MakeSelector instead");
6885
6886 GetPlayer();
6887 if (!fPlayer) return 0;
6888 return fPlayer->MakeCode(filename);
6889}
6890
6891////////////////////////////////////////////////////////////////////////////////
6892/// Generate a skeleton analysis class for this Tree using TBranchProxy.
6893///
6894/// TBranchProxy is the base of a class hierarchy implementing an
6895/// indirect access to the content of the branches of a TTree.
6896///
6897/// "proxyClassname" is expected to be of the form:
6898/// ~~~ {.cpp}
6899/// [path/]fileprefix
6900/// ~~~
6901/// The skeleton will then be generated in the file:
6902/// ~~~ {.cpp}
6903/// fileprefix.h
6904/// ~~~
6905/// located in the current directory or in 'path/' if it is specified.
6906/// The class generated will be named 'fileprefix'
6907///
6908/// "macrofilename" and optionally "cutfilename" are expected to point
6909/// to source files which will be included by the generated skeleton.
6910/// Method of the same name as the file(minus the extension and path)
6911/// will be called by the generated skeleton's Process method as follow:
6912/// ~~~ {.cpp}
6913/// [if (cutfilename())] htemp->Fill(macrofilename());
6914/// ~~~
6915/// "option" can be used select some of the optional features during
6916/// the code generation. The possible options are:
6917///
6918/// - nohist : indicates that the generated ProcessFill should not fill the histogram.
6919///
6920/// 'maxUnrolling' controls how deep in the class hierarchy does the
6921/// system 'unroll' classes that are not split. Unrolling a class
6922/// allows direct access to its data members (this emulates the behavior
6923/// of TTreeFormula).
6924///
6925/// The main features of this skeleton are:
6926///
6927/// * on-demand loading of branches
6928/// * ability to use the 'branchname' as if it was a data member
6929/// * protection against array out-of-bounds errors
6930/// * ability to use the branch data as an object (when the user code is available)
6931///
6932/// For example with Event.root, if
6933/// ~~~ {.cpp}
6934/// Double_t somePx = fTracks.fPx[2];
6935/// ~~~
6936/// is executed by one of the method of the skeleton,
6937/// somePx will updated with the current value of fPx of the 3rd track.
6938///
6939/// Both macrofilename and the optional cutfilename are expected to be
6940/// the name of source files which contain at least a free standing
6941/// function with the signature:
6942/// ~~~ {.cpp}
6943/// x_t macrofilename(); // i.e function with the same name as the file
6944/// ~~~
6945/// and
6946/// ~~~ {.cpp}
6947/// y_t cutfilename(); // i.e function with the same name as the file
6948/// ~~~
6949/// x_t and y_t needs to be types that can convert respectively to a double
6950/// and a bool (because the skeleton uses:
6951///
6952/// if (cutfilename()) htemp->Fill(macrofilename());
6953///
6954/// These two functions are run in a context such that the branch names are
6955/// available as local variables of the correct (read-only) type.
6956///
6957/// Note that if you use the same 'variable' twice, it is more efficient
6958/// to 'cache' the value. For example:
6959/// ~~~ {.cpp}
6960/// Int_t n = fEventNumber; // Read fEventNumber
6961/// if (n<10 || n>10) { ... }
6962/// ~~~
6963/// is more efficient than
6964/// ~~~ {.cpp}
6965/// if (fEventNumber<10 || fEventNumber>10)
6966/// ~~~
6967/// Also, optionally, the generated selector will also call methods named
6968/// macrofilename_methodname in each of 6 main selector methods if the method
6969/// macrofilename_methodname exist (Where macrofilename is stripped of its
6970/// extension).
6971///
6972/// Concretely, with the script named h1analysisProxy.C,
6973///
6974/// - The method calls the method (if it exist)
6975/// - Begin -> void h1analysisProxy_Begin(TTree*);
6976/// - SlaveBegin -> void h1analysisProxy_SlaveBegin(TTree*);
6977/// - Notify -> bool h1analysisProxy_Notify();
6978/// - Process -> bool h1analysisProxy_Process(Long64_t);
6979/// - SlaveTerminate -> void h1analysisProxy_SlaveTerminate();
6980/// - Terminate -> void h1analysisProxy_Terminate();
6981///
6982/// If a file name macrofilename.h (or .hh, .hpp, .hxx, .hPP, .hXX) exist
6983/// it is included before the declaration of the proxy class. This can
6984/// be used in particular to insure that the include files needed by
6985/// the macro file are properly loaded.
6986///
6987/// The default histogram is accessible via the variable named 'htemp'.
6988///
6989/// If the library of the classes describing the data in the branch is
6990/// loaded, the skeleton will add the needed `include` statements and
6991/// give the ability to access the object stored in the branches.
6992///
6993/// To draw px using the file hsimple.root (generated by the
6994/// hsimple.C tutorial), we need a file named hsimple.cxx:
6995/// ~~~ {.cpp}
6996/// double hsimple() {
6997/// return px;
6998/// }
6999/// ~~~
7000/// MakeProxy can then be used indirectly via the TTree::Draw interface
7001/// as follow:
7002/// ~~~ {.cpp}
7003/// new TFile("hsimple.root")
7004/// ntuple->Draw("hsimple.cxx");
7005/// ~~~
7006/// A more complete example is available in the tutorials directory:
7007/// h1analysisProxy.cxx , h1analysProxy.h and h1analysisProxyCut.C
7008/// which reimplement the selector found in h1analysis.C
7010Int_t TTree::MakeProxy(const char* proxyClassname, const char* macrofilename, const char* cutfilename, const char* option, Int_t maxUnrolling)
7011{
7012 GetPlayer();
7013 if (!fPlayer) return 0;
7015}
7016
7017////////////////////////////////////////////////////////////////////////////////
7018/// Generate skeleton selector class for this tree.
7019///
7020/// The following files are produced: selector.h and selector.C.
7021/// If selector is 0, the selector will be called "nameoftree".
7022/// The option can be used to specify the branches that will have a data member.
7023/// - If option is "=legacy", a pre-ROOT6 selector will be generated (data
7024/// members and branch pointers instead of TTreeReaders).
7025/// - If option is empty, readers will be generated for each leaf.
7026/// - If option is "@", readers will be generated for the topmost branches.
7027/// - Individual branches can also be picked by their name:
7028/// - "X" generates readers for leaves of X.
7029/// - "@X" generates a reader for X as a whole.
7030/// - "@X;Y" generates a reader for X as a whole and also readers for the
7031/// leaves of Y.
7032/// - For further examples see the figure below.
7033///
7034/// \image html ttree_makeselector_option_examples.png
7035///
7036/// The generated code in selector.h includes the following:
7037/// - Identification of the original Tree and Input file name
7038/// - Definition of selector class (data and functions)
7039/// - The following class functions:
7040/// - constructor and destructor
7041/// - void Begin(TTree *tree)
7042/// - void SlaveBegin(TTree *tree)
7043/// - void Init(TTree *tree)
7044/// - bool Notify()
7045/// - bool Process(Long64_t entry)
7046/// - void Terminate()
7047/// - void SlaveTerminate()
7048///
7049/// The class selector derives from TSelector.
7050/// The generated code in selector.C includes empty functions defined above.
7051///
7052/// To use this function:
7053///
7054/// - connect your Tree file (eg: `TFile f("myfile.root");`)
7055/// - `T->MakeSelector("myselect");`
7056///
7057/// where T is the name of the Tree in file myfile.root
7058/// and myselect.h, myselect.C the name of the files created by this function.
7059/// In a ROOT session, you can do:
7060/// ~~~ {.cpp}
7061/// root > T->Process("myselect.C")
7062/// ~~~
7064Int_t TTree::MakeSelector(const char* selector, Option_t* option)
7065{
7066 TString opt(option);
7067 if(opt.EqualTo("=legacy", TString::ECaseCompare::kIgnoreCase)) {
7068 return MakeClass(selector, "selector");
7069 } else {
7070 GetPlayer();
7071 if (!fPlayer) return 0;
7072 return fPlayer->MakeReader(selector, option);
7073 }
7074}
7075
7076////////////////////////////////////////////////////////////////////////////////
7077/// Check if adding nbytes to memory we are still below MaxVirtualsize.
7080{
7082 return false;
7083 }
7084 return true;
7085}
7086
7087////////////////////////////////////////////////////////////////////////////////
7088/// Static function merging the trees in the TList into a new tree.
7089///
7090/// Trees in the list can be memory or disk-resident trees.
7091/// The new tree is created in the current directory (memory if gROOT).
7092/// Trees with no branches will be skipped, the branch structure
7093/// will be taken from the first non-zero-branch Tree of {li}
7096{
7097 if (!li) return nullptr;
7098 TIter next(li);
7099 TTree *newtree = nullptr;
7100 TObject *obj;
7101
7102 while ((obj=next())) {
7103 if (!obj->InheritsFrom(TTree::Class())) continue;
7104 TTree *tree = (TTree*)obj;
7105 if (tree->GetListOfBranches()->IsEmpty()) {
7106 if (gDebug > 2) {
7107 tree->Warning("MergeTrees","TTree %s has no branches, skipping.", tree->GetName());
7108 }
7109 continue; // Completely ignore the empty trees.
7110 }
7111 Long64_t nentries = tree->GetEntries();
7112 if (newtree && nentries == 0)
7113 continue; // If we already have the structure and we have no entry, save time and skip
7114 if (!newtree) {
7115 newtree = (TTree*)tree->CloneTree(-1, options);
7116 if (!newtree) continue;
7117
7118 // Once the cloning is done, separate the trees,
7119 // to avoid as many side-effects as possible
7120 // The list of clones is guaranteed to exist since we
7121 // just cloned the tree.
7122 tree->GetListOfClones()->Remove(newtree);
7123 tree->ResetBranchAddresses();
7124 newtree->ResetBranchAddresses();
7125 continue;
7126 }
7127 if (nentries == 0)
7128 continue;
7129 newtree->CopyEntries(tree, -1, options, true);
7130 }
7131 if (newtree && newtree->GetTreeIndex()) {
7132 newtree->GetTreeIndex()->Append(nullptr,false); // Force the sorting
7133 }
7134 return newtree;
7135}
7136
7137////////////////////////////////////////////////////////////////////////////////
7138/// Merge the trees in the TList into this tree.
7139///
7140/// Returns the total number of entries in the merged tree.
7141/// Trees with no branches will be skipped, the branch structure
7142/// will be taken from the first non-zero-branch Tree of {this+li}
7145{
7146 if (fBranches.IsEmpty()) {
7147 if (!li || li->IsEmpty())
7148 return 0; // Nothing to do ....
7149 // Let's find the first non-empty
7150 TIter next(li);
7151 TTree *tree;
7152 while ((tree = (TTree *)next())) {
7153 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
7154 if (gDebug > 2) {
7155 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
7156 }
7157 continue;
7158 }
7159 // We could come from a list made up of different names, the first one still wins
7160 tree->SetName(this->GetName());
7161 auto prevEntries = tree->GetEntries();
7162 auto result = tree->Merge(li, options);
7163 if (result != prevEntries) {
7164 // If there is no additional entries, the first write was enough.
7165 tree->Write();
7166 }
7167 // Make sure things are really written out to disk before attempting any reading.
7168 if (tree->GetCurrentFile()) {
7169 tree->GetCurrentFile()->Flush();
7170 // Read back the complete info in this TTree, so that caller does not
7171 // inadvertently write the empty tree.
7172 tree->GetDirectory()->ReadTObject(this, this->GetName());
7173 }
7174 return result;
7175 }
7176 return 0; // All trees have empty branches
7177 }
7178 if (!li) return 0;
7180 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
7181 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
7182 // Also since this is part of a merging operation, the output file is not as precious as in
7183 // the general case since the input file should still be around.
7184 fAutoSave = 0;
7185 TIter next(li);
7186 TTree *tree;
7187 while ((tree = (TTree*)next())) {
7188 if (tree==this) continue;
7189 if (!tree->InheritsFrom(TTree::Class())) {
7190 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
7192 return -1;
7193 }
7194
7195 Long64_t nentries = tree->GetEntries();
7196 if (nentries == 0) continue;
7197
7198 CopyEntries(tree, -1, options, true);
7199 }
7201 return GetEntries();
7202}
7203
7204////////////////////////////////////////////////////////////////////////////////
7205/// Merge the trees in the TList into this tree.
7206/// If info->fIsFirst is true, first we clone this TTree info the directory
7207/// info->fOutputDirectory and then overlay the new TTree information onto
7208/// this TTree object (so that this TTree object is now the appropriate to
7209/// use for further merging).
7210/// Trees with no branches will be skipped, the branch structure
7211/// will be taken from the first non-zero-branch Tree of {this+li}
7212///
7213/// Returns the total number of entries in the merged tree.
7216{
7217 if (fBranches.IsEmpty()) {
7218 if (!li || li->IsEmpty())
7219 return 0; // Nothing to do ....
7220 // Let's find the first non-empty
7221 TIter next(li);
7222 TTree *tree;
7223 while ((tree = (TTree *)next())) {
7224 if (tree == this || tree->GetListOfBranches()->IsEmpty()) {
7225 if (gDebug > 2) {
7226 Warning("Merge","TTree %s has no branches, skipping.", tree->GetName());
7227 }
7228 continue;
7229 }
7230 // We could come from a list made up of different names, the first one still wins
7231 tree->SetName(this->GetName());
7232 auto prevEntries = tree->GetEntries();
7233 auto result = tree->Merge(li, info);
7234 if (result != prevEntries) {
7235 // If there is no additional entries, the first write was enough.
7236 tree->Write();
7237 }
7238 // Make sure things are really written out to disk before attempting any reading.
7239 info->fOutputDirectory->GetFile()->Flush();
7240 // Read back the complete info in this TTree, so that TFileMerge does not
7241 // inadvertently write the empty tree.
7242 info->fOutputDirectory->ReadTObject(this, this->GetName());
7243 return result;
7244 }
7245 return 0; // All trees have empty branches
7246 }
7247 const char *options = info ? info->fOptions.Data() : "";
7248 if (info && info->fIsFirst && info->fOutputDirectory && info->fOutputDirectory->GetFile() != GetCurrentFile()) {
7249 if (GetCurrentFile() == nullptr) {
7250 // In memory TTree, all we need to do is ... write it.
7251 SetDirectory(info->fOutputDirectory);
7253 fDirectory->WriteTObject(this);
7254 } else if (info->fOptions.Contains("fast")) {
7255 InPlaceClone(info->fOutputDirectory);
7256 } else {
7257 TDirectory::TContext ctxt(info->fOutputDirectory);
7259 TTree *newtree = CloneTree(-1, options);
7260 if (info->fIOFeatures)
7261 fIOFeatures = *(info->fIOFeatures);
7262 else
7264 if (newtree) {
7265 newtree->Write();
7266 delete newtree;
7267 }
7268 // Make sure things are really written out to disk before attempting any reading.
7269 info->fOutputDirectory->GetFile()->Flush();
7270 info->fOutputDirectory->ReadTObject(this,this->GetName());
7271 }
7272 }
7273 if (!li) return 0;
7275 // Disable the autosave as the TFileMerge keeps a list of key and deleting the underlying
7276 // key would invalidate its iteration (or require costly measure to not use the deleted keys).
7277 // Also since this is part of a merging operation, the output file is not as precious as in
7278 // the general case since the input file should still be around.
7279 fAutoSave = 0;
7280 TIter next(li);
7281 TTree *tree;
7282 while ((tree = (TTree*)next())) {
7283 if (tree==this) continue;
7284 if (!tree->InheritsFrom(TTree::Class())) {
7285 Error("Add","Attempt to add object of class: %s to a %s", tree->ClassName(), ClassName());
7287 return -1;
7288 }
7289
7290 CopyEntries(tree, -1, options, true);
7291 }
7293 return GetEntries();
7294}
7295
7296////////////////////////////////////////////////////////////////////////////////
7297/// Move a cache from a file to the current file in dir.
7298/// if src is null no operation is done, if dir is null or there is no
7299/// current file the cache is deleted.
7302{
7303 if (!src) return;
7304 TFile *dst = (dir && dir != gROOT) ? dir->GetFile() : nullptr;
7305 if (src == dst) return;
7306
7308 if (dst) {
7309 src->SetCacheRead(nullptr,this);
7310 dst->SetCacheRead(pf, this);
7311 } else {
7312 if (pf) {
7313 pf->WaitFinishPrefetch();
7314 }
7315 src->SetCacheRead(nullptr,this);
7316 delete pf;
7317 }
7318}
7319
7320////////////////////////////////////////////////////////////////////////////////
7321/// Copy the content to a new new file, update this TTree with the new
7322/// location information and attach this TTree to the new directory.
7323///
7324/// options: Indicates a basket sorting method, see TTreeCloner::TTreeCloner for
7325/// details
7326///
7327/// If new and old directory are in the same file, the data is untouched,
7328/// this "just" does a call to SetDirectory.
7329/// Equivalent to an "in place" cloning of the TTree.
7330bool TTree::InPlaceClone(TDirectory *newdirectory, const char *options)
7331{
7332 if (!newdirectory) {
7334 SetDirectory(nullptr);
7335 return true;
7336 }
7337 if (newdirectory->GetFile() == GetCurrentFile()) {
7339 return true;
7340 }
7341 TTreeCloner cloner(this, newdirectory, options);
7342 if (cloner.IsValid())
7343 return cloner.Exec();
7344 else
7345 return false;
7346}
7347
7348////////////////////////////////////////////////////////////////////////////////
7349/// Function called when loading a new class library.
7351bool TTree::Notify()
7352{
7353 TIter next(GetListOfLeaves());
7354 TLeaf* leaf = nullptr;
7355 while ((leaf = (TLeaf*) next())) {
7356 leaf->Notify();
7357 leaf->GetBranch()->Notify();
7358 }
7359 return true;
7360}
7361
7362////////////////////////////////////////////////////////////////////////////////
7363/// This function may be called after having filled some entries in a Tree.
7364/// Using the information in the existing branch buffers, it will reassign
7365/// new branch buffer sizes to optimize time and memory.
7366///
7367/// The function computes the best values for branch buffer sizes such that
7368/// the total buffer sizes is less than maxMemory and nearby entries written
7369/// at the same time.
7370/// In case the branch compression factor for the data written so far is less
7371/// than compMin, the compression is disabled.
7372///
7373/// if option ="d" an analysis report is printed.
7376{
7377 //Flush existing baskets if the file is writable
7378 if (this->GetDirectory()->IsWritable()) this->FlushBasketsImpl();
7379
7380 TString opt( option );
7381 opt.ToLower();
7382 bool pDebug = opt.Contains("d");
7383 TObjArray *leaves = this->GetListOfLeaves();
7384 Int_t nleaves = leaves->GetEntries();
7386
7387 if (nleaves == 0 || treeSize == 0) {
7388 // We're being called too early, we really have nothing to do ...
7389 return;
7390 }
7392 UInt_t bmin = 512;
7393 UInt_t bmax = 256000;
7394 Double_t memFactor = 1;
7397
7398 //we make two passes
7399 //one pass to compute the relative branch buffer sizes
7400 //a second pass to compute the absolute values
7401 for (Int_t pass =0;pass<2;pass++) {
7402 oldMemsize = 0; //to count size of baskets in memory with old buffer size
7403 newMemsize = 0; //to count size of baskets in memory with new buffer size
7404 oldBaskets = 0; //to count number of baskets with old buffer size
7405 newBaskets = 0; //to count number of baskets with new buffer size
7406 for (i=0;i<nleaves;i++) {
7407 TLeaf *leaf = (TLeaf*)leaves->At(i);
7408 TBranch *branch = leaf->GetBranch();
7409 Double_t totBytes = (Double_t)branch->GetTotBytes();
7412 if (branch->GetEntries() == 0) {
7413 // There is no data, so let's make a guess ...
7415 } else {
7416 sizeOfOneEntry = 1+(UInt_t)(totBytes / (Double_t)branch->GetEntries());
7417 }
7418 Int_t oldBsize = branch->GetBasketSize();
7421 Int_t nb = branch->GetListOfBranches()->GetEntries();
7422 if (nb > 0) {
7424 continue;
7425 }
7426 Double_t bsize = oldBsize*idealFactor*memFactor; //bsize can be very large !
7427 if (bsize < 0) bsize = bmax;
7428 if (bsize > bmax) bsize = bmax;
7430 if (pass) { // only on the second pass so that it doesn't interfere with scaling
7431 // If there is an entry offset, it will be stored in the same buffer as the object data; hence,
7432 // we must bump up the size of the branch to account for this extra footprint.
7433 // If fAutoFlush is not set yet, let's assume that it is 'in the process of being set' to
7434 // the value of GetEntries().
7435 Long64_t clusterSize = (fAutoFlush > 0) ? fAutoFlush : branch->GetEntries();
7436 if (branch->GetEntryOffsetLen()) {
7437 newBsize = newBsize + (clusterSize * sizeof(Int_t) * 2);
7438 }
7439 // We used ATLAS fully-split xAOD for testing, which is a rather unbalanced TTree, 10K branches,
7440 // with 8K having baskets smaller than 512 bytes. To achieve good I/O performance ATLAS uses auto-flush 100,
7441 // resulting in the smallest baskets being ~300-400 bytes, so this change increases their memory by about 8k*150B =~ 1MB,
7442 // at the same time it significantly reduces the number of total baskets because it ensures that all 100 entries can be
7443 // stored in a single basket (the old optimization tended to make baskets too small). In a toy example with fixed sized
7444 // structures we found a factor of 2 fewer baskets needed in the new scheme.
7445 // rounds up, increases basket size to ensure all entries fit into single basket as intended
7446 newBsize = newBsize - newBsize%512 + 512;
7447 }
7449 if (newBsize < bmin) newBsize = bmin;
7450 if (newBsize > 10000000) newBsize = bmax;
7451 if (pass) {
7452 if (pDebug) Info("OptimizeBaskets", "Changing buffer size from %6d to %6d bytes for %s\n",oldBsize,newBsize,branch->GetName());
7453 branch->SetBasketSize(newBsize);
7454 }
7456 // For this number to be somewhat accurate when newBsize is 'low'
7457 // we do not include any space for meta data in the requested size (newBsize) even-though SetBasketSize will
7458 // not let it be lower than 100+TBranch::fEntryOffsetLen.
7460 if (pass == 0) continue;
7461 //Reset the compression level in case the compression factor is small
7462 Double_t comp = 1;
7463 if (branch->GetZipBytes() > 0) comp = totBytes/Double_t(branch->GetZipBytes());
7464 if (comp > 1 && comp < minComp) {
7465 if (pDebug) Info("OptimizeBaskets", "Disabling compression for branch : %s\n",branch->GetName());
7467 }
7468 }
7469 // coverity[divide_by_zero] newMemsize can not be zero as there is at least one leaf
7471 if (memFactor > 100) memFactor = 100;
7474 static const UInt_t hardmax = 1*1024*1024*1024; // Really, really never give more than 1Gb to a single buffer.
7475
7476 // Really, really never go lower than 8 bytes (we use this number
7477 // so that the calculation of the number of basket is consistent
7478 // but in fact SetBasketSize will not let the size go below
7479 // TBranch::fEntryOffsetLen + (100 + strlen(branch->GetName())
7480 // (The 2nd part being a slight over estimate of the key length.
7481 static const UInt_t hardmin = 8;
7484 }
7485 if (pDebug) {
7486 Info("OptimizeBaskets", "oldMemsize = %d, newMemsize = %d\n",oldMemsize, newMemsize);
7487 Info("OptimizeBaskets", "oldBaskets = %d, newBaskets = %d\n",oldBaskets, newBaskets);
7488 }
7489}
7490
7491////////////////////////////////////////////////////////////////////////////////
7492/// Interface to the Principal Components Analysis class.
7493///
7494/// Create an instance of TPrincipal
7495///
7496/// Fill it with the selected variables
7497///
7498/// - if option "n" is specified, the TPrincipal object is filled with
7499/// normalized variables.
7500/// - If option "p" is specified, compute the principal components
7501/// - If option "p" and "d" print results of analysis
7502/// - If option "p" and "h" generate standard histograms
7503/// - If option "p" and "c" generate code of conversion functions
7504/// - return a pointer to the TPrincipal object. It is the user responsibility
7505/// - to delete this object.
7506/// - The option default value is "np"
7507///
7508/// see TTree::Draw for explanation of the other parameters.
7509///
7510/// The created object is named "principal" and a reference to it
7511/// is added to the list of specials Root objects.
7512/// you can retrieve a pointer to the created object via:
7513/// ~~~ {.cpp}
7514/// TPrincipal *principal =
7515/// (TPrincipal*)gROOT->GetListOfSpecials()->FindObject("principal");
7516/// ~~~
7519{
7520 GetPlayer();
7521 if (fPlayer) {
7523 }
7524 return nullptr;
7525}
7526
7527////////////////////////////////////////////////////////////////////////////////
7528/// Print a summary of the tree contents.
7529///
7530/// - If option contains "all" friend trees are also printed.
7531/// - If option contains "toponly" only the top level branches are printed.
7532/// - If option contains "clusters" information about the cluster of baskets is printed.
7533///
7534/// Wildcarding can be used to print only a subset of the branches, e.g.,
7535/// `T.Print("Elec*")` will print all branches with name starting with "Elec".
7537void TTree::Print(Option_t* option) const
7538{
7539 // We already have been visited while recursively looking
7540 // through the friends tree, let's return.
7541 if (kPrint & fFriendLockStatus) {
7542 return;
7543 }
7544 Int_t s = 0;
7545 Int_t skey = 0;
7546 if (fDirectory) {
7547 TKey* key = fDirectory->GetKey(GetName());
7548 if (key) {
7549 skey = key->GetKeylen();
7550 s = key->GetNbytes();
7551 }
7552 }
7555 if (zipBytes > 0) {
7556 total += GetTotBytes();
7557 }
7559 TTree::Class()->WriteBuffer(b, (TTree*) this);
7560 total += b.Length();
7561 Long64_t file = zipBytes + s;
7562 Float_t cx = 1;
7563 if (zipBytes) {
7564 cx = (GetTotBytes() + 0.00001) / zipBytes;
7565 }
7566 Printf("******************************************************************************");
7567 Printf("*Tree :%-10s: %-54s *", GetName(), GetTitle());
7568 Printf("*Entries : %8lld : Total = %15lld bytes File Size = %10lld *", fEntries, total, file);
7569 Printf("* : : Tree compression factor = %6.2f *", cx);
7570 Printf("******************************************************************************");
7571
7572 // Avoid many check of option validity
7573 if (!option)
7574 option = "";
7575
7576 if (strncmp(option,"clusters",std::char_traits<char>::length("clusters"))==0) {
7577 Printf("%-16s %-16s %-16s %8s %20s",
7578 "Cluster Range #", "Entry Start", "Last Entry", "Size", "Number of clusters");
7579 Int_t index= 0;
7582 bool estimated = false;
7583 bool unknown = false;
7585 Long64_t nclusters = 0;
7586 if (recordedSize > 0) {
7587 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / recordedSize);
7588 Printf("%-16d %-16lld %-16lld %8lld %10lld",
7589 ind, start, end, recordedSize, nclusters);
7590 } else {
7591 // NOTE: const_cast ... DO NOT Merge for now
7592 TClusterIterator iter((TTree*)this, start);
7593 iter.Next();
7594 auto estimated_size = iter.GetNextEntry() - start;
7595 if (estimated_size > 0) {
7596 nclusters = TMath::Ceil(static_cast<double>(1 + end - start) / estimated_size);
7597 Printf("%-16d %-16lld %-16lld %8lld %10lld (estimated)",
7598 ind, start, end, recordedSize, nclusters);
7599 estimated = true;
7600 } else {
7601 Printf("%-16d %-16lld %-16lld %8lld (unknown)",
7602 ind, start, end, recordedSize);
7603 unknown = true;
7604 }
7605 }
7606 start = end + 1;
7608 };
7609 if (fNClusterRange) {
7610 for( ; index < fNClusterRange; ++index) {
7613 }
7614 }
7616 if (unknown) {
7617 Printf("Total number of clusters: (unknown)");
7618 } else {
7619 Printf("Total number of clusters: %lld %s", totalClusters, estimated ? "(estimated)" : "");
7620 }
7621 return;
7622 }
7623
7624 Int_t nl = const_cast<TTree*>(this)->GetListOfLeaves()->GetEntries();
7625 Int_t l;
7626 TBranch* br = nullptr;
7627 TLeaf* leaf = nullptr;
7628 if (strstr(option, "toponly")) {
7629 Long64_t *count = new Long64_t[nl];
7630 Int_t keep =0;
7631 for (l=0;l<nl;l++) {
7632 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7633 br = leaf->GetBranch();
7634 // branch is its own (top level) mother only for the top level branches.
7635 if (br != br->GetMother()) {
7636 count[l] = -1;
7637 count[keep] += br->GetZipBytes();
7638 } else {
7639 keep = l;
7640 count[keep] = br->GetZipBytes();
7641 }
7642 }
7643 for (l=0;l<nl;l++) {
7644 if (count[l] < 0) continue;
7645 leaf = (TLeaf *)const_cast<TTree*>(this)->GetListOfLeaves()->At(l);
7646 br = leaf->GetBranch();
7647 Printf("branch: %-20s %9lld",br->GetName(),count[l]);
7648 }
7649 delete [] count;
7650 } else {
7651 TString reg = "*";
7652 if (strlen(option) && strchr(option,'*')) reg = option;
7653 TRegexp re(reg,true);
7654 TIter next(const_cast<TTree*>(this)->GetListOfBranches());
7656 while ((br= (TBranch*)next())) {
7657 TString st = br->GetName();
7658 st.ReplaceAll("/","_");
7659 if (st.Index(re) == kNPOS) continue;
7660 br->Print(option);
7661 }
7662 }
7663
7664 //print TRefTable (if one)
7666
7667 //print friends if option "all"
7668 if (!fFriends || !strstr(option,"all")) return;
7670 TFriendLock lock(const_cast<TTree*>(this),kPrint);
7671 TFriendElement *fr;
7672 while ((fr = (TFriendElement*)nextf())) {
7673 TTree * t = fr->GetTree();
7674 if (t) t->Print(option);
7675 }
7676}
7677
7678////////////////////////////////////////////////////////////////////////////////
7679/// Print statistics about the TreeCache for this tree.
7680/// Like:
7681/// ~~~ {.cpp}
7682/// ******TreeCache statistics for file: cms2.root ******
7683/// Reading 73921562 bytes in 716 transactions
7684/// Average transaction = 103.242405 Kbytes
7685/// Number of blocks in current cache: 202, total size : 6001193
7686/// ~~~
7687/// if option = "a" the list of blocks in the cache is printed
7690{
7691 TFile *f = GetCurrentFile();
7692 if (!f) return;
7694 if (tc) tc->Print(option);
7695}
7696
7697////////////////////////////////////////////////////////////////////////////////
7698/// Process this tree executing the TSelector code in the specified filename.
7699/// The return value is -1 in case of error and TSelector::GetStatus() in
7700/// in case of success.
7701///
7702/// The code in filename is loaded (interpreted or compiled, see below),
7703/// filename must contain a valid class implementation derived from TSelector,
7704/// where TSelector has the following member functions:
7705///
7706/// - `Begin()`: called every time a loop on the tree starts,
7707/// a convenient place to create your histograms.
7708/// - `SlaveBegin()`: called after Begin()
7709/// - `Process()`: called for each event, in this function you decide what
7710/// to read and fill your histograms.
7711/// - `SlaveTerminate()`: called at the end of the loop on the tree
7712/// - `Terminate()`: called at the end of the loop on the tree,
7713/// a convenient place to draw/fit your histograms.
7714///
7715/// If filename is of the form file.C, the file will be interpreted.
7716///
7717/// If filename is of the form file.C++, the file file.C will be compiled
7718/// and dynamically loaded.
7719///
7720/// If filename is of the form file.C+, the file file.C will be compiled
7721/// and dynamically loaded. At next call, if file.C is older than file.o
7722/// and file.so, the file.C is not compiled, only file.so is loaded.
7723///
7724/// ## NOTE1
7725///
7726/// It may be more interesting to invoke directly the other Process function
7727/// accepting a TSelector* as argument.eg
7728/// ~~~ {.cpp}
7729/// MySelector *selector = (MySelector*)TSelector::GetSelector(filename);
7730/// selector->CallSomeFunction(..);
7731/// mytree.Process(selector,..);
7732/// ~~~
7733/// ## NOTE2
7734//
7735/// One should not call this function twice with the same selector file
7736/// in the same script. If this is required, proceed as indicated in NOTE1,
7737/// by getting a pointer to the corresponding TSelector,eg
7738///
7739/// ### Workaround 1
7740///
7741/// ~~~ {.cpp}
7742/// void stubs1() {
7743/// TSelector *selector = TSelector::GetSelector("h1test.C");
7744/// TFile *f1 = new TFile("stubs_nood_le1.root");
7745/// TTree *h1 = (TTree*)f1->Get("h1");
7746/// h1->Process(selector);
7747/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7748/// TTree *h2 = (TTree*)f2->Get("h1");
7749/// h2->Process(selector);
7750/// }
7751/// ~~~
7752/// or use ACLIC to compile the selector
7753///
7754/// ### Workaround 2
7755///
7756/// ~~~ {.cpp}
7757/// void stubs2() {
7758/// TFile *f1 = new TFile("stubs_nood_le1.root");
7759/// TTree *h1 = (TTree*)f1->Get("h1");
7760/// h1->Process("h1test.C+");
7761/// TFile *f2 = new TFile("stubs_nood_le1_coarse.root");
7762/// TTree *h2 = (TTree*)f2->Get("h1");
7763/// h2->Process("h1test.C+");
7764/// }
7765/// ~~~
7768{
7769 GetPlayer();
7770 if (fPlayer) {
7772 }
7773 return -1;
7774}
7775
7776////////////////////////////////////////////////////////////////////////////////
7777/// Process this tree executing the code in the specified selector.
7778/// The return value is -1 in case of error and TSelector::GetStatus() in
7779/// in case of success.
7780///
7781/// The TSelector class has the following member functions:
7782///
7783/// - `Begin()`: called every time a loop on the tree starts,
7784/// a convenient place to create your histograms.
7785/// - `SlaveBegin()`: called after Begin()
7786/// - `Process()`: called for each event, in this function you decide what
7787/// to read and fill your histograms.
7788/// - `SlaveTerminate()`: called at the end of the loop on the tree
7789/// - `Terminate()`: called at the end of the loop on the tree,
7790/// a convenient place to draw/fit your histograms.
7791///
7792/// If the Tree (Chain) has an associated EventList, the loop is on the nentries
7793/// of the EventList, starting at firstentry, otherwise the loop is on the
7794/// specified Tree entries.
7797{
7798 GetPlayer();
7799 if (fPlayer) {
7800 return fPlayer->Process(selector, option, nentries, firstentry);
7801 }
7802 return -1;
7803}
7804
7805////////////////////////////////////////////////////////////////////////////////
7806/// Make a projection of a tree using selections.
7807///
7808/// Depending on the value of varexp (described in Draw) a 1-D, 2-D, etc.,
7809/// projection of the tree will be filled in histogram hname.
7810/// Note that the dimension of hname must match with the dimension of varexp.
7811///
7814{
7815 TString var;
7816 var.Form("%s>>%s", varexp, hname);
7817 TString opt("goff");
7818 if (option) {
7819 opt.Form("%sgoff", option);
7820 }
7822 return nsel;
7823}
7824
7825////////////////////////////////////////////////////////////////////////////////
7826/// Loop over entries and return a TSQLResult object containing entries following selection.
7829{
7830 GetPlayer();
7831 if (fPlayer) {
7833 }
7834 return nullptr;
7835}
7836
7837////////////////////////////////////////////////////////////////////////////////
7838/// Create or simply read branches from filename.
7839///
7840/// if branchDescriptor = "" (default), it is assumed that the Tree descriptor
7841/// is given in the first line of the file with a syntax like
7842/// ~~~ {.cpp}
7843/// A/D:Table[2]/F:Ntracks/I:astring/C
7844/// ~~~
7845/// otherwise branchDescriptor must be specified with the above syntax.
7846/// See all available datatypes [here](\ref addcolumnoffundamentaltypes).
7847///
7848/// - If the type of the first variable is not specified, it is assumed to be "/F"
7849/// - If the type of any other variable is not specified, the type of the previous
7850/// variable is assumed. eg
7851/// - `x:y:z` (all variables are assumed of type "F")
7852/// - `x/D:y:z` (all variables are of type "D")
7853/// - `x:y/D:z` (x is type "F", y and z of type "D")
7854///
7855/// delimiter allows for the use of another delimiter besides whitespace.
7856/// This provides support for direct import of common data file formats
7857/// like csv. If delimiter != ' ' and branchDescriptor == "", then the
7858/// branch description is taken from the first line in the file, but
7859/// delimiter is used for the branch names tokenization rather than ':'.
7860/// Note however that if the values in the first line do not use the
7861/// /[type] syntax, all variables are assumed to be of type "F".
7862/// If the filename ends with extensions .csv or .CSV and a delimiter is
7863/// not specified (besides ' '), the delimiter is automatically set to ','.
7864///
7865/// Lines in the input file starting with "#" are ignored. Leading whitespace
7866/// for each column data is skipped. Empty lines are skipped.
7867///
7868/// A TBranch object is created for each variable in the expression.
7869/// The total number of rows read from the file is returned.
7870///
7871/// ## FILLING a TTree WITH MULTIPLE INPUT TEXT FILES
7872///
7873/// To fill a TTree with multiple input text files, proceed as indicated above
7874/// for the first input file and omit the second argument for subsequent calls
7875/// ~~~ {.cpp}
7876/// T.ReadFile("file1.dat","branch descriptor");
7877/// T.ReadFile("file2.dat");
7878/// ~~~
7880Long64_t TTree::ReadFile(const char* filename, const char* branchDescriptor, char delimiter)
7881{
7882 if (!filename || !*filename) {
7883 Error("ReadFile","File name not specified");
7884 return 0;
7885 }
7886
7887 std::ifstream in;
7888 in.open(filename);
7889 if (!in.good()) {
7890 Error("ReadFile","Cannot open file: %s",filename);
7891 return 0;
7892 }
7893 const char* ext = strrchr(filename, '.');
7894 if(ext && ((strcmp(ext, ".csv") == 0) || (strcmp(ext, ".CSV") == 0)) && delimiter == ' ') {
7895 delimiter = ',';
7896 }
7898}
7899
7900////////////////////////////////////////////////////////////////////////////////
7901/// Determine which newline this file is using.
7902/// Return '\\r' for Windows '\\r\\n' as that already terminates.
7904char TTree::GetNewlineValue(std::istream &inputStream)
7905{
7906 Long_t inPos = inputStream.tellg();
7907 char newline = '\n';
7908 while(true) {
7909 char c = 0;
7910 inputStream.get(c);
7911 if(!inputStream.good()) {
7912 Error("ReadStream","Error reading stream: no newline found.");
7913 return 0;
7914 }
7915 if(c == newline) break;
7916 if(c == '\r') {
7917 newline = '\r';
7918 break;
7919 }
7920 }
7921 inputStream.clear();
7922 inputStream.seekg(inPos);
7923 return newline;
7924}
7925
7926////////////////////////////////////////////////////////////////////////////////
7927/// Create or simply read branches from an input stream.
7928///
7929/// \see TTree::ReadFile
7931Long64_t TTree::ReadStream(std::istream& inputStream, const char *branchDescriptor, char delimiter)
7932{
7933 char newline = 0;
7934 std::stringstream ss;
7935 std::istream *inTemp;
7936 Long_t inPos = inputStream.tellg();
7937 if (!inputStream.good()) {
7938 Error("ReadStream","Error reading stream");
7939 return 0;
7940 }
7941 if (inPos == -1) {
7942 ss << std::cin.rdbuf();
7944 inTemp = &ss;
7945 } else {
7948 }
7949 std::istream& in = *inTemp;
7950 Long64_t nlines = 0;
7951
7952 TBranch *branch = nullptr;
7954 if (nbranches == 0) {
7955 char *bdname = new char[4000];
7956 char *bd = new char[100000];
7957 Int_t nch = 0;
7959 // branch Descriptor is null, read its definition from the first line in the file
7960 if (!nch) {
7961 do {
7962 in.getline(bd, 100000, newline);
7963 if (!in.good()) {
7964 delete [] bdname;
7965 delete [] bd;
7966 Error("ReadStream","Error reading stream");
7967 return 0;
7968 }
7969 char *cursor = bd;
7970 while( isspace(*cursor) && *cursor != '\n' && *cursor != '\0') {
7971 ++cursor;
7972 }
7973 if (*cursor != '#' && *cursor != '\n' && *cursor != '\0') {
7974 break;
7975 }
7976 } while (true);
7977 ++nlines;
7978 nch = strlen(bd);
7979 } else {
7980 strlcpy(bd,branchDescriptor,100000);
7981 }
7982
7983 //parse the branch descriptor and create a branch for each element
7984 //separated by ":"
7985 void *address = &bd[90000];
7986 char *bdcur = bd;
7987 TString desc="", olddesc="F";
7988 char bdelim = ':';
7989 if(delimiter != ' ') {
7990 bdelim = delimiter;
7991 if (strchr(bdcur,bdelim)==nullptr && strchr(bdcur,':') != nullptr) {
7992 // revert to the default
7993 bdelim = ':';
7994 }
7995 }
7996 while (bdcur) {
7997 char *colon = strchr(bdcur,bdelim);
7998 if (colon) *colon = 0;
7999 strlcpy(bdname,bdcur,4000);
8000 char *slash = strchr(bdname,'/');
8001 if (slash) {
8002 *slash = 0;
8003 desc = bdcur;
8004 olddesc = slash+1;
8005 } else {
8006 desc.Form("%s/%s",bdname,olddesc.Data());
8007 }
8008 char *bracket = strchr(bdname,'[');
8009 if (bracket) {
8010 *bracket = 0;
8011 }
8012 branch = new TBranch(this,bdname,address,desc.Data(),32000);
8013 if (branch->IsZombie()) {
8014 delete branch;
8015 Warning("ReadStream","Illegal branch definition: %s",bdcur);
8016 } else {
8018 branch->SetAddress(nullptr);
8019 }
8020 if (!colon)break;
8021 bdcur = colon+1;
8022 }
8023 delete [] bdname;
8024 delete [] bd;
8025 }
8026
8028
8029 if (gDebug > 1) {
8030 Info("ReadStream", "Will use branches:");
8031 for (int i = 0 ; i < nbranches; ++i) {
8032 TBranch* br = (TBranch*) fBranches.At(i);
8033 Info("ReadStream", " %s: %s [%s]", br->GetName(),
8034 br->GetTitle(), br->GetListOfLeaves()->At(0)->IsA()->GetName());
8035 }
8036 if (gDebug > 3) {
8037 Info("ReadStream", "Dumping read tokens, format:");
8038 Info("ReadStream", "LLLLL:BBB:gfbe:GFBE:T");
8039 Info("ReadStream", " L: line number");
8040 Info("ReadStream", " B: branch number");
8041 Info("ReadStream", " gfbe: good / fail / bad / eof of token");
8042 Info("ReadStream", " GFBE: good / fail / bad / eof of file");
8043 Info("ReadStream", " T: Token being read");
8044 }
8045 }
8046
8047 //loop on all lines in the file
8048 Long64_t nGoodLines = 0;
8049 std::string line;
8050 const char sDelimBuf[2] = { delimiter, 0 };
8051 const char* sDelim = sDelimBuf;
8052 if (delimiter == ' ') {
8053 // ' ' really means whitespace
8054 sDelim = "[ \t]";
8055 }
8056 while(in.good()) {
8057 if (newline == '\r' && in.peek() == '\n') {
8058 // Windows, skip '\n':
8059 in.get();
8060 }
8061 std::getline(in, line, newline);
8062 ++nlines;
8063
8065 sLine = sLine.Strip(TString::kLeading); // skip leading whitespace
8066 if (sLine.IsNull()) {
8067 if (gDebug > 2) {
8068 Info("ReadStream", "Skipping empty line number %lld", nlines);
8069 }
8070 continue; // silently skip empty lines
8071 }
8072 if (sLine[0] == '#') {
8073 if (gDebug > 2) {
8074 Info("ReadStream", "Skipping comment line number %lld: '%s'",
8075 nlines, line.c_str());
8076 }
8077 continue;
8078 }
8079 if (gDebug > 2) {
8080 Info("ReadStream", "Parsing line number %lld: '%s'",
8081 nlines, line.c_str());
8082 }
8083
8084 // Loop on branches and read the branch values into their buffer
8085 branch = nullptr;
8086 TString tok; // one column's data
8087 TString leafData; // leaf data, possibly multiple tokens for e.g. /I[2]
8088 std::stringstream sToken; // string stream feeding leafData into leaves
8089 Ssiz_t pos = 0;
8090 Int_t iBranch = 0;
8091 bool goodLine = true; // whether the row can be filled into the tree
8092 Int_t remainingLeafLen = 0; // remaining columns for the current leaf
8093 while (goodLine && iBranch < nbranches
8094 && sLine.Tokenize(tok, pos, sDelim)) {
8095 tok = tok.Strip(TString::kLeading); // skip leading whitespace
8096 if (tok.IsNull() && delimiter == ' ') {
8097 // 1 2 should not be interpreted as 1,,,2 but 1, 2.
8098 // Thus continue until we have a non-empty token.
8099 continue;
8100 }
8101
8102 if (!remainingLeafLen) {
8103 // next branch!
8105 }
8106 TLeaf *leaf = (TLeaf*)branch->GetListOfLeaves()->At(0);
8107 if (!remainingLeafLen) {
8108 remainingLeafLen = leaf->GetLen();
8109 if (leaf->GetMaximum() > 0) {
8110 // This is a dynamic leaf length, i.e. most likely a TLeafC's
8111 // string size. This still translates into one token:
8112 remainingLeafLen = 1;
8113 }
8114
8115 leafData = tok;
8116 } else {
8117 // append token to laf data:
8118 leafData += " ";
8119 leafData += tok;
8120 }
8122 if (remainingLeafLen) {
8123 // need more columns for this branch:
8124 continue;
8125 }
8126 ++iBranch;
8127
8128 // initialize stringstream with token
8129 sToken.clear();
8130 sToken.seekp(0, std::ios_base::beg);
8131 sToken.str(leafData.Data());
8132 sToken.seekg(0, std::ios_base::beg);
8133 leaf->ReadValue(sToken, 0 /* 0 = "all" */);
8134 if (gDebug > 3) {
8135 Info("ReadStream", "%5lld:%3d:%d%d%d%d:%d%d%d%d:%s",
8136 nlines, iBranch,
8137 (int)sToken.good(), (int)sToken.fail(),
8138 (int)sToken.bad(), (int)sToken.eof(),
8139 (int)in.good(), (int)in.fail(),
8140 (int)in.bad(), (int)in.eof(),
8141 sToken.str().c_str());
8142 }
8143
8144 // Error handling
8145 if (sToken.bad()) {
8146 // How could that happen for a stringstream?
8147 Warning("ReadStream",
8148 "Buffer error while reading data for branch %s on line %lld",
8149 branch->GetName(), nlines);
8150 } else if (!sToken.eof()) {
8151 if (sToken.fail()) {
8152 Warning("ReadStream",
8153 "Couldn't read formatted data in \"%s\" for branch %s on line %lld; ignoring line",
8154 tok.Data(), branch->GetName(), nlines);
8155 goodLine = false;
8156 } else {
8157 std::string remainder;
8158 std::getline(sToken, remainder, newline);
8159 if (!remainder.empty()) {
8160 Warning("ReadStream",
8161 "Ignoring trailing \"%s\" while reading data for branch %s on line %lld",
8162 remainder.c_str(), branch->GetName(), nlines);
8163 }
8164 }
8165 }
8166 } // tokenizer loop
8167
8168 if (iBranch < nbranches) {
8169 Warning("ReadStream",
8170 "Read too few columns (%d < %d) in line %lld; ignoring line",
8172 goodLine = false;
8173 } else if (pos != kNPOS) {
8175 if (pos < sLine.Length()) {
8176 Warning("ReadStream",
8177 "Ignoring trailing \"%s\" while reading line %lld",
8178 sLine.Data() + pos - 1 /* also print delimiter */,
8179 nlines);
8180 }
8181 }
8182
8183 //we are now ready to fill the tree
8184 if (goodLine) {
8185 Fill();
8186 ++nGoodLines;
8187 }
8188 }
8189
8190 return nGoodLines;
8191}
8192
8193////////////////////////////////////////////////////////////////////////////////
8194/// Make sure that obj (which is being deleted or will soon be) is no
8195/// longer referenced by this TTree.
8198{
8199 if (obj == fEventList) {
8200 fEventList = nullptr;
8201 }
8202 if (obj == fEntryList) {
8203 fEntryList = nullptr;
8204 }
8205 if (fUserInfo) {
8207 }
8208 if (fPlayer == obj) {
8209 fPlayer = nullptr;
8210 }
8211 if (fTreeIndex == obj) {
8212 fTreeIndex = nullptr;
8213 }
8214 if (fAliases == obj) {
8215 fAliases = nullptr;
8216 } else if (fAliases) {
8218 }
8219 if (fFriends == obj) {
8220 fFriends = nullptr;
8221 } else if (fFriends) {
8223 }
8224}
8225
8226////////////////////////////////////////////////////////////////////////////////
8227/// Refresh contents of this tree and its branches from the current status on disk.
8228///
8229/// One can call this function in case the tree file is being
8230/// updated by another process.
8232void TTree::Refresh()
8233{
8234 if (!fDirectory->GetFile()) {
8235 return;
8236 }
8238 fDirectory->Remove(this);
8239 TTree* tree; fDirectory->GetObject(GetName(),tree);
8240 if (!tree) {
8241 return;
8242 }
8243 //copy info from tree header into this Tree
8244 fEntries = 0;
8245 fNClusterRange = 0;
8246 ImportClusterRanges(tree);
8247
8248 fAutoSave = tree->fAutoSave;
8249 fEntries = tree->fEntries;
8250 fTotBytes = tree->GetTotBytes();
8251 fZipBytes = tree->GetZipBytes();
8252 fSavedBytes = tree->fSavedBytes;
8253 fTotalBuffers = tree->fTotalBuffers.load();
8254
8255 //loop on all branches and update them
8257 for (Int_t i = 0; i < nleaves; i++) {
8259 TBranch* branch = (TBranch*) leaf->GetBranch();
8260 branch->Refresh(tree->GetBranch(branch->GetName()));
8261 }
8262 fDirectory->Remove(tree);
8263 fDirectory->Append(this);
8264 delete tree;
8265 tree = nullptr;
8266}
8267
8268////////////////////////////////////////////////////////////////////////////////
8269/// Record a TFriendElement that we need to warn when the chain switches to
8270/// a new file (typically this is because this chain is a friend of another
8271/// TChain)
8278}
8279
8280
8281////////////////////////////////////////////////////////////////////////////////
8282/// Removes external friend
8287}
8288
8289
8290////////////////////////////////////////////////////////////////////////////////
8291/// Remove a friend from the list of friends.
8294{
8295 // We already have been visited while recursively looking
8296 // through the friends tree, let return
8298 return;
8299 }
8300 if (!fFriends) {
8301 return;
8302 }
8303 TFriendLock lock(this, kRemoveFriend);
8305 TFriendElement* fe = nullptr;
8306 while ((fe = (TFriendElement*) nextf())) {
8307 TTree* friend_t = fe->GetTree();
8308 if (friend_t == oldFriend) {
8309 fFriends->Remove(fe);
8310 delete fe;
8311 fe = nullptr;
8312 }
8313 }
8314}
8315
8316////////////////////////////////////////////////////////////////////////////////
8317/// Reset baskets, buffers and entries count in all branches and leaves.
8320{
8321 fNotify = nullptr;
8322 fEntries = 0;
8323 fNClusterRange = 0;
8324 fTotBytes = 0;
8325 fZipBytes = 0;
8326 fFlushedBytes = 0;
8327 fSavedBytes = 0;
8328 fTotalBuffers = 0;
8329 fChainOffset = 0;
8330 fReadEntry = -1;
8331
8332 delete fTreeIndex;
8333 fTreeIndex = nullptr;
8334
8336 for (Int_t i = 0; i < nb; ++i) {
8338 branch->Reset(option);
8339 }
8340
8341 if (fBranchRef) {
8342 fBranchRef->Reset();
8343 }
8344}
8345
8346////////////////////////////////////////////////////////////////////////////////
8347/// Resets the state of this TTree after a merge (keep the customization but
8348/// forget the data).
8351{
8352 fEntries = 0;
8353 fNClusterRange = 0;
8354 fTotBytes = 0;
8355 fZipBytes = 0;
8356 fSavedBytes = 0;
8357 fFlushedBytes = 0;
8358 fTotalBuffers = 0;
8359 fChainOffset = 0;
8360 fReadEntry = -1;
8361
8362 delete fTreeIndex;
8363 fTreeIndex = nullptr;
8364
8366 for (Int_t i = 0; i < nb; ++i) {
8368 branch->ResetAfterMerge(info);
8369 }
8370
8371 if (fBranchRef) {
8373 }
8374}
8375
8376////////////////////////////////////////////////////////////////////////////////
8377/// Tell a branch to set its address to zero.
8378///
8379/// @note If the branch owns any objects, they are deleted.
8382{
8383 if (br && br->GetTree()) {
8384 br->ResetAddress();
8385 }
8386}
8387
8388////////////////////////////////////////////////////////////////////////////////
8389/// Tell all of our branches to drop their current objects and allocate new ones.
8392{
8393 // We already have been visited while recursively looking
8394 // through the friends tree, let return
8396 return;
8397 }
8399 Int_t nbranches = branches->GetEntriesFast();
8400 for (Int_t i = 0; i < nbranches; ++i) {
8401 TBranch* branch = (TBranch*) branches->UncheckedAt(i);
8402 branch->ResetAddress();
8403 }
8404 if (fFriends) {
8407 auto *frTree = frEl->GetTree();
8408 if (frTree) {
8409 frTree->ResetBranchAddresses();
8410 }
8411 }
8412 }
8413}
8414
8415////////////////////////////////////////////////////////////////////////////////
8416/// Loop over tree entries and print entries passing selection. Interactive
8417/// pagination break is on by default.
8418///
8419/// - If varexp is 0 (or "") then print only first 8 columns.
8420/// - If varexp = "*" print all columns.
8421///
8422/// Otherwise a columns selection can be made using "var1:var2:var3".
8423///
8424/// \param firstentry first entry to scan
8425/// \param nentries total number of entries to scan (starting from firstentry). Defaults to all entries.
8426/// \note see TTree::SetScanField to control how many lines are printed between pagination breaks (Use 0 to disable pagination)
8427/// \see TTreePlayer::Scan, TTreePlayer::SetScanFileName, TTreePlayer::SetScanRedirect
8430{
8431 GetPlayer();
8432 if (fPlayer) {
8434 }
8435 return -1;
8436}
8437
8438////////////////////////////////////////////////////////////////////////////////
8439/// Set a tree variable alias.
8440///
8441/// Set an alias for an expression/formula based on the tree 'variables'.
8442///
8443/// The content of 'aliasName' can be used in TTreeFormula (i.e. TTree::Draw,
8444/// TTree::Scan, TTreeViewer) and will be evaluated as the content of
8445/// 'aliasFormula'.
8446///
8447/// If the content of 'aliasFormula' only contains symbol names, periods and
8448/// array index specification (for example event.fTracks[3]), then
8449/// the content of 'aliasName' can be used as the start of symbol.
8450///
8451/// If the alias 'aliasName' already existed, it is replaced by the new
8452/// value.
8453///
8454/// When being used, the alias can be preceded by an eventual 'Friend Alias'
8455/// (see TTree::GetFriendAlias)
8456///
8457/// Return true if it was added properly.
8458///
8459/// For example:
8460/// ~~~ {.cpp}
8461/// tree->SetAlias("x1","(tdc1[1]-tdc1[0])/49");
8462/// tree->SetAlias("y1","(tdc1[3]-tdc1[2])/47");
8463/// tree->SetAlias("x2","(tdc2[1]-tdc2[0])/49");
8464/// tree->SetAlias("y2","(tdc2[3]-tdc2[2])/47");
8465/// tree->Draw("y2-y1:x2-x1");
8466///
8467/// tree->SetAlias("theGoodTrack","event.fTracks[3]");
8468/// tree->Draw("theGoodTrack.fPx"); // same as "event.fTracks[3].fPx"
8469/// ~~~
8471bool TTree::SetAlias(const char* aliasName, const char* aliasFormula)
8472{
8473 if (!aliasName || !aliasFormula) {
8474 return false;
8475 }
8476 if (!aliasName[0] || !aliasFormula[0]) {
8477 return false;
8478 }
8479 if (!fAliases) {
8480 fAliases = new TList;
8481 } else {
8483 if (oldHolder) {
8484 oldHolder->SetTitle(aliasFormula);
8485 return true;
8486 }
8487 }
8490 return true;
8491}
8492
8493////////////////////////////////////////////////////////////////////////////////
8494/// This function may be called at the start of a program to change
8495/// the default value for fAutoFlush.
8496///
8497/// ### CASE 1 : autof > 0
8498///
8499/// autof is the number of consecutive entries after which TTree::Fill will
8500/// flush all branch buffers to disk.
8501///
8502/// ### CASE 2 : autof < 0
8503///
8504/// When filling the Tree the branch buffers will be flushed to disk when
8505/// more than autof bytes have been written to the file. At the first FlushBaskets
8506/// TTree::Fill will replace fAutoFlush by the current value of fEntries.
8507///
8508/// Calling this function with autof<0 is interesting when it is hard to estimate
8509/// the size of one entry. This value is also independent of the Tree.
8510///
8511/// The Tree is initialized with fAutoFlush=-30000000, ie that, by default,
8512/// the first AutoFlush will be done when 30 MBytes of data are written to the file.
8513///
8514/// ### CASE 3 : autof = 0
8515///
8516/// The AutoFlush mechanism is disabled.
8517///
8518/// Flushing the buffers at regular intervals optimize the location of
8519/// consecutive entries on the disk by creating clusters of baskets.
8520///
8521/// A cluster of baskets is a set of baskets that contains all
8522/// the data for a (consecutive) set of entries and that is stored
8523/// consecutively on the disk. When reading all the branches, this
8524/// is the minimum set of baskets that the TTreeCache will read.
8526void TTree::SetAutoFlush(Long64_t autof /* = -30000000 */ )
8527{
8528 // Implementation note:
8529 //
8530 // A positive value of autoflush determines the size (in number of entries) of
8531 // a cluster of baskets.
8532 //
8533 // If the value of autoflush is changed over time (this happens in
8534 // particular when the TTree results from fast merging many trees),
8535 // we record the values of fAutoFlush in the data members:
8536 // fClusterRangeEnd and fClusterSize.
8537 // In the code we refer to a range of entries where the size of the
8538 // cluster of baskets is the same (i.e the value of AutoFlush was
8539 // constant) is called a ClusterRange.
8540 //
8541 // The 2 arrays (fClusterRangeEnd and fClusterSize) have fNClusterRange
8542 // active (used) values and have fMaxClusterRange allocated entries.
8543 //
8544 // fClusterRangeEnd contains the last entries number of a cluster range.
8545 // In particular this means that the 'next' cluster starts at fClusterRangeEnd[]+1
8546 // fClusterSize contains the size in number of entries of all the cluster
8547 // within the given range.
8548 // The last range (and the only one if fNClusterRange is zero) start at
8549 // fNClusterRange[fNClusterRange-1]+1 and ends at the end of the TTree. The
8550 // size of the cluster in this range is given by the value of fAutoFlush.
8551 //
8552 // For example printing the beginning and end of each the ranges can be done by:
8553 //
8554 // Printf("%-16s %-16s %-16s %5s",
8555 // "Cluster Range #", "Entry Start", "Last Entry", "Size");
8556 // Int_t index= 0;
8557 // Long64_t clusterRangeStart = 0;
8558 // if (fNClusterRange) {
8559 // for( ; index < fNClusterRange; ++index) {
8560 // Printf("%-16d %-16lld %-16lld %5lld",
8561 // index, clusterRangeStart, fClusterRangeEnd[index], fClusterSize[index]);
8562 // clusterRangeStart = fClusterRangeEnd[index] + 1;
8563 // }
8564 // }
8565 // Printf("%-16d %-16lld %-16lld %5lld",
8566 // index, prevEntry, fEntries - 1, fAutoFlush);
8567 //
8568
8569 // Note: We store the entry number corresponding to the end of the cluster
8570 // rather than its start in order to avoid using the array if the cluster
8571 // size never varies (If there is only one value of AutoFlush for the whole TTree).
8572
8573 if( fAutoFlush != autof) {
8574 if ((fAutoFlush > 0 || autof > 0) && fFlushedBytes) {
8575 // The mechanism was already enabled, let's record the previous
8576 // cluster if needed.
8578 }
8579 fAutoFlush = autof;
8580 }
8581}
8582
8583////////////////////////////////////////////////////////////////////////////////
8584/// Mark the previous event as being at the end of the event cluster.
8585///
8586/// So, if fEntries is set to 10 (and this is the first cluster) when MarkEventCluster
8587/// is called, then the first cluster has 9 events.
8589{
8590 if (!fEntries) return;
8591
8592 if ( (fNClusterRange+1) > fMaxClusterRange ) {
8593 if (fMaxClusterRange) {
8594 // Resize arrays to hold a larger event cluster.
8597 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8599 newsize*sizeof(Long64_t),fMaxClusterRange*sizeof(Long64_t));
8601 } else {
8602 // Cluster ranges have never been initialized; create them now.
8603 fMaxClusterRange = 2;
8606 }
8607 }
8609 // If we are auto-flushing, then the cluster size is the same as the current auto-flush setting.
8610 if (fAutoFlush > 0) {
8611 // Even if the user triggers MarkEventRange prior to fAutoFlush being present, the TClusterIterator
8612 // will appropriately go to the next event range.
8614 // Otherwise, assume there is one cluster per event range (e.g., user is manually controlling the flush).
8615 } else if (fNClusterRange == 0) {
8617 } else {
8619 }
8621}
8622
8623/// Estimate the median cluster size for the TTree.
8624/// This value provides e.g. a reasonable cache size default if other heuristics fail.
8625/// Clusters with size 0 and the very last cluster range, that might not have been committed to fClusterSize yet,
8626/// are ignored for the purposes of the calculation.
8628{
8629 std::vector<Long64_t> clusterSizesPerRange;
8631
8632 // We ignore cluster sizes of 0 for the purposes of this function.
8633 // We also ignore the very last cluster range which might not have been committed to fClusterSize.
8634 std::copy_if(fClusterSize, fClusterSize + fNClusterRange, std::back_inserter(clusterSizesPerRange),
8635 [](Long64_t size) { return size != 0; });
8636
8637 std::vector<double> nClustersInRange; // we need to store doubles because of the signature of TMath::Median
8638 nClustersInRange.reserve(clusterSizesPerRange.size());
8639
8640 auto clusterRangeStart = 0ll;
8641 for (int i = 0; i < fNClusterRange; ++i) {
8642 const auto size = fClusterSize[i];
8643 R__ASSERT(size >= 0);
8644 if (fClusterSize[i] == 0)
8645 continue;
8646 const auto nClusters = (1 + fClusterRangeEnd[i] - clusterRangeStart) / fClusterSize[i];
8647 nClustersInRange.emplace_back(nClusters);
8649 }
8650
8652 const auto medianClusterSize =
8654 return medianClusterSize;
8655}
8656
8657////////////////////////////////////////////////////////////////////////////////
8658/// In case of a program crash, it will be possible to recover the data in the
8659/// tree up to the last AutoSave point.
8660/// This function may be called before filling a TTree to specify when the
8661/// branch buffers and TTree header are flushed to disk as part of
8662/// TTree::Fill().
8663/// The default is -300000000, ie the TTree will write data to disk once it
8664/// exceeds 300 MBytes.
8665/// CASE 1: If fAutoSave is positive the watermark is reached when a multiple of
8666/// fAutoSave entries have been filled.
8667/// CASE 2: If fAutoSave is negative the watermark is reached when -fAutoSave
8668/// bytes can be written to the file.
8669/// CASE 3: If fAutoSave is 0, AutoSave() will never be called automatically
8670/// as part of TTree::Fill().
8675}
8676
8677////////////////////////////////////////////////////////////////////////////////
8678/// Set a branch's basket size.
8679///
8680/// bname is the name of a branch.
8681///
8682/// - if bname="*", apply to all branches.
8683/// - if bname="xxx*", apply to all branches with name starting with xxx
8684///
8685/// see TRegexp for wildcarding options
8686/// bufsize = branch basket size
8688void TTree::SetBasketSize(const char* bname, Int_t bufsize)
8689{
8691 TRegexp re(bname, true);
8692 Int_t nb = 0;
8693 for (Int_t i = 0; i < nleaves; i++) {
8695 TBranch* branch = (TBranch*) leaf->GetBranch();
8696 TString s = branch->GetName();
8697 if (strcmp(bname, branch->GetName()) && (s.Index(re) == kNPOS)) {
8698 continue;
8699 }
8700 nb++;
8701 branch->SetBasketSize(bufsize);
8702 }
8703 if (!nb) {
8704 Error("SetBasketSize", "unknown branch -> '%s'", bname);
8705 }
8706}
8707
8708////////////////////////////////////////////////////////////////////////////////
8709/// Change branch address, dealing with clone trees properly.
8710/// See TTree::CheckBranchAddressType for the semantic of the return value.
8711///
8712/// Note: See the comments in TBranchElement::SetAddress() for the
8713/// meaning of the addr parameter and the object ownership policy.
8715Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
8716{
8717 TBranch* branch = GetBranch(bname);
8718 if (!branch) {
8719 if (ptr) *ptr = nullptr;
8720 Error("SetBranchAddress", "unknown branch -> %s", bname);
8721 return kMissingBranch;
8722 }
8723 return SetBranchAddressImp(branch,addr,ptr);
8724}
8725
8726////////////////////////////////////////////////////////////////////////////////
8727/// Verify the validity of the type of addr before calling SetBranchAddress.
8728/// See TTree::CheckBranchAddressType for the semantic of the return value.
8729///
8730/// Note: See the comments in TBranchElement::SetAddress() for the
8731/// meaning of the addr parameter and the object ownership policy.
8733Int_t TTree::SetBranchAddress(const char* bname, void* addr, TClass* ptrClass, EDataType datatype, bool isptr)
8734{
8735 return SetBranchAddress(bname, addr, nullptr, ptrClass, datatype, isptr);
8736}
8739 bool isptr)
8740{
8741 if (auto *branchFromSelf = GetBranchFromSelf(bname)) {
8743
8744 // This will set the value of *ptr to branch.
8745 if (res >= 0) {
8746 // The check succeeded.
8747 if ((res & kNeedEnableDecomposedObj) && !branchFromSelf->GetMakeClass())
8748 branchFromSelf->SetMakeClass(true);
8750 } else {
8751 if (ptr)
8752 *ptr = nullptr;
8753 }
8754 return res;
8755 }
8756
8757 // Check friends
8758 if (fFriends) {
8759 int status{kMissingBranch};
8761 if (auto *tree = fe->GetTree()) {
8762 status = tree->SetBranchAddress(bname, addr, ptr, ptrClass, datatype, isptr, true);
8763 // We exit early from visiting all friends only if a perfect match was found
8764 if (status == kMatch)
8765 return status;
8766 }
8767 }
8768 // This allows for the valid case of friend TChain(s) which might hold
8769 // the requested branch, but might not know it yet since they haven't loaded
8770 // the tree. This is encoded in the kNoCheck == 5 value.
8771 if (status != kMissingBranch)
8772 return status;
8773 }
8774
8775 // Branch not found
8776 if (ptr)
8777 *ptr = nullptr;
8778
8779 return kMissingBranch;
8780}
8781
8782////////////////////////////////////////////////////////////////////////////////
8783/// Verify the validity of the type of addr before calling SetBranchAddress.
8784/// See TTree::CheckBranchAddressType for the semantic of the return value.
8785///
8786/// Note: See the comments in TBranchElement::SetAddress() for the
8787/// meaning of the addr parameter and the object ownership policy.
8789Int_t TTree::SetBranchAddress(const char *bname, void *addr, TBranch **ptr, TClass *ptrClass, EDataType datatype,
8790 bool isptr)
8791{
8792 auto res = SetBranchAddressImp(bname, addr, ptr, ptrClass, datatype, isptr);
8793 if (res == kMissingBranch)
8794 Error("SetBranchAddress", "unknown branch -> %s", bname);
8795 return res;
8796}
8798Int_t TTree::SetBranchAddress(const char *bname, void *addr, TBranch **ptr, TClass *ptrClass, EDataType datatype,
8799 bool isptr, bool)
8800{
8801 // This has been called while setting the branch address of friends of a TTree. We can't know a priori
8802 // which friend actually has the branch bname, so we avoid printing an error in case of missing branch
8803 return SetBranchAddressImp(bname, addr, ptr, ptrClass, datatype, isptr);
8804}
8805
8806////////////////////////////////////////////////////////////////////////////////
8807/// Change branch address, dealing with clone trees properly.
8808/// See TTree::CheckBranchAddressType for the semantic of the return value.
8809///
8810/// Note: See the comments in TBranchElement::SetAddress() for the
8811/// meaning of the addr parameter and the object ownership policy.
8814{
8815 if (ptr) {
8816 *ptr = branch;
8817 }
8818 if (fClones) {
8819 void* oldAddr = branch->GetAddress();
8820 TIter next(fClones);
8821 TTree* clone = nullptr;
8822 const char *bname = branch->GetName();
8823 while ((clone = (TTree*) next())) {
8824 TBranch* cloneBr = clone->GetBranch(bname);
8825 if (cloneBr && (cloneBr->GetAddress() == oldAddr)) {
8826 cloneBr->SetAddress(addr);
8827 }
8828 }
8829 }
8830 branch->SetAddress(addr);
8831 return kVoidPtr;
8832}
8833
8834////////////////////////////////////////////////////////////////////////////////
8835/// Set branch status to Process or DoNotProcess.
8836///
8837/// When reading a Tree, by default, all branches are read.
8838/// One can speed up considerably the analysis phase by activating
8839/// only the branches that hold variables involved in a query.
8840///
8841/// bname is the name of a branch.
8842///
8843/// - if bname="*", apply to all branches.
8844/// - if bname="xxx*", apply to all branches with name starting with xxx
8845///
8846/// see TRegexp for wildcarding options
8847///
8848/// - status = 1 branch will be processed
8849/// - = 0 branch will not be processed
8850///
8851/// Example:
8852///
8853/// Assume a tree T with sub-branches a,b,c,d,e,f,g,etc..
8854/// when doing T.GetEntry(i) all branches are read for entry i.
8855/// to read only the branches c and e, one can do
8856/// ~~~ {.cpp}
8857/// T.SetBranchStatus("*",0); //disable all branches
8858/// T.SetBranchStatus("c",1);
8859/// T.setBranchStatus("e",1);
8860/// T.GetEntry(i);
8861/// ~~~
8862/// bname is interpreted as a wild-carded TRegexp (see TRegexp::MakeWildcard).
8863/// Thus, "a*b" or "a.*b" matches branches starting with "a" and ending with
8864/// "b", but not any other branch with an "a" followed at some point by a
8865/// "b". For this second behavior, use "*a*b*". Note that TRegExp does not
8866/// support '|', and so you cannot select, e.g. track and shower branches
8867/// with "track|shower".
8868///
8869/// __WARNING! WARNING! WARNING!__
8870///
8871/// SetBranchStatus is matching the branch based on match of the branch
8872/// 'name' and not on the branch hierarchy! In order to be able to
8873/// selectively enable a top level object that is 'split' you need to make
8874/// sure the name of the top level branch is prefixed to the sub-branches'
8875/// name (by adding a dot ('.') at the end of the Branch creation and use the
8876/// corresponding bname.
8877///
8878/// I.e If your Tree has been created in split mode with a parent branch "parent."
8879/// (note the trailing dot).
8880/// ~~~ {.cpp}
8881/// T.SetBranchStatus("parent",1);
8882/// ~~~
8883/// will not activate the sub-branches of "parent". You should do:
8884/// ~~~ {.cpp}
8885/// T.SetBranchStatus("parent*",1);
8886/// ~~~
8887/// Without the trailing dot in the branch creation you have no choice but to
8888/// call SetBranchStatus explicitly for each of the sub branches.
8889///
8890/// An alternative to this function is to read directly and only
8891/// the interesting branches. Example:
8892/// ~~~ {.cpp}
8893/// TBranch *brc = T.GetBranch("c");
8894/// TBranch *bre = T.GetBranch("e");
8895/// brc->GetEntry(i);
8896/// bre->GetEntry(i);
8897/// ~~~
8898/// If found is not 0, the number of branch(es) found matching the regular
8899/// expression is returned in *found AND the error message 'unknown branch'
8900/// is suppressed.
8902void TTree::SetBranchStatus(const char* bname, bool status, UInt_t* found)
8903{
8904 // We already have been visited while recursively looking
8905 // through the friends tree, let return
8907 return;
8908 }
8909
8910 if (!bname || !*bname) {
8911 Error("SetBranchStatus", "Input regexp is an empty string: no match against branch names will be attempted.");
8912 return;
8913 }
8914
8916 TLeaf *leaf, *leafcount;
8917
8918 Int_t i,j;
8920 TRegexp re(bname,true);
8921 Int_t nb = 0;
8922
8923 // first pass, loop on all branches
8924 // for leafcount branches activate/deactivate in function of status
8925 for (i=0;i<nleaves;i++) {
8927 branch = (TBranch*)leaf->GetBranch();
8928 TString s = branch->GetName();
8929 if (strcmp(bname,"*")) { //Regexp gives wrong result for [] in name
8931 longname.Form("%s.%s",GetName(),branch->GetName());
8932 if (strcmp(bname,branch->GetName())
8933 && longname != bname
8934 && s.Index(re) == kNPOS) continue;
8935 }
8936 nb++;
8937 if (status) branch->ResetBit(kDoNotProcess);
8938 else branch->SetBit(kDoNotProcess);
8939 leafcount = leaf->GetLeafCount();
8940 if (leafcount) {
8941 bcount = leafcount->GetBranch();
8942 if (status) bcount->ResetBit(kDoNotProcess);
8943 else bcount->SetBit(kDoNotProcess);
8944 }
8945 }
8946 if (nb==0 && !strchr(bname,'*')) {
8947 branch = GetBranch(bname);
8948 if (branch) {
8949 if (status) branch->ResetBit(kDoNotProcess);
8950 else branch->SetBit(kDoNotProcess);
8951 ++nb;
8952 }
8953 }
8954
8955 //search in list of friends
8957 if (fFriends) {
8958 TFriendLock lock(this,kSetBranchStatus);
8961 TString name;
8962 while ((fe = (TFriendElement*)nextf())) {
8963 TTree *t = fe->GetTree();
8964 if (!t) continue;
8965
8966 // If the alias is present replace it with the real name.
8967 const char *subbranch = strstr(bname,fe->GetName());
8968 if (subbranch!=bname) subbranch = nullptr;
8969 if (subbranch) {
8970 subbranch += strlen(fe->GetName());
8971 if ( *subbranch != '.' ) subbranch = nullptr;
8972 else subbranch ++;
8973 }
8974 if (subbranch) {
8975 name.Form("%s.%s",t->GetName(),subbranch);
8976 } else {
8977 name = bname;
8978 }
8979 t->SetBranchStatus(name,status, &foundInFriend);
8980 }
8981 }
8982 if (!nb && !foundInFriend) {
8983 if (!found) {
8984 if (status) {
8985 if (strchr(bname,'*') != nullptr)
8986 Error("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8987 else
8988 Error("SetBranchStatus", "unknown branch -> %s", bname);
8989 } else {
8990 if (strchr(bname,'*') != nullptr)
8991 Warning("SetBranchStatus", "No branch name is matching wildcard -> %s", bname);
8992 else
8993 Warning("SetBranchStatus", "unknown branch -> %s", bname);
8994 }
8995 }
8996 return;
8997 }
8998 if (found) *found = nb + foundInFriend;
8999
9000 // second pass, loop again on all branches
9001 // activate leafcount branches for active branches only
9002 for (i = 0; i < nleaves; i++) {
9004 branch = (TBranch*)leaf->GetBranch();
9005 if (!branch->TestBit(kDoNotProcess)) {
9006 leafcount = leaf->GetLeafCount();
9007 if (leafcount) {
9008 bcount = leafcount->GetBranch();
9009 bcount->ResetBit(kDoNotProcess);
9010 }
9011 } else {
9012 //Int_t nbranches = branch->GetListOfBranches()->GetEntriesFast();
9013 Int_t nbranches = branch->GetListOfBranches()->GetEntries();
9014 for (j=0;j<nbranches;j++) {
9015 bson = (TBranch*)branch->GetListOfBranches()->UncheckedAt(j);
9016 if (!bson) continue;
9017 if (!bson->TestBit(kDoNotProcess)) {
9018 if (bson->GetNleaves() <= 0) continue;
9019 branch->ResetBit(kDoNotProcess);
9020 break;
9021 }
9022 }
9023 }
9024 }
9025}
9026
9027////////////////////////////////////////////////////////////////////////////////
9028/// Set the current branch style. (static function)
9029///
9030/// - style = 0 old Branch
9031/// - style = 1 new Bronch
9036}
9037
9038////////////////////////////////////////////////////////////////////////////////
9039/// Set maximum size of the file cache (TTreeCache) in bytes.
9040//
9041/// - if cachesize = 0 the existing cache (if any) is disabled (deleted if any).
9042/// - if cachesize > 0, the cache is enabled or extended, if necessary
9043/// - if cachesize = -1 (default) it is set to the AutoFlush value when writing
9044/// the Tree (default is 30 MBytes).
9045///
9046/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
9047///
9048/// TTreeCache's 'real' job is to actually prefetch (early grab from disk) the compressed data.
9049/// The cachesize controls the size of the read bytes from disk.
9050///
9051/// Returns:
9052/// - 0 size set, cache was created if possible
9053/// - -1 on error
9056{
9057 // remember that the user has requested an explicit cache setup
9058 fCacheUserSet = true;
9059
9060 return SetCacheSizeAux(false, cacheSize);
9061}
9062
9063////////////////////////////////////////////////////////////////////////////////
9064/// Set the maximum size of the file cache (TTreeCache) in bytes and create it if possible.
9065///
9066/// If autocache is true:
9067/// this may be an autocreated cache, possibly enlarging an existing
9068/// autocreated cache. The size is calculated. The value passed in cacheSize:
9069/// - cacheSize = 0 make cache if default cache creation is enabled.
9070/// - cachesize > 0 the cache is enabled or extended, if necessary
9071/// - cacheSize = -1 make a default sized cache in any case
9072///
9073/// If autocache is false:
9074/// this is a user requested cache. cacheSize is used to size the cache.
9075/// This cache should never be automatically adjusted. If cachesize is
9076/// 0, the cache is disabled (deleted if any).
9077///
9078/// The cacheSize might be clamped, see TFileCacheRead::SetBufferSize
9079///
9080/// TTreeCache's 'real' job is to actually prefetch (early grab from disk) the compressed data.
9081/// The cachesize controls the size of the read bytes from disk.
9082///
9083/// Returns:
9084/// - 0 size set, or existing autosized cache almost large enough.
9085/// (cache was created if possible)
9086/// - -1 on error
9088Int_t TTree::SetCacheSizeAux(bool autocache /* = true */, Long64_t cacheSize /* = 0 */ )
9089{
9090 if (autocache) {
9091 // used as a once only control for automatic cache setup
9092 fCacheDoAutoInit = false;
9093 }
9094
9095 if (!autocache) {
9096 // negative size means the user requests the default
9097 if (cacheSize < 0) {
9098 cacheSize = GetCacheAutoSize(true);
9099 }
9100 } else {
9101 if (cacheSize == 0) {
9102 cacheSize = GetCacheAutoSize();
9103 } else if (cacheSize < 0) {
9104 cacheSize = GetCacheAutoSize(true);
9105 }
9106 }
9107
9108 TFile* file = GetCurrentFile();
9109 if (!file || GetTree() != this) {
9110 // if there's no file or we are not a plain tree (e.g. if we're a TChain)
9111 // do not create a cache, only record the size if one was given
9112 if (!autocache) {
9113 fCacheSize = cacheSize;
9114 }
9115 if (GetTree() != this) {
9116 return 0;
9117 }
9118 if (!autocache && cacheSize>0) {
9119 Warning("SetCacheSizeAux", "A TTreeCache could not be created because the TTree has no file");
9120 }
9121 return 0;
9122 }
9123
9124 // Check for an existing cache
9125 TTreeCache* pf = GetReadCache(file);
9126 if (pf) {
9127 if (autocache) {
9128 // reset our cache status tracking in case existing cache was added
9129 // by the user without using one of the TTree methods
9130 fCacheSize = pf->GetBufferSize();
9131 fCacheUserSet = !pf->IsAutoCreated();
9132
9133 if (fCacheUserSet) {
9134 // existing cache was created by the user, don't change it
9135 return 0;
9136 }
9137 } else {
9138 // update the cache to ensure it records the user has explicitly
9139 // requested it
9140 pf->SetAutoCreated(false);
9141 }
9142
9143 // if we're using an automatically calculated size and the existing
9144 // cache is already almost large enough don't resize
9145 if (autocache && Long64_t(0.80*cacheSize) < fCacheSize) {
9146 // already large enough
9147 return 0;
9148 }
9149
9150 if (cacheSize == fCacheSize) {
9151 return 0;
9152 }
9153
9154 if (cacheSize == 0) {
9155 // delete existing cache
9156 pf->WaitFinishPrefetch();
9157 file->SetCacheRead(nullptr,this);
9158 delete pf;
9159 pf = nullptr;
9160 } else {
9161 // resize
9162 Int_t res = pf->SetBufferSize(cacheSize);
9163 if (res < 0) {
9164 return -1;
9165 }
9166 cacheSize = pf->GetBufferSize(); // update after potential clamp
9167 }
9168 } else {
9169 // no existing cache
9170 if (autocache) {
9171 if (fCacheUserSet) {
9172 // value was already set manually.
9173 if (fCacheSize == 0) return 0;
9174 // Expected a cache should exist; perhaps the user moved it
9175 // Do nothing more here.
9176 if (cacheSize) {
9177 Error("SetCacheSizeAux", "Not setting up an automatically sized TTreeCache because of missing cache previously set");
9178 }
9179 return -1;
9180 }
9181 }
9182 }
9183
9184 fCacheSize = cacheSize;
9185 if (cacheSize == 0 || pf) {
9186 return 0;
9187 }
9188
9189#ifdef R__USE_IMT
9191 pf = new TTreeCacheUnzip(this, cacheSize);
9192 else
9193#endif
9194 pf = new TTreeCache(this, cacheSize);
9195
9196 pf->SetAutoCreated(autocache);
9197
9198 return 0;
9199}
9200
9201////////////////////////////////////////////////////////////////////////////////
9202///interface to TTreeCache to set the cache entry range
9203///
9204/// Returns:
9205/// - 0 entry range set
9206/// - -1 on error
9209{
9210 if (!GetTree()) {
9211 if (LoadTree(0)<0) {
9212 Error("SetCacheEntryRange","Could not load a tree");
9213 return -1;
9214 }
9215 }
9216 if (GetTree()) {
9217 if (GetTree() != this) {
9218 return GetTree()->SetCacheEntryRange(first, last);
9219 }
9220 } else {
9221 Error("SetCacheEntryRange", "No tree is available. Could not set cache entry range");
9222 return -1;
9223 }
9224
9225 TFile *f = GetCurrentFile();
9226 if (!f) {
9227 Error("SetCacheEntryRange", "No file is available. Could not set cache entry range");
9228 return -1;
9229 }
9230 TTreeCache *tc = GetReadCache(f,true);
9231 if (!tc) {
9232 Error("SetCacheEntryRange", "No cache is available. Could not set entry range");
9233 return -1;
9234 }
9235 tc->SetEntryRange(first,last);
9236 return 0;
9237}
9238
9239////////////////////////////////////////////////////////////////////////////////
9240/// Interface to TTreeCache to set the number of entries for the learning phase
9245}
9246
9247////////////////////////////////////////////////////////////////////////////////
9248/// Enable/Disable circularity for this tree.
9249///
9250/// if maxEntries > 0 a maximum of maxEntries is kept in one buffer/basket
9251/// per branch in memory.
9252/// Note that when this function is called (maxEntries>0) the Tree
9253/// must be empty or having only one basket per branch.
9254/// if maxEntries <= 0 the tree circularity is disabled.
9255///
9256/// #### NOTE 1:
9257/// Circular Trees are interesting in online real time environments
9258/// to store the results of the last maxEntries events.
9259/// #### NOTE 2:
9260/// Calling SetCircular with maxEntries <= 0 is necessary before
9261/// merging circular Trees that have been saved on files.
9262/// #### NOTE 3:
9263/// SetCircular with maxEntries <= 0 is automatically called
9264/// by TChain::Merge
9265/// #### NOTE 4:
9266/// A circular Tree can still be saved in a file. When read back,
9267/// it is still a circular Tree and can be filled again.
9270{
9271 if (maxEntries <= 0) {
9272 // Disable circularity.
9273 fMaxEntries = 1000000000;
9274 fMaxEntries *= 1000;
9276 //in case the Tree was originally created in gROOT, the branch
9277 //compression level was set to -1. If the Tree is now associated to
9278 //a file, reset the compression level to the file compression level
9279 if (fDirectory) {
9282 if (bfile) {
9283 compress = bfile->GetCompressionSettings();
9284 }
9286 for (Int_t i = 0; i < nb; i++) {
9288 branch->SetCompressionSettings(compress);
9289 }
9290 }
9291 } else {
9292 // Enable circularity.
9295 }
9296}
9297
9298////////////////////////////////////////////////////////////////////////////////
9299/// Set the debug level and the debug range.
9300///
9301/// For entries in the debug range, the functions TBranchElement::Fill
9302/// and TBranchElement::GetEntry will print the number of bytes filled
9303/// or read for each branch.
9305void TTree::SetDebug(Int_t level, Long64_t min, Long64_t max)
9306{
9307 fDebug = level;
9308 fDebugMin = min;
9309 fDebugMax = max;
9310}
9311
9312////////////////////////////////////////////////////////////////////////////////
9313/// Update the default value for the branch's fEntryOffsetLen.
9314/// If updateExisting is true, also update all the existing branches.
9315/// If newdefault is less than 10, the new default value will be 10.
9318{
9319 if (newdefault < 10) {
9320 newdefault = 10;
9321 }
9323 if (updateExisting) {
9324 TIter next( GetListOfBranches() );
9325 TBranch *b;
9326 while ( ( b = (TBranch*)next() ) ) {
9327 b->SetEntryOffsetLen( newdefault, true );
9328 }
9329 if (fBranchRef) {
9331 }
9332 }
9333}
9334
9335////////////////////////////////////////////////////////////////////////////////
9336/// Change the tree's directory.
9337///
9338/// Remove reference to this tree from current directory and
9339/// add reference to new directory dir. The dir parameter can
9340/// be 0 in which case the tree does not belong to any directory.
9341///
9344{
9345 if (fDirectory == dir) {
9346 return;
9347 }
9348 if (fDirectory) {
9349 fDirectory->Remove(this);
9350
9351 // Delete or move the file cache if it points to this Tree
9352 TFile *file = fDirectory->GetFile();
9353 MoveReadCache(file,dir);
9354 }
9355 fDirectory = dir;
9356 if (fDirectory) {
9357 fDirectory->Append(this);
9358 }
9359 TFile* file = nullptr;
9360 if (fDirectory) {
9361 file = fDirectory->GetFile();
9362 }
9363 if (fBranchRef) {
9364 fBranchRef->SetFile(file);
9365 }
9366 TBranch* b = nullptr;
9367 TIter next(GetListOfBranches());
9368 while((b = (TBranch*) next())) {
9369 b->SetFile(file);
9370 }
9371}
9372
9373////////////////////////////////////////////////////////////////////////////////
9374/// Change number of entries in the tree.
9375///
9376/// If n >= 0, set number of entries in the tree = n.
9377///
9378/// If n < 0, set number of entries in the tree to match the
9379/// number of entries in each branch. (default for n is -1)
9380///
9381/// This function should be called only when one fills each branch
9382/// independently via TBranch::Fill without calling TTree::Fill.
9383/// Calling TTree::SetEntries() make sense only if the number of entries
9384/// in each branch is identical, a warning is issued otherwise.
9385/// The function returns the number of entries.
9386///
9389{
9390 // case 1 : force number of entries to n
9391 if (n >= 0) {
9392 fEntries = n;
9393 return n;
9394 }
9395
9396 // case 2; compute the number of entries from the number of entries in the branches
9397 TBranch* b(nullptr), *bMin(nullptr), *bMax(nullptr);
9399 Long64_t nMax = 0;
9400 TIter next(GetListOfBranches());
9401 while((b = (TBranch*) next())){
9402 Long64_t n2 = b->GetEntries();
9403 if (!bMin || n2 < nMin) {
9404 nMin = n2;
9405 bMin = b;
9406 }
9407 if (!bMax || n2 > nMax) {
9408 nMax = n2;
9409 bMax = b;
9410 }
9411 }
9412 if (bMin && nMin != nMax) {
9413 Warning("SetEntries", "Tree branches have different numbers of entries, eg %s has %lld entries while %s has %lld entries.",
9414 bMin->GetName(), nMin, bMax->GetName(), nMax);
9415 }
9416 fEntries = nMax;
9417 return fEntries;
9418}
9419
9420////////////////////////////////////////////////////////////////////////////////
9421/// Set an EntryList
9424{
9425 if (fEntryList) {
9426 //check if the previous entry list is owned by the tree
9428 delete fEntryList;
9429 }
9430 }
9431 fEventList = nullptr;
9432 if (!enlist) {
9433 fEntryList = nullptr;
9434 return;
9435 }
9437 fEntryList->SetTree(this);
9438
9439}
9440
9441////////////////////////////////////////////////////////////////////////////////
9442/// This function transfroms the given TEventList into a TEntryList
9443/// The new TEntryList is owned by the TTree and gets deleted when the tree
9444/// is deleted. This TEntryList can be returned by GetEntryList() function.
9447{
9449 if (fEntryList){
9452 fEntryList = nullptr; // Avoid problem with RecursiveRemove.
9453 delete tmp;
9454 } else {
9455 fEntryList = nullptr;
9456 }
9457 }
9458
9459 if (!evlist) {
9460 fEntryList = nullptr;
9461 fEventList = nullptr;
9462 return;
9463 }
9464
9466 char enlistname[100];
9467 snprintf(enlistname,100, "%s_%s", evlist->GetName(), "entrylist");
9468 fEntryList = new TEntryList(enlistname, evlist->GetTitle());
9469 fEntryList->SetDirectory(nullptr); // We own this.
9470 Int_t nsel = evlist->GetN();
9471 fEntryList->SetTree(this);
9473 for (Int_t i=0; i<nsel; i++){
9474 entry = evlist->GetEntry(i);
9476 }
9477 fEntryList->SetReapplyCut(evlist->GetReapplyCut());
9479}
9480
9481////////////////////////////////////////////////////////////////////////////////
9482/// Set number of entries to estimate variable limits.
9483/// If n is -1, the estimate is set to be the current maximum
9484/// for the tree (i.e. GetEntries() + 1)
9485/// If n is less than -1, the behavior is undefined.
9487void TTree::SetEstimate(Long64_t n /* = 1000000 */)
9488{
9489 if (n == 0) {
9490 n = 10000;
9491 } else if (n < 0) {
9492 n = fEntries - n;
9493 }
9494 fEstimate = n;
9495 GetPlayer();
9496 if (fPlayer) {
9498 }
9499}
9500
9501////////////////////////////////////////////////////////////////////////////////
9502/// Provide the end-user with the ability to enable/disable various experimental
9503/// IO features for this TTree.
9504///
9505/// Returns all the newly-set IO settings.
9508{
9509 // Purposely ignore all unsupported bits; TIOFeatures implementation already warned the user about the
9510 // error of their ways; this is just a safety check.
9512
9517
9519 return newSettings;
9520}
9521
9522////////////////////////////////////////////////////////////////////////////////
9523/// Set fFileNumber to number.
9524/// fFileNumber is used by TTree::Fill to set the file name
9525/// for a new file to be created when the current file exceeds fgTreeMaxSize.
9526/// (see TTree::ChangeFile)
9527/// if fFileNumber=10, the new file name will have a suffix "_11",
9528/// ie, fFileNumber is incremented before setting the file name
9530void TTree::SetFileNumber(Int_t number)
9531{
9532 if (fFileNumber < 0) {
9533 Warning("SetFileNumber", "file number must be positive. Set to 0");
9534 fFileNumber = 0;
9535 return;
9536 }
9537 fFileNumber = number;
9538}
9539
9540////////////////////////////////////////////////////////////////////////////////
9541/// Set all the branches in this TTree to be in decomposed object mode
9542/// (also known as MakeClass mode).
9543///
9544/// For MakeClass mode 0, the TTree expects the address where the data is stored
9545/// to be set by either the user or the TTree to the address of a full object
9546/// through the top level branch.
9547/// For MakeClass mode 1, this address is expected to point to a numerical type
9548/// or C-style array (variable or not) of numerical type, representing the
9549/// primitive data members.
9550/// The function's primary purpose is to allow the user to access the data
9551/// directly with numerical type variable rather than having to have the original
9552/// set of classes (or a reproduction thereof).
9553/// In other words, SetMakeClass sets the branch(es) into a
9554/// mode that allow its reading via a set of independent variables
9555/// (see the result of running TTree::MakeClass on your TTree) by changing the
9556/// interpretation of the address passed to SetAddress from being the beginning
9557/// of the object containing the data to being the exact location where the data
9558/// should be loaded. If you have the shared library corresponding to your object,
9559/// it is better if you do
9560/// `MyClass *objp = 0; tree->SetBranchAddress("toplevel",&objp);`, whereas
9561/// if you do not have the shared library but know your branch data type, e.g.
9562/// `Int_t* ptr = new Int_t[10];`, then:
9563/// `tree->SetMakeClass(1); tree->GetBranch("x")->SetAddress(ptr)` is the way to go.
9565void TTree::SetMakeClass(Int_t make)
9566{
9567 fMakeClass = make;
9568
9570 for (Int_t i = 0; i < nb; ++i) {
9572 branch->SetMakeClass(make);
9573 }
9574}
9575
9576////////////////////////////////////////////////////////////////////////////////
9577/// Set the maximum size in bytes of a Tree file (static function).
9578/// The default size is 100000000000LL, ie 100 Gigabytes.
9579///
9580/// In TTree::Fill, when the file has a size > fgMaxTreeSize,
9581/// the function closes the current file and starts writing into
9582/// a new file with a name of the style "file_1.root" if the original
9583/// requested file name was "file.root".
9588}
9589
9590////////////////////////////////////////////////////////////////////////////////
9591/// Change the name of this tree.
9593void TTree::SetName(const char* name)
9594{
9595 if (gPad) {
9596 gPad->Modified();
9597 }
9598 // Trees are named objects in a THashList.
9599 // We must update hashlists if we change the name.
9600 TFile *file = nullptr;
9601 TTreeCache *pf = nullptr;
9602 if (fDirectory) {
9603 fDirectory->Remove(this);
9604 if ((file = GetCurrentFile())) {
9605 pf = GetReadCache(file);
9606 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9607 }
9608 }
9609 // This changes our hash value.
9610 fName = name;
9611 if (fDirectory) {
9612 fDirectory->Append(this);
9613 if (pf) {
9615 }
9616 }
9617}
9619void TTree::SetNotify(TObject *obj)
9620{
9621 if (obj && fNotify && dynamic_cast<TNotifyLinkBase *>(fNotify)) {
9622 auto *oldLink = static_cast<TNotifyLinkBase *>(fNotify);
9623 auto *newLink = dynamic_cast<TNotifyLinkBase *>(obj);
9624 if (!newLink) {
9625 Warning("TTree::SetNotify",
9626 "The tree or chain already has a fNotify registered and it is a TNotifyLink, while the new object is "
9627 "not a TNotifyLink. Setting fNotify to the new value will lead to an orphan linked list of "
9628 "TNotifyLinks and it is most likely not intended. If this is the intended goal, please call "
9629 "SetNotify(nullptr) first to silence this warning.");
9630 } else if (newLink->GetNext() != oldLink && oldLink->GetNext() != newLink) {
9631 // If newLink->GetNext() == oldLink then we are prepending the new head, as in TNotifyLink::PrependLink
9632 // If oldLink->GetNext() == newLink then we are removing the head of the list, as in TNotifyLink::RemoveLink
9633 // Otherwise newLink and oldLink are unrelated:
9634 Warning("TTree::SetNotify",
9635 "The tree or chain already has a TNotifyLink registered, and the new TNotifyLink `obj` does not link "
9636 "to it. Setting fNotify to the new value will lead to an orphan linked list of TNotifyLinks and it is "
9637 "most likely not intended. If this is the intended goal, please call SetNotify(nullptr) first to "
9638 "silence this warning.");
9639 }
9640 }
9641
9642 fNotify = obj;
9643}
9644
9645////////////////////////////////////////////////////////////////////////////////
9646/// Change the name and title of this tree.
9648void TTree::SetObject(const char* name, const char* title)
9649{
9650 if (gPad) {
9651 gPad->Modified();
9652 }
9653
9654 // Trees are named objects in a THashList.
9655 // We must update hashlists if we change the name
9656 TFile *file = nullptr;
9657 TTreeCache *pf = nullptr;
9658 if (fDirectory) {
9659 fDirectory->Remove(this);
9660 if ((file = GetCurrentFile())) {
9661 pf = GetReadCache(file);
9662 file->SetCacheRead(nullptr,this,TFile::kDoNotDisconnect);
9663 }
9664 }
9665 // This changes our hash value.
9666 fName = name;
9667 fTitle = title;
9668 if (fDirectory) {
9669 fDirectory->Append(this);
9670 if (pf) {
9672 }
9673 }
9674}
9675
9676////////////////////////////////////////////////////////////////////////////////
9677/// Enable or disable parallel unzipping of Tree buffers.
9680{
9681#ifdef R__USE_IMT
9682 if (GetTree() == nullptr) {
9684 if (!GetTree())
9685 return;
9686 }
9687 if (GetTree() != this) {
9688 GetTree()->SetParallelUnzip(opt, RelSize);
9689 return;
9690 }
9691 TFile* file = GetCurrentFile();
9692 if (!file)
9693 return;
9694
9695 TTreeCache* pf = GetReadCache(file);
9696 if (pf && !( opt ^ (nullptr != dynamic_cast<TTreeCacheUnzip*>(pf)))) {
9697 // done with opt and type are in agreement.
9698 return;
9699 }
9700 delete pf;
9701 auto cacheSize = GetCacheAutoSize(true);
9702 if (opt) {
9703 auto unzip = new TTreeCacheUnzip(this, cacheSize);
9704 unzip->SetUnzipBufferSize( Long64_t(cacheSize * RelSize) );
9705 } else {
9706 pf = new TTreeCache(this, cacheSize);
9707 }
9708#else
9709 (void)opt;
9710 (void)RelSize;
9711#endif
9712}
9713
9714////////////////////////////////////////////////////////////////////////////////
9715/// Set perf stats
9720}
9721
9722////////////////////////////////////////////////////////////////////////////////
9723/// The current TreeIndex is replaced by the new index.
9724/// Note that this function does not delete the previous index.
9725/// This gives the possibility to play with more than one index, e.g.,
9726/// ~~~ {.cpp}
9727/// TVirtualIndex* oldIndex = tree.GetTreeIndex();
9728/// tree.SetTreeIndex(newIndex);
9729/// tree.Draw();
9730/// tree.SetTreeIndex(oldIndex);
9731/// tree.Draw(); etc
9732/// ~~~
9735{
9736 if (fTreeIndex) {
9737 fTreeIndex->SetTree(nullptr);
9738 }
9739 fTreeIndex = index;
9740}
9741
9742////////////////////////////////////////////////////////////////////////////////
9743/// Set tree weight.
9744///
9745/// The weight is used by TTree::Draw to automatically weight each
9746/// selected entry in the resulting histogram.
9747///
9748/// For example the equivalent of:
9749/// ~~~ {.cpp}
9750/// T.Draw("x", "w")
9751/// ~~~
9752/// is:
9753/// ~~~ {.cpp}
9754/// T.SetWeight(w);
9755/// T.Draw("x");
9756/// ~~~
9757/// This function is redefined by TChain::SetWeight. In case of a
9758/// TChain, an option "global" may be specified to set the same weight
9759/// for all trees in the TChain instead of the default behaviour
9760/// using the weights of each tree in the chain (see TChain::SetWeight).
9763{
9764 fWeight = w;
9765}
9766
9767////////////////////////////////////////////////////////////////////////////////
9768/// Print values of all active leaves for entry.
9769///
9770/// - if entry==-1, print current entry (default)
9771/// - if a leaf is an array, a maximum of lenmax elements is printed.
9774{
9775 if (entry != -1) {
9777 if (ret == -2) {
9778 Error("Show()", "Cannot read entry %lld (entry does not exist)", entry);
9779 return;
9780 } else if (ret == -1) {
9781 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9782 return;
9783 }
9784 ret = GetEntry(entry);
9785 if (ret == -1) {
9786 Error("Show()", "Cannot read entry %lld (I/O error)", entry);
9787 return;
9788 } else if (ret == 0) {
9789 Error("Show()", "Cannot read entry %lld (no data read)", entry);
9790 return;
9791 }
9792 }
9793 printf("======> EVENT:%lld\n", fReadEntry);
9795 Int_t nleaves = leaves->GetEntriesFast();
9796 Int_t ltype;
9797 for (Int_t i = 0; i < nleaves; i++) {
9798 TLeaf* leaf = (TLeaf*) leaves->UncheckedAt(i);
9799 TBranch* branch = leaf->GetBranch();
9800 if (branch->TestBit(kDoNotProcess)) {
9801 continue;
9802 }
9803 Int_t len = leaf->GetLen();
9804 if (len <= 0) {
9805 continue;
9806 }
9808 if (leaf->IsA() == TLeafElement::Class()) {
9809 leaf->PrintValue(lenmax);
9810 continue;
9811 }
9812 if (branch->GetListOfBranches()->GetEntriesFast() > 0) {
9813 continue;
9814 }
9815 ltype = 10;
9816 if (leaf->IsA() == TLeafF::Class()) {
9817 ltype = 5;
9818 }
9819 if (leaf->IsA() == TLeafD::Class()) {
9820 ltype = 5;
9821 }
9822 if (leaf->IsA() == TLeafC::Class()) {
9823 len = 1;
9824 ltype = 5;
9825 };
9826 printf(" %-15s = ", leaf->GetName());
9827 for (Int_t l = 0; l < len; l++) {
9828 leaf->PrintValue(l);
9829 if (l == (len - 1)) {
9830 printf("\n");
9831 continue;
9832 }
9833 printf(", ");
9834 if ((l % ltype) == 0) {
9835 printf("\n ");
9836 }
9837 }
9838 }
9839}
9840
9841////////////////////////////////////////////////////////////////////////////////
9842/// Start the TTreeViewer on this tree.
9843///
9844/// - ww is the width of the canvas in pixels
9845/// - wh is the height of the canvas in pixels
9847void TTree::StartViewer()
9848{
9849 GetPlayer();
9850 if (fPlayer) {
9851 fPlayer->StartViewer(600, 400);
9852 }
9853}
9854
9855////////////////////////////////////////////////////////////////////////////////
9856/// Stop the cache learning phase
9857///
9858/// Returns:
9859/// - 0 learning phase stopped or not active
9860/// - -1 on error
9863{
9864 if (!GetTree()) {
9865 if (LoadTree(0)<0) {
9866 Error("StopCacheLearningPhase","Could not load a tree");
9867 return -1;
9868 }
9869 }
9870 if (GetTree()) {
9871 if (GetTree() != this) {
9872 return GetTree()->StopCacheLearningPhase();
9873 }
9874 } else {
9875 Error("StopCacheLearningPhase", "No tree is available. Could not stop cache learning phase");
9876 return -1;
9877 }
9878
9879 TFile *f = GetCurrentFile();
9880 if (!f) {
9881 Error("StopCacheLearningPhase", "No file is available. Could not stop cache learning phase");
9882 return -1;
9883 }
9884 TTreeCache *tc = GetReadCache(f,true);
9885 if (!tc) {
9886 Error("StopCacheLearningPhase", "No cache is available. Could not stop learning phase");
9887 return -1;
9888 }
9889 tc->StopLearningPhase();
9890 return 0;
9891}
9892
9893////////////////////////////////////////////////////////////////////////////////
9894/// Set the fTree member for all branches and sub branches.
9897{
9898 Int_t nb = branches.GetEntriesFast();
9899 for (Int_t i = 0; i < nb; ++i) {
9900 TBranch* br = (TBranch*) branches.UncheckedAt(i);
9901 br->SetTree(tree);
9902
9903 Int_t writeBasket = br->GetWriteBasket();
9904 for (Int_t j = writeBasket; j >= 0; --j) {
9905 TBasket *bk = (TBasket*)br->GetListOfBaskets()->UncheckedAt(j);
9906 if (bk) {
9907 tree->IncrementTotalBuffers(bk->GetBufferSize());
9908 }
9909 }
9910
9911 tree->RegisterBranchFullName({std::string{br->GetFullName()}, br});
9912
9913 ROOT::Internal::TreeUtils::TBranch__SetTree(tree, *br->GetListOfBranches());
9914 }
9915}
9916
9917////////////////////////////////////////////////////////////////////////////////
9918/// Set the fTree member for all friend elements.
9921{
9922 if (frlist) {
9923 TObjLink *lnk = frlist->FirstLink();
9924 while (lnk) {
9925 TFriendElement *elem = (TFriendElement*)lnk->GetObject();
9926 elem->fParentTree = tree;
9927 lnk = lnk->Next();
9928 }
9929 }
9930}
9931
9932////////////////////////////////////////////////////////////////////////////////
9933/// Stream a class object.
9936{
9937 if (b.IsReading()) {
9938 UInt_t R__s, R__c;
9939 if (fDirectory) {
9940 fDirectory->Remove(this);
9941 //delete the file cache if it points to this Tree
9942 TFile *file = fDirectory->GetFile();
9943 MoveReadCache(file,nullptr);
9944 }
9945 fDirectory = nullptr;
9946 fCacheDoAutoInit = true;
9947 fCacheUserSet = false;
9948 fNamesToBranches.clear();
9949 Version_t R__v = b.ReadVersion(&R__s, &R__c);
9950 if (R__v > 4) {
9951 b.ReadClassBuffer(TTree::Class(), this, R__v, R__s, R__c);
9952
9953 fBranches.SetOwner(true); // True needed only for R__v < 19 and most R__v == 19
9954
9955 if (fBranchRef) fBranchRef->SetTree(this);
9958
9959 if (fTreeIndex) {
9960 fTreeIndex->SetTree(this);
9961 }
9962 if (fIndex.fN) {
9963 Warning("Streamer", "Old style index in this tree is deleted. Rebuild the index via TTree::BuildIndex");
9964 fIndex.Set(0);
9965 fIndexValues.Set(0);
9966 }
9967 if (fEstimate <= 10000) {
9968 fEstimate = 1000000;
9969 }
9970
9971 if (fNClusterRange) {
9972 // The I/O allocated just enough memory to hold the
9973 // current set of ranges.
9975 }
9976
9977 // Throughs calls to `GetCacheAutoSize` or `EnableCache` (for example
9978 // by TTreePlayer::Process, the cache size will be automatically
9979 // determined unless the user explicitly call `SetCacheSize`
9980 fCacheSize = 0;
9981 fCacheUserSet = false;
9982
9984 return;
9985 }
9986 //====process old versions before automatic schema evolution
9987 Stat_t djunk;
9988 Int_t ijunk;
9993 b >> fScanField;
9996 b >> djunk; fEntries = (Long64_t)djunk;
10001 if (fEstimate <= 10000) fEstimate = 1000000;
10003 if (fBranchRef) fBranchRef->SetTree(this);
10007 if (R__v > 1) fIndexValues.Streamer(b);
10008 if (R__v > 2) fIndex.Streamer(b);
10009 if (R__v > 3) {
10011 OldInfoList.Streamer(b);
10012 OldInfoList.Delete();
10013 }
10014 fNClusterRange = 0;
10017 b.CheckByteCount(R__s, R__c, TTree::IsA());
10018 //====end of old versions
10019 } else {
10020 if (fBranchRef) {
10021 fBranchRef->Clear();
10022 }
10024 if (table) TRefTable::SetRefTable(nullptr);
10025
10026 b.WriteClassBuffer(TTree::Class(), this);
10027
10028 if (table) TRefTable::SetRefTable(table);
10029 }
10030}
10031
10032////////////////////////////////////////////////////////////////////////////////
10033/// Unbinned fit of one or more variable(s) from a tree.
10034///
10035/// funcname is a TF1 function.
10036///
10037/// \note see TTree::Draw for explanations of the other parameters.
10038///
10039/// Fit the variable varexp using the function funcname using the
10040/// selection cuts given by selection.
10041///
10042/// The list of fit options is given in parameter option.
10043///
10044/// - option = "Q" Quiet mode (minimum printing)
10045/// - option = "V" Verbose mode (default is between Q and V)
10046/// - option = "E" Perform better Errors estimation using Minos technique
10047/// - option = "M" More. Improve fit results
10048///
10049/// You can specify boundary limits for some or all parameters via
10050/// ~~~ {.cpp}
10051/// func->SetParLimits(p_number, parmin, parmax);
10052/// ~~~
10053/// if parmin>=parmax, the parameter is fixed
10054///
10055/// Note that you are not forced to fix the limits for all parameters.
10056/// For example, if you fit a function with 6 parameters, you can do:
10057/// ~~~ {.cpp}
10058/// func->SetParameters(0,3.1,1.e-6,0.1,-8,100);
10059/// func->SetParLimits(4,-10,-4);
10060/// func->SetParLimits(5, 1,1);
10061/// ~~~
10062/// With this setup:
10063///
10064/// - Parameters 0->3 can vary freely
10065/// - Parameter 4 has boundaries [-10,-4] with initial value -8
10066/// - Parameter 5 is fixed to 100.
10067///
10068/// For the fit to be meaningful, the function must be self-normalized.
10069///
10070/// i.e. It must have the same integral regardless of the parameter
10071/// settings. Otherwise the fit will effectively just maximize the
10072/// area.
10073///
10074/// It is mandatory to have a normalization variable
10075/// which is fixed for the fit. e.g.
10076/// ~~~ {.cpp}
10077/// TF1* f1 = new TF1("f1", "gaus(0)/sqrt(2*3.14159)/[2]", 0, 5);
10078/// f1->SetParameters(1, 3.1, 0.01);
10079/// f1->SetParLimits(0, 1, 1); // fix the normalization parameter to 1
10080/// data->UnbinnedFit("f1", "jpsimass", "jpsipt>3.0");
10081/// ~~~
10082/// 1, 2 and 3 Dimensional fits are supported. See also TTree::Fit
10083///
10084/// Return status:
10085///
10086/// - The function return the status of the fit in the following form
10087/// fitResult = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
10088/// - The fitResult is 0 is the fit is OK.
10089/// - The fitResult is negative in case of an error not connected with the fit.
10090/// - The number of entries used in the fit can be obtained via mytree.GetSelectedRows();
10091/// - If the number of selected entries is null the function returns -1
10094{
10095 GetPlayer();
10096 if (fPlayer) {
10098 }
10099 return -1;
10100}
10101
10102////////////////////////////////////////////////////////////////////////////////
10103/// Replace current attributes by current style.
10126}
10127
10128////////////////////////////////////////////////////////////////////////////////
10129/// Write this object to the current directory. For more see TObject::Write
10130/// If option & kFlushBasket, call FlushBasket before writing the tree.
10132Int_t TTree::Write(const char *name, Int_t option, Int_t bufsize) const
10133{
10136 return 0;
10138}
10139
10140////////////////////////////////////////////////////////////////////////////////
10141/// Write this object to the current directory. For more see TObject::Write
10142/// If option & kFlushBasket, call FlushBasket before writing the tree.
10145{
10146 return ((const TTree*)this)->Write(name, option, bufsize);
10147}
10148
10149////////////////////////////////////////////////////////////////////////////////
10150/// \class TTreeFriendLeafIter
10151///
10152/// Iterator on all the leaves in a TTree and its friend
10153
10154
10155////////////////////////////////////////////////////////////////////////////////
10156/// Create a new iterator. By default the iteration direction
10157/// is kIterForward. To go backward use kIterBackward.
10160: fTree(const_cast<TTree*>(tree))
10161, fLeafIter(nullptr)
10162, fTreeIter(nullptr)
10163, fDirection(dir)
10164{
10165}
10166
10167////////////////////////////////////////////////////////////////////////////////
10168/// Copy constructor. Does NOT copy the 'cursor' location!
10171: TIterator(iter)
10172, fTree(iter.fTree)
10173, fLeafIter(nullptr)
10174, fTreeIter(nullptr)
10175, fDirection(iter.fDirection)
10176{
10177}
10178
10179////////////////////////////////////////////////////////////////////////////////
10180/// Overridden assignment operator. Does NOT copy the 'cursor' location!
10183{
10184 if (this != &rhs && rhs.IsA() == TTreeFriendLeafIter::Class()) {
10186 fDirection = rhs1.fDirection;
10187 }
10188 return *this;
10189}
10190
10191////////////////////////////////////////////////////////////////////////////////
10192/// Overridden assignment operator. Does NOT copy the 'cursor' location!
10195{
10196 if (this != &rhs) {
10197 fDirection = rhs.fDirection;
10198 }
10199 return *this;
10200}
10201
10202////////////////////////////////////////////////////////////////////////////////
10203/// Go the next friend element
10206{
10207 if (!fTree) return nullptr;
10208
10209 TObject * next;
10210 TTree * nextTree;
10211
10212 if (!fLeafIter) {
10213 TObjArray *list = fTree->GetListOfLeaves();
10214 if (!list) return nullptr; // Can happen with an empty chain.
10215 fLeafIter = list->MakeIterator(fDirection);
10216 if (!fLeafIter) return nullptr;
10217 }
10218
10219 next = fLeafIter->Next();
10220 if (!next) {
10221 if (!fTreeIter) {
10223 if (!list) return next;
10224 fTreeIter = list->MakeIterator(fDirection);
10225 if (!fTreeIter) return nullptr;
10226 }
10228 ///nextTree = (TTree*)fTreeIter->Next();
10229 if (nextFriend) {
10230 nextTree = const_cast<TTree*>(nextFriend->GetTree());
10231 if (!nextTree) return Next();
10233 fLeafIter = nextTree->GetListOfLeaves()->MakeIterator(fDirection);
10234 if (!fLeafIter) return nullptr;
10235 next = fLeafIter->Next();
10236 }
10237 }
10238 return next;
10239}
10240
10241////////////////////////////////////////////////////////////////////////////////
10242/// Returns the object option stored in the list.
10245{
10246 if (fLeafIter) return fLeafIter->GetOption();
10247 return "";
10248}
10254}
10260}
#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
bool Bool_t
Boolean (0=false, 1=true) (bool)
Definition RtypesCore.h:77
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:59
short Version_t
Class version identifier (short)
Definition RtypesCore.h:79
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:68
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:60
float Float_t
Float 4 bytes (float)
Definition RtypesCore.h:71
double Double_t
Double 8 bytes.
Definition RtypesCore.h:73
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:131
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:83
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:84
const char Option_t
Option string (const char)
Definition RtypesCore.h:80
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:145
int nentries
R__EXTERN TInterpreter * gCling
Binding & operator=(OUT(*fun)(void))
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:783
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:426
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2510
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:4841
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:9919
bool CheckReshuffling(TTree &mainTree, TTree &friendTree)
Definition TTree.cxx:1267
constexpr Float_t kNEntriesResortInv
Definition TTree.cxx:475
#define R__LOCKGUARD(mutex)
#define gPad
#define snprintf
Definition civetweb.c:1579
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:21
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition TAttMarker.h:34
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition TAttMarker.h:41
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition TAttMarker.h:33
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition TAttMarker.h:35
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition TAttMarker.h:43
virtual void Streamer(TBuffer &)
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition TAttMarker.h:48
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:2417
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:3490
@ kDoNotDisconnect
Definition TFile.h:148
virtual void Flush()
Synchronize a file's in-memory and on-disk states.
Definition TFile.cxx:1152
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:3787
virtual void WriteHeader()
Write File Header.
Definition TFile.cxx:2667
@ kCancelTTreeChangeRequest
Definition TFile.h:275
TFileCacheRead * GetCacheRead(const TObject *tree=nullptr) const
Return a pointer to the current read cache.
Definition TFile.cxx:1273
<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:615
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:459
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:224
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1081
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:986
@ 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:885
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:546
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1095
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1123
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:1069
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:425
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:2060
const char * Data() const
Definition TString.h:384
Bool_t EqualTo(const char *cs, ECaseCompare cmp=kExact) const
Definition TString.h:654
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:713
@ 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:2385
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2363
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:641
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:660
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:776
TTree * fTree
tree being iterated
Definition TTree.h:779
TIterator & operator=(const TIterator &rhs) override
Overridden assignment operator. Does NOT copy the 'cursor' location!
Definition TTree.cxx:10181
TObject * Next() override
Go the next friend element.
Definition TTree.cxx:10204
TIterator * fLeafIter
current leaf sub-iterator.
Definition TTree.h:780
Option_t * GetOption() const override
Returns the object option stored in the list.
Definition TTree.cxx:10243
TIterator * fTreeIter
current tree sub-iterator.
Definition TTree.h:781
bool fDirection
iteration direction
Definition TTree.h:782
static TClass * Class()
Helper class to iterate over cluster of baskets.
Definition TTree.h:322
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:359
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:229
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:233
TTree * fTree
Definition TTree.h:232
~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:4653
virtual TFriendElement * AddFriend(const char *treename, const char *filename="")
Add a TFriendElement to the list of friends.
Definition TTree.cxx:1359
double ComputeExtremum(const char *columname, double errVal, bool(*cmp)(double, double))
Computes the extremum (minimum or maximum) for the input column name.
Definition TTree.cxx:6435
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:5384
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr, TClass *realClass, EDataType datatype, bool isptr, bool suppressMissingBranchError)
Definition TTree.cxx:8797
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:4948
virtual void SetBranchStatus(const char *bname, bool status=true, UInt_t *found=nullptr)
Set branch status to Process or DoNotProcess.
Definition TTree.cxx:8901
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:5436
static Int_t GetBranchStyle()
Static function returning the current branch style.
Definition TTree.cxx:5477
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:5462
UInt_t fFriendLockStatus
! Record which method is locking the friend recursion
Definition TTree.h:147
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:5184
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:9772
TEventList * fEventList
! Pointer to event selection list (if one)
Definition TTree.h:135
virtual Long64_t GetAutoSave() const
Definition TTree.h:503
virtual Int_t StopCacheLearningPhase()
Stop the cache learning phase.
Definition TTree.cxx:9861
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:5724
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:9268
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:8626
virtual TClusterIterator GetClusterIterator(Long64_t firstentry)
Return an iterator over the cluster of baskets starting at firstentry.
Definition TTree.cxx:5549
virtual void ResetBranchAddress(TBranch *)
Tell a branch to set its address to zero.
Definition TTree.cxx:8380
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:7903
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:5996
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:9387
virtual TObjArray * GetListOfLeaves()
Definition TTree.h:584
TLeaf * SearchLeafInListOfLeaves(const char *branchName, const char *leafName)
Definition TTree.cxx:6204
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:6014
Long64_t GetCacheAutoSize(bool withDefault=false)
Used for automatic sizing of the cache.
Definition TTree.cxx:5489
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:5561
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:5134
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:9934
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:8196
TVirtualTreePlayer * GetPlayer()
Load the TTreePlayer (if not already done).
Definition TTree.cxx:6538
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:7009
virtual Long64_t ReadStream(std::istream &inputStream, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from an input stream.
Definition TTree.cxx:7930
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:9304
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:486
virtual TTree * GetFriend(const char *) const
Return a pointer to the TTree friend whose name or alias is friendname.
Definition TTree.cxx:6062
virtual void SetNotify(TObject *obj)
Sets the address of the object to be notified when the tree is loaded.
Definition TTree.cxx:9618
virtual Double_t GetMaximum(const char *columname)
Return maximum of column with name columname.
Definition TTree.cxx:6512
virtual Long64_t GetEntryNumberWithBestIndex(Long64_t major, Long64_t minor=0) const
Return entry number corresponding to major and minor number.
Definition TTree.cxx:5976
static void SetMaxTreeSize(Long64_t maxsize=100000000000LL)
Set the maximum size in bytes of a Tree file (static function).
Definition TTree.cxx:9584
void Print(Option_t *option="") const override
Print a summary of the tree contents.
Definition TTree.cxx:7536
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:10092
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:7688
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:6199
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:9564
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:7329
virtual void IncrementTotalBuffers(Int_t nbytes)
Definition TTree.h:641
TObjArray fBranches
List of Branches.
Definition TTree.h:132
TDirectory * GetDirectory() const
Definition TTree.h:517
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:6551
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
@ kSplitCollectionOfPointers
Definition TTree.h:318
virtual TEntryList * GetEntryList()
Returns the entry list assigned to this tree.
Definition TTree.cxx:5940
virtual void SetWeight(Double_t w=1, Option_t *option="")
Set tree weight.
Definition TTree.cxx:9761
void InitializeBranchLists(bool checkLeafCount)
Divides the top-level branches into two vectors: (i) branches to be processed sequentially and (ii) b...
Definition TTree.cxx:5867
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:9716
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:9241
TEntryList * fEntryList
! Pointer to event selection list (if one)
Definition TTree.h:136
TBranch * FindBranchFromFriends(const char *branchName)
Definition TTree.cxx:4904
virtual TVirtualIndex * GetTreeIndex() const
Definition TTree.h:613
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:7143
virtual void SetMaxVirtualSize(Long64_t size=0)
Definition TTree.h:725
virtual void DropBaskets()
Remove some baskets from memory.
Definition TTree.cxx:4568
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:8671
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:9678
virtual void SetDirectory(TDirectory *dir)
Change the tree's directory.
Definition TTree.cxx:9342
void SortBranchesByTime()
Sorts top-level branches by the last average task time recorded per branch.
Definition TTree.cxx:5920
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:505
TLeaf * SearchLeafInListOfFriends(const char *branchName, const char *leafName)
Definition TTree.cxx:6253
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:7766
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:9445
void MoveReadCache(TFile *src, TDirectory *dir)
Move a cache from a file to the current file in dir.
Definition TTree.cxx:7300
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:8349
virtual Long64_t GetEntries() const
Definition TTree.h:518
virtual void SetEstimate(Long64_t nentries=1000000)
Set number of entries to estimate variable limits.
Definition TTree.cxx:9486
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:9087
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:5951
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)
Searches in this tree and any of its friends for a leaf named leafname in branch branchname ,...
Definition TTree.cxx:6304
virtual Long64_t GetZipBytes() const
Definition TTree.h:640
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:8318
virtual void KeepCircular()
Keep a maximum of fMaxEntries in memory.
Definition TTree.cxx:6648
virtual void SetDefaultEntryOffsetLen(Int_t newdefault, bool updateExisting=false)
Update the default value for the branch's fEntryOffsetLen.
Definition TTree.cxx:9316
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:611
virtual Int_t MakeSelector(const char *selector=nullptr, Option_t *option="")
Generate skeleton selector class for this tree.
Definition TTree.cxx:7063
virtual void SetObject(const char *name, const char *title)
Change the name and title of this tree.
Definition TTree.cxx:9647
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:5348
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:405
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:7094
bool MemoryFull(Int_t nbytes)
Check if adding nbytes to memory we are still below MaxVirtualsize.
Definition TTree.cxx:7078
virtual Long64_t GetReadEntry() const
Definition TTree.h:604
virtual TObjArray * GetListOfBranches()
Definition TTree.h:583
Long64_t fZipBytes
Total number of bytes in all branches after compression.
Definition TTree.h:97
virtual TTree * GetTree() const
Definition TTree.h:612
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:9422
bool Notify() override
Function called when loading a new class library.
Definition TTree.cxx:7350
virtual void AddZipBytes(Int_t zip)
Definition TTree.h:384
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition TTree.cxx:6706
virtual Long64_t ReadFile(const char *filename, const char *branchDescriptor="", char delimiter=' ')
Create or simply read branches from filename.
Definition TTree.cxx:7879
virtual const char * GetAlias(const char *aliasName) const
Returns the expanded value of the alias. Search in the friends if any.
Definition TTree.cxx:5281
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:9506
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:6530
virtual void RemoveFriend(TTree *)
Remove a friend from the list of friends.
Definition TTree.cxx:8292
virtual Long64_t GetEntriesFast() const
Return a number greater or equal to the total number of entries in the dataset.
Definition TTree.h:560
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:6589
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:308
@ kEntriesReshuffled
If set, signals that this TTree is the output of the processing of another TTree, and the entries are...
Definition TTree.h:313
@ kCircular
Definition TTree.h:304
virtual Long64_t GetEntriesFriend() const
Returns a number corresponding to:
Definition TTree.cxx:5596
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:7827
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:8687
static void SetBranchStyle(Int_t style=1)
Set the current branch style.
Definition TTree.cxx:9032
~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:6605
TClass * IsA() const override
Definition TTree.h:765
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:5201
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:6798
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:10143
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:10104
virtual Int_t GetTreeNumber() const
Definition TTree.h:614
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:582
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:253
@ kResetBranchAddresses
Definition TTree.h:274
@ kFindLeaf
Definition TTree.h:254
@ kGetEntryWithIndex
Definition TTree.h:258
@ kPrint
Definition TTree.h:268
@ kGetFriend
Definition TTree.h:259
@ kGetBranch
Definition TTree.h:256
@ kSetBranchStatus
Definition TTree.h:273
@ kLoadTree
Definition TTree.h:262
@ kGetEntry
Definition TTree.h:257
@ kGetLeaf
Definition TTree.h:261
@ kRemoveFriend
Definition TTree.h:272
@ kGetFriendAlias
Definition TTree.h:260
@ kGetAlias
Definition TTree.h:255
virtual void SetTreeIndex(TVirtualIndex *index)
The current TreeIndex is replaced by the new index.
Definition TTree.cxx:9733
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:7374
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:7812
virtual Int_t SetCacheEntryRange(Long64_t first, Long64_t last)
interface to TTreeCache to set the cache entry range
Definition TTree.cxx:9207
static Long64_t GetMaxTreeSize()
Static function which returns the tree file size limit in bytes.
Definition TTree.cxx:6520
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:8470
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:4581
virtual TList * GetListOfFriends() const
Definition TTree.h:585
virtual void Refresh()
Refresh contents of this tree and its branches from the current status on disk.
Definition TTree.cxx:8231
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:8525
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:8587
TBranch * FindBranchFromSelf(const char *branchName)
Definition TTree.cxx:4884
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:9529
virtual TLeaf * FindLeaf(const char *name)
Find first leaf containing searchname.
Definition TTree.cxx:4971
virtual void StartViewer()
Start the TTreeViewer on this tree.
Definition TTree.cxx:9846
Int_t GetMakeClass() const
Definition TTree.h:590
virtual Int_t MakeCode(const char *filename=nullptr)
Generate a skeleton function for this tree.
Definition TTree.cxx:6881
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:296
@ kClassMismatch
Definition TTree.h:289
@ kVoidPtr
Definition TTree.h:294
@ kMatchConversionCollection
Definition TTree.h:292
@ kMissingCompiledCollectionProxy
Definition TTree.h:287
@ kMismatch
Definition TTree.h:288
@ kMatchConversion
Definition TTree.h:291
@ kInternalError
Definition TTree.h:286
@ kMatch
Definition TTree.h:290
@ kMissingBranch
Definition TTree.h:285
@ kMakeClass
Definition TTree.h:293
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:8390
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:9592
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:8272
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:8737
virtual Int_t SetCacheSize(Long64_t cachesize=-1)
Set maximum size of the file cache (TTreeCache) in bytes.
Definition TTree.cxx:9054
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:6191
virtual Int_t MakeClass(const char *classname=nullptr, Option_t *option="")
Generate a skeleton analysis class for this tree.
Definition TTree.cxx:6848
virtual const char * GetFriendAlias(TTree *) const
If the 'tree' is a friend, this method returns its alias name.
Definition TTree.cxx:6119
virtual void RemoveExternalFriend(TFriendElement *)
Removes external friend.
Definition TTree.cxx:8283
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:8428
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:383
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:6684
static constexpr Long64_t kMaxEntries
Used as the max value for any TTree range operation.
Definition TTree.h:281
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:7517
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:502
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:10255
TBranch * CallBranchImpRef(TTree &tree, const char *branchname, TClass *ptrClass, EDataType datatype, void *addobj, Int_t bufsize=32000, Int_t splitlevel=99)
Definition TTree.cxx:10249
void TBranch__SetTree(TTree *tree, TObjArray &branches)
Set the fTree member for all branches and sub branches.
Definition TTree.cxx:9895
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:675
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:415
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)
Same as RMS.
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